OPEN-SOURCE SCRIPT

SMT Divergence [UAlgo]

4 960
SMT Divergence is a comparative market structure indicator designed to detect disagreement between a primary instrument and a second reference symbol. The script looks for situations where the main chart prints a stronger structural move, while the comparison symbol fails to confirm that move. This kind of disagreement is often referred to as SMT divergence and is commonly used to identify potential weakness in continuation or hidden strength into reversal conditions.

The script works by tracking confirmed swing highs and swing lows on both instruments. Once enough pivots are stored, it compares the latest structural movement in the primary chart against the latest comparable movement in the reference symbol. If the primary chart makes a lower low while the comparison symbol makes a higher low, the script identifies bullish SMT divergence. If the primary chart makes a higher high while the comparison symbol makes a lower high, the script identifies bearish SMT divergence.

What makes this script especially practical is its flexible comparison logic. It can work in a time matched mode, where the comparison swings must occur near the same bars as the primary swings, or in an independent mode, where the script simply uses the most recent valid swings from both instruments. It also supports inverse correlation logic, allowing the user to compare instruments that normally move in opposite directions.

The indicator can then display SMT labels directly on the main chart, draw structure lines between the relevant swing points, show a live information table, and optionally render the comparison symbol as candles inside the oscillator pane. This creates a complete workflow for divergence monitoring instead of only printing occasional labels.

In practical use, SMT Divergence can help traders identify moments when the primary symbol appears to be making an aggressive structural move without proper confirmation from a related market. These moments can provide useful context for potential exhaustion, liquidity events, or directional imbalance between correlated instruments.

🔹 Features

🔸 Dual Symbol Market Structure Comparison
The script compares the active chart against a second user selected symbol. Both instruments are processed using the same pivot logic, which creates a consistent framework for structural comparison.

🔸 Bullish SMT Detection
Bullish SMT is identified when the primary chart makes a lower low while the comparison symbol makes a higher low. This can suggest hidden relative strength in the comparison instrument or possible exhaustion in the primary one.

🔸 Bearish SMT Detection
Bearish SMT is identified when the primary chart makes a higher high while the comparison symbol makes a lower high. This can suggest weakening confirmation and possible vulnerability in the primary move.

🔸 Positive and Inverse Correlation Modes
The script supports both normal and inverse correlation logic. In normal mode, lows are compared with lows and highs are compared with highs. In inverse mode, lows are compared with highs and highs are compared with lows. This makes the tool flexible enough for both positively correlated and negatively correlated markets.

🔸 Time Matched and Independent Swing Modes
The user can choose whether swing comparison should require approximate time alignment or simply use the most recent valid swings from each symbol. This allows the script to be either stricter or more flexible depending on the relationship between the two markets.

🔸 Pivot Strength Control
Swing highs and lows are built from confirmed pivots using user defined left and right bar settings. This allows the user to control how sensitive or how selective the swing structure should be.

🔸 Minimum Price Difference Filter
A minimum price difference percentage can be required before a divergence is accepted. This helps avoid labeling very small and potentially insignificant swing differences.

🔸 Max Swing Memory Control
The script stores a limited number of recent swings for both the primary and comparison symbol. This keeps the logic focused on relevant structure and prevents unnecessary buildup of stale pivots.

🔸 On Chart Labels and Lines
Detected SMT events can be labeled directly on the main chart. The script can also draw structure lines across the primary and comparison swing legs used in the divergence.

🔸 Live Info Table
An information table can display the active comparison symbol, correlation mode, divergence count, and the latest signal direction. This makes the script easier to monitor in real time.

🔸 Optional Compare Candle Panel
The comparison symbol can be plotted as candles in the indicator pane. This allows the user to visually inspect whether the second instrument is confirming or rejecting the move seen in the primary chart.

🔸 Alert Support
The script includes separate alerts for bullish SMT, bearish SMT, and any SMT event.

🔹 Calculations

1) Defining Swing and Divergence Objects

Pine Script®


This is the structural base of the whole script.

A SwingPoint stores one confirmed pivot with its bar index, time, price, and whether it is a high or a low.

An SMTDivergence object stores the final event once a divergence is confirmed. It keeps the primary and comparison prices, the involved symbols, the direction, and the visual references used for labels and lines.

A SymbolData object is used as a clean container for each symbol’s high, low, and close series.

So before any logic runs, the script already has a full structure for swing storage and divergence output.

2) Requesting the Comparison Symbol Data

Pine Script®


This block loads the second symbol on the same chart timeframe.

The primary chart uses the current symbol’s own high, low, and close. The comparison symbol is requested with request.security, and its values are placed into a matching data structure.

This means both symbols are analyzed on an equal timeframe basis, which is essential for consistent swing comparison.

3) Finding Pivot Highs and Pivot Lows on Both Symbols

Pine Script®


This is the swing discovery engine.

The script uses the same pivot settings for both instruments. A pivot high or pivot low is only confirmed after the required number of bars has passed on each side.

This means the divergence engine is built from confirmed structure, not from temporary highs and lows that can disappear before confirmation.

4) Storing Swings in Memory

Pine Script®


Pine Script®


Once a pivot is confirmed, it is pushed into the appropriate swing array.

The true pivot bar is pivotRightBars bars in the past, so the script subtracts that offset from the current bar index and time. Each array only keeps the latest user defined number of swings.

So the script maintains a rolling structural memory for both markets without allowing the arrays to grow indefinitely.

5) Retrieving the Latest and Previous Swings

Pine Script®


Pine Script®


These two helper methods are used to build the swing pairs required for divergence detection.

getLastSwing returns the most recent high or low swing of the requested type.
getPreviousSwing returns the swing before that.

This is important because SMT logic always compares two consecutive structure points on the primary side and two corresponding structure points on the comparison side.

6) Enforcing Maximum Distance Between Swing Points

Pine Script®


This method makes sure the two swings being compared are not too far apart in time.

If the latest and previous swing are separated by more than the allowed bar distance, the setup is ignored.

This helps keep the analysis focused on fresh and structurally related moves rather than comparing swings that are too old or too distant to be meaningful together.

7) Time Matched Swing Search

Pine Script®


This method is used only when the user selects time matched mode.

The idea is to find a comparison symbol swing that occurred near the same bar as the primary swing. The script searches for the nearest swing of the correct type inside the allowed tolerance window.

So time matched mode is stricter because it requires approximate timing alignment between the two instruments.

8) Minimum Price Difference Filter

Pine Script®


This function measures the percentage difference between two prices.

The result is later used as an optional minimum swing magnitude filter. If the primary chart’s new swing differs only slightly from its previous one, the script can ignore that divergence candidate.

So the minimum difference filter helps reduce weaker signals that are based on very small structure changes.

9) Bullish SMT Detection Logic

Pine Script®


This is the setup stage for bullish SMT.

The script only begins the test when a new primary pivot low has just been confirmed and both the latest and previous primary lows are available.

Then it decides what kind of comparison swings are needed.

In normal correlation mode, bullish SMT compares primary lows to comparison lows.
In inverse correlation mode, bullish SMT compares primary lows to comparison highs.

Then the script either uses time matched lookup or independent swing retrieval depending on the chosen mode.

So before the bullish condition itself is tested, the script first builds the proper comparison pair according to both timing mode and correlation mode.

10) Bullish SMT Confirmation Conditions

Pine Script®


Bullish SMT is confirmed when three things happen.

First, the primary chart must make a lower low:
primaryLastLow.price < primaryPrevLow.price

Second, the comparison symbol must fail to confirm that weakness. In normal correlation mode this means the comparison symbol makes a higher low. In inverse correlation mode the logic is adjusted accordingly because the relationship is reversed.

Third, if the minimum difference filter is enabled, the primary low must differ enough from the previous low.

So bullish SMT is essentially a lower low in the main chart that is not properly confirmed by the comparison market.

11) Creating the Bullish Divergence Event

Pine Script®


Once the bullish conditions are met, the script creates a new SMT divergence object.

It stores the primary swing information, the comparison swing information, the involved symbols, and the bullish direction. Then it calls the visual drawing method and pushes the divergence into the history array.

The duplicate protection check against lastBullPrimaryIdx prevents the same primary swing from being labeled repeatedly.

12) Bearish SMT Detection Logic

Pine Script®


This is the mirror setup stage for bearish SMT.

It begins only when a new primary pivot high has been confirmed and the required primary highs exist. Then it selects the proper comparison swing type according to the chosen correlation mode.

In normal correlation mode, bearish SMT compares highs with highs.
In inverse correlation mode, bearish SMT compares highs with lows.

So this block prepares the correct structural pair for the bearish test.

13) Bearish SMT Confirmation Conditions

Pine Script®


Bearish SMT is confirmed when the primary chart makes a higher high while the comparison symbol fails to confirm that strength.

In normal correlation mode, the comparison symbol must make a lower high. In inverse correlation mode the logic is adjusted to preserve the intended structural disagreement.

The minimum difference filter is applied here as well.

So bearish SMT is the opposite structure of bullish SMT, focused on unconfirmed upside continuation.

14) Creating the Bearish Divergence Event

Pine Script®


Once the bearish rules are satisfied, the script creates a bearish SMT divergence object, draws its visuals, and stores it in the divergence history array.

The duplicate protection check against lastBearPrimaryIdx prevents repeated labeling of the same primary high.

15) Drawing Labels and Lines

Pine Script®


Pine Script®


This method creates the chart visuals for each divergence.

The label is placed directly at the primary swing location, above price for bearish SMT and below price for bullish SMT.

If line drawing is enabled, the script also draws one line across the primary chart’s two relevant swing points and another line across the comparison symbol’s swing leg.

So the user can see both the signal marker and the underlying structural disagreement that produced it.

16) Limiting Divergence History

Pine Script®


This block controls object history.

If the stored divergence count exceeds the chosen limit, the oldest divergence is removed from the array and all its visuals are deleted.

This keeps the chart clean and prevents unlimited buildup of old labels and lines.

17) Building the Information Table

Pine Script®


Pine Script®


Pine Script®


Pine Script®


This table provides a compact real time summary.

It shows:
the primary symbol,
the comparison symbol,
the current correlation mode,
the number of stored divergences,
and the most recent signal direction.

So the table functions as a monitoring dashboard rather than only a decorative element.

18) Determining the Last Signal for the Table

Pine Script®


This block determines what the table should show as the latest signal.

If at least one divergence has been stored, the script reads the newest one and displays whether it was bullish or bearish, along with the corresponding color.

So the info table always reflects the current state of the divergence history.

19) Alert Conditions

Pine Script®


The script provides three alert types.

One triggers only on bullish SMT.
One triggers only on bearish SMT.
One triggers on any SMT event.

This makes the indicator useful both for visual study and for live event monitoring.

20) Compare Candle Panel

Pine Script®


This block renders the comparison symbol as candles inside the indicator pane.

The candle colors are determined by the comparison symbol’s own open and close direction. If the user enables the candle panel, this gives a quick visual reference for how the second instrument is behaving without needing to open a separate chart.

So the user can study SMT signals and the comparison structure in the same pane.

כתב ויתור

המידע והפרסומים אינם מיועדים להיות, ואינם מהווים, ייעוץ או המלצה פיננסית, השקעתית, מסחרית או מכל סוג אחר המסופקת או מאושרת על ידי TradingView. קרא עוד ב־תנאי השימוש.