Volume Sampled Supertrend [BackQuant]Volume Sampled Supertrend
A Supertrend that runs on a volume sampled price series instead of fixed time. New synthetic bars are only created after sufficient traded activity, which filters out low participation noise and makes the trend much easier to read and model.
Original Script Link
This indicator is built on top of my volume sampling engine. See the base implementation here:
Why Volume Sampling
Traditional charts print a bar every N minutes regardless of how active the tape is. During quiet periods you accumulate many small, low information bars that add noise and whipsaws to downstream signals.
Volume sampling replaces the clock with participation. A new synthetic bar is created only when a pre-set amount of volume accumulates (or, in Dollar Bars mode, when pricevolume reaches a dollar threshold). The result is a non-uniform time series that stretches in busy regimes and compresses in quiet regimes. This naturally:
filters dead time by skipping low volume chop;
standardizes the information content per bar, improving comparability across regimes;
stabilizes volatility estimates used inside banded indicators;
gives trend and breakout logic cleaner state transitions with fewer micro flips.
What this tool does
It builds a synthetic OHLCV stream from volume based buckets and then applies a Supertrend to that synthetic price. You are effectively running Supertrend on a participation clock rather than a wall clock.
Core Features
Sampling Engine - Choose Volume buckets or Dollar Bars . Thresholds can be dynamic from a rolling mean or median, or fixed by the user.
Synthetic Candles - Plots the volume sampled OHLC candles so you can visually compare against regular time candles.
Supertrend on Synthetic Price - ATR bands and direction are computed on the sampled series, not on time bars.
Adaptive Coloring - Candle colors can reflect side, intensity by volume, or a neutral scheme.
Research Panels - Table shows total samples, current bucket fill, threshold, bars-per-sample, and synthetic return stats.
Alerts - Long and Short triggers on Supertrend direction flips for the synthetic series.
How it works
Sampling
Pick Sampling Method = Volume or Dollar Bars.
Set the dynamic threshold via Rolling Lookback and Filter (Mean or Median), or enable Use Fixed and type a constant.
The script accumulates volume (or pricevolume) each time bar. When the bucket reaches the threshold, it finalizes one or more synthetic candles and resets accumulation.
Each synthetic candle stores its own OHLCV and is appended to the synthetic series used for all downstream logic.
Supertrend on the sampled stream
Choose Supertrend Source (Open, High, Low, Close, HLC3, HL2, OHLC4, HLCC4) derived from the synthetic candle.
Compute ATR over the synthetic series with ATR Period , then form upperBand = src + factorATR and lowerBand = src - factorATR .
Apply classic trailing band and direction rules to produce Supertrend and trend state.
Because bars only come when there is sufficient participation, band touches and flips tend to align with meaningful pushes, not idle prints.
Reading the display
Synthetic Volume Bars - The non-uniform candles that represent equal information buckets. Expect more candles during active sessions and fewer during lulls.
Volume Sampled Supertrend - The main line. Green when Trend is 1, red when Trend is -1.
Markers - Small dots appear when a new synthetic sample is created, useful for aligning activity cycles.
Time Bars Overlay (optional) - Plot regular time candles to compare how the synthetic stream compresses quiet chop.
Settings you will use most
Data Settings
Sampling Method - Volume or Dollar Bars.
Rolling Lookback and Filter - Controls the dynamic threshold. Median is robust to outliers, Mean is smoother.
Use Fixed and Fixed Threshold - Force a constant bucket size for consistent sampling across regimes.
Max Stored Samples - Ring buffer limit for performance.
Indicator Settings
SMA over last N samples - A moving average computed on the synthetic close series. Can be hidden for a cleaner layout.
Supertrend Source - Price field from the synthetic candle.
ATR Period and Factor - Standard Supertrend controls applied on the synthetic series.
Visuals and UI
Show Synthetic Bars - Turn synthetic candles on or off.
Candle Color Mode - Green/Red, Volume Intensity, Neutral, or Adaptive.
Mark new samples - Puts a dot when a bucket closes.
Show Time Bars - Overlay regular candles for comparison.
Paint candles according to Trend - Colors chart candles using current synthetic Supertrend direction.
Line Width , Colors , and Stats Table toggles.
Some workflow notes:
Trend Following
Set Sampling Method = Volume, Filter = Median, and a reasonable Rolling Lookback so busy regimes produce more samples.
Trade in the direction of the Volume Sampled Supertrend. Because flips require real participation, you tend to avoid micro whipsaws seen on time bars.
Use the synthetic SMA as a bias rail and trailing reference for partials or re-entries.
Breakout and Continuation
Watch for rapid clustering of new sample markers and a clean flip of the synthetic Supertrend.
The compression of quiet time and expansion in busy bursts often makes breakouts more legible than on uniform time charts.
Mean Reversion
In instruments that oscillate, faded moves against the synthetic Supertrend are easier to time when the bucket cadence slows and Supertrend flattens.
Combine with the synthetic SMA and return statistics in the table for sizing and expectation setting.
Stats table (top right)
Method and Total Samples - Sampling regime and current synthetic history length.
Current Vol or Dollar and Threshold - Live bucket fill versus the trigger.
Bars in Bucket and Avg Bars per Sample - How much time data each synthetic bar tends to compress.
Avg Return and Return StdDev - Simple research metrics over synthetic close-to-close changes.
Why this reduces noise
Time based bars treat a 5 minute print with 1 percent of average participation the same as one with 300 percent. Volume sampling equalizes bar information content. By advancing the bar only when sufficient activity occurs, you skip low quality intervals that add variance but little signal. For banded systems like Supertrend, this often means fewer false flips and cleaner runs.
Notes and tips
Use Dollar Bars on assets where nominal price varies widely over time or across symbols.
Median filter can resist single burst outliers when setting dynamic thresholds.
If you need a stable research baseline, set Use Fixed and keep the threshold constant across tests.
Enable Show Time Bars occasionally to sanity check what the synthetic stream is compressing or stretching.
Link again for reference
Original Volume Based Sampling engine:
Bottom line
When you let participation set the clock, your Supertrend reacts to meaningful flow instead of idle prints. The result is a cleaner state machine, fewer micro whipsaws, and a trend read that respects when the market is actually trading.
Statistics
Extreme Candle Pattern Visualizer🟠 OVERVIEW
This indicator compares the current candle's percentage change against historical data, then highlights past candles with equal or bigger magnitude of movement. Also, for all the highlighted past candles, it tracks how far price extends before recovering to its starting point. It also provides statistical context through percentile rankings.
IN SHORT: Quickly spot similar price movements in the past and understand how unusual the current candle is using percentile rankings.
🟠 CORE CONCEPT
The indicator operates on two fundamental principles:
1. Statistical Rarity Detection
The script calculates the percentage change (open to close) of every candle within a user-defined lookback period and determines where the current candle ranks in this distribution. A candle closing at -9% might fall in the bottom 5th percentile, indicating it's more extreme than 95% of recent candles. This percentile ranking helps traders identify statistically unusual moves that often precede reversals or extended trends.
2. Recovery Path Mapping
Once extreme candles are identified (those matching or exceeding the current candle's magnitude), the indicator tracks their subsequent price action. For bearish candles, it measures how far price dropped before recovering back to the candle's opening price. For bullish candles, it tracks how high price climbed before returning to the open. This reveals whether extreme moves typically extend further or reverse quickly.
🟠 PRACTICAL APPLICATIONS
Mean Reversion Trading:
Candles in extreme percentiles (below 10% or above 90%) often signal oversold/overbought conditions. The recovery lines show typical extension distances, helping traders set profit targets for counter-trend entries.
Momentum Continuation:
When extreme candles show small recovery percentages before price reverses back, it suggests strong directional momentum that may continue.
Stop Loss Placement:
Historical recovery data reveals typical extension ranges after extreme moves, informing more precise stop loss positioning beyond noise but before major reversals.
Pattern Recognition:
By visualizing how similar historical extremes resolved, traders gain context for current price action rather than trading in isolation.
🟠 VISUAL ELEMENTS
Orange Circles: Mark historical candles with similar or greater magnitude to current candle
Red Lines: Track downward extensions after bearish extreme candles
Green Lines: Track upward extensions after bullish extreme candles
Percentage Labels: Show exact extension distance from candle close to extreme point
Percentile Label: Color-coded box displaying current candle's statistical ranking
Hollow Candles: Background rendering for clean chart presentation
🟠 ORIGINALITY
This indicator uniquely combines statistical percentile analysis with forward-looking recovery tracking. While many indicators identify extreme moves, few show what happened next across multiple historical instances simultaneously. The dual approach provides both the "how rare is this?" question (percentile) and "what typically happens after?" answer (recovery paths) in a single visual framework.
𝕸𝖎𝖈𝖍𝖆𝖑 𝕯. 𝕷𝖆𝖌𝖑𝖊𝖘𝖘 𝕸𝖔𝖛𝖎𝖓𝖌 𝕬𝖛𝖊𝖗𝖆𝖌𝖊 | 𝕸𝖎𝖘𝖎𝖓𝖐𝖔𝕸𝖆𝖘𝖙𝖊𝖗The 𝕸𝖎𝖈𝖍𝖆𝖑 𝕯. 𝕷𝖆𝖌𝖑𝖊𝖘𝖘 𝕸𝖔𝖛𝖎𝖓𝖌 𝕬𝖛𝖊𝖗𝖆𝖌𝖊 is my latest creation of a trend following tool, which is a bit different from the rest. By trying to de-lag the classical moving average, it gives you fast signals on changes in trend as fast as possible, keeping traders & investors always in check for potential risks they might want to avoid.
How does it work?
First we need to calculate lengths. The lengths are calcuted using a user defined input called the "Length Multiplier" and we of course need as well the length input too.
The indicator uses 10 lengths, 5 for an average price, 5 for median price.
The length for the average is the following:
length_2_avg = length_1_avg * length_multiplier
length_3_avg = length_2_avg * length_multiplier
...
and for the median lengths:
length_1_median = length_2_avg
length_2_median = length_3_avg
Here applies this rule
length_x_median < length_x_avg
This is intentional, and it is because the average is a little more reactive, while the median is a bit slower. To make up for the "slowness" of the median, we simple reduce the length of it a bit more than the average.
Now that we have our length we are ready to calculate averages and medians over their respective period. This is the a normal average from elementary school, nothing too fancy.
Now that we have all of them we match the pairs using another user defined input called "Median Weight" like so:
(Average_x * (2-median_weight) + Median_x * median_weight)/2
This gives more weight to the average (also due to the max value limit set to avoid breaking the fundational logic behind it).
After doing it to all the pairs we now average those pairs using another input called "Exponential Weight Multiplier".
The Exponential Weight Multiplier is used for weights which I will cover soon:
weight1 = weight
weight2 = weight * weight
weight3 = weight * weight * weight....
This is done until we have all the weights calculated
This gives exponentially more weight to the less lagging indicators, which is how we delag the indicator.
Then we sum all the pairs like so:
sum = pair1 * weight1 + pair2 * weight2 + pair3 * weight3 + pair4 * weight4 + pair5 * weight5
Then the sum is divided by the sum of weights, this results in us getting the final value.
Methodology & What is the actual point & how was it made?
I want to cover this one a bit deeper:
The methodology behind this was creating an indicator that would not be lagging, and would be able to avoid lag while not producing signals too often.
In many attempts in the first part, I tried using EMA, RMA, DEMA, TEMA, HMA, SMA and so on, but they were too noisy (except for SMA & RMA, but those had their flaws), so I tried the classical average taught in elementary school. This one worked better, but the noise was too high still after all this time. This made me include the median, which helped the noise, but made it far too lagging.
Here came the idea of making the median length lower and adding weights to counter the lag of the median, but it was still too lagging. This made me make the weights for lengths more exponential, while previously they were calculated using a little bit amplified sums that were alright, but nowhere near my desired result.
Using the new weights I got further, and after a bit of testing I was sattisfied with the results.
The logic for the trend was a big part in my development part, there were many I could think of, but not enough time to try them, so I stuck to the usual one, and I leave it up to YOU to beat my trend logic and get even better results.
Use Cases:
- Price/MA Crossovers
Simple, effective, useful
- Source for other indicators
This I tried myself, and it worked in a cool way, making the signals of for example RSI much smoother, so definitely try it out if you know how to code, or just simply put it in the source of the RSI.
- ROC
This trend logic stuck with me, I think you could find a way to make it good, but mainly for the people that can code in pine, trying out to combine the trend logic with ROC could work very well, do not sleep on it!
- Education
This concept is not really that complex, so for people looking for new ideas, inspiration, or just watching how trend following tools behave in general this is something that could benefit anyone, as the concept can be applied to ANYTHING, even the classical RSI, MACD, you could try even the Parabolic SAR, maybe STC or VZO, there is no limit to imagination.
- Strategy creation
Filtering this indicator with "and" conditions, or maybe even "or" or anything really could be very useful in a strategy that desires fast signals.
- Price Distance from bands
I noticed this while looking at past performance:
The stronger the trend the higher the distance from the Moving Average.
Final Notes
Watch out for mean reverting markets, as this is trend following you could get easily screwed in them.
Play around with this if it fits your desired outcome, you might find something I did not.
Hope you find it useful,
See you next time!
Opening Range Fibonacci Extensions (ATR Adjusted)this script displays daily, weekly, or monthly range extensions as a function of ATR in a Fibonacci retracement
Stochastic %K Colored by VolumeDescription:
"Stochastic %K Colored by Volume is a technical indicator that combines the traditional Stochastic %K oscillator with volume-based coloring. It highlights periods of high, low, and neutral trading volume by changing the color of the %K line. Additionally, it identifies bullish and bearish divergences between price and the %K oscillator, helping traders spot potential reversals and trend changes. The indicator also includes key levels for overbought, oversold, and extreme zones to guide trading decisions."
HTF Live View - GSK-VIZAG-AP-INDIA📘 HTF Live View — GSK-VIZAG-AP-INDIA
🧩 Overview
The HTF Live View indicator provides a real-time visual representation of higher-timeframe (HTF) candle structures — such as 15min, 30min, 1H, 4H, and Daily — all derived directly from live 1-minute data.
This allows traders to see how higher timeframe candles are forming within the current session — without switching chart timeframes.
⚙️ Core Features
📊 Live Multi-Timeframe OHLC Tracking
Continuously calculates and displays Open, High, Low, and Close values for each key timeframe (15m, 30m, 1H, 4H, and Daily) based on the ongoing session.
⏱ Session-Aware Calculation
Automatically syncs with market hours defined by user-selected start and end times. Works across multiple timezones for global compatibility.
🕹 Visual Candle Representation
Draws mini-candles on the chart for each higher timeframe to represent their current body and wick — updated live.
Green body → bullish development
Red body → bearish development
📅 Informative Table Panel
Displays a summary table showing:
Timeframe label
Period (start–end time)
Live OHLC values
Color-coded close values
🌍 Timezone Support
Fully compatible with common regions such as Asia/Kolkata, New York, London, Tokyo, and Sydney.
🔧 User Inputs
Parameter Description
Market Start Hour/Minute Define session start time (default: 09:15)
Session End Hour/Minute Define market close (default: 15:30)
Timezone Select your preferred timezone for session alignment
💡 How It Works
The indicator uses a rolling OHLC calculation function that dynamically computes candle values based on elapsed session time.
Each timeframe (15m, 30m, 1H, 4H, and Daily) is built from 1-minute data to maintain precision even during intraday updates.
Both a visual representation (candles and wicks) and a data table (numeric summary) are displayed for clarity.
🧠 Use Cases
Monitor how HTF candles are forming live without switching chart intervals.
Understand intraday structure shifts (e.g., when 1H turns from red to green).
Confirm trend alignment across multiple timeframes visually.
Combine with your volume, delta, or liquidity tools for deeper confluence.
🪶 Signature
Developed by GSK-VIZAG-AP-INDIA
© prowelltraders — Educational and analytical use only.
⚠️ Disclaimer
This indicator is for educational and informational purposes only.
It does not provide financial advice or guaranteed trading results.
Always perform your own analysis before making investment decisions.
SPYDER ORBITSPYDER ORBIT is an adaptation of the original Kaiser Windowed Sinc Moving Average by The_Peaceful_Lizard.
This version adds the dynamic standard deviation bands with the precision of a Kaiser windowed sinc filter for ultra-smooth, low-lag trend extraction — ideal for identifying dominant directional bias while minimizing market noise.
Around this smoothed orbit, SPYDER ORBIT adds multi-level deviation envelopes (1σ, 2σ, 3σ) to visualize volatility expansion and contraction zones. These act like adaptive shells, helping identify exhaustion, breakout volatility, and mean-reversion opportunities.
Credits:
Sinc MA © The_Peaceful_Lizard
Background Trend Follower by exp3rtsThe Background Trend Follower indicator visually highlights the market’s daily directional bias using subtle background colors. It calculates the price change from the daily open and shades the chart background according to the current intraday momentum.
🟢 Green background → Price is significantly above the daily open (strong bullish trend)
🔴 Red background → Price is significantly below the daily open (strong bearish trend)
🟡 Yellow background → Price is trading near the daily open (neutral or consolidating phase)
The script automatically detects each new trading day.
It records the opening price at the start of the day.
As the session progresses, it continuously measures how far the current price has moved from that open.
When the move exceeds ±50 points (custom threshold), the background color adapts to reflect the trend strength.
Perfect for traders who want a quick visual sense of intraday bias — bullish, bearish, or neutral — without cluttering the chart with extra indicators.
SJA WINFUT B3-10
INDICATOR FOR WINFUT B3 – 5-minute chart.
This indicator was designed to trade the Bovespa index futures contract (WINFUT) on the 5-minute chart.
It integrates technical analysis and macroeconomic context elements.
It combines several indicators in which the system calculates a score weighted by color and intensity for each indicator, generating a metric called “STRENGTH %,” which reflects the dominance of buyers (green), sellers (red), or sideways movement (orange) at the moment.
The calculation is adapted to market hours:
Between 9:00 a.m. and 9:59 a.m., it considers only the available indicators; after 10:00 a.m., it uses all data.
The panel displays real-time information, including divergences between strength and price, providing robust decision support for short-term operations on the mini index.
Buying trend.
The more green indicators (at the top of the panel) and dark blue indicators (at the bottom of the panel) and the higher the strength percentage, the greater the probability of buying.
Selling trend.
The more red indicators (at the top of the panel) and dark blue indicators (at the bottom of the panel) and the higher the strength percentage, the greater the probability of selling.
Translated with DeepL.com (free version)
Simple Custom Watermark & Symbol Info ジAdd a clean, configurable watermark to any chart. This lightweight indicator displays a custom name or brand plus optional symbol, timeframe, and current date in any corner of the chart. Perfect for traders, streamers, analysts, and content creators who want consistent chart branding, fast timestamps, or tidy screenshots.
Key features
Custom watermark text (brand, username, or logo text)
Toggle display of Symbol, Timeframe, and Date
Choose position: Top/Bottom × Left/Center/Right
Text color, background color (with alpha) and text size (small/normal/large)
Ultra-light, overlay-only — no chart clutter or extra objects
Why use it
Professionalize screenshots and shared charts with consistent branding
Add automatic timestamps to charts for auditability or content posts
Useful for streaming, educational content, reports, or trading journals
Minimal footprint keeps the chart readable while adding essential metadata
How traders use it
Add your name/handle for attribution on social posts
Show timeframe & symbol automatically when switching charts
Use date stamp for sessions, reports, and evidence of analysis timing
Built for clarity, speed, and clean visuals. Simple to configure — drop it on any chart and customize the watermark to match your workflow.
JK_Traders_Reality_LibLibrary "JK_Traders_Reality_Lib"
This library contains common elements used in Traders Reality scripts
calcPvsra(pvsraVolume, pvsraHigh, pvsraLow, pvsraClose, pvsraOpen, redVectorColor, greenVectorColor, violetVectorColor, blueVectorColor, darkGreyCandleColor, lightGrayCandleColor)
calculate the pvsra candle color and return the color as well as an alert if a vector candle has apperared.
Situation "Climax"
Bars with volume >= 200% of the average volume of the 10 previous chart TFs, or bars
where the product of candle spread x candle volume is >= the highest for the 10 previous
chart time TFs.
Default Colors: Bull bars are green and bear bars are red.
Situation "Volume Rising Above Average"
Bars with volume >= 150% of the average volume of the 10 previous chart TFs.
Default Colors: Bull bars are blue and bear are violet.
Parameters:
pvsraVolume (float) : the instrument volume series (obtained from request.sequrity)
pvsraHigh (float) : the instrument high series (obtained from request.sequrity)
pvsraLow (float) : the instrument low series (obtained from request.sequrity)
pvsraClose (float) : the instrument close series (obtained from request.sequrity)
pvsraOpen (float) : the instrument open series (obtained from request.sequrity)
redVectorColor (simple color) : red vector candle color
greenVectorColor (simple color) : green vector candle color
violetVectorColor (simple color) : violet/pink vector candle color
blueVectorColor (simple color) : blue vector candle color
darkGreyCandleColor (simple color) : regular volume candle down candle color - not a vector
lightGrayCandleColor (simple color) : regular volume candle up candle color - not a vector
@return
adr(length, barsBack)
Parameters:
length (simple int) : how many elements of the series to calculate on
barsBack (simple int) : starting possition for the length calculation - current bar or some other value eg last bar
@return adr the adr for the specified lenght
adrHigh(adr, fromDo)
Calculate the ADR high given an ADR
Parameters:
adr (float) : the adr
fromDo (simple bool) : boolean flag, if false calculate traditional adr from high low of today, if true calcualte from exchange midnight
@return adrHigh the position of the adr high in price
adrLow(adr, fromDo)
Parameters:
adr (float) : the adr
fromDo (simple bool) : boolean flag, if false calculate traditional adr from high low of today, if true calcualte from exchange midnight
@return adrLow the position of the adr low in price
splitSessionString(sessXTime)
given a session in the format 0000-0100:23456 split out the hours and minutes
Parameters:
sessXTime (simple string) : the session time string usually in the format 0000-0100:23456
@return
calcSessionStartEnd(sessXTime, gmt)
calculate the start and end timestamps of the session
Parameters:
sessXTime (simple string) : the session time string usually in the format 0000-0100:23456
gmt (simple string) : the gmt offset string usually in the format GMT+1 or GMT+2 etc
@return
drawOpenRange(sessXTime, sessXcol, showOrX, gmt)
draw open range for a session
Parameters:
sessXTime (simple string) : session string in the format 0000-0100:23456
sessXcol (simple color) : the color to be used for the opening range box shading
showOrX (simple bool) : boolean flag to toggle displaying the opening range
gmt (simple string) : the gmt offset string usually in the format GMT+1 or GMT+2 etc
@return void
drawSessionHiLo(sessXTime, showRectangleX, showLabelX, sessXcolLabel, sessXLabel, gmt, sessionLineStyle)
Parameters:
sessXTime (simple string) : session string in the format 0000-0100:23456
showRectangleX (simple bool)
showLabelX (simple bool)
sessXcolLabel (simple color) : the color to be used for the hi/low lines and label
sessXLabel (simple string) : the session label text
gmt (simple string) : the gmt offset string usually in the format GMT+1 or GMT+2 etc
sessionLineStyle (simple string) : the line stile for the session high low lines
@return void
calcDst()
calculate market session dst on/off flags
@return indicating if DST is on or off for a particular region
timestampPreviousDayOfWeek(previousDayOfWeek, hourOfDay, gmtOffset, oneWeekMillis)
Timestamp any of the 6 previous days in the week (such as last Wednesday at 21 hours GMT)
Parameters:
previousDayOfWeek (simple string) : Monday or Satruday
hourOfDay (simple int) : the hour of the day when psy calc is to start
gmtOffset (simple string) : the gmt offset string usually in the format GMT+1 or GMT+2 etc
oneWeekMillis (simple int) : the amount if time for a week in milliseconds
@return the timestamp of the psy level calculation start time
getdayOpen()
get the daily open - basically exchange midnight
@return the daily open value which is float price
newBar(res)
new_bar: check if we're on a new bar within the session in a given resolution
Parameters:
res (simple string) : the desired resolution
@return true/false is a new bar for the session has started
toPips(val)
to_pips Convert value to pips
Parameters:
val (float) : the value to convert to pips
@return the value in pips
rLabel(ry, rtext, rstyle, rcolor, valid, labelXOffset)
a function that draws a right aligned lable for a series during the current bar
Parameters:
ry (float) : series float the y coordinate of the lable
rtext (simple string) : the text of the label
rstyle (simple string) : the style for the lable
rcolor (simple color) : the color for the label
valid (simple bool) : a boolean flag that allows for turning on or off a lable
labelXOffset (int) : how much to offset the label from the current position
rLabelOffset(ry, rtext, rstyle, rcolor, valid, labelOffset)
a function that draws a right aligned lable for a series during the current bar
Parameters:
ry (float) : series float the y coordinate of the lable
rtext (string) : the text of the label
rstyle (simple string) : the style for the lable
rcolor (simple color) : the color for the label
valid (simple bool) : a boolean flag that allows for turning on or off a lable
labelOffset (int)
rLabelLastBar(ry, rtext, rstyle, rcolor, valid, labelXOffset)
a function that draws a right aligned lable for a series only on the last bar
Parameters:
ry (float) : series float the y coordinate of the lable
rtext (string) : the text of the label
rstyle (simple string) : the style for the lable
rcolor (simple color) : the color for the label
valid (simple bool) : a boolean flag that allows for turning on or off a lable
labelXOffset (int) : how much to offset the label from the current position
drawLine(xSeries, res, tag, xColor, xStyle, xWidth, xExtend, isLabelValid, xLabelOffset, validTimeFrame)
a function that draws a line and a label for a series
Parameters:
xSeries (float) : series float the y coordinate of the line/label
res (simple string) : the desired resolution controlling when a new line will start
tag (simple string) : the text for the lable
xColor (simple color) : the color for the label
xStyle (simple string) : the style for the line
xWidth (simple int) : the width of the line
xExtend (simple string) : extend the line
isLabelValid (simple bool) : a boolean flag that allows for turning on or off a label
xLabelOffset (int)
validTimeFrame (simple bool) : a boolean flag that allows for turning on or off a line drawn
drawLineDO(xSeries, res, tag, xColor, xStyle, xWidth, xExtend, isLabelValid, xLabelOffset, validTimeFrame)
a function that draws a line and a label for the daily open series
Parameters:
xSeries (float) : series float the y coordinate of the line/label
res (simple string) : the desired resolution controlling when a new line will start
tag (simple string) : the text for the lable
xColor (simple color) : the color for the label
xStyle (simple string) : the style for the line
xWidth (simple int) : the width of the line
xExtend (simple string) : extend the line
isLabelValid (simple bool) : a boolean flag that allows for turning on or off a label
xLabelOffset (int)
validTimeFrame (simple bool) : a boolean flag that allows for turning on or off a line drawn
drawPivot(pivotLevel, res, tag, pivotColor, pivotLabelColor, pivotStyle, pivotWidth, pivotExtend, isLabelValid, validTimeFrame, levelStart, pivotLabelXOffset)
draw a pivot line - the line starts one day into the past
Parameters:
pivotLevel (float) : series of the pivot point
res (simple string) : the desired resolution
tag (simple string) : the text to appear
pivotColor (simple color) : the color of the line
pivotLabelColor (simple color) : the color of the label
pivotStyle (simple string) : the line style
pivotWidth (simple int) : the line width
pivotExtend (simple string) : extend the line
isLabelValid (simple bool) : boolean param allows to turn label on and off
validTimeFrame (simple bool) : only draw the line and label at a valid timeframe
levelStart (int) : basically when to start drawing the levels
pivotLabelXOffset (int) : how much to offset the label from its current postion
@return the pivot line series
getPvsraFlagByColor(pvsraColor, redVectorColor, greenVectorColor, violetVectorColor, blueVectorColor, lightGrayCandleColor)
convert the pvsra color to an internal code
Parameters:
pvsraColor (color) : the calculated pvsra color
redVectorColor (simple color) : the user defined red vector color
greenVectorColor (simple color) : the user defined green vector color
violetVectorColor (simple color) : the user defined violet vector color
blueVectorColor (simple color) : the user defined blue vector color
lightGrayCandleColor (simple color) : the user defined regular up candle color
@return pvsra internal code
updateZones(pvsra, direction, boxArr, maxlevels, pvsraHigh, pvsraLow, pvsraOpen, pvsraClose, transperancy, zoneupdatetype, zonecolor, zonetype, borderwidth, coloroverride, redVectorColor, greenVectorColor, violetVectorColor, blueVectorColor)
a function that draws the unrecovered vector candle zones
Parameters:
pvsra (int) : internal code
direction (simple int) : above or below the current pa
boxArr (array) : the array containing the boxes that need to be updated
maxlevels (simple int) : the maximum number of boxes to draw
pvsraHigh (float) : the pvsra high value series
pvsraLow (float) : the pvsra low value series
pvsraOpen (float) : the pvsra open value series
pvsraClose (float) : the pvsra close value series
transperancy (simple int) : the transparencfy of the vecor candle zones
zoneupdatetype (simple string) : the zone update type
zonecolor (simple color) : the zone color if overriden
zonetype (simple string) : the zone type
borderwidth (simple int) : the width of the border
coloroverride (simple bool) : if the color overriden
redVectorColor (simple color) : the user defined red vector color
greenVectorColor (simple color) : the user defined green vector color
violetVectorColor (simple color) : the user defined violet vector color
blueVectorColor (simple color) : the user defined blue vector color
cleanarr(arr)
clean an array from na values
Parameters:
arr (array) : the array to clean
@return if the array was cleaned
calcPsyLevels(oneWeekMillis, showPsylevels, psyType, sydDST)
calculate the psy levels
4 hour res based on how mt4 does it
mt4 code
int Li_4 = iBarShift(NULL, PERIOD_H4, iTime(NULL, PERIOD_W1, Li_0)) - 2 - Offset;
ObjectCreate("PsychHi", OBJ_TREND, 0, Time , iHigh(NULL, PERIOD_H4, iHighest(NULL, PERIOD_H4, MODE_HIGH, 2, Li_4)), iTime(NULL, PERIOD_W1, 0), iHigh(NULL, PERIOD_H4,
iHighest(NULL, PERIOD_H4, MODE_HIGH, 2, Li_4)));
so basically because the session is 8 hours and we are looking at a 4 hour resolution we only need to take the highest high an lowest low of 2 bars
we use the gmt offset to adjust the 0000-0800 session to Sydney open which is at 2100 during dst and at 2200 otherwize. (dst - spring foward, fall back)
keep in mind sydney is in the souther hemisphere so dst is oposite of when london and new york go into dst
Parameters:
oneWeekMillis (simple int) : a constant value
showPsylevels (simple bool) : should psy levels be calculated
psyType (simple string) : the type of Psylevels - crypto or forex
sydDST (bool) : is Sydney in DST
@return
adrHiLo(length, barsBack, fromDO)
Parameters:
length (simple int) : how many elements of the series to calculate on
barsBack (simple int) : starting possition for the length calculation - current bar or some other value eg last bar
fromDO (simple bool) : boolean flag, if false calculate traditional adr from high low of today, if true calcualte from exchange midnight
@return adr, adrLow and adrHigh - the adr, the position of the adr High and adr Low with respect to price
drawSessionHiloLite(sessXTime, showRectangleX, showLabelX, sessXcolLabel, sessXLabel, gmt, sessionLineStyle, sessXcol)
Parameters:
sessXTime (simple string) : session string in the format 0000-0100:23456
showRectangleX (simple bool)
showLabelX (simple bool)
sessXcolLabel (simple color) : the color to be used for the hi/low lines and label
sessXLabel (simple string) : the session label text
gmt (simple string) : the gmt offset string usually in the format GMT+1 or GMT+2 etc
sessionLineStyle (simple string) : the line stile for the session high low lines
sessXcol (simple color) : - the color for the box color that will color the session
@return void
msToHmsString(ms)
converts milliseconds into an hh:mm string. For example, 61000 ms to '0:01:01'
Parameters:
ms (int) : - the milliseconds to convert to hh:mm
@return string - the converted hh:mm string
countdownString(openToday, closeToday, showMarketsWeekends, oneDay)
that calculates how much time is left until the next session taking the session start and end times into account. Note this function does not work on intraday sessions.
Parameters:
openToday (int) : - timestamps of when the session opens in general - note its a series because the timestamp was created using the dst flag which is a series itself thus producing a timestamp series
closeToday (int) : - timestamp of when the session closes in general - note its a series because the timestamp was created using the dst flag which is a series itself thus producing a timestamp series
@return a countdown of when next the session opens or 'Open' if the session is open now
showMarketsWeekends (simple bool)
oneDay (simple int)
countdownStringSyd(sydOpenToday, sydCloseToday, showMarketsWeekends, oneDay)
that calculates how much time is left until the next session taking the session start and end times into account. special case of intraday sessions like sydney
Parameters:
sydOpenToday (int)
sydCloseToday (int)
showMarketsWeekends (simple bool)
oneDay (simple int)
Swing Data - SimplifiedThe swing data indicator by jfsrev but simplified. Thank you jfsrev for your work!
Bitcoin Halving Cycle Strategy ProBitcoin Halving Cycle Strategy Pro - Advanced Market Cycle Analysis Tool
This professional indicator analyzes Bitcoin's 4-year halving cycles using precise mathematical calculations. It identifies bull and bear market phases based on 500 days before and 560 days after each halving event, providing traders with data-driven market cycle insights.
Key Features:
• Automatic Bull/Bear Market Zone Detection with color-coded areas
• Historical Halving Analysis (2012-2028) with future projections
• Live Performance Tracking during bull phases (returns, max drawdown)
• Customizable cycle parameters (days before/after halving)
• Interactive info table showing current cycle phase and metrics
• Visual timeline markers for halving dates and cycle boundaries
Perfect for long-term Bitcoin investors, cycle analysts, and traders who want to understand market psychology and timing based on historical halving patterns. Uses proven 1060-day cycle theory backed by empirical data.
Aladin Pair Trading System v1Aladin Pair Trading System v1
What is This Indicator?
The Aladin Pair Trading System is a sophisticated tool designed to help traders identify profitable opportunities by comparing two related stocks that historically move together. Think of it as finding when one twin is running ahead or lagging behind the other - these moments often present trading opportunities as they tend to return to moving together.
Who Should Use This?
Beginners: Learn about statistical arbitrage and pair trading
Intermediate Traders: Execute mean-reversion strategies with confidence
Advanced Traders: Fine-tune parameters for optimal pair relationships
Portfolio Managers: Implement market-neutral strategies
💡 What is Pair Trading?
Imagine two ice cream shops next to each other. They usually have similar customer traffic because they're in the same area. If one day Shop A is packed while Shop B is empty, you might expect this imbalance to correct itself soon.
Pair trading works the same way:
You find two stocks that normally move together (like TCS and Infosys)
When one stock moves too far from the other, you trade expecting them to realign
You buy the lagging stock and sell the leading stock
When they come back together, you profit from both sides
Key Features
1. Z-Score Analysis
What it is: A statistical measure showing how far the price relationship has deviated from normal
What it means:
Z-Score near 0 = Normal relationship
Z-Score at +2 = Stock A is expensive relative to Stock B (Sell A, Buy B)
Z-Score at -2 = Stock A is cheap relative to Stock B (Buy A, Sell B)
2. Multiple Timeframe Analysis
Long-term Z-Score (300 bars): Shows the big picture trend
Short-term Z-Score (100 bars): Shows recent movements
Signal Z-Score (20 bars): Generates quick trading signals
3. Statistical Validation
The indicator checks if the pair is suitable for trading:
Correlation (must be > 0.7): Confirms the stocks move together
1.0 = Perfect positive correlation
0.7 = Strong correlation
Below 0.7 = Warning: pair may not be reliable
ADF P-Value (should be < 0.05): Tests if the relationship is stable
Low value = Good for pair trading
High value = Relationship may be random
Cointegration: Confirms long-term equilibrium relationship
YES = Pair tends to revert to mean
NO = Pair may drift apart permanently
Visual Elements Explained
Chart Zones (Color-Coded Areas)
Yellow Zone (-1.5 to +1.5)
Normal Zone: Relationship is stable
Action: Wait for better opportunities
Blue Zone (±1.5 to ±2.0)
Entry Zone: Deviation is significant
Action: Prepare for potential trades
Green/Red Zone (±2.0 to ±3.0)
Opportunity Zone: Strong deviation
Action: High-probability trade setups
Beyond ±3.0
Risk Limit: Extreme deviation
Action: Either maximum opportunity or structural break
Signal Arrows
Green Arrow Up (Buy A + Sell B):
Stock A is undervalued relative to B
Buy Stock A, Short Stock B
Red Arrow Down (Sell A + Buy B):
Stock A is overvalued relative to B
Sell Stock A, Buy Stock B
Settings Guide
Symbol Inputs
Pair Symbol (Symbol B): Choose the second stock to compare
Default: NSE:INFY (Infosys)
Example pairs: TCS/INFY, HDFCBANK/ICICIBANK, RELIANCE/ONGC
Z-Score Parameters
Long Z-Score Period (300): Historical context
Short Z-Score Period (100): Recent trend
Signal Period (20): Trading signals
Z-Score Threshold (2.0): Entry trigger level
Higher = Fewer but stronger signals
Lower = More frequent signals
Statistical Parameters
Correlation Period (240): How many bars to check correlation
Hurst Exponent Period (50): Measures mean-reversion tendency
Probability Lookback (100): Historical probability calculations
Trading Parameters
Entry Threshold (0.0): Minimum Z-score for entry
Risk Threshold (1.5): Warning level
Risk Limit (3.0): Maximum deviation to trade
How to Use (Step-by-Step)
Step 1: Choose Your Pair
Add the indicator to your chart (this becomes Stock A)
In settings, select Stock B (the comparison stock)
Choose stocks from the same sector for best results
Step 2: Verify Pair Quality
Check the Statistics Table (top-right corner):
✅ Correlation > 0.70 (Green = Good)
✅ ADF P-value < 0.05 (Green = Good)
✅ Cointegrated = YES (Green = Good)
If all three are green, the pair is suitable for trading!
Step 3: Wait for Signals
BUY SIGNAL (Green Arrow Up)
Z-Score crosses above -2.0
Action: Buy Stock A, Sell Stock B
Exit: When Z-Score returns to 0
SELL SIGNAL (Red Arrow Down)
Z-Score crosses below +2.0
Action: Sell Stock A, Buy Stock B
Exit: When Z-Score returns to 0
Step 4: Risk Management
Yellow Zone: Monitor only
Blue Zone: Prepare for entry
Green/Red Zone: Active trading zone
Beyond ±3.0: Maximum risk - use caution
⚠️ Important Warnings
Not All Pairs Work: Always check the statistics table first
Market Conditions Matter: Correlation can break during market stress
Use Stop Losses: Set stops at Z-Score ±3.5 or beyond
Position Sizing: Trade both legs with appropriate hedge ratios
Transaction Costs: Factor in brokerage and slippage for both stocks
Example Trade
Scenario: TCS vs INFOSYS
Correlation: 0.85 ✅
Z-Score: -2.3 (TCS is cheap vs INFY)
Action to be taken:
Buy 1lot of TCS Future
Sell 1lot of INFOSYS Future
Expected Outcome:
As Z-Score moves toward 0, TCS outperforms INFOSYS
Close both positions when Z-Score crosses 0
Profit from the convergence
Best Practices
Test Before Trading: Use paper trading first
Sector Focus: Choose pairs from the same industry
Monitor Statistics: Check correlation daily
Avoid News Events: Don't trade pairs during earnings/major news
Size Appropriately: Start small, scale with experience
Be Patient: Wait for high-quality setups (±2.0 or beyond)
What Makes This Indicator Unique?
Multi-timeframe Z-Score analysis: Three different perspectives
Statistical validation: Built-in correlation and cointegration tests
Visual risk zones: Easy-to-understand color-coded areas
Real-time statistics: Live pair quality monitoring
Beginner-friendly: Clear signals with educational zones
Technical Background
The indicator uses:
Engle-Granger Cointegration Test: Validates pair relationship
ADF (Augmented Dickey-Fuller) Test: Tests stationarity
Pearson Correlation: Measures linear relationship
Z-Score Normalization: Standardizes deviations
Log Returns: Handles price differences properly
Support & Community
For questions, suggestions, or to share your pair trading experiences:
Comment below the indicator
Share your successful pair combinations
Report any issues for quick fixes
Disclaimer
This indicator is for educational and informational purposes only. It does not constitute financial advice. Pair trading involves risk, including the risk of loss.
Always:
Do your own research
Understand the risks
Trade with money you can afford to lose
Consider consulting a financial advisor
📌 Quick Reference Card
Z-ScoreInterpretationAction-3.0 to -2.0A very cheap vs BStrong Buy A, Sell B-2.0 to -1.5A cheap vs BBuy A, Sell B-1.5 to +1.5Normal rangeHold/Wait+1.5 to +2.0A expensive vs BSell A, Buy B+2.0 to +3.0A very expensive vs BStrong Sell A, Buy B
Good Pair Statistics:
Correlation: > 0.70
ADF P-value: < 0.05
Cointegration: YES
Version: 1.0
Last Updated: 10th October 2025
Compatible: TradingView Pine Script v6
Happy Trading!
FOREXSOM Session Boxes (Local Time) — Asian, London & New YorkFOREXSOM Session Boxes (Local Time) highlights the three major Forex sessions — Asian, London, and New York — using your chart’s local timezone automatically.
This indicator helps traders visualize market structure, liquidity zones, and timing across global trading hours with accuracy and clarity.
Key Features
Automatically adjusts to your chart’s local timezone
Highlights Asian, London, and New York sessions with clean color zones
Works on all timeframes and asset classes
Ideal for Smart Money Concepts (SMC), ICT, and price action strategies
Helps identify range breakouts, session highs/lows, and liquidity grabs
How It Works
Each session box updates in real time to show the current range as the market develops.
The boxes reset at the end of each session, making it easy to compare volatility and liquidity shifts between regions.
Sessions (default times):
Asian: 17:00 – 03:00
London: 02:00 – 11:00
New York: 07:00 – 16:00
How to Use
Add the indicator to your chart.
Ensure your chart timezone matches your local time in chart settings.
Watch session ranges form and look for liquidity sweeps or breakouts between overlaps (London/New York).
Created by FOREXSOM
Empowering traders worldwide with precision-built tools for Smart Money and institutional trading education.
Date Marker📅 Date Marker
Date Marker is a simple, lightweight indicator that draws a single vertical line on a chosen date — ideal for quickly comparing how different charts looked at the same point in time.
Switch between symbols or timeframes, and the line automatically stays fixed at your selected date.
Perfect for studying market reactions to key events, earnings, announcements, or macro shifts.
Multi Brownian Forecast📊 Multi Brownian Forecast (Time-Adaptive, Probabilistic)
This indicator uses a sophisticated Geometric Brownian Motion (GBM) Monte Carlo simulation to project future price paths. It adapts to any chart timeframe and provides quantitative, multi-period probability signals.
---
🧠 Core Mathematical Methodology
The model relies on GBM, which is a continuous-time stochastic process that models asset prices.
1. Historical Analysis (Drift & Volatility):
* The script first calculates Logarithmic Returns over a user-defined Historical Lookback (Hours) .
* Drift ($\mu$): Computed as the average of the log returns.
* Volatility ($\sigma$): Computed as the standard deviation of the log returns.
* These values are then time-adapted to an hourly step, compensating for the chart's current timeframe (e.g., 5-minute, 1-hour).
2. Monte Carlo Simulation:
* It runs a specified Number of Simulations (e.g., 1000).
* For each simulation, the price is stepped forward hourly using the GBM formula, which incorporates the calculated drift and a random shock drawn from a normal distribution (generated via the Box-Muller transform ).
---
✨ Key Features
Probabilistic Quartile Forecast: Plots a dynamic "cone" of probability on the chart. It shows key price percentiles (Q1, Q2/Median, Q3, and Q4/Outer Bound) at the forecast's expiration, visualizing the expected range of price outcomes based on the simulations.
Multi-Period Probability Signals: This is the core signal feature. Users can define multiple, independent forecast periods (e.g., 4h, 16h, 48h) in a comma-separated list.
* For each period, a Probability Up and Probability Down is calculated based on hitting a custom Target Price Change (%) (e.g., 2%) at a certain confidence level given a simulation over the historical backlook.
* The probabilities are displayed in a chart table. The cell text turns white if the calculated probability exceeds the user-defined Signal Confidence (%) .
Conditional Fibonacci Retracement: Optionally displays a Fibonacci Retracement on the chart. This feature is only activated when one of the multi-period signals reaches its minimum confidence threshold, providing a contextual technical level when a probabilistic edge is found.
Advanced HMM - 3 States CompleteHidden Markov Model
Aconsistent challenge for quantitative traders is the frequent behaviour modification of financial
markets, often abruptly, due to changing periods of government policy, regulatory environment
and other macroeconomic effects. Such periods are known as market regimes. Detecting such
changes is a common, albeit difficult, process undertaken by quantitative market participants.
These various regimes lead to adjustments of asset returns via shifts in their means, variances,
autocorrelation and covariances. This impacts the effectiveness of time series methods that rely
on stationarity. In particular it can lead to dynamically-varying correlation, excess kurtosis ("fat
tails"), heteroskedasticity (volatility clustering) and skewed returns.
There is a clear need to effectively detect these regimes. This aids optimal deployment of
quantitative trading strategies and tuning the parameters within them. The modeling task then
becomes an attempt to identify when a new regime has occurred adjusting strategy deployment,
risk management and position sizing criteria accordingly.
A principal method for carrying out regime detection is to use a statistical time series tech
nique known as a Hidden Markov Model . These models are well-suited to the task since they
involve inference on "hidden" generative processes via "noisy" indirect observations correlated
to these processes. In this instance the hidden, or latent, process is the underlying regime state,
while the asset returns are the indirect noisy observations that are influenced by these states.
Smart Money Volume Activity [AlgoAlpha]🟠 OVERVIEW
This tool visualizes how Smart Money and Retail participants behave through lower-timeframe volume analysis. It detects volume spikes far beyond normal activity, classifies them as institutional or retail, and projects those zones as reactive levels. The script updates dynamically with each bar, showing when large players enter while tracking whether those events remain profitable. Each event is drawn as a horizontal line with bubble markers and summarized in a live P/L table comparing Smart Money versus Retail.
🟠 CONCEPTS
The core logic uses Z-score normalization on lower-timeframe volumes (like 5m inside a 1h chart). This lets the script detect statistically extreme bursts of buying or selling activity. It classifies each detected event as:
Smart Money — volume inside the candle body (suggesting hidden accumulation or distribution)
Retail — volume closing at bar extremes (suggesting chase entries or panic exits)
When new events appear, the script plots them as horizontal levels that persist until price interacts again. Each level acts as a potential reaction zone or liquidity footprint. The integrated P/L table then measures which class (Retail or Smart Money) is currently “winning” — comparing cumulative profitable versus losing volume.
🟠 FEATURES
Classifies flows into Smart Money or Retail based on candle-body context.
Displays live P/L comparison table for Smart vs Retail performance.
Alerts for each detected Smart or Retail buy/sell event.
🟠 USAGE
Setup : Add the script to any chart. Set Lower Timeframe Value (e.g., “5” for 5m) smaller than your main chart timeframe. The Period input controls how many bars are analyzed for the Z-score baseline. The Threshold (|Z|) decides how extreme a volume must be to plot a level.
Read the chart : Horizontal lines mark where heavy Smart or Retail volume occurred. Bright bubbles show the strongest events — their size reflects Z-score intensity. The on-chart table updates live: green cells show profitable flows, red cells show losing flows. A dominant green Smart Money row suggests institutions are currently controlling price.
See what others are doing :
Settings that matter : Raising Threshold (|Z|) filters noise, showing only large players. Increasing Period smooths results but reacts slower to new bursts. Use Show = “Both” for full comparison or isolate “Smart Money” / “Retail” to focus on one class.
Market Structure Report Library [TradingFinder]🔵 Introduction
Market Structure is one of the most fundamental concepts in Price Action and Smart Money theory. In simple terms, it represents how price moves between highs and lows and reveals which phase of the market cycle we are currently in uptrend, downtrend, or transition.
Each structure in the market is formed by a combination of Breaks of Structure (BoS) and Changes of Character (CHoCH) :
BoS occurs when the market breaks a previous high or low, confirming the continuation of the current trend.
CHoCH occurs when price breaks in the opposite direction for the first time, signaling a potential trend reversal.
Since price movement is inherently fractal, market structure can be analyzed on two distinct levels :
Major / External Structure: represents the dominant macro trend.
Minor / Internal Structure: represents corrective or smaller-scale movements within the larger trend.
🔵 Library Purpose
The “Market Structure Report Library” is designed to automatically detect the current market structure type in real time.
Without drawing or displaying any visuals, it analyzes raw price data and returns a series of logical and textual outputs (Return Values) that describe the current structural state of the market.
It provides the following information :
Trend Type :
External Trend (Major): Up Trend, Down Trend, No Trend
Internal Trend (Minor): Up Trend, Down Trend, No Trend
Structure Type :
BoS : Confirms trend continuation
CHoCH : Indicates a potential trend reversal
Consecutive BoS Counter : Measures trend strength on both Major and Minor levels.
Candle Type : Returns the current candle’s condition(Bullish, Bearish, Doji)
This library is specifically designed for use in Smart Money–based screeners, indicators, and algorithmic strategies.
It can analyze multiple symbols and timeframes simultaneously and return the exact structure type (BoS or CHoCH) and trend direction for each.
🔵 Function Outputs
The function MS() processes the price data and returns seven key outputs,
each representing a distinct structural state of the market. These values can be used in indicators, strategies, or multi-symbol screeners.
🟣 ExternalTrend
Type : string
Description : Represents the direction of the Major (External) market structure.
Possible values :
Up Trend
Down Trend
No Trend
This is determined based on the behavior of Major Pivots (swing highs/lows).
🟣 InternalTrend
Type : string
Description : Represents the direction of the Minor (Internal) market structure.
Possible values :
Up Trend
Down Trend
No Trend
🟣 M_State
Type : string
Description : Specifies the type of the latest Major Structure event.
Possible values :
BoS
CHoCH
🟣 m_State
Type : string
Description : Specifies the type of the latest Minor Structure event.
Possible values :
BoS
CHoCH
🟣 MBoS_Counter
Type : integer
Description : Counts the number of consecutive structural breaks (BoS) in the Major structure.
Useful for evaluating trend strength :
Increasing count: indicates trend continuation.
Reset to zero: typically occurs after a CHoCH.
🟣 mBoS_Counter
Type : integer
Description : Counts the number of consecutive structural breaks in the Minor structure.
Helps analyze the micro structure of the market on lower timeframes.
Higher value : strong internal trend.
Reset : indicates a minor pullback or reversal.
🟣 Candle_Type
Type : string
Description : Represents the type of the current candle.
Possible values :
Bullish
Bearish
Doji
import TFlab/Market_Structure_Report_Library_TradingFinder/1 as MSS
PP = input.int (5 , 'Market Structure Pivot Period' , group = 'Symbol 1' )
= MSS.MS(PP)
PnL PortfolioThis indicator provides a comprehensive, real-time overview of your open trading portfolio directly on the chart. It allows you to track up to 20 different trading pairs simultaneously.
For each asset, simply input the Pair Symbol, Average Entry Price, and Position Quantity. The script securely fetches the current market price and dynamically calculates and displays a customizable table showing:
Real-Time Profit/Loss ($)
Percentage PnL (%)
Entry Price and Position Quantity
The table uses color coding to clearly highlight profitable (green) or losing (red) positions, and its location on the chart (top/bottom, left/right) is fully adjustable.