TradingView strategy research

Divergence trading: from swing comparison to trade rules

Divergence trading compares the direction of price swings with an oscillator. Regular divergence is a possible reversal setup; hidden divergence is a possible continuation setup within an existing trend. Neither comparison supplies an entry by itself. A testable strategy also needs fixed swing-pairing rules, the time each swing becomes known, a price trigger, exits, and conditions that cancel the setup.

Draft a divergence strategy

Regular and hidden divergence answer different questions

Read each row from the older swing to the newer swing. The hidden patterns below have the same price/oscillator relationships that TradingView describes as Cardwell positive and negative reversals for RSI. The labels describe a setup, not a measured probability that the next move will follow it.

SetupPriceOscillatorHypothesis to test
Regular bullish divergenceLower lowHigher lowA decline may reverse or produce a rebound.
Regular bearish divergenceHigher highLower highAn advance may reverse or produce a pullback.
Hidden bullish divergenceHigher lowLower lowAn established uptrend may resume after a pullback.
Hidden bearish divergenceLower highHigher highAn established downtrend may resume after a bounce.

Choose one swing-pairing method

This illustrative rulebook anchors every comparison to price pivots and samples the oscillator on those same bars. It does not independently locate oscillator pivots. Requiring separate pivots on both series is another valid research design, but it needs its own maximum alignment distance and tie-breaking rule; it will produce different signals.

  • Use standard candles on one symbol and timeframe. Select one oscillator series for each experiment, such as RSI of close with length 14. Do not switch from MACD line to histogram after seeing which agrees with price.
  • Define a price low as strictly lower than the lows of the three preceding and three following bars; reverse the comparison for highs. Reject ties. The pivot becomes eligible only when the third following bar closes.
  • Pair only consecutive confirmed price lows, or consecutive confirmed highs, with pivot bars 5 to 60 bars apart. If that pair fails, do not search farther back for a better-looking match.
  • At the two pivot bars, compare the saved price extremes and oscillator values using strict inequalities. Equal oscillator values do not qualify. The oscillator samples need not be their own local extrema.
  • Freeze each qualifying pair at confirmation and identify it by its two bar timestamps. Process it once. All numbers here are research settings, not optimized defaults.

Define context, trigger, and expiry before testing

Run each of the four setup types as a separate experiment. For hidden bullish setups, this example requires the confirmation close above a 50-bar EMA and that EMA above its value five bars earlier. Reverse both conditions for hidden bearish setups. Regular setups use no EMA filter in this baseline. These are explicit context proxies, not proof of a trend or reversal.

  • Check invalidation before the trigger on each bar. If the five-bar window ends without a trigger, discard the setup.
  • Allow only one active setup and one position in each experiment. Ignore new candidates while either is active; do not silently replace a pending pair.
  • Freeze the context decision at confirmation. Changing that decision on each later bar would be a different strategy.
DecisionBullish setupBearish setup
Freeze the trigger levelHighest high strictly between the two price lows.Lowest low strictly between the two price highs.
Reject an early breakSkip if any close after the second pivot and through its confirmation is already above the trigger.Skip if any close after the second pivot and through its confirmation is already below the trigger.
Confirm entryFirst close above the trigger within the next five bars after pivot confirmation.First close below the trigger within the next five bars after pivot confirmation.
Invalidate before entryAny low at or below the second pivot low cancels the setup, including on the trigger bar.Any high at or above the second pivot high cancels the setup, including on the trigger bar.
Submit the orderAfter the qualifying close, submit a market buy. In a default bar-close backtest, expect the earliest fill at the next bar open.After the qualifying close, submit a market sell. Use the same calculation and fill settings as the long experiment.

Specify exits and size independently of the signal

For the illustrative baseline, place the initial stop one minimum tick below the second low for a long, or above the second high for a short. Define R as the absolute distance from the actual entry fill to that stop. Set the target at two times R from the fill in the trade direction, and keep both prices fixed. This is a price-distance definition of R before fees, not a promise about realized loss.

  • Define how the stop is submitted and when the target becomes active in the implementation. If a market entry gaps through the intended stop, do not erase the fill from the test: close it at the first executable opportunity and record the gap case.
  • Use a fixed quantity of one tradable unit for the baseline, with sufficient capital and margin for that instrument. This is a comparison convention, not a position-size recommendation. Record point value and minimum lot size.
  • If neither exit fills, submit a market close at the close of the twentieth chart bar after the entry bar. The fill follows the selected execution model. Do not add an opposite-signal exit midway through a comparison.
  • When both stop and target fall inside one bar, inspect order activation and intrabar sequencing. Document the broker-emulator assumptions and use finer historical detail where available.
  • Include the applicable commission and a stated slippage scenario. Stops can fill worse than their price, so realized loss can exceed the planned distance.

A hypothetical bullish setup with an honest timeline

Suppose consecutive price lows at bars 80 and 100 are 100 and 98, while the oscillator samples are 24 and 31. The pair has regular bullish divergence under this price-anchored method. Assume the intervening high is 103, the tick size is 0.01, and no early break or invalidation occurs. These are invented numbers for explaining the rules, not observed trades.

  • If price had already closed above 103 on bar 102, the example rules would reject the setup at confirmation instead of claiming an earlier trade.
  • A chart may draw the divergence line back to bar 100. Keep a separate marker at bar 103 for detection and bar 104 for the entry decision.
TimeInformation availableAction
Bar 100The second low exists, but its three right-side bars have not closed.No confirmed setup and no backdated entry.
Close of bar 103The second price pivot is confirmed; the pair passes all checks.Save the trigger at 103 and begin the five-bar eligibility window.
Close of bar 104Price closes at 103.20, above the trigger, without invalidation.Submit the entry order after this close.
Open of bar 105Assume an illustrative fill of 103.40.Stop is 97.99. R is 5.41 price units; a 2R target is 114.22, before costs.

When to skip or reject a divergence setup

A divergence can coexist with continued price movement against the proposed trade. Additional confirmation changes the entry time and price; it does not remove that possibility. Record rejected setups as well as accepted trades so the rules can be audited.

  • Skip missing oscillator values, tied pivots, insufficient warm-up history, pairs outside the spacing limit, and hidden setups that fail the frozen trend filter.
  • Reject stale, invalidated, or expired candidates. A later attractive move does not justify reopening the same pair.
  • Do not treat several oscillators derived from the same prices as independent votes without testing that assumption. Keep a single-series baseline for comparison.
  • Reject a backtest that enters on the original pivot bar while using right-side bars to recognize that pivot. Future confirmation cannot authorize a past order.
  • Keep SMT divergence separate: it compares the structure of related assets rather than price and an oscillator on this one instrument.

Test whether the rulebook survives another sample

Save the symbol, exchange, session, timeframe, date ranges, script version, pivot parameters, oscillator, costs, and fill settings with each run. Reserve a later period before choosing parameters. A parameter search on the full dataset leaves no untouched period for evaluating the selected rules.

  • Pineify Strategy Optimizer can test exposed parameter combinations. Select a small research range and retain the untouched evaluation period separately.
  • Backtest Deep Report can analyze exported trade records. Keep the signal log and script alongside the CSV: completed trades alone cannot prove when a pivot was first known.
  • No performance experiment is reported on this page. Fewer trades after a filter are a change in sample, not evidence of better signals.
ExperimentKeep fixedInspect
Separate setup typesData, costs, size, and execution assumptions.Trade count, drawdown, and net results for each type; do not hide a weak branch inside a combined total.
Nearby settingsA short parameter range chosen in advance.Whether one isolated setting carries the result; save unsuccessful combinations too.
Untouched datesRules chosen on the earlier sample.Outcome and sample size without retuning the later period.
Cost and fill scenariosSignals and trade-management rules.Which trades change under higher costs or different intrabar assumptions.
Forward observationFrozen strategy and settings.Detection and trigger timestamps before and after reload, including canceled setups.
Where Pineify fits

Pine Script AI Coding Agent

Give the coding agent the pairing method, confirmation delay, trigger window, order timing, and exit rules to draft a Pine Script strategy. Review its source and compare timestamped signals with the written rules before interpreting a backtest.

Also useful: Strategy Optimizer. Compare exposed strategy inputs after the baseline works. Parameter search does not establish profitability or replace evaluation on untouched data.

Draft a divergence strategy

Frequently asked questions

Educational strategy design, not investment advice. The rulebook and numeric example are illustrative and have not been performance-tested. Trading can result in losses; historical simulations and parameter searches do not guarantee future results.

Sources and verification

Published by Pineify. Pineify is an independent product and is not affiliated with TradingView. Sources support the technical explanations; examples do not establish trading performance.