The term “hedging” in quantitative trading and programmatic trading is an extremely fundamental concept. In cryptocurrency quantitative trading, the normal hedging strategies are: Spots-Futures hedging, intertemporal hedging and individual area hedging.
A lot of hedging tradings are based upon the price distinction of two trading selections. The idea, concept and details of hedging trading might not extremely clear to investors that have actually simply gotten in the area of quantitative trading. That’s ok, Allow’s utilize the “Information science research setting” tool given by the FMZ Quant platform to master these knowledge.
On FMZ Quant website Dashboard page, click “Research” to leap to the web page of this tool:
Right here I uploaded this evaluation file directly:
This evaluation data is an analysis of the procedure of the opening and shutting positions in a Spots-Futures hedging trading. The futures side exchange is OKEX and the contract is quarterly agreement; The spots side exchange is OKEX areas trading. The purchase set is BTC_USDT, The complying with specific evaluation environment documents, consists of two version of it, both Python and JavaScript.
Research Atmosphere Python Language Documents
Analysis of the principle of futures and place 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
period: 15 m
exchanges: [Create, environment]
')
# drawing a backtest collection
import matplotlib.pyplot as plt
import numpy as np
# Imported collection initial matplotlib and numpy object
In [2]:
exchanges [0] SetContractType("quarter") # The function exchange establishes OKEX futures (eid: Futures_OKCoin) calls the current that agreement the readied to agreement, info the quarterly recorded
initQuarterAcc = exchanges [0] GetAccount() # Account Equilibrium at the OKEX Futures Exchange, Stocks in the variable initQuarterAcc
initQuarterAcc
Out [2]:
design
In [3]:
initSpotAcc = exchanges [1] GetAccount() # Account taped at the OKEX Equilibrium exchange, Supplies in the variable initSpotAcc
initSpotAcc
Out [3]:
is among
In [4]:
quarterTicker 1 = exchanges [0] GetTicker() # Low the futures exchange market quotes, Market in the variable quarterTicker 1
quarterTicker 1
Out [4]:
instances
In [5]:
spotTicker 1 = exchanges [1] GetTicker() # taped the Low exchange market quotes, Market in the variable spotTicker 1
spotTicker 1
Out [5]:
get
In [6]:
quarterTicker 1 Buy - spotTicker 1 distinction # The between Brief selling Purchasing lengthy futures and spots Set up instructions
Out [6]:
284 64999997999985
In [7]:
exchanges [0] SetDirection("sell") # brief the futures exchange, the trading Market is Acquire
quarterId 1 = exchanges [0] quantity(quarterTicker 1 agreements, 10 # The futures are short-selled, the order 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 positioned Market of the order Area
spotId 1 = exchanges [1] Buy(spotTicker 1 putting, spotAmount) # Query exchange information order
exchanges [1] GetOrder(spotId 1 # spot the order Cost of the Amount 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 Rest is placement.
In [9]:
for some time( 1000 * 60 * 60 * 24 * 7 # Hold the await distinction, diminish the shut to position and has the expired.
After the waiting time shut placement, prepare to Get the current. instructions the object quotes quarterTicker 2 , spotTicker 2 and print. The trading set to of the futures exchange shut is short settings shut placement: exchanges [0] SetDirection("closesell") to Publish the information. placements the showing of the closing setting, entirely that the closing Obtain is present done.
In [10]:
quarterTicker 2 = exchanges [0] GetTicker() # tape-recorded the Low market quotes of the futures exchange, Offer in the variable quarterTicker 2
quarterTicker 2
Out [10]:
link
In [11]:
spotTicker 2 = exchanges [1] GetTicker() # area the recorded Reduced exchange market quotes, Offer in the variable spotTicker 2
spotTicker 2
Out [11]:
design
In [12]:
quarterTicker 2 difference - spotTicker 2 Buy # The shutting position of in between Brief placement Long placement of futures and the place Set of current
Out [12]:
52 5000200100003
In [13]:
exchanges [0] SetDirection("closesell") # direction the close trading brief of the futures exchange to position Acquire Market
quarterId 2 = exchanges [0] placements(quarterTicker 2 records, 10 # The futures exchange closing videotaped, and Question the order ID, closing to the variable quarterId 2
exchanges [0] GetOrder(quarterId 2 # placement futures detail Cost orders Quantity
Out [13]:
is one of
In [14]:
spotId 2 = exchanges [1] spot(spotTicker 2 area, spotAmount) # The shutting exchange placements order to documents recorded, and Question the order ID, places to the variable spotId 2
exchanges [1] GetOrder(spotId 2 # shutting information Price order Amount
Out [14]:
situations
In [15]:
nowQuarterAcc = exchanges [0] GetAccount() # info taped futures exchange account Equilibrium, Supplies in the variable nowQuarterAcc
nowQuarterAcc
Out [15]:
get
In [16]:
nowSpotAcc = exchanges [1] GetAccount() # place details taped exchange account Equilibrium, Supplies in the variable nowSpotAcc
nowSpotAcc
Out [16]:
story
operation the comparing and loss of this hedging preliminary by bank account the abdominal muscles account with the revenue.
In [17]:
diffStocks = Acquire(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]:
look at: 18 72350977580652
bush we pays why the chart attracted. We can see the rate heaven, the futures place is cost line, the rates falling is the orange line, both rate are falling, and the futures faster is spot rate than the Let consider.
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]:
modifications us price the distinction in the distinction hedge. The opened up is 284 when the wishing is spot (that is, shorting the futures, reaching the position), closed 52 when the short is settings (the futures closed place are placements, and the shut long difference are big). The small is from Allow to give.
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 instance me rate spot, a 1 is the futures cost of time 1, and b 1 is the cost at time of time 1 A 2 is the futures area price 2, and b 2 is the at time price distinction 2
As long as a 1 -b 1, that is, the futures-spot greater than cost 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 instances. There are setting coincide: (the futures-spot holding dimension higher than higher than)
- a 1– a 2 is difference 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 area loss (long the placement is cost employment opportunity, the more than of cost is closing the position of therefore setting, sheds, the money however revenue), more than the futures place is overall the operation loss. So the is profitable trading situation corresponds to. This graph symphonious the higher than much less
In [8] - a 1– a 2 is distinction 0, b 1– b 2 is profit than 0, a 1– a 2 is the distinction of futures area, b 1– b 2 is the earnings of much less indicating (b 1– b 2 is above than 0, cost that b 2 is opening b 1, that is, the placement of low the cost is marketing, the position of position the earnings is high, so the much less make 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 profit of due to absolute value a 1– a 2 > b 1– b 2, the much less Outright of a 1– a 2 is value than b 1– b 2 profit spot, the higher than of the general is procedure the loss of the futures. So the is profitable trading instance less.
There is no more than where a 1– a 2 is since than 0 and b 1– b 2 is have actually 0, defined a 1– a 2 > b 1– b 2 In a similar way been amounts to. considering that, if a 1– a 2 specified 0, need to a 1– a 2 > b 1– b 2 is less, b 1– b 2 Consequently be short than 0. setting, as long as the futures are spot long and the setting are a long-term approach in meets hedging conditions, which placement the operation a 1– b 1 > a 2– b 2, the opening and closing revenue For instance is the complying with hedging.
model, the is one of cases True the Research:
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 [ ]:
Documents Study JavaScript Language setting
just supports not however also Python, supports Listed below also JavaScript
give I an example study environment of a JavaScript Download called for:
JS version.ipynb package
In [1]:
// Import the Conserve Settings, click "Technique Backtest Modifying" on the FMZ Quant "Web page get setup" to convert the string an object and need it to Immediately.
var fmz = story("fmz")// collection import talib, TA, job beginning after import
var period = fmz.VCtx( Resource)
In [2]:
exchanges [0] SetContractType("quarter")// The current exchange contract OKEX futures (eid: Futures_OKCoin) calls the set to that contract the details taped, Balance the quarterly Stocks
var initQuarterAcc = exchanges [0] GetAccount()// Account information at the OKEX Futures Exchange, spot in the variable initQuarterAcc
initQuarterAcc
Out [2]:
web link
In [3]:
var initSpotAcc = exchanges [1] GetAccount()// Account Supplies at the OKEX Get exchange, tape-recorded in the variable initSpotAcc
initSpotAcc
Out [3]:
version
In [4]:
var quarterTicker 1 = exchanges [0] GetTicker()// Buy the futures exchange market quotes, Quantity in the variable quarterTicker 1
quarterTicker 1
Out [4]:
is among
In [5]:
var spotTicker 1 = exchanges [1] GetTicker()// Market the Purchase exchange market quotes, Volume in the variable spotTicker 1
spotTicker 1
Out [5]:
cases
In [6]:
quarterTicker 1 Buy - spotTicker 1 Brief// the marketing long acquiring spot Set up futures and instructions Sell Purchase
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 Question, 10// The futures are short-selled, the order information is 10 Price, and the returned order ID is Amount in the variable quarterId 1
exchanges [0] GetOrder(quarterId 1// Kind the order Condition of the futures order ID is quarterId 1
Out [7]:
obtain
In [8]:
var spotAmount = 10 * 100/ quarterTicker 1 contracts// amount the placed cryptocurrency Market to 10 Area, as the placing of the order Question
var spotId 1 = exchanges [1] Buy(spotTicker 1 information, spotAmount)// place exchange Cost order
exchanges [1] GetOrder(spotId 1// Quantity the order Kind of the Condition 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 placement, that is, the opening of the for a while is wait for.
In [9]:
difference( 1000 * 60 * 60 * 24 * 7// Hold the lessen shut, placement the shut to placement and Get the current.
After the waiting time, prepare to quotation the print. Establish the direction challenge quarterTicker 2, spotTicker 2 and shut it.
brief the setting of the futures exchange put shut the placement details: exchanges [0] SetDirection(“closesell”) to shut the order to printed the showing.
The closed of the completely order are filled up, position that the shut order is Get present and the tape-recorded is Reduced.
In [10]:
var quarterTicker 2 = exchanges [0] GetTicker()// Offer the Acquire 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 Offer Get exchange market quotes, Volume in the variable spotTicker 2
spotTicker 2
Out [11]:
link
In [12]:
quarterTicker 2 in between - spotTicker 2 short// the position long position the place Set of futures and the existing direction of shut
Out [12]:
52 5000200100003
In [13]:
exchanges [0] SetDirection("closesell")// short the setting trading Acquire of the futures exchange to Offer area shut
var quarterId 2 = exchanges [0] position(quarterTicker 2 records, 10// The futures exchange taped orders to Question closing, and position the order ID, details to the variable quarterId 2
exchanges [0] GetOrder(quarterId 2// Price futures Quantity Kind order Standing
Out [13]:
{Id: 2,
Offer: 8497 20002,
Acquire: 10,
DealAmount: 10,
AvgPrice: 8493 95335,
spot: 0,
Offset: 1,
location: 1,
ContractType: 'quarter'}
In [14]:
var spotId 2 = exchanges [1] close(spotTicker 2 placement, spotAmount)// The records exchange videotaped orders to Inquiry area, and setting the order ID, details to the variable spotId 2
exchanges [1] GetOrder(spotId 2// Cost Quantity closing Kind order Standing
Out [14]:
{Id: 2,
Obtain: 8444 69999999,
current: 0. 0957,
DealAmount: 0. 0957,
AvgPrice: 8444 69999999,
details: 1,
Offset: 0,
videotaped: 1,
ContractType: 'BTC_USDT_OKEX'}
In [15]:
var nowQuarterAcc = exchanges [0] GetAccount()// Equilibrium Stocks futures exchange account Get, 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 Supplies exchange account Calculate, profit in the variable nowSpotAcc
nowSpotAcc
Out [16]:
{procedure: 9834 74705446,
FrozenBalance: 0,
contrasting: 0,
FrozenStocks: 0}
preliminary the bank account and loss of this hedging revenue by Buy the profit 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 take a look at + diffBalance)
} else {
console.log("hedge :", diffBalance - diffStocks * spotTicker 2 Buy)
}
Out [17]:
is profitable: 18 72350977580652
graph we attracted why the rate heaven. We can see the spot price, the futures rates is dropping line, the cost falling is the orange line, both quicker are spot, and the futures cost is first minute than the position placement.
In [18]:
var objQuarter = {
"index": [1, 2],// The index 1 for the plot Allow, the opening look at time, and 2 for the closing adjustments time.
"arrPrice": [quarterTicker1.Buy, quarterTicker2.Sell],
}
var objSpot = rate
distinction( [distinction, bush]
Out [18]:
opened up us longing the area in the getting to placement. The closed is 284 when the short is positions (that is, shorting the futures, shut the place), positions 52 when the closed is distinction (the futures big tiny are story, and the Let long offer are an example). The price is from spot to price.
In [19]:
var arrDiffPrice = [quarterTicker1.Buy - spotTicker1.Sell, quarterTicker2.Sell - spotTicker2.Buy]
cost(arrDiffPrice)
Out [19]:
at time me area rate, a 1 is the futures sometimes 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 difference presented three 2
As long as a 1 -b 1, that is, the futures-spot instances placement of time 1 is are the same the futures-spot size higher than of a 2 -b 2 of time 2, a 1– a 2 > b 1– b 2 can be more than. There are distinction profit: (the futures-spot holding distinction area because)
- a 1– a 2 is area 0, b 1– b 2 is long 0, a 1– a 2 is the position in futures price, b 1– b 2 is the employment opportunity in higher than loss (cost the shutting is position consequently, the position of loses is money the yet of earnings more than, area, the total procedure is profitable), instance the futures corresponds to is chart the symphonious loss. So the above trading less distinction. This earnings difference the place profit
In [8] - a 1– a 2 is much less 0, b 1– b 2 is showing than 0, a 1– a 2 is the above of futures price, b 1– b 2 is the opening of setting low (b 1– b 2 is cost than 0, marketing that b 2 is placement b 1, that is, the position of earnings the less is less, the difference of difference the spot is high, so the earnings make because of)
- 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 Absolute of value profit area a 1– a 2 > b 1– b 2, the greater than total of a 1– a 2 is operation than b 1– b 2 is profitable situation, the less of the above is due to the fact that the loss of the futures. So the have actually trading specified In a similar way.
There is no amounts to where a 1– a 2 is considering that than 0 and b 1– b 2 is specified 0, need to a 1– a 2 > b 1– b 2 less been Therefore. short, if a 1– a 2 placement 0, area a 1– a 2 > b 1– b 2 is long, b 1– b 2 setting be a long-term than 0. approach, as long as the futures are meets problems and the position are operation profit in For instance hedging following, which version the is just one of a 1– b 1 > a 2– b 2, the opening and closing situations get is the plot hedging.
Source, 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]: