Div-to-Div CCI Strategy: Catch the Divergences on Autopilot

The provided algorithm implements a trading strategy known as the Div-to-Div CCI Strategy. This is a momentum-based, mean-reversion strategy that operates on the principle of detecting divergences between the price action of an asset and the Commodity Channel Index (CCI) oscillator. The key advantage of this strategy, which distinguishes it from traditional CCI algorithms, is its ability to capture extended market moves from one divergence to the opposite one.

The core idea of the Div-to-Div CCI Strategy is to identify potential reversal points in the market by spotting moments when the price is making a new extreme but the momentum, as measured by the CCI, is failing to confirm that extreme. This discrepancy, known as a divergence, suggests that the prevailing trend is weakening and a price reversal is likely.

The Div-to-Div CCI Strategy is designed to be systematic, removing emotional decision-making from trading by providing clear, rule-based entry and exit signals. It is particularly popular among traders who seek to capitalize on trend exhaustion and the subsequent corrective moves.

Principle of Operation

The fundamental principle behind the Div-to-Div CCI Strategy is the concept of divergence. In technical analysis, divergence occurs when the price of an asset moves in the opposite direction of a technical indicator. This strategy specifically hunts for two types of divergences: bullish and bearish.

A bullish divergence forms when the price records a lower low, but the CCI indicator forms a higher low. This indicates that while the selling pressure is pushing the price to a new low, the underlying momentum of the downtrend is waning, and buyers are starting to step in.

DIV-TO-DIV-CCI Strategy bullish divergence

Conversely, a bearish divergence occurs when the price makes a higher high, but the CCI indicator makes a lower high. This signals that the buying force behind the upward move is deteriorating, and sellers are likely to take control soon.

The Div-to-Div CCI Strategy systematically scans for these patterns over a user-defined lookback period. Upon detecting a valid divergence, the strategy generates an entry signal. To manage risk, it employs a volatility-based stop-loss calculated using the Average True Range (ATR), which places the stop loss at a distance proportional to recent market volatility.

An optional Exponential Moving Average (EMA) filter can be applied to ensure that trades are only taken in the direction of the broader short-term trend, thereby increasing the probability of success by filtering out counter-trend signals in a strong trending market.

What is CCI?

The Commodity Channel Index (CCI) is a versatile momentum oscillator developed by Donald Lambert. It is used to identify cyclical trends in a security, as well as to gauge overbought and oversold conditions. The CCI calculates the difference between the current price and its historical average price, normalized by the mean deviation.

The formula is:

CCI = (Typical Price – Simple Moving Average of Typical Price) / (0.015 * Mean Deviation)

Typical Price is the average of the high, low, and close of each bar. The constant 0.015 is used to ensure that approximately 70% to 80% of the CCI values fall between -100 and +100. While traditional usage interprets readings above +100 as overbought (potential sell signal) and readings below -100 as oversold (potential buy signal), the Div-to-Div CCI Strategy uses the CCI not for its absolute levels but for the shape and direction of its curve relative to the price. This allows the strategy to identify momentum shifts that are not yet apparent in the price action alone.

What is CCI Divergence?

CCI divergence is the cornerstone of the Div-to-Div CCI Strategy. It is a powerful technical analysis concept that highlights a disagreement between the price movement and the momentum shown by the CCI oscillator. This disagreement often foreshadows a potential trend reversal. There are two primary types of CCI divergence that the strategy seeks to exploit.

The first is CCI bullish divergence. This occurs when the price of an asset forms a lower low on the chart, but simultaneously, the CCI indicator forms a higher low. This is a classic sign of selling pressure exhaustion. Even though the price is dropping to a new low, the momentum of the decline is not as strong as it was during the previous low, indicating that bears are losing control and a bullish reversal may be imminent.

The second type is bearish divergence, which is the exact opposite. A bearish CCI divergence forms when the price makes a higher high, but the CCI indicator makes a lower high. This suggests that the buying momentum is weakening despite the price reaching a new peak. It signals that the uptrend is running out of steam and a bearish reversal could be on the horizon. The CCI divergence indicator within the strategy automates the detection of these patterns, scanning a specified number of bars into the past to find these significant swing points.

DIV-TO-DIV-CCI Strategy bearish divergence

Key Feature

The main advantage of this strategy over traditional CCI methods is capturing long market swings from one divergence to the next.

The significant and defining feature of the Div-to-Div CCI Strategy is its sole reliance on the automated detection of CCI divergence for trade initiation. Unlike many strategies that use a confluence of multiple indicators, the core engine of the Div-to-Div CCI Strategy is the identification of the divergence pattern itself. This makes it a pure momentum-reversal system.

Its robustness is further enhanced by two key components: an integrated, volatility-adjusted stop-loss mechanism and an optional trend filter. The ATR-based stop-loss ensures that risk is managed in proportion to the market’s current noise level, protecting capital during periods of high volatility.

Risk management in this strategy does not function in the classical sense of traditional trading. The stop-loss does not serve as the primary exit mechanism. Instead, it acts as a secondary safety fuse, designed to protect the account from sharp, extended market moves against the position. This is because the script’s logic typically closes positions faster when a new, opposite divergence signal appears. As backtesting results demonstrate, the stop-loss is triggered extremely rarely, underscoring its role as a final safeguard rather than a core component of the exit strategy.

The optional EMA filter adds a layer of trend confirmation, helping the strategy to avoid taking counter-trend divergence signals that are likely to fail in a strongly trending market. This combination of a clear trigger (divergence), a disciplined risk management tool (ATR stop), and a contextual filter (EMA) makes the Div-to-Div CCI Strategy a sophisticated and systematic approach to trading.

Components Used

CCI divergence indicator

The Div-to-Div CCI Strategy is built using several key technical components that work in concert. The primary component is the CCI divergence indicator, which is the core signal generator. It calculates the CCI values and then implements functions to identify swing highs and swing lows in both the price and the CCI line over a defined lookback period.

DIV-TO-DIV-CCI Strategy CCI Indicator

ATR-based stop-loss

The second crucial component is the Average True Range (ATR), which is used for risk management. The ATR measures market volatility by calculating the average range of price movement over a specified period. In this strategy, the ATR is multiplied by a user-defined factor (e.g., 4.0) to set a dynamic stop-loss level that adapts to current market conditions.

EMA-based trend filter

The third component is an optional Exponential Moving Average (EMA), which acts as a trend filter. When enabled, this filter ensures that long positions are only considered when the price is above the EMA (bullish trend) and short positions are only considered when the price is below the EMA (bearish trend). This helps to align the trades with the short-term trend.

Finally, the strategy’s logic includes a position management component that automatically closes all open positions before entering a new one, ensuring that only one trade (either long or short) is active at any given time.

Programming Language and Usage

The Div-to-Div CCI Strategy is written in Pine Script, which is a domain-specific programming language developed by TradingView. Pine Script is specifically designed for creating custom technical indicators and strategies that can be backtested and visualized directly on TradingView’s charting platform.

Its syntax is relatively straightforward, making it accessible for programmers and technically-minded traders to create, modify, and experiment with their own trading ideas. To use this strategy, a trader simply needs to copy the Pine Script code and paste it into the Pine Editor on the TradingView website. After saving and adding the script to a chart, it will automatically plot the entries, exits, and background coloring based on the active position.

Traders can visually assess the performance of the Div-to-Div CCI Strategy on historical data and observe its signals in real-time. The input parameters, such as CCI length, divergence lookback, and ATR multiplier, can be easily customized through the strategy’s settings menu to adapt it to different assets and trading styles.

Backtesting and Automation

Backtesting in TradingView is a seamless process for the Div-to-Div CCI Strategy. Once the script is added to a chart, TradingView’s built-in strategy tester can be used to conduct a comprehensive backtest. The strategy tester provides a detailed performance report, including metrics like net profit, drawdown, number of trades, win rate, and profit factor. This allows traders to evaluate the historical effectiveness of the Div-to-Div CCI Strategy on any traded instrument and timeframe, enabling them to optimize parameters and assess viability before risking real capital.

Furthermore, the strategy can be fully automated, moving from the realm of discretionary trading into the domain of algotrading. Algorithmic trading strategies like this one are ideal for automation as they are based on unambiguous, programmatic rules. Automation can be achieved in two primary ways.

The first method is directly through TradingView using its integrated alerts and webhook functionality. An alert can be set up on the strategy to trigger a webhook URL whenever an entry or exit signal is generated. This webhook can be connected to a supported exchange that executes the trades automatically.

The second method involves using third-party auto trading platforms. These platforms act as intermediaries, connecting TradingView alerts to a wide range of brokers and exchanges. They parse the alert message from the Div-to-Div CCI Strategy and automatically send the corresponding buy or sell order to the trader’s brokerage account, enabling a completely hands-free trading experience.

Visualization Implementation

The visualization of the Div-to-Div CCI Strategy on the TradingView chart is implemented to be clear and intuitive.

DIV-TO-DIV-CCI Strategy chart

  • The primary visual cue is the background color of the chart itself, which is dynamically changed based on the strategy’s current market position.
  • When the strategy holds a long position, the chart background is tinted a light green. When a short position is held, the background is tinted a light red. When the strategy is out of the market, the background remains its default color, typically a light gray. This provides an immediate, at-a-glance understanding of the strategy’s stance.
  • Furthermore, the strategy’s entry and exit points are explicitly plotted on the price chart. Long entry signals are typically marked with a “Long” label and a corresponding arrow below the price bar, while short entry signals are marked with a “Short” label and an arrow above the price bar.
  • The stop-loss levels for each position are also calculated and could be visualized, although in the provided code they are used for exit logic without being plotted.

This comprehensive visual feedback allows the trader to quickly analyze the strategy’s behavior, understand its decision-making process, and monitor its performance in real-time without needing to interpret the underlying code.

Entry and Exit Process

The entry and exit process for the Div-to-Div CCI Strategy is governed by a strict set of rules. A trade entry is triggered solely by the detection of a valid divergence signal. For a long entry, the strategy must identify a bullish CCI divergence (price lower low, CCI higher low). If the EMA filter is enabled, it also requires that the current closing price is above the EMA to confirm a short-term bullish trend.

Conversely, for a short entry, a bearish CCI divergence (price higher high, CCI lower high) must be identified, and if the filter is on, the price must be below the EMA. A critical part of the entry logic is that the strategy closes any existing position before opening a new one. This means the strategy will never be simultaneously long and short, and a new divergence signal will always flatten the position before initiating a new trade in the opposite direction.

Upon entry, a stop-loss order is immediately placed. For long positions, the stop loss is set at a level below the entry price, calculated as close - (atr * atrMultiplier). For short positions, the stop loss is set above the entry price at close + (atr * atrMultiplier).

The exit from a trade occurs in one of two ways: either when a new opposing divergence signal closes the position, or when the stop-loss level is hit, limiting the loss on the trade.

Default Settings

The Div-to-Div CCI Strategy comes with a set of thoughtfully chosen default parameters that provide a balanced starting point for most assets.

DIV-TO-DIV-CCI Strategy pine script inputs

  • The CCI Length is set to 15 periods, which is a standard setting that provides a responsive yet smooth momentum reading.
  • The “Bars to Look Back for Divergence” is set to 6, meaning the strategy will compare the current swing point to the one that occurred 6 bars ago to identify the divergence pattern.
  • For risk management, the ATR Length is set to 14 (another industry standard), and the ATR Multiplier is set to 4.0. This multiplier is relatively wide, aiming to account for normal market volatility and avoid being stopped out by minor price fluctuations.
  • The EMA Trend Filter is enabled by default with a short period of 3, which helps to align trades with a very recent and strong short-term trend.

These default settings for the Div-to-Div CCI Strategy are not universal and should be considered a template. They must be optimized and fine-tuned through rigorous backtesting to suit the specific volatility and characteristics of the asset being traded, be it forex, stocks, or cryptocurrencies.

Performance on Higher Timeframes

The Div-to-Div CCI Strategy tends to perform more reliably on timeframes of one hour (H1) and above for several fundamental reasons. Firstly, higher timeframes, such as H1, H4, and Daily, contain more data per bar and are less susceptible to market noise, false signals, and the “whipsaw” action that is prevalent on lower timeframes like 1-minute or 5-minute charts. The signals generated by the CCI divergence indicator on these higher timeframes are generally stronger and more significant because they represent a longer period of market consensus and a more substantial shift in momentum.

Secondly, the economic rationale behind a divergence has more time to play out. A divergence spotted on a daily chart suggests a potential multi-day or multi-week reversal, allowing the new trend ample time to develop and capture a substantial move.

On a lower timeframe, a divergence might only predict a reversal that lasts for a few minutes, which may not be sufficient to overcome trading spreads and commissions. The wider ATR stop-loss used in the Div-to-Div CCI Strategy is also more appropriate for higher timeframes, as the volatility it measures is more meaningful and less erratic, resulting in more consistent risk management.

How to Conduct a Backtest

Conducting a backtest for the Div-to-Div CCI Strategy on TradingView is a straightforward process that is crucial for validating its performance.

DIV-TO-DIV-CCI Strategy pine script

  • To begin, open the asset chart you wish to test on TradingView.
  • Then, open the Pine Editor, paste the complete strategy code, and save it.
  • The strategy, named “Script_Algo – Div-to-Div CCI Strategy,” will now appear on your chart.
  • Next, navigate to the “Strategy Tester” tab, which is usually located at the bottom of the TradingView interface.

Here, you will see a list of available strategies; select the Div-to-Div CCI Strategy. The strategy tester will then populate a detailed performance report based on the visible data on your chart. It is advisable to ensure your chart covers a significant period of historical data, ideally several years, to include various market conditions (bull markets, bear markets, and sideways markets).

The report will provide key metrics such as total net profit, maximum drawdown, number of trades, win rate, and profit factor. You can adjust the input parameters of the strategy and re-run the backtest to see how different settings affect its performance, a process known as optimization. This rigorous backtesting in TradingView is an indispensable step before committing any real capital to the Div-to-Div CCI Strategy.

Through the selection of input parameters, optimal backtesting results can be achieved. Empirically, the following parameters were selected for the DOT coin:

DIV-TO-DIV-CCI Strategy backtest setting inputs
DIV-TO-DIV-CCI Strategy backtest setting capital

As can be seen in the screenshot below, backtesting results for the DOTUSDT cryptocurrency pair over a 20-month period on the 1-hour timeframe demonstrated the following performance:

DIV-TO-DIV-CCI Strategy backtest results

27% profit with 4% maximum drawdown. The strategy executed 128 trades52% of which were profitable. The profit factor reached nearly 2.0.

Testing and evaluating the results using the example of the High Low Range MA Trading Strategy is described in detail in our article How to Backtest TradingView Strategy: Step-by-Step Guide with a Real Example.

How to automate Div-to-Div CCI Strategy

Automation via TradingView Webhooks

Automating the Div-to-Div CCI Strategy directly through TradingView webhooks involves creating alert-based triggers that communicate with an external execution service, such as Binance exchange.

Direct integration will transform a TradingView trading strategy into a fully automated bot that will open and close fixed positions based on signals from a specified algorithm. The order size is fixed and set on the exchange. The process of direct integration of Pine Script strategies with the Binance exchange is described in our article How to Automate Trades on TradingView Directly without Third-Party-Services. If, however, you desire more flexible position management and the ability to trade automatically on alternative markets such as CFDs, you will require integration through third-party services.

Automation via Third-Party Services

For traders who may not have the technical expertise to set up their own server to handle webhooks, using third-party auto trading platforms is an excellent and user-friendly alternative for automating the Div-to-Div CCI Strategy. These services, such as Octobot, Tradeadapter, Arrow Algo or TradingView Hub, specialize in bridging the gap between TradingView alerts and broker APIs.

The process typically involves creating an account with one of these auto trading platforms and linking it to your brokerage account through a secure API key. Then, you create a TradingView alert for the Div-to-Div CCI Strategy signals, just as you would for a webhook, but instead of a custom URL, you use the alert URL provided by the third-party service.

The alert message is formatted in a specific way that the service can understand, for example: “BUY {{ticker}} MARKET” or “SELL SHORT {{ticker}} MARKET”. When the alert is triggered, TradingView sends the message to the third-party service, which then parses the command and relays the corresponding market order directly to your broker.

This method greatly simplifies the automation process, as the service handles all the complex API communication, error handling, and order management, allowing you to focus solely on refining the Div-to-Div CCI Strategy itself. Moreover, third-party services provide broader functionality in terms of position management. This includes trailing stops, partial take-profit, and other useful features.

Conclusion

In summary, the Div-to-Div CCI Strategy represents a powerful and systematic approach to trading that leverages the predictive power of momentum divergence. By automating the detection of CCI divergence, coupling it with robust ATR-based risk management, and optionally filtering for trend direction, it offers a disciplined framework for identifying potential market reversals. Its implementation in Pine Script makes it accessible to a wide audience on the TradingView platform, where it can be easily backtested, visualized, and refined.

The true potential of the Div-to-Div CCI Strategy is unlocked through automation, allowing for emotion-free execution that can capture opportunities across various markets and timeframes, 24/7. Whether automated directly via webhooks or through user-friendly third-party services, this strategy embodies the principles of modern algotrading.

As with any systematic approach, its success is not guaranteed and is highly dependent on proper parameter optimization, rigorous backtesting, and prudent risk management. However, for traders seeking a rule-based method to trade market turning points, the Div-to-Div CCI Strategy provides a compelling and well-structured toolkit.

Disclaimer

This article are for educational and informational purposes only. It does not constitute financial advice, a trading recommendation, or an offer to buy or sell any financial instrument. Trading financial markets involves substantial risk and is not suitable for all investors. You should carefully consider your investment objectives, level of experience, and risk appetite before making any investment decisions.

Past performance of the Div-to-Div CCI Strategy, as shown through backtesting, is not indicative of future results. There is no guarantee that any account will achieve profits or losses similar to those discussed or demonstrated. You are solely responsible for any trading decisions you make. We wish you disciplined execution and successful trading.

FAQ – Frequently Asked Questions

What is the core signal of this strategy?

The core signal is a divergence between price and the CCI indicator, specifically a bullish divergence for long entries and a bearish divergence for short entries.

How does the strategy manage risk?

It uses an ATR-based stop loss, calculated by multiplying the ATR by a user-defined multiplier (default 4.0) and placing the stop loss relative to the entry price.

Can I use this strategy on a 15-minute chart?

While possible, the strategy is designed to be more reliable on higher timeframes (1 hour and above) where signals are less noisy and more significant.

Does the strategy use a take-profit level?

The provided code version does not use a fixed take-profit level. It exits either when a new opposite signal occurs or when the stop-loss is hit.

What is the purpose of the EMA filter?

The EMA filter is an optional setting that ensures trades are only taken in the direction of the short-term trend, helping to filter out lower-probability, counter-trend divergence signals.

Is the strategy always in the market?

No, the strategy closes all positions before entering a new one, so it can be in a long position, a short position, or be flat (out of the market).

Leave a Comment