{"id":13770,"date":"2022-03-03T13:41:55","date_gmt":"2022-03-03T13:41:55","guid":{"rendered":"https:\/\/algotrading101.com\/learn\/?p=13770"},"modified":"2023-04-03T21:02:18","modified_gmt":"2023-04-03T21:02:18","slug":"deribit-api-guide","status":"publish","type":"post","link":"https:\/\/algotrading101.com\/learn\/deribit-api-guide\/","title":{"rendered":"Deribit &#8211; An Introductory API Guide"},"content":{"rendered":"<div class=\"pvc_clear\"><\/div><p id=\"pvc_stats_13770\" class=\"pvc_stats total_only  \" data-element-id=\"13770\" style=\"\"><i class=\"pvc-stats-icon medium\" aria-hidden=\"true\"><svg aria-hidden=\"true\" focusable=\"false\" data-prefix=\"far\" data-icon=\"chart-bar\" role=\"img\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" viewBox=\"0 0 512 512\" class=\"svg-inline--fa fa-chart-bar fa-w-16 fa-2x\"><path fill=\"currentColor\" d=\"M396.8 352h22.4c6.4 0 12.8-6.4 12.8-12.8V108.8c0-6.4-6.4-12.8-12.8-12.8h-22.4c-6.4 0-12.8 6.4-12.8 12.8v230.4c0 6.4 6.4 12.8 12.8 12.8zm-192 0h22.4c6.4 0 12.8-6.4 12.8-12.8V140.8c0-6.4-6.4-12.8-12.8-12.8h-22.4c-6.4 0-12.8 6.4-12.8 12.8v198.4c0 6.4 6.4 12.8 12.8 12.8zm96 0h22.4c6.4 0 12.8-6.4 12.8-12.8V204.8c0-6.4-6.4-12.8-12.8-12.8h-22.4c-6.4 0-12.8 6.4-12.8 12.8v134.4c0 6.4 6.4 12.8 12.8 12.8zM496 400H48V80c0-8.84-7.16-16-16-16H16C7.16 64 0 71.16 0 80v336c0 17.67 14.33 32 32 32h464c8.84 0 16-7.16 16-16v-16c0-8.84-7.16-16-16-16zm-387.2-48h22.4c6.4 0 12.8-6.4 12.8-12.8v-70.4c0-6.4-6.4-12.8-12.8-12.8h-22.4c-6.4 0-12.8 6.4-12.8 12.8v70.4c0 6.4 6.4 12.8 12.8 12.8z\" class=\"\"><\/path><\/svg><\/i> <img decoding=\"async\" width=\"16\" height=\"16\" alt=\"Loading\" src=\"https:\/\/algotrading101.com\/learn\/wp-content\/plugins\/page-views-count\/ajax-loader-2x.gif\" border=0 \/><\/p><div class=\"pvc_clear\"><\/div>\n\n\n<figure class=\"wp-block-image size-full\"><img fetchpriority=\"high\" decoding=\"async\" width=\"604\" height=\"212\" src=\"https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2022\/07\/Deribit-Logo.jpg\" alt=\"Deribit API Guide\" class=\"wp-image-15867\" srcset=\"https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2022\/07\/Deribit-Logo.jpg 604w, https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2022\/07\/Deribit-Logo-300x105.jpg 300w\" sizes=\"(max-width: 604px) 100vw, 604px\" \/><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\">Table of contents:<\/h2>\n\n\n\n<ol><li><a href=\"#what-is-deribit\">What is Deribit?<\/a><\/li><li><a href=\"#what-is-deribit-api\">What is Deribit API?<\/a><\/li><li><a href=\"#is-deribit-free\">Is Deribit free?<\/a><\/li><li><a href=\"#kyc\">Does Deribit require KYC?<\/a><\/li><li><a href=\"#deribit-pros\">Why should I use Deribit?<\/a><\/li><li><a href=\"#deribit-cons\">Why shouldn\u2019t I use the Deribit?<\/a><\/li><li><a href=\"#deribit-countries\">Is Deribit available in my country?<\/a><\/li><li><a href=\"#deribit-alternatives\">What are the alternatives to using Deribit?<\/a><\/li><li><a href=\"#deribit-clients\">What clients are available for the Deribit API?<\/a><\/li><li><a href=\"#getting-started\">How to get started with Deribit?<\/a><\/li><li><a href=\"#currency\">How to get currency info with Deribit?<\/a><\/li><li><a href=\"#price\">How to get Price Data on Deribit?<\/a><\/li><li><a href=\"#historical\">How to get historical data with Deribit?<\/a><\/li><li><a href=\"#order-book\">How to get Order Book data with Deribit?<\/a><\/li><li><a href=\"#transactions\">How to get Transactions with Deribit?<\/a><\/li><li><a href=\"#order\">How to fire an order with Deribit?<\/a><\/li><li><a href=\"#perpetual-order\">How to fire an order on a Perpetual contract with Deribit?<\/a><\/li><li><a href=\"#futures-order\">How to fire an order on a Futures contract with Deribit?<\/a><\/li><li><a href=\"#option-order\">How to fire an order on an Option contract with Deribit?<\/a><\/li><li><a href=\"#order-example1\">How to execute a trade on ETH when BTC hits a certain price with the Deribit API?<\/a><\/li><li><a href=\"#order-example2\">How to execute an ETH trade when BTC moves 5% in the last 5 minutes with the Deribit API?<\/a><\/li><li><a href=\"#cancel-orders\">How to cancel orders with Deribit?<\/a><\/li><li><a href=\"#full-code\">Full code<\/a><\/li><\/ol>\n\n\n\n<a name=\"what-is-deribit\">\n\n\n\n<h2 class=\"wp-block-heading\">What is Deribit?<\/h2>\n\n\n\n<p>Deribit is an online cryptocurrency derivatives exchange that focuses on cryptocurrency futures and options trading. <\/p>\n\n\n\n<p>Link:<a href=\" https:\/\/www.deribit.com\"> https:\/\/www.deribit.com<\/a><\/p>\n\n\n\n<a name=\"what-is-deribit-api\">\n\n\n\n<h2 class=\"wp-block-heading\">What is Deribit API?<\/h2>\n\n\n\n<p>Derbit API is a method that allows us to automatically trade cryptocurrency futures and options on Deribit via code.<\/p>\n\n\n\n<a name=\"is-deribit-free\">\n\n\n\n<h2 class=\"wp-block-heading\">Is Deribit free?<\/h2>\n\n\n\n<p>Opening an account on Deribit is completely free while the exchange does impose trading fees on its customers. The exchanges&#8217; fee model is based on a maker-taker premise.<\/p>\n\n\n\n<p>A maker order is an order that removes liquidity from the order book while the taker order does the opposite. Deribit fees vary per product and are calculated as a percentage of the underlying asset of the contract.<\/p>\n\n\n\n<p>When it comes to contracts here is how the fee structure looks like:<\/p>\n\n\n\n<figure class=\"wp-block-image size-large\"><img decoding=\"async\" width=\"1024\" height=\"258\" src=\"https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2022\/07\/1-2-1024x258.jpg\" alt=\"\" class=\"wp-image-15868\" srcset=\"https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2022\/07\/1-2-1024x258.jpg 1024w, https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2022\/07\/1-2-300x76.jpg 300w, https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2022\/07\/1-2-768x194.jpg 768w, https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2022\/07\/1-2.jpg 1035w\" sizes=\"(max-width: 1024px) 100vw, 1024px\" \/><\/figure>\n\n\n\n<p>Have in mind that the Options fees can&#8217;t go over the 12.5% of the options price. Moreover, Futures and Options contracts have a delivery fee as shown in the picture below:<\/p>\n\n\n\n<figure class=\"wp-block-image size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"1008\" height=\"296\" src=\"https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2022\/07\/2-2.jpg\" alt=\"\" class=\"wp-image-15869\" srcset=\"https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2022\/07\/2-2.jpg 1008w, https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2022\/07\/2-2-300x88.jpg 300w, https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2022\/07\/2-2-768x226.jpg 768w\" sizes=\"(max-width: 1008px) 100vw, 1008px\" \/><\/figure>\n\n\n\n<p>When it comes to liquidation fees they are the following:<\/p>\n\n\n\n<figure class=\"wp-block-image size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"1019\" height=\"355\" src=\"https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2022\/07\/3-1.jpg\" alt=\"\" class=\"wp-image-15870\" srcset=\"https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2022\/07\/3-1.jpg 1019w, https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2022\/07\/3-1-300x105.jpg 300w, https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2022\/07\/3-1-768x268.jpg 768w\" sizes=\"(max-width: 1019px) 100vw, 1019px\" \/><\/figure>\n\n\n\n<p>Deribit doesn&#8217;t impose any deposit fees while the withdrawal fees for BTC may depend on the current state of the Bitcoin network.<\/p>\n\n\n\n<p>When it comes to funding your account you have <strong>only one option<\/strong> and that is <strong>Bitcoin <\/strong>\ud83d\ude42 . This means that Deribit doesn&#8217;t support any fiat currency deposit methods.<\/p>\n\n\n\n<a name=\"kyc\">\n\n\n\n<h2 class=\"wp-block-heading\">Does Deribit require KYC?<\/h2>\n\n\n\n<p>As of 9<sup>th<\/sup> November 2020, Deribit requires all new clients to obtain a verified status in order to get allowed to trade. This implies providing a proof of residence and an ID document.<\/p>\n\n\n\n<a name=\"deribit-pros\">\n\n\n\n<h2 class=\"wp-block-heading\">Why should I use Deribit?<\/h2>\n\n\n\n<ul><li>Deribit is easy to use<\/li><li>Has low fees<\/li><li>Offers leveraged trading (up to 100x leverage)<\/li><li>Has a good API<\/li><li>Has a test environment<\/li><li>Has an insurance fund protection<\/li><\/ul>\n\n\n\n<a name=\"deribit-cons\">\n\n\n\n<h2 class=\"wp-block-heading\">Why shouldn\u2019t I use the Deribit?<\/h2>\n\n\n\n<ul><li>Deribit may be a bit confusing for beginners<\/li><li>Deribit is not a regulated exchange<\/li><li>It doesn&#8217;t provide fiat deposits<\/li><\/ul>\n\n\n\n<a name=\"deribit-countries\">\n\n\n\n<h2 class=\"wp-block-heading\">Is Deribit available in my country?<\/h2>\n\n\n\n<p>As of 2021, access to Deribit is not available <\/p>\n\n\n\n<p>if you are located, incorporated, or otherwise established in, or a citizen or resident of any of the countries in the list below:<\/p>\n\n\n\n<ul><li>Cuba<\/li><li>Guam<\/li><li>Iran<\/li><li>Iraq<\/li><li>Japan<\/li><li>Democratic People&#8217;s Republic of Korea<\/li><li>Panama<\/li><li>Puerto Rico<\/li><li>Samoa<\/li><li>Sudan<\/li><li>Syrian Arab Republic<\/li><li>United States<\/li><li>Virgin Islands (U.S.)<\/li><\/ul>\n\n\n\n<a name=\"deribit-alternatives\">\n\n\n\n<h2 class=\"wp-block-heading\">What are the alternatives to using Deribit?<\/h2>\n\n\n\n<p>Deribit can be replaced with other applications that can be more suitable for you needs. Here is the list:<\/p>\n\n\n\n<ul><li><a href=\"https:\/\/algotrading101.com\/learn\/coinbase-api-guide\/\">Coinbase<\/a><\/li><li><a href=\"https:\/\/algotrading101.com\/learn\/binance-python-api-guide\/\">Binance<\/a><\/li><li><a href=\"https:\/\/algotrading101.com\/learn\/bitmex-api-introduction-guide\/\">BitMex<\/a><\/li><li>Gemini<\/li><li>KuCoin<\/li><li>ByBit<\/li><li>Phemex<\/li><li>Bittrex<\/li><li>Kraken<\/li><li>Bittrex<\/li><li>Bitfinex<\/li><li>Poloniex<\/li><li>UPHOLD and more.<\/li><\/ul>\n\n\n\n<a name=\"deribit-clients\">\n\n\n\n<h2 class=\"wp-block-heading\">What clients are available for the Deribit API?<\/h2>\n\n\n\n<p>Deribit features the following clients:<\/p>\n\n\n\n<ul><li>C<\/li><li>C#<\/li><li>Python<\/li><li>Go<\/li><li>Java<\/li><li>JavaScript<\/li><li>Swift<\/li><li>Ruby<\/li><li>R and more.<\/li><\/ul>\n\n\n\n<p>Be sure to visit the following GitHub to access these clients:<\/p>\n\n\n\n<p><a href=\"https:\/\/github.com\/deribit\/deribit-api-clients\">https:\/\/github.com\/deribit\/deribit-api-clients<\/a><\/p>\n\n\n\n<a name=\"getting-started\">\n\n\n\n<h2 class=\"wp-block-heading\">How to get started with Deribit?<\/h2>\n\n\n\n<p>In order to fully see what the Deribit API is capable of, we will first need to open up an account to obtain the API Key. As I will show you a few trading scenarios, the account we need is the test account that is found on this link:<\/p>\n\n\n\n<p><a href=\"https:\/\/test.deribit.com\/\">https:\/\/test.deribit.com\/<\/a><\/p>\n\n\n\n<p>The sign-up process for both the test and production Deribit account is pretty much the same. Here is a link to the production website:<\/p>\n\n\n\n<p><a href=\"https:\/\/www.deribit.com\/\">https:\/\/www.deribit.com\/<\/a><\/p>\n\n\n\n<figure class=\"wp-block-image size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"340\" src=\"https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2022\/07\/4-3-1024x340.jpg\" alt=\"\" class=\"wp-image-15871\" srcset=\"https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2022\/07\/4-3-1024x340.jpg 1024w, https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2022\/07\/4-3-300x100.jpg 300w, https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2022\/07\/4-3-768x255.jpg 768w, https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2022\/07\/4-3-1536x510.jpg 1536w, https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2022\/07\/4-3.jpg 1868w\" sizes=\"(max-width: 1024px) 100vw, 1024px\" \/><\/figure>\n\n\n\n<p>When there, you will see an account creation box right in front of you. Be sure to click the green &#8220;Create Account&#8221; button and fill in your email address, nickname, create a password, and select your country.<\/p>\n\n\n\n<p>After that, you will receive a verification email from Deribit. Be sure to go over and confirm it. When done, you will be taken to the following screen:<\/p>\n\n\n\n<figure class=\"wp-block-image alignwide size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"496\" src=\"https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2022\/07\/5-2-1024x496.jpg\" alt=\"\" class=\"wp-image-15872\" srcset=\"https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2022\/07\/5-2-1024x496.jpg 1024w, https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2022\/07\/5-2-300x145.jpg 300w, https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2022\/07\/5-2-768x372.jpg 768w, https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2022\/07\/5-2-1536x744.jpg 1536w, https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2022\/07\/5-2.jpg 1902w\" sizes=\"(max-width: 1024px) 100vw, 1024px\" \/><\/figure>\n\n\n\n<p>Now, all we need is the API key. For this go to your profile icon that is found in the upper right corner and click on settings. After that, navigate to the API section and click the &#8220;Add a new key&#8221; button.<\/p>\n\n\n\n<figure class=\"wp-block-image alignwide size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"289\" src=\"https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2022\/07\/6-2-1024x289.jpg\" alt=\"\" class=\"wp-image-15873\" srcset=\"https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2022\/07\/6-2-1024x289.jpg 1024w, https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2022\/07\/6-2-300x85.jpg 300w, https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2022\/07\/6-2-768x217.jpg 768w, https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2022\/07\/6-2-1536x434.jpg 1536w, https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2022\/07\/6-2.jpg 1698w\" sizes=\"(max-width: 1024px) 100vw, 1024px\" \/><\/figure>\n\n\n\n<p>A pop-up screen will appear that will prompt you to assign the main functions of your new API key. The options range from account to custody permissions. For this article, I&#8217;ll give all of them a read + write permission.<\/p>\n\n\n\n<figure class=\"wp-block-image size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"594\" height=\"557\" src=\"https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2022\/07\/7-1.jpg\" alt=\"\" class=\"wp-image-15875\" srcset=\"https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2022\/07\/7-1.jpg 594w, https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2022\/07\/7-1-300x281.jpg 300w\" sizes=\"(max-width: 594px) 100vw, 594px\" \/><\/figure>\n\n\n\n<p>After you approve, the API key will be created and you will clearly see your Client ID and Client Secret. You will also have several action possibilities like the QR Code, Reset Secret, Remove Key, and more.<\/p>\n\n\n\n<figure class=\"wp-block-image alignwide size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"122\" src=\"https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2022\/07\/8-2-1024x122.jpg\" alt=\"\" class=\"wp-image-15876\" srcset=\"https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2022\/07\/8-2-1024x122.jpg 1024w, https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2022\/07\/8-2-300x36.jpg 300w, https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2022\/07\/8-2-768x92.jpg 768w, https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2022\/07\/8-2-1536x183.jpg 1536w, https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2022\/07\/8-2.jpg 1693w\" sizes=\"(max-width: 1024px) 100vw, 1024px\" \/><\/figure>\n\n\n\n<p>As all that we need is set, the following headers will explore the API starting with the main public endpoints and finishing with private API order within two trading scenarios.<\/p>\n\n\n\n<a name=\"currency\">\n\n\n\n<h2 class=\"wp-block-heading\">How to get currency info with Deribit?<\/h2>\n\n\n\n<p>In order to obtain all the currencies that Deribit has to offer you can use the get_currencies endpoint. We will import the required libraries and call their API in the following way:<\/p>\n\n\n\n<div class=\"hcb_wrap\"><pre class=\"prism line-numbers lang-python\" data-lang=\"Python\"><code>import asyncio\nimport websockets\nimport json\nimport pandas as pd\nimport pprint\nimport nest_asyncio\nnest_asyncio.apply()\n\nmsg = \\\n{\n  &quot;jsonrpc&quot; : &quot;2.0&quot;,\n  &quot;id&quot; : 7538,\n  &quot;method&quot; : &quot;public\/get_currencies&quot;,\n  &quot;params&quot; : {\n\n  }\n}\n\nasync def call_api(msg):\n    async with websockets.connect(&#39;wss:\/\/test.deribit.com\/ws\/api\/v2&#39;) as websocket:\n        await websocket.send(msg)\n        while websocket.open:\n            response = await websocket.recv()\n            json_par = json.loads(response)\n            print(json_par)\n            return(json_par)\n            \nresponse = asyncio.get_event_loop().run_until_complete(call_api(json.dumps(msg)))<\/code><\/pre><\/div>\n\n\n\n<figure class=\"wp-block-image size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"133\" src=\"https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2021\/03\/9-3-1024x133.png\" alt=\"\" class=\"wp-image-8387\" srcset=\"https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2021\/03\/9-3-1024x133.png 1024w, https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2021\/03\/9-3-300x39.png 300w, https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2021\/03\/9-3-768x99.png 768w, https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2021\/03\/9-3.png 1197w\" sizes=\"(max-width: 1024px) 100vw, 1024px\" \/><\/figure>\n\n\n\n<p>As the response doesn&#8217;t look too nice we will pretty print it by using the pprint library.<\/p>\n\n\n\n<div class=\"hcb_wrap\"><pre class=\"prism line-numbers lang-python\" data-lang=\"Python\"><code>pprint.pprint(response)<\/code><\/pre><\/div>\n\n\n\n<figure class=\"wp-block-image size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"924\" height=\"591\" src=\"https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2022\/07\/10-2.jpg\" alt=\"\" class=\"wp-image-15877\" srcset=\"https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2022\/07\/10-2.jpg 924w, https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2022\/07\/10-2-300x192.jpg 300w, https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2022\/07\/10-2-768x491.jpg 768w\" sizes=\"(max-width: 924px) 100vw, 924px\" \/><\/figure>\n\n\n\n<p>Much better, let&#8217;s add the pprint as our main printing way in the function and call the next endpoint that will obtain the price data.<\/p>\n\n\n\n<a name=\"price\">\n\n\n\n<h2 class=\"wp-block-heading\">How to get Price Data on Deribit?<\/h2>\n\n\n\n<p>There are several Deribit endpoints that include the price data but the most &#8220;precise&#8221; one would be the public ticker endpoint. Let&#8217;s update the function for a prettier print.<\/p>\n\n\n\n<div class=\"hcb_wrap\"><pre class=\"prism line-numbers lang-python\" data-lang=\"Python\"><code>msg = {\n  &quot;jsonrpc&quot; : &quot;2.0&quot;,\n  &quot;id&quot; : 8106,\n  &quot;method&quot; : &quot;public\/ticker&quot;,\n  &quot;params&quot; : {\n    &quot;instrument_name&quot; : &quot;BTC-PERPETUAL&quot;\n  }\n}\n\nasync def call_api(msg):\n    async with websockets.connect(&#39;wss:\/\/test.deribit.com\/ws\/api\/v2&#39;) as websocket:\n        await websocket.send(msg)\n        while websocket.open:\n            response = await websocket.recv()\n            json_par = json.loads(response)\n            pprint.pprint(json_par)\n            return(json_par)\n            \nresponse = asyncio.get_event_loop().run_until_complete(call_api(json.dumps(msg)))<\/code><\/pre><\/div>\n\n\n\n<figure class=\"wp-block-image size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"612\" height=\"706\" src=\"https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2022\/07\/12-1.jpg\" alt=\"\" class=\"wp-image-15878\" srcset=\"https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2022\/07\/12-1.jpg 612w, https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2022\/07\/12-1-260x300.jpg 260w\" sizes=\"(max-width: 612px) 100vw, 612px\" \/><\/figure>\n\n\n\n<p>If you want to obtain the index price, you an use the &#8220;get_index_price&#8221; endpoint.<\/p>\n\n\n\n<div class=\"hcb_wrap\"><pre class=\"prism line-numbers lang-python\" data-lang=\"Python\"><code>msg = {&quot;jsonrpc&quot;: &quot;2.0&quot;,\n     &quot;method&quot;: &quot;public\/get_index_price&quot;,\n     &quot;id&quot;: 42,\n     &quot;params&quot;: {\n     &quot;index_name&quot;: &quot;btc_usd&quot;}\n    }\n\nresponse = asyncio.get_event_loop().run_until_complete(call_api(json.dumps(msg)))<\/code><\/pre><\/div>\n\n\n\n<pre class=\"wp-block-code\"><code>{'id': 42,\n 'jsonrpc': '2.0',\n 'result': {'estimated_delivery_price': 57848.15, 'index price': 57848.15},\n 'testnet': True,\n 'usDiff': 177,\n 'usIn': 1616071078267979,\n 'usOut': 16160710782681561}\n<\/code><\/pre>\n\n\n\n<a name=\"historical\">\n\n\n\n<h2 class=\"wp-block-heading\">How to get historical data with Deribit?<\/h2>\n\n\n\n<p>Deribit offers a few Historical data endpoints like the funding rate history and historical volatility. Let us go ahead and obtain the two starting with the latter one:<\/p>\n\n\n\n<div class=\"hcb_wrap\"><pre class=\"prism line-numbers lang-python\" data-lang=\"Python\"><code>msg = {\n  &quot;jsonrpc&quot; : &quot;2.0&quot;,\n  &quot;id&quot; : 8387,\n  &quot;method&quot; : &quot;public\/get_historical_volatility&quot;,\n  &quot;params&quot; : {\n    &quot;currency&quot; : &quot;BTC&quot;\n  }\n}\n\nresponse = asyncio.get_event_loop().run_until_complete(call_api(json.dumps(msg)))<\/code><\/pre><\/div>\n\n\n\n<figure class=\"wp-block-image size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"580\" height=\"480\" src=\"https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2022\/07\/13-1.jpg\" alt=\"\" class=\"wp-image-15880\" srcset=\"https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2022\/07\/13-1.jpg 580w, https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2022\/07\/13-1-300x248.jpg 300w\" sizes=\"(max-width: 580px) 100vw, 580px\" \/><\/figure>\n\n\n\n<p>The next thin we want to do is to put the response into a pandas data frame so it can be used for later on.<\/p>\n\n\n\n<div class=\"hcb_wrap\"><pre class=\"prism line-numbers lang-python\" data-lang=\"Python\"><code>volatility = pd.DataFrame(response[&#39;result&#39;])\nvolatility.head()<\/code><\/pre><\/div>\n\n\n\n<figure class=\"wp-block-image size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"316\" height=\"246\" src=\"https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2022\/07\/14-1.jpg\" alt=\"\" class=\"wp-image-15881\" srcset=\"https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2022\/07\/14-1.jpg 316w, https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2022\/07\/14-1-300x234.jpg 300w\" sizes=\"(max-width: 316px) 100vw, 316px\" \/><\/figure>\n\n\n\n<p>In order to get some basic stats about the dataframe you can use the pd.describe function:<\/p>\n\n\n\n<div class=\"hcb_wrap\"><pre class=\"prism line-numbers lang-python\" data-lang=\"Python\"><code>pd.set_option(&#39;precision&#39;, 3)\nvolatility.describe()<\/code><\/pre><\/div>\n\n\n\n<figure class=\"wp-block-image size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"278\" height=\"356\" src=\"https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2022\/07\/15.jpg\" alt=\"\" class=\"wp-image-15882\" srcset=\"https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2022\/07\/15.jpg 278w, https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2022\/07\/15-234x300.jpg 234w\" sizes=\"(max-width: 278px) 100vw, 278px\" \/><\/figure>\n\n\n\n<p>And now for the funding rate history:<\/p>\n\n\n\n<div class=\"hcb_wrap\"><pre class=\"prism line-numbers lang-python\" data-lang=\"Python\"><code>msg = {\n  &quot;jsonrpc&quot; : &quot;2.0&quot;,\n  &quot;id&quot; : 7617,\n  &quot;method&quot; : &quot;public\/get_funding_rate_history&quot;,\n  &quot;params&quot; : {\n    &quot;instrument_name&quot; : &quot;BTC-PERPETUAL&quot;,\n    &quot;start_timestamp&quot; : 1569888000000,\n    &quot;end_timestamp&quot; : 1569902400000\n  }\n}\n\nresponse = asyncio.get_event_loop().run_until_complete(call_api(json.dumps(msg)))<\/code><\/pre><\/div>\n\n\n\n<figure class=\"wp-block-image size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"620\" height=\"655\" src=\"https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2022\/07\/16.jpg\" alt=\"\" class=\"wp-image-15883\" srcset=\"https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2022\/07\/16.jpg 620w, https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2022\/07\/16-284x300.jpg 284w\" sizes=\"(max-width: 620px) 100vw, 620px\" \/><\/figure>\n\n\n\n<a name=\"order-book\">\n\n\n\n<h2 class=\"wp-block-heading\">How to get Order Book data with Deribit?<\/h2>\n\n\n\n<p>Order book data can be obtained by utilizing the public get_order_book endpoint. The max level depth of the order book is not specified by the exchange. We&#8217;ll use level 25 for our request:<\/p>\n\n\n\n<div class=\"hcb_wrap\"><pre class=\"prism line-numbers lang-python\" data-lang=\"Python\"><code>msg = {\n  &quot;jsonrpc&quot; : &quot;2.0&quot;,\n  &quot;id&quot; : 8772,\n  &quot;method&quot; : &quot;public\/get_order_book&quot;,\n  &quot;params&quot; : {\n    &quot;instrument_name&quot; : &quot;BTC-PERPETUAL&quot;,\n    &quot;depth&quot; : 25\n  }\n}\n\nresponse = asyncio.get_event_loop().run_until_complete(call_api(json.dumps(msg)))<\/code><\/pre><\/div>\n\n\n\n<p>We should clean up the response now by extracting the important bits out of it. For this, I will create separate data frames for both bids and asks and then merge the two together.<\/p>\n\n\n\n<div class=\"hcb_wrap\"><pre class=\"prism line-numbers lang-python\" data-lang=\"Python\"><code>bids = pd.DataFrame(response[&#39;result&#39;][&#39;bids&#39;])\nasks = pd.DataFrame(response[&#39;result&#39;][&#39;asks&#39;])\n\nbook = pd.merge(bids, asks, left_index=True, right_index=True)\nbook.head()<\/code><\/pre><\/div>\n\n\n\n<figure class=\"wp-block-image size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"386\" height=\"243\" src=\"https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2022\/07\/17.jpg\" alt=\"\" class=\"wp-image-15884\" srcset=\"https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2022\/07\/17.jpg 386w, https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2022\/07\/17-300x189.jpg 300w\" sizes=\"(max-width: 386px) 100vw, 386px\" \/><\/figure>\n\n\n\n<p>If you want to rename the columns you can pass this:<\/p>\n\n\n\n<div class=\"hcb_wrap\"><pre class=\"prism line-numbers lang-python\" data-lang=\"Python\"><code>book = df.rename({&quot;0_x&quot;:&quot;Bid Price&quot;,&quot;1_x&quot;:&quot;Bid Amount&quot;,\n                &quot;0_y&quot;:&quot;Ask Price&quot;,&quot;1_y&quot;:&quot;Ask Amount&quot;}, axis=&#39;columns&#39;)<\/code><\/pre><\/div>\n\n\n\n<a name=\"transactions\">\n\n\n\n<h2 class=\"wp-block-heading\">How to get Transactions with Deribit?<\/h2>\n\n\n\n<p>Transactions aka trades can be obtained from Deribit by using the get trades by currency or by instrument endpoints. For settlements, all you need to do is to change the &#8220;trades&#8221; to &#8220;settlements&#8221; in the request message.<\/p>\n\n\n\n<p>Let&#8217;s obtain the trades and settlements by currency starting with the former:<\/p>\n\n\n\n<div class=\"hcb_wrap\"><pre class=\"prism line-numbers lang-python\" data-lang=\"Python\"><code>msg = {\n  &quot;jsonrpc&quot; : &quot;2.0&quot;,\n  &quot;id&quot; : 9290,\n  &quot;method&quot; : &quot;public\/get_last_trades_by_currency&quot;,\n  &quot;params&quot; : {\n    &quot;currency&quot; : &quot;BTC&quot;,\n    &quot;count&quot; : 2\n  }\n}\n\nresponse = asyncio.get_event_loop().run_until_complete(call_api(json.dumps(msg)))<\/code><\/pre><\/div>\n\n\n\n<figure class=\"wp-block-image size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"712\" height=\"686\" src=\"https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2022\/07\/19.jpg\" alt=\"\" class=\"wp-image-15885\" srcset=\"https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2022\/07\/19.jpg 712w, https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2022\/07\/19-300x289.jpg 300w\" sizes=\"(max-width: 712px) 100vw, 712px\" \/><\/figure>\n\n\n\n<p>And now for the settlements:<\/p>\n\n\n\n<div class=\"hcb_wrap\"><pre class=\"prism line-numbers lang-python\" data-lang=\"Python\"><code>msg = {\n  &quot;jsonrpc&quot; : &quot;2.0&quot;,\n  &quot;id&quot; : 4497,\n  &quot;method&quot; : &quot;public\/get_last_settlements_by_currency&quot;,\n  &quot;params&quot; : {\n    &quot;currency&quot; : &quot;BTC&quot;,\n    &quot;type&quot; : &quot;delivery&quot;,\n    &quot;count&quot; : 2\n  }\n}\n\nresponse = asyncio.get_event_loop().run_until_complete(call_api(json.dumps(msg)))<\/code><\/pre><\/div>\n\n\n\n<figure class=\"wp-block-image size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"1198\" height=\"606\" src=\"https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2021\/03\/18-1024x518.png\" alt=\"\" class=\"wp-image-8399\" srcset=\"https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2021\/03\/18-1024x518.png 1024w, https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2021\/03\/18-300x152.png 300w, https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2021\/03\/18-768x388.png 768w, https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2021\/03\/18.png 1198w\" sizes=\"(max-width: 1198px) 100vw, 1198px\" \/><\/figure>\n\n\n\n<a name=\"order\">\n\n\n\n<h2 class=\"wp-block-heading\">How to order with Deribit?<\/h2>\n\n\n\n<p>Deribit offers several order types that can be launched through their endpoints. But before we go over each of them and code up two trading scenarios, we should see what parameters make the order.<\/p>\n\n\n\n<p>The basic order parameters are the following:<\/p>\n\n\n\n<ul><li><code>instrument_name<\/code> &#8211; the name of your asset (required)<\/li><li><code>amount <\/code>&#8211; requested order size (required)<\/li><li><code>type <\/code>&#8211; default is &#8220;limit&#8221; but it can be stop_limit, market, stop_market<\/li><li><code>label <\/code>&#8211; user-defined label for the order <\/li><li><code>price <\/code>&#8211; the order price in the base currency that works only for limit and stop_limit orders.<\/li><li><code>time_in_force <\/code>&#8211; specifies how long the order lasts. It can be &#8220;good_til_cancelled&#8221;, &#8220;fill_or_kill&#8221;, &#8220;immediate_or_cancel&#8221;.<\/li><li><code>max_show <\/code>&#8211; maximum amount within an order that is shown to other customers (e.g. 0 makes the order invisible)<\/li><li><code>post_only <\/code>&#8211; &#8220;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 spread. Only valid in combination with time_in_force = <code>good_til_cancelled<\/code>&#8220;<\/li><li><code>reject_post_only <\/code>&#8211;  &#8220;If an order is considered post-only and this field is set to true then the order is put to order book unmodified or request is rejected and order is canceled.&#8221;<\/li><li><code>reduce_only <\/code>&#8211; if true, it reduces the current position<\/li><li><code>stop_price <\/code>&#8211; Stop price for stop limit orders<\/li><li><code>trigger <\/code>&#8211; it defines the trigger type for stop_limit and stop_market orders.<\/li><li><code>advanced <\/code>&#8211; advanced option order type (only for options)<\/li><li><code>mmp <\/code>&#8211; order MMP Flag<\/li><\/ul>\n\n\n\n<p>Now that we have the main order building blocks in mind, let&#8217;s explore some peculiar ones and how to launch them.<\/p>\n\n\n\n<a name=\"perpetual-order\">\n\n\n\n<h2 class=\"wp-block-heading\">How to fire an order on a Perpetual contract with Deribit?<\/h2>\n\n\n\n<p>All orders in Deribit share a similar structure as shown in the last header. This means that in order to fire an order on a perpetual contract we just need to specify the right instrument name (e.g. BTC-PERPETUAL).<\/p>\n\n\n\n<p>Here is an example of how the order message should look like:<\/p>\n\n\n\n<div class=\"hcb_wrap\"><pre class=\"prism line-numbers lang-python\" data-lang=\"Python\"><code>msg = {\n  &quot;jsonrpc&quot; : &quot;2.0&quot;,\n  &quot;id&quot; : 4122,\n  &quot;method&quot; : &quot;private\/cancel_all_by_instrument&quot;,\n  &quot;params&quot; : {\n    &quot;instrument_name&quot; : &quot;BTC-PERPETUAL&quot;,\n    &quot;type&quot; : &quot;all&quot;\n  }\n}<\/code><\/pre><\/div>\n\n\n\n<p>If you skipped to this part this is the function that we use to send a request:<\/p>\n\n\n\n<div class=\"hcb_wrap\"><pre class=\"prism line-numbers lang-python\" data-lang=\"Python\"><code>async def call_api(msg):\n    async with websockets.connect(&#39;wss:\/\/test.deribit.com\/ws\/api\/v2&#39;) as websocket:\n        ###############\n       # Before sending a message, make sure that your connection\n       # is authenticated (use public\/auth call before) \n       ###############\n        await websocket.send(msg)\n        while websocket.open:\n            response = await websocket.recv()\n            json_par = json.loads(response)\n            print(json_par)\n            return(json_par)<\/code><\/pre><\/div>\n\n\n\n<p>The Deribit perpetual contract features a&nbsp;continuous measurement of the difference between the mark price of the contract and the Deribit BTC Index. <\/p>\n\n\n\n<p>The percentage difference between these two price levels is the basis for the 8-hourly funding rate&nbsp;that is applied to all outstanding perpetual contracts. For more information visit the following link:<\/p>\n\n\n\n<p><a href=\"https:\/\/www.deribit.com\/pages\/docs\/perpetual\">https:\/\/www.deribit.com\/pages\/docs\/perpetual<\/a><\/p>\n\n\n\n<a name=\"futures-order\">\n\n\n\n<h2 class=\"wp-block-heading\">How to fire an order on a Futures contract with Deribit?<\/h2>\n\n\n\n<p>All orders in Deribit share a similar structure. This means that in order to fire an order on a futures contract we just need to specify the right instrument name (e.g. BTC-24SEP21).<\/p>\n\n\n\n<p>Here is an example of how the order message should look like:<\/p>\n\n\n\n<div class=\"hcb_wrap\"><pre class=\"prism line-numbers lang-python\" data-lang=\"Python\"><code>msg = {\n  &quot;jsonrpc&quot; : &quot;2.0&quot;,\n  &quot;id&quot; : 4122,\n  &quot;method&quot; : &quot;private\/cancel_all_by_instrument&quot;,\n  &quot;params&quot; : {\n    &quot;instrument_name&quot; : &quot;BTC-24SEP21&quot;,\n    &quot;type&quot; : &quot;all&quot;\n  }\n}<\/code><\/pre><\/div>\n\n\n\n<p>Bitcoin Futures on Deribit are cash settled rather than settled by &#8220;physical&#8221; delivery of BTC. This means that at the settlement, the buyer of BTC Futures will not buy the actual BTC, neither will the seller sell BTC. <\/p>\n\n\n\n<p>There will only be a transfer of losses\/gains at the settlement of the contract, based on the expiration price (calculated as the last 30 minute average of the BTC price index). For more information visit the following link:<\/p>\n\n\n\n<p><a href=\"https:\/\/www.deribit.com\/pages\/docs\/futures\">https:\/\/www.deribit.com\/pages\/docs\/futures<\/a><\/p>\n\n\n\n<a name=\"option-order\">\n\n\n\n<h2 class=\"wp-block-heading\">How to fire an order on an Option contract with Deribit?<\/h2>\n\n\n\n<p>All orders in Deribit share a similar structure. This means that in order to fire an order on a futures contract we just need to specify the right instrument name (e.g. ETH-19MAR21).<\/p>\n\n\n\n<p>Here is an example of how the order message should look like:<\/p>\n\n\n\n<div class=\"hcb_wrap\"><pre class=\"prism line-numbers lang-python\" data-lang=\"Python\"><code>msg = {\n  &quot;jsonrpc&quot; : &quot;2.0&quot;,\n  &quot;id&quot; : 4122,\n  &quot;method&quot; : &quot;private\/cancel_all_by_instrument&quot;,\n  &quot;params&quot; : {\n    &quot;instrument_name&quot; : &quot;ETH-19MAR21&quot;,\n    &quot;type&quot; : &quot;all&quot;\n  }\n}<\/code><\/pre><\/div>\n\n\n\n<p>Deribit follows the European style cash-settled options which means that the options are exercised only at expiry and cannot be exercised before. On Deribit, this will happen automatically. <\/p>\n\n\n\n<p>For more information visit the following link:<\/p>\n\n\n\n<p><a href=\"https:\/\/www.deribit.com\/pages\/docs\/options\">https:\/\/www.deribit.com\/pages\/docs\/options<\/a><\/p>\n\n\n\n<a name=\"order-example1\">\n\n\n\n<h2 class=\"wp-block-heading\">How to execute a trade on ETH when BTC hits a certain price with the Deribit API?<\/h2>\n\n\n\n<p>In this example, I will show you how to properly and securely launch an order with specified requirements. The thing that we want to do is to launch a trade on ETH when BTC hits a certain price.<\/p>\n\n\n\n<p>In order to make this work, we will need to set our order foundation and then create a loop that will check if the price level is hit. If the price is hit, we will execute a market order. On the contrary, we will continue looping.<\/p>\n\n\n\n<p>When the price is executed we will wait for a few seconds and then check if the order was filled. This additional step is very important to have in your trading strategies as the exchange server may encounter some troubles. <\/p>\n\n\n\n<p>Let us go ahead and import the relevant libraries and set up the main trading loop.<\/p>\n\n\n\n<div class=\"hcb_wrap\"><pre class=\"prism line-numbers lang-python\" data-lang=\"Python\"><code>#Order Foundation\nimport asyncio\nimport websockets\nimport json\nimport pandas as pd\nfrom time import sleep\nimport pprint\nimport hmac\nimport hashlib\nfrom datetime import datetime\nimport nest_asyncio\nnest_asyncio.apply()\n\nasync def call_api(msg):\n    async with websockets.connect(&#39;wss:\/\/test.deribit.com\/ws\/api\/v2&#39;) as websocket:\n        await websocket.send(msg)\n        while websocket.open:\n            response = await websocket.recv()\n            json_par = json.loads(response)\n            #print(json_par)\n            return(json_par)\n        \nclientId = &quot;TzxHdA_N&quot;\nclientSecret = &quot;3LsbOcO7Fqzv_oT9-RDy1JwvYG7uR3NnF5HXDnvn6AA&quot;\ntimestamp = round(datetime.now().timestamp() * 1000)\nnonce = &quot;123&quot;\ndata = &quot;&quot;\n\nsignature = hmac.new(\n    bytes(clientSecret, &quot;latin-1&quot;),\n    msg=bytes(&#39;{}\\n{}\\n{}&#39;.format(timestamp, nonce, data), &quot;latin-1&quot;),\n    digestmod=hashlib.sha256).hexdigest().lower()        \n        \nauth_msg = {\n  &quot;jsonrpc&quot; : &quot;2.0&quot;,\n  &quot;id&quot; : 42,\n  &quot;method&quot; : &quot;public\/auth&quot;,\n  &quot;params&quot; : {\n    &quot;grant_type&quot; : &quot;client_signature&quot;,\n    &quot;client_id&quot; : clientId,\n    &quot;timestamp&quot; : timestamp,\n    &quot;signature&quot; : signature,\n    &quot;nonce&quot; : nonce,\n    &quot;data&quot; : data\n  }\n}\n\nprice_msg = {\n  &quot;jsonrpc&quot; : &quot;2.0&quot;,\n  &quot;id&quot; : 42,\n  &quot;method&quot; : &quot;public\/ticker&quot;,\n  &quot;params&quot; : {\n    &quot;instrument_name&quot; : &quot;BTC-PERPETUAL&quot;\n  }\n}\n\n\norder_msg = {\n  &quot;jsonrpc&quot; : &quot;2.0&quot;,\n  &quot;id&quot; : 42,\n  &quot;method&quot; : &quot;private\/buy&quot;,\n  &quot;params&quot; : {\n    &quot;instrument_name&quot; : &quot;ETH-PERPETUAL&quot;,\n    &quot;amount&quot; : 5,\n    &quot;type&quot; : &quot;market&quot;,\n    &quot;label&quot; : &quot;algoorder&quot;\n  }\n}\n\ncheck_order = {\n  &quot;jsonrpc&quot; : &quot;2.0&quot;,\n  &quot;id&quot; : 42,\n  &quot;method&quot; : &quot;private\/get_order_state&quot;,\n  &quot;params&quot; : {\n    &quot;order_id&quot; : &quot;ETH-331562&quot;\n  }\n}\n\n#Main order loop\nwhile True:\n    try:\n        btc = asyncio.get_event_loop().run_until_complete(call_api(json.dumps(price_msg)))\n    except exception as e:\n        print(&quot;Unable to obtain BTC price&quot;)\n    \n    if btc[&#39;result&#39;][&#39;best_ask_price&#39;] &lt; 58800.0:\n        print(&quot;The price mark was not reached.&quot;)\n        sleep(60)\n        continue\n    \n    elif btc[&#39;result&#39;][&#39;best_ask_price&#39;] &gt;= 58800.0:\n        try:\n            auth = asyncio.get_event_loop().run_until_complete(call_api(json.dumps(auth_msg)))\n            pprint.pprint(auth)\n        except exception as e:\n            print(&#39;There was an authentication error&#39;)\n        \n        try:\n            order = asyncio.get_event_loop().run_until_complete(call_api(json.dumps(order_msg)))\n            #print(order)\n        except exception as e:\n            print(&quot;Error occurred while placing order&quot;)\n        \n        sleep(2)\n        \n        try:\n            order_check = asyncio.get_event_loop().run_until_complete(call_api(json.dumps(check_order)))\n            pprint.pprint(order_check)\n        except excpetion as e:\n            print(&quot;Error checking order&quot;)\n        \n        if order_check[&#39;result&#39;][&#39;order_state&#39;] == &#39;filled&#39; or order_check[&#39;result&#39;][&#39;order_state&#39;] == &quot;open&quot;:\n            print (&#39;Order placed at {}&#39;.format(pd.Timestamp.now()))\n            break\n            \n        else:\n            print(&#39;Order was canceled {}&#39;.format(pd.Timestamp.now()))\n            break<\/code><\/pre><\/div>\n\n\n\n<a name=\"order-example2\">\n\n\n\n<h2 class=\"wp-block-heading\">How to execute an ETH trade when BTC moves 5% in the last 5 minutes with the Deribit API?<\/h2>\n\n\n\n<p>What if we want to calculate the percentage move between two currencies and then launch an order? Well, this example will take care of that!<\/p>\n\n\n\n<p>The main task will be to execute an ETH  trade when BTC moves 5% in the last 5 minutes. This means that we will want to create a loop that will obtain the prices of the two cryptos and calculate the percentage change between the two.<\/p>\n\n\n\n<p>If the percentage change is less than 5%, the algorithm will be sleeping for 5 minutes and calculating the percentage change again. If the percentage change is equal to or more than 5% the trade will execute.<\/p>\n\n\n\n<p>After the trade execution, we will sleep for a few seconds and then check on the trade if it was filled or not. Now that the logic is set, it is time to code it out:<\/p>\n\n\n\n<div class=\"hcb_wrap\"><pre class=\"prism line-numbers lang-python\" data-lang=\"Python\"><code>clientId = &quot;ID_HERE&quot;\nclientSecret = &quot;SECRET_HERE&quot;\ntimestamp = round(datetime.now().timestamp() * 1000)\nnonce = &quot;123&quot;\ndata = &quot;&quot;\n\nsignature = hmac.new(\n    bytes(clientSecret, &quot;latin-1&quot;),\n    msg=bytes(&#39;{}\\n{}\\n{}&#39;.format(timestamp, nonce, data), &quot;latin-1&quot;),\n    digestmod=hashlib.sha256).hexdigest().lower()        \n        \nauth_msg = {\n  &quot;jsonrpc&quot; : &quot;2.0&quot;,\n  &quot;id&quot; : 42,\n  &quot;method&quot; : &quot;public\/auth&quot;,\n  &quot;params&quot; : {\n    &quot;grant_type&quot; : &quot;client_signature&quot;,\n    &quot;client_id&quot; : clientId,\n    &quot;timestamp&quot; : timestamp,\n    &quot;signature&quot; : signature,\n    &quot;nonce&quot; : nonce,\n    &quot;data&quot; : data\n  }\n}\n\nbtc_price_msg = {\n  &quot;jsonrpc&quot; : &quot;2.0&quot;,\n  &quot;id&quot; : 42,\n  &quot;method&quot; : &quot;public\/ticker&quot;,\n  &quot;params&quot; : {\n    &quot;instrument_name&quot; : &quot;BTC-PERPETUAL&quot;\n  }\n}\n\norder_msg = {\n  &quot;jsonrpc&quot; : &quot;2.0&quot;,\n  &quot;id&quot; : 42,\n  &quot;method&quot; : &quot;private\/buy&quot;,\n  &quot;params&quot; : {\n    &quot;instrument_name&quot; : &quot;ETH-PERPETUAL&quot;,\n    &quot;amount&quot; : 5,\n    &quot;type&quot; : &quot;market&quot;,\n    &quot;label&quot; : &quot;algoorder&quot;\n  }\n}\n\ncheck_order = {\n  &quot;jsonrpc&quot; : &quot;2.0&quot;,\n  &quot;id&quot; : 42,\n  &quot;method&quot; : &quot;private\/get_order_state&quot;,\n  &quot;params&quot; : {\n    &quot;order_id&quot; : &quot;ETH-331562&quot;\n  }\n}\n\nwhile True:\n    try:\n        btc_old = asyncio.get_event_loop().run_until_complete(call_api(json.dumps(btc_price_msg)))\n    except exception as e:\n        print(&quot;Unable to obtain BTC price&quot;)\n    \n    sleep(300)\n    \n    try:\n        btc_new = asyncio.get_event_loop().run_until_complete(call_api(json.dumps(btc_price_msg)))\n    except exception as e:\n        print(&quot;Unable to obtain BTC price&quot;)\n    \n    percent = (btc_new[&#39;result&#39;][&#39;best_ask_price&#39;] - btc_old[&#39;result&#39;][&#39;best_ask_price&#39;] * 100) \/ btc_old[&#39;result&#39;][&#39;best_ask_price&#39;]\n    \n    if percent &lt; 5:\n        print(&quot;The requirement was not fulfilled.&quot;)\n        sleep(0.1)\n        continue\n    \n    elif percent &gt;= 5:\n        try:\n            auth = asyncio.get_event_loop().run_until_complete(call_api(json.dumps(auth_msg)))\n            pprint.pprint(auth)\n        except exception as e:\n            print(&#39;There was an authentication error&#39;)\n        \n        try:\n            order = asyncio.get_event_loop().run_until_complete(call_api(json.dumps(order_msg)))\n            #print(order)\n        except exception as e:\n            print(&quot;Error occurred while placing order&quot;)\n        \n        sleep(2)\n        \n        try:\n            order_check = asyncio.get_event_loop().run_until_complete(call_api(json.dumps(check_order)))\n            pprint.pprint(order_check)\n        except excpetion as e:\n            print(&quot;Error checking order&quot;)\n        \n        if order_check[&#39;result&#39;][&#39;order_state&#39;] == &#39;filled&#39; or order_check[&#39;result&#39;][&#39;order_state&#39;] == &quot;open&quot;:\n            print (&#39;Order placed at {}&#39;.format(pd.Timestamp.now()))\n            break\n            \n        else:\n            print(&#39;Order was canceled {}&#39;.format(pd.Timestamp.now()))\n            break<\/code><\/pre><\/div>\n\n\n\n<a name=\"cancel-orders\">\n\n\n\n<h2 class=\"wp-block-heading\">How to cancel orders with Deribit?<\/h2>\n\n\n\n<p>If you want to cancel and order with Deribit you can pass something like the following request:<\/p>\n\n\n\n<div class=\"hcb_wrap\"><pre class=\"prism line-numbers lang-python\" data-lang=\"Python\"><code>msg = \\\n{\n  &quot;jsonrpc&quot; : &quot;2.0&quot;,\n  &quot;id&quot; : 4214,\n  &quot;method&quot; : &quot;private\/cancel&quot;,\n  &quot;params&quot; : {\n    &quot;order_id&quot; : &quot;ETH-SLIS-12&quot;\n  }\n}\n\nasync def call_api(msg):\n   async with websockets.connect(&#39;wss:\/\/test.deribit.com\/ws\/api\/v2&#39;) as websocket:\n       ###############\n       # Before sending the message, make sure that your connection\n       # is authenticated (use public\/auth call before) \n       ###############\n       await websocket.send(msg)\n       while websocket.open:\n           response = await websocket.recv()\n           # do something with the response...\n           print(response)\n\nasyncio.get_event_loop().run_until_complete(call_api(json.dumps(msg)))<\/code><\/pre><\/div>\n\n\n\n<a name=\"full-code\">\n\n\n\n<h2 class=\"wp-block-heading\">Full code<\/h2>\n\n\n\n<p><a href=\"https:\/\/github.com\/IgorWounds\/Deribit-API-Algotrading101\">GitHub Link<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<div class=\"pvc_clear\"><\/div>\n<p id=\"pvc_stats_13770\" class=\"pvc_stats total_only  \" data-element-id=\"13770\" style=\"\"><i class=\"pvc-stats-icon medium\" aria-hidden=\"true\"><svg aria-hidden=\"true\" focusable=\"false\" data-prefix=\"far\" data-icon=\"chart-bar\" role=\"img\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" viewBox=\"0 0 512 512\" class=\"svg-inline--fa fa-chart-bar fa-w-16 fa-2x\"><path fill=\"currentColor\" d=\"M396.8 352h22.4c6.4 0 12.8-6.4 12.8-12.8V108.8c0-6.4-6.4-12.8-12.8-12.8h-22.4c-6.4 0-12.8 6.4-12.8 12.8v230.4c0 6.4 6.4 12.8 12.8 12.8zm-192 0h22.4c6.4 0 12.8-6.4 12.8-12.8V140.8c0-6.4-6.4-12.8-12.8-12.8h-22.4c-6.4 0-12.8 6.4-12.8 12.8v198.4c0 6.4 6.4 12.8 12.8 12.8zm96 0h22.4c6.4 0 12.8-6.4 12.8-12.8V204.8c0-6.4-6.4-12.8-12.8-12.8h-22.4c-6.4 0-12.8 6.4-12.8 12.8v134.4c0 6.4 6.4 12.8 12.8 12.8zM496 400H48V80c0-8.84-7.16-16-16-16H16C7.16 64 0 71.16 0 80v336c0 17.67 14.33 32 32 32h464c8.84 0 16-7.16 16-16v-16c0-8.84-7.16-16-16-16zm-387.2-48h22.4c6.4 0 12.8-6.4 12.8-12.8v-70.4c0-6.4-6.4-12.8-12.8-12.8h-22.4c-6.4 0-12.8 6.4-12.8 12.8v70.4c0 6.4 6.4 12.8 12.8 12.8z\" class=\"\"><\/path><\/svg><\/i> <img decoding=\"async\" width=\"16\" height=\"16\" alt=\"Loading\" src=\"https:\/\/algotrading101.com\/learn\/wp-content\/plugins\/page-views-count\/ajax-loader-2x.gif\" border=0 \/><\/p>\n<div class=\"pvc_clear\"><\/div>\n<p>Table of contents: What is Deribit? What is Deribit API? Is Deribit free? Does Deribit require KYC? Why should I use Deribit? Why shouldn\u2019t I use the Deribit? Is Deribit available in my country? What are the alternatives to using Deribit? What clients are available for the Deribit API? How to get started with Deribit? [&hellip;]<\/p>\n","protected":false},"author":14,"featured_media":13788,"comment_status":"closed","ping_status":"open","sticky":true,"template":"","format":"standard","meta":{"_lmt_disableupdate":"no","_lmt_disable":"no","_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0},"categories":[3,2],"tags":[],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v20.7 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>Deribit - An Introductory API Guide - AlgoTrading101 Blog<\/title>\n<meta name=\"description\" content=\"Authentic Stories about Algorithmic trading, coding and life.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/algotrading101.com\/learn\/deribit-api-guide\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Deribit - An Introductory API Guide - AlgoTrading101 Blog\" \/>\n<meta property=\"og:description\" content=\"Authentic Stories about Algorithmic trading, coding and life.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/algotrading101.com\/learn\/deribit-api-guide\/\" \/>\n<meta property=\"og:site_name\" content=\"Quantitative Trading Ideas and Guides - AlgoTrading101 Blog\" \/>\n<meta property=\"article:published_time\" content=\"2022-03-03T13:41:55+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2023-04-03T21:02:18+00:00\" \/>\n<meta property=\"og:image\" content=\"http:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2022\/03\/Deribit-API-Guide.png\" \/>\n\t<meta property=\"og:image:width\" content=\"600\" \/>\n\t<meta property=\"og:image:height\" content=\"400\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/png\" \/>\n<meta name=\"author\" content=\"Igor Radovanovic\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Igor Radovanovic\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"18 minutes\" \/>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Deribit - An Introductory API Guide - AlgoTrading101 Blog","description":"Authentic Stories about Algorithmic trading, coding and life.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/algotrading101.com\/learn\/deribit-api-guide\/","og_locale":"en_US","og_type":"article","og_title":"Deribit - An Introductory API Guide - AlgoTrading101 Blog","og_description":"Authentic Stories about Algorithmic trading, coding and life.","og_url":"https:\/\/algotrading101.com\/learn\/deribit-api-guide\/","og_site_name":"Quantitative Trading Ideas and Guides - AlgoTrading101 Blog","article_published_time":"2022-03-03T13:41:55+00:00","article_modified_time":"2023-04-03T21:02:18+00:00","og_image":[{"width":600,"height":400,"url":"http:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2022\/03\/Deribit-API-Guide.png","type":"image\/png"}],"author":"Igor Radovanovic","twitter_card":"summary_large_image","twitter_misc":{"Written by":"Igor Radovanovic","Est. reading time":"18 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/algotrading101.com\/learn\/deribit-api-guide\/#article","isPartOf":{"@id":"https:\/\/algotrading101.com\/learn\/deribit-api-guide\/"},"author":{"name":"Igor Radovanovic","@id":"https:\/\/algotrading101.com\/learn\/#\/schema\/person\/a7ae60c112a73b7c3fe14ac56726a0ae"},"headline":"Deribit &#8211; An Introductory API Guide","datePublished":"2022-03-03T13:41:55+00:00","dateModified":"2023-04-03T21:02:18+00:00","mainEntityOfPage":{"@id":"https:\/\/algotrading101.com\/learn\/deribit-api-guide\/"},"wordCount":2283,"publisher":{"@id":"https:\/\/algotrading101.com\/learn\/#organization"},"articleSection":["Programming","Trading"],"inLanguage":"en-US"},{"@type":"WebPage","@id":"https:\/\/algotrading101.com\/learn\/deribit-api-guide\/","url":"https:\/\/algotrading101.com\/learn\/deribit-api-guide\/","name":"Deribit - An Introductory API Guide - AlgoTrading101 Blog","isPartOf":{"@id":"https:\/\/algotrading101.com\/learn\/#website"},"datePublished":"2022-03-03T13:41:55+00:00","dateModified":"2023-04-03T21:02:18+00:00","description":"Authentic Stories about Algorithmic trading, coding and life.","breadcrumb":{"@id":"https:\/\/algotrading101.com\/learn\/deribit-api-guide\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/algotrading101.com\/learn\/deribit-api-guide\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/algotrading101.com\/learn\/deribit-api-guide\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/algotrading101.com\/learn\/"},{"@type":"ListItem","position":2,"name":"Deribit &#8211; An Introductory API Guide"}]},{"@type":"WebSite","@id":"https:\/\/algotrading101.com\/learn\/#website","url":"https:\/\/algotrading101.com\/learn\/","name":"Quantitative Trading Ideas and Guides - AlgoTrading101 Blog","description":"Authentic Stories about Algorithmic trading, coding and life.","publisher":{"@id":"https:\/\/algotrading101.com\/learn\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/algotrading101.com\/learn\/?s={search_term_string}"},"query-input":"required name=search_term_string"}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/algotrading101.com\/learn\/#organization","name":"AlgoTrading101","url":"https:\/\/algotrading101.com\/learn\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/algotrading101.com\/learn\/#\/schema\/logo\/image\/","url":"https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2020\/11\/AlgoTrading101-Lucas-Liew.jpg","contentUrl":"https:\/\/algotrading101.com\/learn\/wp-content\/uploads\/2020\/11\/AlgoTrading101-Lucas-Liew.jpg","width":1200,"height":627,"caption":"AlgoTrading101"},"image":{"@id":"https:\/\/algotrading101.com\/learn\/#\/schema\/logo\/image\/"}},{"@type":"Person","@id":"https:\/\/algotrading101.com\/learn\/#\/schema\/person\/a7ae60c112a73b7c3fe14ac56726a0ae","name":"Igor Radovanovic","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/algotrading101.com\/learn\/#\/schema\/person\/image\/","url":"https:\/\/secure.gravatar.com\/avatar\/d46175c509b3ee240a1e2bbe735a4d1e?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/d46175c509b3ee240a1e2bbe735a4d1e?s=96&d=mm&r=g","caption":"Igor Radovanovic"},"sameAs":["https:\/\/igorradovanovic.com","https:\/\/www.linkedin.com\/in\/igor-radovanovic-profile"],"url":"https:\/\/algotrading101.com\/learn\/author\/igor\/"}]}},"modified_by":"Igor Radovanovic","_links":{"self":[{"href":"https:\/\/algotrading101.com\/learn\/wp-json\/wp\/v2\/posts\/13770"}],"collection":[{"href":"https:\/\/algotrading101.com\/learn\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/algotrading101.com\/learn\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/algotrading101.com\/learn\/wp-json\/wp\/v2\/users\/14"}],"replies":[{"embeddable":true,"href":"https:\/\/algotrading101.com\/learn\/wp-json\/wp\/v2\/comments?post=13770"}],"version-history":[{"count":7,"href":"https:\/\/algotrading101.com\/learn\/wp-json\/wp\/v2\/posts\/13770\/revisions"}],"predecessor-version":[{"id":21144,"href":"https:\/\/algotrading101.com\/learn\/wp-json\/wp\/v2\/posts\/13770\/revisions\/21144"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/algotrading101.com\/learn\/wp-json\/wp\/v2\/media\/13788"}],"wp:attachment":[{"href":"https:\/\/algotrading101.com\/learn\/wp-json\/wp\/v2\/media?parent=13770"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/algotrading101.com\/learn\/wp-json\/wp\/v2\/categories?post=13770"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/algotrading101.com\/learn\/wp-json\/wp\/v2\/tags?post=13770"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}