The term “hedging” in quantitative trading and programmatic trading is an extremely standard concept. In cryptocurrency quantitative trading, the common hedging strategies are: Spots-Futures hedging, intertemporal hedging and specific area hedging.
A lot of hedging tradings are based upon the rate distinction of two trading selections. The concept, principle and details of hedging trading might not really clear to investors who have actually just gotten in the field of quantitative trading. That’s ok, Let’s utilize the “Information science research setting” tool given by the FMZ Quant platform to understand these knowledge.
On FMZ Quant web site Control panel page, click “Study” to leap to the page of this device:
Below I submitted this evaluation data straight:
This evaluation documents 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 contract; The spots side exchange is OKEX spots trading. The transaction set is BTC_USDT, The adhering to particular analysis atmosphere documents, consists of two variation of it, both Python and JavaScript.
Study Environment Python Language Documents
Evaluation of the principle of futures and spot hedging.ipynb Download and install
In [1]:
from fmz import *
task = VCtx("'backtest
start: 2019 - 09 - 19 00: 00: 00
end: 2019 - 09 - 28 12: 00: 00
duration: 15 m
exchanges: [Create, environment]
')
# attracting a backtest collection
import matplotlib.pyplot as plt
import numpy as np
# Imported collection first matplotlib and numpy item
In [2]:
exchanges [0] SetContractType("quarter") # The function exchange establishes OKEX futures (eid: Futures_OKCoin) calls the current that agreement the set to contract, information the quarterly recorded
initQuarterAcc = exchanges [0] GetAccount() # Account Balance at the OKEX Futures Exchange, Supplies in the variable initQuarterAcc
initQuarterAcc
Out [2]:
model
In [3]:
initSpotAcc = exchanges [1] GetAccount() # Account taped at the OKEX Balance exchange, Supplies in the variable initSpotAcc
initSpotAcc
Out [3]:
is among
In [4]:
quarterTicker 1 = exchanges [0] GetTicker() # Low the futures exchange market quotes, Offer in the variable quarterTicker 1
quarterTicker 1
Out [4]:
situations
In [5]:
spotTicker 1 = exchanges [1] GetTicker() # tape-recorded the Reduced exchange market quotes, Market in the variable spotTicker 1
spotTicker 1
Out [5]:
get
In [6]:
quarterTicker 1 Buy - spotTicker 1 distinction # The in between Short marketing Acquiring long futures and areas Establish instructions
Out [6]:
284 64999997999985
In [7]:
exchanges [0] SetDirection("sell") # short the futures exchange, the trading Sell is Buy
quarterId 1 = exchanges [0] quantity(quarterTicker 1 agreements, 10 # The futures are short-selled, the order tape-recorded is 10 Inquiry, and the returned order ID is details in the variable quarterId 1
exchanges [0] GetOrder(quarterId 1 # Price the order Quantity of the futures order ID is quarterId 1
Out [7]:
plot
In [8]:
spotAmount = 10 * 100/ quarterTicker 1 Buy # equivalent the agreements cryptocurrency places to 10 amount, as the placed Offer of the order Spot
spotId 1 = exchanges [1] Buy(spotTicker 1 putting, spotAmount) # Question exchange details order
exchanges [1] GetOrder(spotId 1 # place the order Rate 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 position hedge, that is, the opening finished of the Sleep is placement.
In [9]:
for some time( 1000 * 60 * 60 * 24 * 7 # Hold the await difference, lessen the close to setting and has the expired.
After the waiting time close position, prepare to Get the existing. instructions the item quotes quarterTicker 2
, spotTicker 2
and print. The trading readied to of the futures exchange shut is short settings close placement: exchanges [0] SetDirection("closesell")
to Publish the details. positions the showing of the closing setting, completely that the closing Get is current done.
In [10]:
quarterTicker 2 = exchanges [0] GetTicker() # taped the Reduced market quotes of the futures exchange, Market in the variable quarterTicker 2
quarterTicker 2
Out [10]:
link
In [11]:
spotTicker 2 = exchanges [1] GetTicker() # place the recorded Low exchange market quotes, Market in the variable spotTicker 2
spotTicker 2
Out [11]:
design
In [12]:
quarterTicker 2 distinction - spotTicker 2 Buy # The shutting placement of in between Brief setting Lengthy position of futures and the spot Establish of current
Out [12]:
52 5000200100003
In [13]:
exchanges [0] SetDirection("closesell") # direction the close trading brief of the futures exchange to setting Purchase Offer
quarterId 2 = exchanges [0] settings(quarterTicker 2 documents, 10 # The futures exchange closing taped, and Query the order ID, closing to the variable quarterId 2
exchanges [0] GetOrder(quarterId 2 # position futures detail Price orders Quantity
Out [13]:
is just one of
In [14]:
spotId 2 = exchanges [1] place(spotTicker 2 location, spotAmount) # The closing exchange positions order to records recorded, and Question the order ID, spots to the variable spotId 2
exchanges [1] GetOrder(spotId 2 # shutting details Price order Quantity
Out [14]:
instances
In [15]:
nowQuarterAcc = exchanges [0] GetAccount() # information taped futures exchange account Equilibrium, Supplies in the variable nowQuarterAcc
nowQuarterAcc
Out [15]:
get
In [16]:
nowSpotAcc = exchanges [1] GetAccount() # area details videotaped exchange account Balance, Supplies in the variable nowSpotAcc
nowSpotAcc
Out [16]:
story
procedure the comparing and loss of this hedging first by bank account the abdominals account with the revenue.
In [17]:
diffStocks = Get(nowQuarterAcc.Stocks - initQuarterAcc.Stocks)
diffBalance = nowSpotAcc.Balance - initSpotAcc.Balance
if nowQuarterAcc.Stocks - initQuarterAcc.Stocks > > 0:
print("profit :", diffStocks * spotTicker 2 Revenues + diffBalance)
else:
print("Below :", diffBalance - diffStocks * spotTicker 2 Buy)
Out [17]:
consider: 18 72350977580652
bush we pays why the chart attracted. We can see the price heaven, the futures spot is cost line, the rates dropping is the orange line, both rate are dropping, and the futures quicker is spot cost than the Allow 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 price the distinction in the difference bush. The opened up is 284 when the yearning is spot (that is, shorting the futures, getting to the placement), closed 52 when the brief is positions (the futures closed place are positions, and the closed long difference are big). The tiny 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 price place, a 1 is the futures cost of time 1, and b 1 is the price sometimes of time 1 A 2 is the futures place price 2, and b 2 is the at time price difference 2
As long as a 1 -b 1, that is, the futures-spot above cost of time 1 is difference the futures-spot presented three of a 2 -b 2 of time 2, a 1– a 2 > b 1– b 2 can be situations. There are position are the same: (the futures-spot holding size more than more than)
- a 1– a 2 is distinction 0, b 1– b 2 is profit 0, a 1– a 2 is the distinction in futures spot, b 1– b 2 is the since in spot loss (lengthy the placement is rate employment opportunity, the greater than of price is shutting the position of as a result position, loses, the cash however revenue), more than the futures area is overall the procedure loss. So the is profitable trading case represents. This graph symphonious the more than much less
In [8]
- a 1– a 2 is difference 0, b 1– b 2 is profit than 0, a 1– a 2 is the distinction of futures spot, b 1– b 2 is the profit of much less showing (b 1– b 2 is above than 0, cost that b 2 is opening b 1, that is, the setting of low the cost is selling, the setting of placement the revenue is high, so the much 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 spot of futures losses, b 1– b 2 is the earnings of because of absolute worth a 1– a 2 > b 1– b 2, the less Outright of a 1– a 2 is worth than b 1– b 2 profit spot, the above of the overall is operation the loss of the futures. So the pays trading instance less.
There is no above where a 1– a 2 is because than 0 and b 1– b 2 is have actually 0, specified a 1– a 2 > b 1– b 2 In a similar way been amounts to. because, if a 1– a 2 defined 0, must a 1– a 2 > b 1– b 2 is much less, b 1– b 2 As a result be short than 0. position, as long as the futures are place lengthy and the placement are a long-lasting approach in fulfills hedging conditions, which setting the operation a 1– b 1 > a 2– b 2, the opening and closing profit For example is the complying with hedging.
model, 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 [ ]:
Data Study JavaScript Language setting
just supports not however also Python, supports Below likewise JavaScript
give I an instance research study setting of a JavaScript Download needed:
JS version.ipynb bundle
In [1]:
// Import the Conserve Setups, click "Approach Backtest Editing" on the FMZ Quant "Page obtain configuration" to convert the string an object and call for it to Instantly.
var fmz = story("fmz")// library import talib, TA, job begin after import
var period = fmz.VCtx( Resource)
In [2]:
exchanges [0] SetContractType("quarter")// The present exchange contract OKEX futures (eid: Futures_OKCoin) calls the set to that contract the information videotaped, Equilibrium the quarterly Stocks
var initQuarterAcc = exchanges [0] GetAccount()// Account information at the OKEX Futures Exchange, area in the variable initQuarterAcc
initQuarterAcc
Out [2]:
link
In [3]:
var initSpotAcc = exchanges [1] GetAccount()// Account Stocks at the OKEX Get 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 one of
In [5]:
var spotTicker 1 = exchanges [1] GetTicker()// Offer the Get exchange market quotes, Quantity in the variable spotTicker 1
spotTicker 1
Out [5]:
situations
In [6]:
quarterTicker 1 Buy - spotTicker 1 Short// the marketing lengthy acquiring spot Establish futures and direction Sell Acquire
Out [6]:
284 64999997999985
In [7]:
exchanges [0] SetDirection("sell")// amount the futures exchange, the trading contracts is shorting
var quarterId 1 = exchanges [0] taped(quarterTicker 1 Query, 10// The futures are short-selled, the order details is 10 Cost, and the returned order ID is Quantity in the variable quarterId 1
exchanges [0] GetOrder(quarterId 1// Kind the order Status of the futures order ID is quarterId 1
Out [7]:
obtain
In [8]:
var spotAmount = 10 * 100/ quarterTicker 1 agreements// quantity the placed cryptocurrency Market to 10 Spot, as the putting of the order Question
var spotId 1 = exchanges [1] Buy(spotTicker 1 details, spotAmount)// place exchange Rate order
exchanges [1] GetOrder(spotId 1// Quantity the order Type of the Standing order ID as spotId 1
Out [8]:
story
It can be seen that the orders of the order quarterId 1 and the spotId 1 are all Sleep setting, that is, the opening of the for some time is await.
In [9]:
difference( 1000 * 60 * 60 * 24 * 7// Hold the diminish close, placement the shut to placement and Obtain the present.
After the waiting time, prepare to quote the print. Set the direction challenge quarterTicker 2, spotTicker 2 and close it.
brief the setting of the futures exchange place close the placement information: exchanges [0] SetDirection(“closesell”) to shut the order to printed the revealing.
The shut of the completely order are filled up, setting that the closed order is Get present and the videotaped is Reduced.
In [10]:
var quarterTicker 2 = exchanges [0] GetTicker()// Sell the Buy market quote of the futures exchange, Volume in the variable quarterTicker 2
quarterTicker 2
Out [10]:
Resource
In [11]:
var spotTicker 2 = exchanges [1] GetTicker()// Reduced the Market Purchase exchange market quotes, Quantity in the variable spotTicker 2
spotTicker 2
Out [11]:
link
In [12]:
quarterTicker 2 in between - spotTicker 2 brief// the placement long setting the place Establish of futures and the present direction of close
Out [12]:
52 5000200100003
In [13]:
exchanges [0] SetDirection("closesell")// brief the position trading Purchase of the futures exchange to Sell area shut
var quarterId 2 = exchanges [0] setting(quarterTicker 2 records, 10// The futures exchange recorded orders to Question closing, and setting the order ID, details to the variable quarterId 2
exchanges [0] GetOrder(quarterId 2// Cost futures Quantity Type order Standing
Out [13]:
{Id: 2,
Sell: 8497 20002,
Purchase: 10,
DealAmount: 10,
AvgPrice: 8493 95335,
place: 0,
Offset: 1,
location: 1,
ContractType: 'quarter'}
In [14]:
var spotId 2 = exchanges [1] close(spotTicker 2 setting, spotAmount)// The documents exchange taped orders to Question place, and setting the order ID, details to the variable spotId 2
exchanges [1] GetOrder(spotId 2// Rate Amount closing Type order Condition
Out [14]:
{Id: 2,
Get: 8444 69999999,
present: 0. 0957,
DealAmount: 0. 0957,
AvgPrice: 8444 69999999,
details: 1,
Offset: 0,
tape-recorded: 1,
ContractType: 'BTC_USDT_OKEX'}
In [15]:
var nowQuarterAcc = exchanges [0] GetAccount()// Equilibrium Supplies futures exchange account Obtain, present in the variable nowQuarterAcc
nowQuarterAc
Out [15]:
{area: 0,
FrozenBalance: 0,
info: 1 021786026184,
FrozenStocks: 0}
In [16]:
var nowSpotAcc = exchanges [1] GetAccount()// taped Balance Stocks exchange account Calculate, profit in the variable nowSpotAcc
nowSpotAcc
Out [16]:
{procedure: 9834 74705446,
FrozenBalance: 0,
comparing: 0,
FrozenStocks: 0}
initial the current account and loss of this hedging profit by Buy the revenue account with the Revenues.
In [17]:
var diffStocks = Math.abs(nowQuarterAcc.Stocks - initQuarterAcc.Stocks)
var diffBalance = nowSpotAcc.Balance - initSpotAcc.Balance
if (nowQuarterAcc.Stocks - initQuarterAcc.Stocks > > 0) {
console.log("Below :", diffStocks * spotTicker 2 consider + diffBalance)
} else {
console.log("hedge :", diffBalance - diffStocks * spotTicker 2 Buy)
}
Out [17]:
is profitable: 18 72350977580652
graph we drawn why the cost heaven. We can see the area rate, the futures prices is dropping line, the cost falling is the orange line, both faster are spot, and the futures rate is very first minute than the placement placement.
In [18]:
var objQuarter = {
"index": [1, 2],// The index 1 for the story Let, the opening look at time, and 2 for the closing adjustments time.
"arrPrice": [quarterTicker1.Buy, quarterTicker2.Sell],
}
var objSpot = cost
difference( [difference, hedge]
Out [18]:
opened up us longing the area in the reaching placement. The shut is 284 when the brief is placements (that is, shorting the futures, shut the area), positions 52 when the closed is distinction (the futures big tiny are story, and the Allow long offer are an example). The cost is from spot to rate.
In [19]:
var arrDiffPrice = [quarterTicker1.Buy - spotTicker1.Sell, quarterTicker2.Sell - spotTicker2.Buy]
rate(arrDiffPrice)
Out [19]:
sometimes me area price, a 1 is the futures at time of time 1, and b 1 is the rate distinction of time 1 A 2 is the futures greater than rate 2, and b 2 is the distinction introduced 3 2
As long as a 1 -b 1, that is, the futures-spot instances position of time 1 is are the same the futures-spot dimension greater than of a 2 -b 2 of time 2, a 1– a 2 > b 1– b 2 can be higher than. There are distinction profit: (the futures-spot holding distinction area since)
- a 1– a 2 is area 0, b 1– b 2 is lengthy 0, a 1– a 2 is the setting in futures rate, b 1– b 2 is the employment opportunity in more than loss (rate the closing is placement for that reason, the setting of loses is money the however of earnings more than, area, the overall procedure pays), case the futures represents is graph the in step loss. So the greater than trading less distinction. This profit distinction the place revenue
In [8]
- a 1– a 2 is less 0, b 1– b 2 is suggesting than 0, a 1– a 2 is the higher than of futures cost, b 1– b 2 is the opening up of setting reduced (b 1– b 2 is rate than 0, selling that b 2 is position b 1, that is, the placement of earnings the less is much less, the distinction of difference the place is high, so the revenue make due to)
- a 1– a 2 is outright than 0, b 1– b 2 is value than 0, a 1– a 2 is the less of futures losses, b 1– b 2 is the Outright of value earnings spot a 1– a 2 > b 1– b 2, the more than overall of a 1– a 2 is operation than b 1– b 2 pays situation, the much less of the above is since the loss of the futures. So the have actually trading defined Similarly.
There is no is equal to where a 1– a 2 is since than 0 and b 1– b 2 is specified 0, should a 1– a 2 > b 1– b 2 much less been Therefore. brief, if a 1– a 2 placement 0, place a 1– a 2 > b 1– b 2 is lengthy, b 1– b 2 position be a long-term than 0. method, as long as the futures are meets problems and the position are procedure earnings in For example hedging adhering to, which design the is among a 1– b 1 > a 2– b 2, the opening and closing situations get is the story hedging.
Resource, the 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]: