OPEN-SOURCE SCRIPT

Intramarket Difference Index Strategy

Di Amjad_S
Intramarket Difference Indicator (IDI) Strategy:

In layman’s terms this strategy compares two indicators across (correlated) markets and exploits their differences.

📍 Import Notes:

  • This Strategy calculates trade position size independently, this means that the ‘Order size’ input in the ‘Properties’ tab will have no effect on the strategy. Why ? because this allows us to define custom position size algorithms which we can use to improve our risk management and equity growth over time. Here we have the option to have fixed quantity or fixed percentage of equity ATR (Average True Range) based stops in addition to the turtle trading position size algorithm.
  • ‘Pyramiding’ does not work for this strategy’, similar to the order size input togeling this input will have no effect on the strategy as the strategy explicitly defines the maximum order size to be 1.
  • This strategy is not perfect, and as of writing of this post I have not traded this algo.
  • Always take your time to backtests and debug the strategy.


🔷 The IDI Strategy:

By default this strategy pulls data from your current TV chart and then compares it to the base market, be default BTCUSD . The strategy pulls SMA and RSI data from either market (we call this the difference data), standardizes the data (solving the different unit problem across markets) such that it is comparable and then differentiates the data, calling the result of this transformation and difference the Intramarket Difference (ID). The formula for the the ID is

ID = market1_diff_data - market2_diff_data (1)

Where

market(i)_diff_data = diff_data / ATR(j)_market(i)^0.5,

where i = {1, 2} and j = the natural numbers excluding 0

Formula (1) interpretation is the following
  1. When ID > 0: this means the current market outperforms the base market
  2. When ID = 0: Markets are at long run equilibrium
  3. When ID < 0: this means the current market underperforms the base market


To form the strategy we define one of two strategy type’s which are Trend and Mean Revesion respectively.

🔸 Trend Case:

Given the ‘‘Strategy Type’’ is equal to TREND we define a threshold for which if the ID crosses over we go long and if the ID crosses under the negative of the threshold we go short.

The motivating idea is that the ID is an indicator of the two symbols being out of sync, and given we know volatility clustering, momentum and mean reversion of anomalies to be a stylised fact of financial data we can construct a trading premise. Let's first talk more about this premise.

For some markets (cryptocurrency markets - synthetic symbols in TV) the stylised fact of momentum is true, this means that higher momentum is followed by higher momentum, and given we know momentum to be a vector quantity (with magnitude and direction) this momentum can be both positive and negative i.e. when the ID crosses above some threshold we make an assumption it will continue in that direction for some time before executing back to its long run equilibrium of 0 which is a reasonable assumption to make if the market are correlated. For example for the BTCUSD - ETHUSD pair, if the ID > +threshold (inputs for MA and RSI based ID thresholds are found under the ‘‘INTRAMARKET DIFFERENCE INDEX’’ group’), ETHUSD outperforms BTCUSD, we assume the momentum to continue so we go long ETHUSD.

In the standard case we would exit the market when the IDI returns to its long run equilibrium of 0 (for the positive case the ID may return to 0 because ETH’s difference data may have decreased or BTC’s difference data may have increased). However in this strategy we will not define this as our exit condition, why ?

This is because we want to ‘‘let our winners run’’, to achieve this we define a trailing Donchian Channel stop loss (along with a fixed ATR based stop as our volatility proxy). If we were too use the 0 exit the strategy may print a buy signal (ID > +threshold in the simple case, market regimes may be used), return to 0 and then print another buy signal, and this process can loop may times, this high trade frequency means we fail capture the entire market move lowering our profit, furthermore on lower time frames this high trade frequencies mean we pay more transaction costs (due to price slippage, commission and big-ask spread) which means less profit.

Note it is possible that after printing a buy the strategy then prints many sell signals before returning to a buy, which again has the same implications. The image below showcases the theory above, by allowing our winner to run we may capture more profit.

istantanea
Valid trades are denoted by solid green and red arrows respectively and all other valid trades which occur within the original signal are light green and red small arrows, if we were to close our trades when the IDI returns to its equilibrium of 0 our average bars per trade would be very low and we would not capture the general trend.

Note by capturing the sum of many momentum moves we are essentially following the trend hence the trend following strategy type.

istantanea
Here we also print the IDI (with default strategy settings with the MA difference type), we can see that by letting our winners run we may catch many valid momentum moves, that results in a larger final pnl that if we would otherwise exit based on the equilibrium condition.

Note if you would like to plot the IDI separately copy and paste the following code in a new Pine Script indicator template.



🔸 Mean Reversion Case:

We stated prior that mean reversion of anomalies is an standerdies fact of financial data, how can we exploit this ?

We exploit this by normalizing the ID by applying the Ehlers fisher transformation. We now assume our series is approximately normally distributed. To form the strategy we employ the same logic as for e the z score, if the FT normalized ID >< 2.5 or -2.5 respectively we buy or short respectively. We also employ the same exit conditions (fixed ATR stop and trailing Donchian Trailing stop)

🔷 Position Sizing:

If ‘‘Fixed Risk From Initial Balance’’ is toggled true this means we risk a fixed percentage of our initial balance, if false we risk a fixed percentage of our equity (current balance).

Note we also employ a volatility adjusted position sizing formula, the turtle training method which is defined as follows.

Turtle position size = (1/ r * ATR * DV) * C

Where,
r = risk factor coefficient (default is 20)
ATR(j) = risk proxy, over j times steps
DV = Dollar Volatility, where DV = (1/Asset Price) * Capital at Risk

🔷 Risk Management:

Correct money management means we can limit risk and increase reward (theoretically). Here we employ
  1. Max loss and gain per day
  2. Max loss per trade
  3. Max number of consecutive losing trades until trade skip

To read more see the tooltips (info circle).

Note the ATR stop losses and take profits are defined, with the prior being default.

istantanea
ATR SL and TP defined

🔷 Hurst Regime (Regime Filter):

The Hurst Exponent (H) aims to segment the market into three different states, Trending (H > 0.5), Random Geometric Brownian Motion (H = 0.5) and Mean Reverting / Contrarian (H < 0.5). In my interpretation this can be used as a trend filter that eliminates market noise.

We utilize the trending and mean reverting based states, as extra conditions required for valid trades both strategy types respectively, in the process increasing our trade entry quality.

🔷 Example model Architecture:

Here is an example of one configuration of this strategy, combining all aspect discussed in this post.

istantanea
ATRdonchainchannelmeanreversionmomentumindicatormovingavarageMoving Averagesrelative-strength-indexRelative Strength Index (RSI)riskmanagmentstrategyTrend Analysistrendfollowing

Script open-source

In pieno spirito TradingView, l'autore di questo script lo ha pubblicato open-source, in modo che i trader possano comprenderlo e verificarlo. Un saluto all'autore! È possibile utilizzarlo gratuitamente, ma il riutilizzo di questo codice in una pubblicazione è regolato dal nostro Regolamento. Per aggiungerlo al grafico, mettilo tra i preferiti.

Vuoi usare questo script sui tuoi grafici?

Declinazione di responsabilità