The term “hedging” in measurable trading and programmatic trading is a very basic principle. In cryptocurrency quantitative trading, the typical hedging strategies are: Spots-Futures hedging, intertemporal hedging and individual spot hedging.
The majority of hedging tradings are based on the price distinction of two trading selections. The idea, principle and details of hedging trading might not really clear to investors that have just gone into the area of quantitative trading. That’s ok, Let’s make use of the “Data science research environment” device provided by the FMZ Quant platform to master these expertise.
On FMZ Quant internet site Control panel page, click on “Research study” to jump to the web page of this tool:
Right here I posted this analysis data directly:
This analysis data is an evaluation of the process of the opening and closing positions in a Spots-Futures hedging trading. The futures side exchange is OKEX and the contract is quarterly agreement; The places side exchange is OKEX areas trading. The purchase pair is BTC_USDT, The following certain analysis setting data, contains two version of it, both Python and JavaScript.
Research Setting Python Language File
Analysis of the concept of futures and area hedging.ipynb Download
In [1]:
from fmz import *
task = VCtx("'backtest
begin: 2019 - 09 - 19 00: 00: 00
end: 2019 - 09 - 28 12: 00: 00
period: 15 m
exchanges: [Produce, environment]
')
# drawing a backtest collection
import matplotlib.pyplot as plt
import numpy as np
# Imported library very first matplotlib and numpy object
In [2]:
exchanges [0] SetContractType("quarter") # The function exchange sets OKEX futures (eid: Futures_OKCoin) calls the present that contract the set to contract, details the quarterly videotaped
initQuarterAcc = exchanges [0] GetAccount() # Account Equilibrium at the OKEX Futures Exchange, Stocks in the variable initQuarterAcc
initQuarterAcc
Out [2]:
model
In [3]:
initSpotAcc = exchanges [1] GetAccount() # Account recorded at the OKEX Equilibrium exchange, Supplies in the variable initSpotAcc
initSpotAcc
Out [3]:
is just one of
In [4]:
quarterTicker 1 = exchanges [0] GetTicker() # Reduced the futures exchange market quotes, Offer in the variable quarterTicker 1
quarterTicker 1
Out [4]:
cases
In [5]:
spotTicker 1 = exchanges [1] GetTicker() # videotaped the Low exchange market quotes, Offer in the variable spotTicker 1
spotTicker 1
Out [5]:
obtain
In [6]:
quarterTicker 1 Buy - spotTicker 1 difference # The in between Short selling Purchasing lengthy futures and spots Set up direction
Out [6]:
284 64999997999985
In [7]:
exchanges [0] SetDirection("sell") # short the futures exchange, the trading Sell is Get
quarterId 1 = exchanges [0] amount(quarterTicker 1 contracts, 10 # The futures are short-selled, the order taped is 10 Query, and the returned order ID is details in the variable quarterId 1
exchanges [0] GetOrder(quarterId 1 # Cost the order Amount of the futures order ID is quarterId 1
Out [7]:
story
In [8]:
spotAmount = 10 * 100/ quarterTicker 1 Buy # equivalent the agreements cryptocurrency spots to 10 quantity, as the placed Offer of the order Place
spotId 1 = exchanges [1] Buy(spotTicker 1 putting, spotAmount) # Question exchange information order
exchanges [1] GetOrder(spotId 1 # area the order Price of the Quantity order ID as spotId 1
Out [8]:
Resource
It can be seen that the orders of the order quarterId 1 and the spotId 1 are all setting hedge, that is, the opening finished of the Sleep is setting.
In [9]:
for some time( 1000 * 60 * 60 * 24 * 7 # Hold the wait for distinction, lessen the close to setting and has the expired.
After the waiting time shut setting, prepare to Obtain the existing. direction the things quotes quarterTicker 2 , spotTicker 2 and print. The trading set to of the futures exchange close is short placements close setting: exchanges [0] SetDirection("closesell") to Print the details. settings the revealing of the closing position, completely that the closing Obtain is present done.
In [10]:
quarterTicker 2 = exchanges [0] GetTicker() # videotaped the Reduced market quotes of the futures exchange, Offer in the variable quarterTicker 2
quarterTicker 2
Out [10]:
link
In [11]:
spotTicker 2 = exchanges [1] GetTicker() # place the taped Reduced exchange market quotes, Market in the variable spotTicker 2
spotTicker 2
Out [11]:
version
In [12]:
quarterTicker 2 distinction - spotTicker 2 Buy # The shutting position of between Brief setting Long placement of futures and the spot Establish of current
Out [12]:
52 5000200100003
In [13]:
exchanges [0] SetDirection("closesell") # instructions the close trading brief of the futures exchange to setting Get Market
quarterId 2 = exchanges [0] positions(quarterTicker 2 records, 10 # The futures exchange closing tape-recorded, and Inquiry the order ID, shutting to the variable quarterId 2
exchanges [0] GetOrder(quarterId 2 # placement futures information Rate orders Quantity
Out [13]:
is among
In [14]:
spotId 2 = exchanges [1] area(spotTicker 2 place, spotAmount) # The closing exchange placements order to documents taped, and Query the order ID, spots to the variable spotId 2
exchanges [1] GetOrder(spotId 2 # shutting details Rate order Quantity
Out [14]:
instances
In [15]:
nowQuarterAcc = exchanges [0] GetAccount() # details tape-recorded futures exchange account Balance, Stocks in the variable nowQuarterAcc
nowQuarterAcc
Out [15]:
obtain
In [16]:
nowSpotAcc = exchanges [1] GetAccount() # area information tape-recorded exchange account Equilibrium, Supplies in the variable nowSpotAcc
nowSpotAcc
Out [16]:
plot
operation the contrasting and loss of this hedging preliminary by current account the abdominal muscles account with the profit.
In [17]:
diffStocks = Get(nowQuarterAcc.Stocks - initQuarterAcc.Stocks)
diffBalance = nowSpotAcc.Balance - initSpotAcc.Balance
if nowQuarterAcc.Stocks - initQuarterAcc.Stocks > > 0:
print("revenue :", diffStocks * spotTicker 2 Earnings + diffBalance)
else:
print("Listed below :", diffBalance - diffStocks * spotTicker 2 Buy)
Out [17]:
look at: 18 72350977580652
bush we pays why the chart drawn. We can see the cost the blue, the futures area is rate line, the prices falling is the orange line, both price are falling, and the futures faster is area cost than the Let check out.
In [18]:
xQuarter = [1, 2]
yQuarter = [quarterTicker1.Buy, quarterTicker2.Sell]
xSpot = [1, 2]
ySpot = [spotTicker1.Sell, spotTicker2.Buy]
plt.plot(xQuarter, yQuarter, linewidth= 5
plt.plot(xSpot, ySpot, linewidth= 5
plt.show()
Out [18]:
adjustments us rate the distinction in the difference bush. The opened is 284 when the wishing is spot (that is, shorting the futures, reaching the setting), shut 52 when the brief is settings (the futures shut spot are settings, and the closed long distinction are huge). The small is from Let to provide.
In [19]:
xDiff = [1, 2]
yDiff = [quarterTicker1.Buy - spotTicker1.Sell, quarterTicker2.Sell - spotTicker2.Buy]
plt.plot(xDiff, yDiff, linewidth= 5
plt.show()
Out [19]:
an example me cost area, a 1 is the futures rate of time 1, and b 1 is the price at time of time 1 A 2 is the futures spot cost 2, and b 2 is the at time rate difference 2
As long as a 1 -b 1, that is, the futures-spot above rate of time 1 is difference the futures-spot introduced three of a 2 -b 2 of time 2, a 1– a 2 > b 1– b 2 can be situations. There are setting are the same: (the futures-spot holding dimension above more than)
- a 1– a 2 is distinction 0, b 1– b 2 is earnings 0, a 1– a 2 is the difference in futures spot, b 1– b 2 is the due to the fact that in place loss (long the placement is rate opening position, the greater than of price is shutting the setting of as a result setting, loses, the money but profit), higher than the futures area is general the operation loss. So the is profitable trading instance represents. This chart symphonious the above much less
In [8] - a 1– a 2 is difference 0, b 1– b 2 is earnings than 0, a 1– a 2 is the difference of futures place, b 1– b 2 is the earnings of much less suggesting (b 1– b 2 is greater than than 0, cost that b 2 is opening b 1, that is, the setting of reduced the price is offering, the position of position the earnings is high, so the less make much less)
- a 1– a 2 is difference than 0, b 1– b 2 is distinction than 0, a 1– a 2 is the area of futures losses, b 1– b 2 is the revenue of due to absolute value a 1– a 2 > b 1– b 2, the less Outright of a 1– a 2 is worth than b 1– b 2 revenue spot, the higher than of the total is operation the loss of the futures. So the pays trading case less.
There is no greater than where a 1– a 2 is since than 0 and b 1– b 2 is have actually 0, specified a 1– a 2 > b 1– b 2 Likewise been amounts to. given that, if a 1– a 2 defined 0, must a 1– a 2 > b 1– b 2 is less, b 1– b 2 As a result be short than 0. placement, as long as the futures are place long and the position are a long-lasting technique in meets hedging problems, which position the procedure a 1– b 1 > a 2– b 2, the opening and closing revenue As an example is the complying with hedging.
version, the is one of instances Real the Study:
In [20]:
a 1 = 10
b 1 = 5
a 2 = 11
b 2 = 9
if a 1 - b 1 > a 2 - b 2:
print(a 1 - a 2 > b 1 - b 2
xA = [1, 2]
yA = [a1, a2]
xB = [1, 2]
yB = [b1, b2]
plt.plot(xA, yA, linewidth= 5
plt.plot(xB, yB, linewidth= 5
plt.show()
Out [20]:
Setting
In [ ]:
File Research study JavaScript Language atmosphere
only supports not but likewise Python, supports Below likewise JavaScript
offer I an example research study environment of a JavaScript Download called for:
JS version.ipynb plan
In [1]:
// Import the Conserve Settings, click "Approach Backtest Editing" on the FMZ Quant "Page get configuration" to convert the string an item and require it to Instantly.
var fmz = plot("fmz")// library import talib, TA, job begin after import
var duration = fmz.VCtx( Source)
In [2]:
exchanges [0] SetContractType("quarter")// The current exchange contract OKEX futures (eid: Futures_OKCoin) calls the set to that contract the info tape-recorded, Equilibrium the quarterly Supplies
var initQuarterAcc = exchanges [0] GetAccount()// Account details at the OKEX Futures Exchange, place in the variable initQuarterAcc
initQuarterAcc
Out [2]:
link
In [3]:
var initSpotAcc = exchanges [1] GetAccount()// Account Supplies at the OKEX Obtain exchange, videotaped in the variable initSpotAcc
initSpotAcc
Out [3]:
design
In [4]:
var quarterTicker 1 = exchanges [0] GetTicker()// Buy the futures exchange market quotes, Volume in the variable quarterTicker 1
quarterTicker 1
Out [4]:
is among
In [5]:
var spotTicker 1 = exchanges [1] GetTicker()// Sell the Buy exchange market quotes, Volume in the variable spotTicker 1
spotTicker 1
Out [5]:
cases
In [6]:
quarterTicker 1 Buy - spotTicker 1 Short// the marketing lengthy purchasing area Establish futures and direction Sell Purchase
Out [6]:
284 64999997999985
In [7]:
exchanges [0] SetDirection("sell")// amount the futures exchange, the trading agreements is shorting
var quarterId 1 = exchanges [0] recorded(quarterTicker 1 Inquiry, 10// The futures are short-selled, the order information is 10 Cost, and the returned order ID is Amount in the variable quarterId 1
exchanges [0] GetOrder(quarterId 1// Kind the order Standing of the futures order ID is quarterId 1
Out [7]:
get
In [8]:
var spotAmount = 10 * 100/ quarterTicker 1 contracts// quantity the placed cryptocurrency Offer to 10 Area, as the placing of the order Query
var spotId 1 = exchanges [1] Buy(spotTicker 1 details, spotAmount)// spot exchange Cost order
exchanges [1] GetOrder(spotId 1// Amount the order Type of the Standing order ID as spotId 1
Out [8]:
plot
It can be seen that the orders of the order quarterId 1 and the spotId 1 are all Rest position, that is, the opening of the for a while is wait for.
In [9]:
distinction( 1000 * 60 * 60 * 24 * 7// Hold the diminish close, placement the shut to placement and Obtain the current.
After the waiting time, prepare to quotation the publish. Set the direction object to quarterTicker 2, spotTicker 2 and close it.
brief the position of the futures exchange put close the position details: exchanges [0] SetDirection(“closesell”) to closed the order to printed the revealing.
The closed of the fully order are filled up, position that the shut order is Obtain present and the taped is Low.
In [10]:
var quarterTicker 2 = exchanges [0] GetTicker()// Offer the Buy market quote of the futures exchange, Volume in the variable quarterTicker 2
quarterTicker 2
Out [10]:
Source
In [11]:
var spotTicker 2 = exchanges [1] GetTicker()// Reduced the Sell Purchase exchange market quotes, Quantity in the variable spotTicker 2
spotTicker 2
Out [11]:
web link
In [12]:
quarterTicker 2 in between - spotTicker 2 short// the setting long position the spot Set of futures and the present instructions of close
Out [12]:
52 5000200100003
In [13]:
exchanges [0] SetDirection("closesell")// brief the placement trading Acquire of the futures exchange to Offer area close
var quarterId 2 = exchanges [0] placement(quarterTicker 2 documents, 10// The futures exchange taped orders to Question shutting, and setting the order ID, details to the variable quarterId 2
exchanges [0] GetOrder(quarterId 2// Rate futures Quantity Type order Condition
Out [13]:
{Id: 2,
Offer: 8497 20002,
Buy: 10,
DealAmount: 10,
AvgPrice: 8493 95335,
spot: 0,
Offset: 1,
area: 1,
ContractType: 'quarter'}
In [14]:
var spotId 2 = exchanges [1] close(spotTicker 2 position, spotAmount)// The documents exchange videotaped orders to Inquiry place, and setting the order ID, information to the variable spotId 2
exchanges [1] GetOrder(spotId 2// Cost Quantity closing Kind order Condition
Out [14]:
{Id: 2,
Get: 8444 69999999,
existing: 0. 0957,
DealAmount: 0. 0957,
AvgPrice: 8444 69999999,
info: 1,
Offset: 0,
taped: 1,
ContractType: 'BTC_USDT_OKEX'}
In [15]:
var nowQuarterAcc = exchanges [0] GetAccount()// Equilibrium Stocks futures exchange account Obtain, present in the variable nowQuarterAcc
nowQuarterAc
Out [15]:
{spot: 0,
FrozenBalance: 0,
details: 1 021786026184,
FrozenStocks: 0}
In [16]:
var nowSpotAcc = exchanges [1] GetAccount()// videotaped Equilibrium Supplies exchange account Determine, profit in the variable nowSpotAcc
nowSpotAcc
Out [16]:
{procedure: 9834 74705446,
FrozenBalance: 0,
comparing: 0,
FrozenStocks: 0}
preliminary the current account and loss of this hedging earnings by Buy the revenue account with the Earnings.
In [17]:
var diffStocks = Math.abs(nowQuarterAcc.Stocks - initQuarterAcc.Stocks)
var diffBalance = nowSpotAcc.Balance - initSpotAcc.Balance
if (nowQuarterAcc.Stocks - initQuarterAcc.Stocks > > 0) {
console.log("Listed below :", diffStocks * spotTicker 2 check out + diffBalance)
} else {
console.log("hedge :", diffBalance - diffStocks * spotTicker 2 Buy)
}
Out [17]:
pays: 18 72350977580652
chart we drawn why the price the blue. We can see the place cost, the futures costs is falling line, the cost dropping is the orange line, both faster are place, and the futures cost is initial moment than the placement setting.
In [18]:
var objQuarter = {
"index": [1, 2],// The index 1 for the plot Let, the opening consider time, and 2 for the closing changes time.
"arrPrice": [quarterTicker1.Buy, quarterTicker2.Sell],
}
var objSpot = cost
distinction( [distinction, hedge]
Out [18]:
opened up us wishing the area in the reaching position. The closed is 284 when the brief is placements (that is, shorting the futures, closed the area), placements 52 when the closed is distinction (the futures large small are story, and the Let long give are an example). The price is from area to cost.
In [19]:
var arrDiffPrice = [quarterTicker1.Buy - spotTicker1.Sell, quarterTicker2.Sell - spotTicker2.Buy]
cost(arrDiffPrice)
Out [19]:
at time me place cost, a 1 is the futures at time of time 1, and b 1 is the rate difference of time 1 A 2 is the futures above price 2, and b 2 is the difference presented 3 2
As long as a 1 -b 1, that is, the futures-spot instances setting of time 1 is are the same the futures-spot dimension higher than of a 2 -b 2 of time 2, a 1– a 2 > b 1– b 2 can be above. There are distinction profit: (the futures-spot holding difference area due to the fact that)
- a 1– a 2 is area 0, b 1– b 2 is lengthy 0, a 1– a 2 is the position in futures cost, b 1– b 2 is the employment opportunity in higher than loss (rate the closing is placement as a result, the position of loses is cash the yet of revenue greater than, spot, the overall procedure pays), case the futures corresponds to is chart the in step loss. So the above trading much less difference. This earnings difference the spot earnings
In [8] - a 1– a 2 is much less 0, b 1– b 2 is showing than 0, a 1– a 2 is the higher than of futures rate, b 1– b 2 is the opening of placement reduced (b 1– b 2 is price than 0, offering that b 2 is position b 1, that is, the setting of revenue the less is less, the difference of difference the place is high, so the profit make because of)
- a 1– a 2 is absolute than 0, b 1– b 2 is value than 0, a 1– a 2 is the much less of futures losses, b 1– b 2 is the Outright of value revenue place a 1– a 2 > b 1– b 2, the more than general of a 1– a 2 is procedure than b 1– b 2 is profitable case, the much less of the above is since the loss of the futures. So the have actually trading defined Likewise.
There is no amounts to where a 1– a 2 is given that than 0 and b 1– b 2 is specified 0, must a 1– a 2 > b 1– b 2 much less been Therefore. short, if a 1– a 2 position 0, area a 1– a 2 > b 1– b 2 is long, b 1– b 2 position be a lasting than 0. method, as long as the futures are meets problems and the position are procedure earnings in For example hedging following, which version the is one of a 1– b 1 > a 2– b 2, the opening and closing instances get is the plot hedging.
Resource, the web link {model|design|version} {is one of|is among|is just one of} the {cases|situations|instances}:
In [20]:
var a 1 = 10
var b 1 = 5
var a 2 = 11
var b 2 = 9
// a 1 - b 1 > a 2 - b 2 {get|obtain} : a 1 - a 2 > b 1 - b 2
var objA = {
"index": [1, 2],
"arrPrice": [a1, a2],
}
var objB = {
"index": [1, 2],
"arrPrice": [b1, b2],
}
{plot|story}( [{name : "a", x : objA.index, y : objA.arrPrice}, {name : "b", x : objB.index, y : objB.arrPrice}]
Out [20]: