Reform Deribit futures API to adapt to quantitative trading of options
Tags: trading, api, fmzquant, futures
Published: 2024-05-15 01:19:34

At present, there are many digital currency futures exchanges. However, as a futures derivative, there are few exchanges in the market for digital currency option trading. Deribit and BitMEX support option trading. In the field of quantitative trading, options trading also has a variety of strategies, such as the options strategies mentioned in some materials searched:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tph1f3mphg1xi5fpm4jf.png)

Quoted from [link](http://www.360doc.com/content/19/0419/13/19962827_829883317.shtml)

To prepare an option trading strategy, you need to lay a solid foundation first, and be familiar with basic operations such as placing an order, obtaining ticker, cancelling an order, and obtaining positions. The strategy writing still uses the FMZ Quant Trading platform, although the FMZ Quant Trading platform currently supports currency-currency trading, contract trading and leverage trading in the field of digital currency quantitative trading. There is not much information about options trading. Let's take the "Deribit" exchange as an example to introduce how to use the FMZ Quant Trading platform to get familiar with digital currency options trading.

### Deribit related materials
API document: https://docs.deribit.com/v2/?javascript#public-get_last_settlements_by_instrument
Simulation bot: https://docs.deribit.com/v2/?javascript#public-get_last_settlements_by_instrument

You can register an account on the simulation bot website, open the API KEY, and obtain the API KEY. Configuring on the FMZ Quant Trading platform is the same as configuring a real bot.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/clc7yqaymu8se7s0pkx5.png)

There are four basic concepts to understand about option trading:

-Exercise date: the long and short parties of the option complete the delivery of the option contract on this date.
-Exercise price: On the exercise date, the long and short parties of the option complete the delivery of the option contract at the exercise price.
-Premium: that is, the price of options. Like spot and futures, it is quoted at a bid price and an ask price.
  It is worth noting that since the liquidity of options is generally lower than that of futures and spot, the price difference between bid and ask may be large, so much attention should be paid here! After the transaction, the transaction price is the cost of the option long positions, at which time the long positions get the right (the right to exercise the option); The short option, as the party receiving the premium, adds an obligation. Once the long option requests to exercise its rights, the short option must cooperate.
-Call put options:
  The so-called call option means that the option long positions have the right to ask the option short positions to buy the given Bitcoin at a certain exercise price on a certain exercise date, and the short positions have the obligation to cooperate with the long positions; The so-called put option means that the long side of the option has the right to ask the short side to sell the given Bitcoin at a certain exercise price on a certain exercise date, and the short side has the obligation to cooperate with the long side.

### Ticker acquisition
After reading the API document of Deribit Exchange, we can see that the ticker interface of Deribit for accessing futures or options tickers is simply a matter of passing in different instrument_name parameters (instrument_name is set by the function SetContractType), so basically, you can follow the The interface GetTicker to get the ticker of the options.

Of course, the FMZ Quant Trading platform encapsulates the real bot of Deribit Exchange by default. First, we need to switch to the simulation bot, using the following code:

```
exchange.IO("base", "https://test.deribit.com")
```

Then we set up the option contract BTC-27DEC19-7000-P currently.
This is a put option with an exercise date of: 27DEC19 and an exercise price of: 7000.

```
exchange.SetContractType("BTC-27DEC19-7000-P")
```

Then get, let's write it together and let the code run to test getting the ticker for this option contract.

```
function main () {
    exchange.IO("base", "https://test.deribit.com")
    exchange.SetContractType("BTC-27DEC19-7000-P")
    var ticker = exchange.GetTicker()
    Log(ticker)
}
```

It is easy to test by using the debugging tool:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vzez2lc6jvj36jp413s8.png)

It can be seen that the price is consistent with that on the simulation bot.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5xp64k8q8kp0h1kvesnx.png)

Other ticker interfaces are called in the same way, which will not be repeated here. Note:
Option trading is not very active. Sometimes there is no order to buy or sell. At this time, the FMZ Quant Trading platform will detect the value of 0 at the bottom, and it will report an error. You can use SetErrorFilter("Invalid ticker") to ignore this error, and use the function GetRawJSON to obtain the original information of the ticker and encapsulate the data. Here I write an example to achieve similar functions:

```
function init() {
    SetErrorFilter("Invalid ticker")
}

$.GetTicker = function(e) {
    var ticker = e.GetTicker()
    if (!ticker) {
        try {
            var ret = JSON.parse(e.GetRawJSON())
            return {
                Info : ret,
                High : ret.result.stats.high,
                Low : ret.result.stats.low, 
                Buy : ret.result.best_bid_price,
                Sell : ret.result.best_ask_price,
                Last : ret.result.last_price, 
                Volume : ret.result.stats.volume,
                OpenInterest : 0,
                Time : new Date().getTime()
            }
        } catch (err) {
            Log(err)
        }
    }
    
    return ticker
}
```

When called, we write: Log($.GetTicker(exchange))

### Place an order
The operation of placing an order is very simple, compared to futures trading, there are only two directions of buying and selling. The functions Sell, Buy are also used to place an order.

```
function main () {
    exchange.IO("base", "https://test.deribit.com")
    exchange.SetContractType("BTC-27DEC19-7000-P")
    
    var id = exchange.Buy(0.017, 1)
    Log(exchange.GetOrder(id))
}
```

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/m7fbcj5noxq9eang0w7z.png)

The order that was just placed also appears on the simulation bot.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ygqx0aqcylzlojxl9e0v.png)

And exchange.GetOrder(id) can look up the order information.

### Cancellation of orders
The same CancelOrder function is used for order cancellation, just like the order cancellation for futures trading.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sffn6p7t60a1t8a6e540.png)

### Get account available assets
Getting account available assets is exactly the same as futures trading, just call the GetAccount function directly.

Simulate the display on the exchange page:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0b24mv7vdxv4a4mlf8zf.png)

Run the code to get.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xz17glrys6chmhueo6ja.png)

### Get position information
We can't use the encapsulated GetPosition function directly for positions, because the default Deribit transaction is a futures transaction, not an options transaction, we can only use this function to get futures positions.
So this will have to be our own encapsulated function to get the options position.

Function interface for obtaining positions in the API document:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ocb7htwc3darp452dmi5.png)

```
$.GetPosition = function(e) {
    // /private/get_positions
    // currency  ， kind 
    
    var positions = [] 
    var currency = e.GetCurrency()
    var arr = currency.split("_")
    var baseCurrency = arr[0]
    
    try {
        var ret = e.IO("api", "GET", "/api/v2/private/get_positions", "currency=" + baseCurrency + "&kind=option")
        for (var i in ret.result) {
            if (ret.result[i].size == 0 || ret.result[i].direction == "zero") {
                continue    
            } 
            
            var pos = {
                Info : ret.result[i], 
                Amount : ret.result[i].size,
                FrozenAmount : 0,
                Price : ret.result[i].average_price,
                Profit : ret.result[i].floating_profit_loss,
                MarginLevel : 0,
                Margin : 0,
                ContractType : ret.result[i].instrument_name,
                Type : ret.result[i].direction == "buy" ? ORDER_TYPE_BUY : ORDER_TYPE_SELL,
            }
            
            positions.push(pos)
        }
    } catch (err) {
        Log(err)
        positions = null
    }
    
    return positions
}
```

Call Log($.GetPosition(exchange)) to print the position information.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tybd2wujqkq0euxyy2x8.png)

Thus, the basic operations can be implemented, and the rest can be studied for options trading strategies.

From: https://blog.mathquant.com/2022/12/28/reform-deribit-futures-api-to-adapt-to-quantitative-trading-of-options.html