OPEN-SOURCE SCRIPT

Intramarket Difference Index Strategy

Hi Traders !!

The IDI Strategy:

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

note: it is best the two markets are correlated as then we know we are trading a short to long term deviation from both markets' general trend with the assumption both markets will trend again sometime in the future thereby exhausting our trading opportunity.

📍 Import Notes:

  • This Strategy calculates trade position size independently (i.e. risk per trade is controlled in the user inputs tab), 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.

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

ảnh chụp nhanh
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(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).

another example...
ảnh chụp nhanh

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


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 implication (less profit. Potentially because we exit early only for price to continue upwards hence missing the larger "trend"). The image below showcases this cenario and again, by allowing our winner to run we may capture more profit (theoretically).

This should be clear...
ảnh chụp nhanh

🔸 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. The transformed data is then assumed to be approximately normally distributed. To form the strategy we employ the same logic as for the z score, if the FT normalized ID > 2.5 (< -2.5) we buy (short). Our exit conditions remain unchanged (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).

🔷 Take Profit:

By defualt the script uses a Donchain Channel as a trailing stop and take profit, In addition to this the script defines a fixed ATR stop losses (by defualt, this covers cases where the DC range may be to wide making a fixed ATR stop usefull), ATR take profits however are defined but optional.

ảnh chụp nhanh
ATR SL and TP defined for all trades

🔷 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 for 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 aspects discussed in this post.

ảnh chụp nhanh

Future Updates

- Automation integration (next update)
ATRdonchainchannelmeanreversionmomentumindicatormovingavarageMoving Averagesrelative-strength-indexRelative Strength Index (RSI)riskmanagmentstrategyTrend Analysistrendfollowing

Mã nguồn mở

Theo tinh thần TradingView thực sự, tác giả của tập lệnh này đã xuất bản dưới dạng nguồn mở để các nhà giao dịch có thể hiểu và xác minh. Chúc mừng tác giả! Bạn có thể sử dụng miễn phí. Tuy nhiên, bạn cần sử dụng lại mã này theo Quy tắc nội bộ. Bạn có thể yêu thích nó để sử dụng nó trên biểu đồ.

Bạn muốn sử dụng tập lệnh này trên biểu đồ?


Ngoài ra, trên:

Thông báo miễn trừ trách nhiệm