High-Low BandsThis is a simple but powerful indicator. It calculates (selectable) moving averages separately from high , low and close .
It can be used as support-resistance, trend or volatility indicator.
Cerca negli script per "high low"
HIGH LOW just differentSo lets make more fun with discovering trends
here I put high pivot and low pivot and from it we make our lines based on them
look cool:)
High/Low LabelsThis simple Version 6 script labels each bar on the chart with Green labels noting HH for higher highs and HL for higher lows. And Red labels noting LH for lower highs and LL for lower lows. Works on any Trading View chart and any time frame. Any comments or suggestions, please do!
High/Low X Bars AgoThis indicator will plot a line on your chart that shows the highest high point between two previous points on the chart. It does this by reporting the highest point of X number of candles, and begins the look-back X number of candles ago.
Default candle group size is 50, and default look-back begins 50 candles back.
With these settings, the script will essentially plot the highest high point between the candle that printed 100 candles ago, and the candle that printed 50 candles ago.
Options are available for looking for the highest point, or lowest point, with configurable distances in the look-back and candle group ranges.
This script was custom built by Pine-Labs for a user who requested it.
High Low Markers v1Retrieves the previous day’s high using request.security(...), so it works on any timeframe, even intraday.
Creates a single label (stored in a var variable) at that previous day high.
Places the text on the right of the anchor point by using label.style_label_right.
Updates the label’s position each bar (or only on a new day, if desired) so it always reflects the most recent previous day’s high.
Highs-Lows Bands Trend FollowingTwo bands formed by moving averages of highs and lows.
The lower band should provide zone of support in uptrends while the upper band should provide zone of resistance during downtrends.
Bands that turn green in bullish trends should provide buy signals while bands that turn red in bearish trends should provide sell signals.
High/Low bandsGives good idea about trend.
In last 100 days the lowest price was this.
In last 100 days the highest price was this.
Price makes new 100 days high! (uptrend)
High_Low_ProjectionHigh Low Projections of daily/weekly/quarterly/yearly price movement. Dark/night mode version. Green when broken through to upside, red when broken through to bottom side.
High Low Bollinger Bands Better than Bollinger Bands for finding extreme points timed by an oscillator where the price is statistically likely to stay inside the boundaries.
Good for setting credit spreads such as call and put vertical spreads.
Stochastic Enhanced [DCAUT]█ Stochastic Enhanced
📊 ORIGINALITY & INNOVATION
The Stochastic Enhanced indicator builds upon George Lane's classic momentum oscillator (developed in the late 1950s) by providing comprehensive smoothing algorithm flexibility. While traditional implementations limit users to Simple Moving Average (SMA) smoothing, this enhanced version offers 21 advanced smoothing algorithms, allowing traders to optimize the indicator's characteristics for different market conditions and trading styles.
Key Improvements:
Extended from single SMA smoothing to 21 professional-grade algorithms including adaptive filters (KAMA, FRAMA), zero-lag methods (ZLEMA, T3), and advanced digital filters (Kalman, Laguerre)
Maintains backward compatibility with traditional Stochastic calculations through SMA default setting
Unified smoothing algorithm applies to both %K and %D lines for consistent signal processing characteristics
Enhanced visual feedback with clear color distinction and background fill highlighting for intuitive signal recognition
Comprehensive alert system covering crossovers and zone entries for systematic trade management
Differentiation from Traditional Stochastic:
Traditional Stochastic indicators use fixed SMA smoothing, which introduces consistent lag regardless of market volatility. This enhanced version addresses the limitation by offering adaptive algorithms that adjust to market conditions (KAMA, FRAMA), reduce lag without sacrificing smoothness (ZLEMA, T3, HMA), or provide superior noise filtering (Kalman Filter, Laguerre filters). The flexibility helps traders balance responsiveness and stability according to their specific needs.
📐 MATHEMATICAL FOUNDATION
Core Stochastic Calculation:
The Stochastic Oscillator measures the position of the current close relative to the high-low range over a specified period:
Step 1: Raw %K Calculation
%K_raw = 100 × (Close - Lowest Low) / (Highest High - Lowest Low)
Where:
Close = Current closing price
Lowest Low = Lowest low over the %K Length period
Highest High = Highest high over the %K Length period
Result ranges from 0 (close at period low) to 100 (close at period high)
Step 2: Smoothed %K Calculation
%K = MA(%K_raw, K Smoothing Period, MA Type)
Where:
MA = Selected moving average algorithm (SMA, EMA, etc.)
K Smoothing = 1 for Fast Stochastic, 3+ for Slow Stochastic
Traditional Fast Stochastic uses %K_raw directly without smoothing
Step 3: Signal Line %D Calculation
%D = MA(%K, D Smoothing Period, MA Type)
Where:
%D acts as a signal line and moving average of %K
D Smoothing typically set to 3 periods in traditional implementations
Both %K and %D use the same MA algorithm for consistent behavior
Available Smoothing Algorithms (21 Options):
Standard Moving Averages:
SMA (Simple): Equal-weighted average, traditional default, consistent lag characteristics
EMA (Exponential): Recent price emphasis, faster response to changes, exponential decay weighting
RMA (Rolling/Wilder's): Smoothed average used in RSI, less reactive than EMA
WMA (Weighted): Linear weighting favoring recent data, moderate responsiveness
VWMA (Volume-Weighted): Incorporates volume data, reflects market participation intensity
Advanced Moving Averages:
HMA (Hull): Reduced lag with smoothness, uses weighted moving averages and square root period
ALMA (Arnaud Legoux): Gaussian distribution weighting, minimal lag with good noise reduction
LSMA (Least Squares): Linear regression based, fits trend line to data points
DEMA (Double Exponential): Reduced lag compared to EMA, uses double smoothing technique
TEMA (Triple Exponential): Further lag reduction, triple smoothing with lag compensation
ZLEMA (Zero-Lag Exponential): Lag elimination attempt using error correction, very responsive
TMA (Triangular): Double-smoothed SMA, very smooth but slower response
Adaptive & Intelligent Filters:
T3 (Tilson T3): Six-pass exponential smoothing with volume factor adjustment, excellent smoothness
FRAMA (Fractal Adaptive): Adapts to market fractal dimension, faster in trends, slower in ranges
KAMA (Kaufman Adaptive): Efficiency ratio based adaptation, responds to volatility changes
McGinley Dynamic: Self-adjusting mechanism following price more accurately, reduced whipsaws
Kalman Filter: Optimal estimation algorithm from aerospace engineering, dynamic noise filtering
Advanced Digital Filters:
Ultimate Smoother: Advanced digital filter design, superior noise rejection with minimal lag
Laguerre Filter: Time-domain filter with N-order implementation, adjustable lag characteristics
Laguerre Binomial Filter: 6-pole Laguerre filter, extremely smooth output for long-term analysis
Super Smoother: Butterworth filter implementation, removes high-frequency noise effectively
📊 COMPREHENSIVE SIGNAL ANALYSIS
Absolute Level Interpretation (%K Line):
%K Above 80: Overbought condition, price near period high, potential reversal or pullback zone, caution for new long entries
%K in 70-80 Range: Strong upward momentum, bullish trend confirmation, uptrend likely continuing
%K in 50-70 Range: Moderate bullish momentum, neutral to positive outlook, consolidation or mild uptrend
%K in 30-50 Range: Moderate bearish momentum, neutral to negative outlook, consolidation or mild downtrend
%K in 20-30 Range: Strong downward momentum, bearish trend confirmation, downtrend likely continuing
%K Below 20: Oversold condition, price near period low, potential bounce or reversal zone, caution for new short entries
Crossover Signal Analysis:
%K Crosses Above %D (Bullish Cross): Momentum shifting bullish, faster line overtakes slower signal, consider long entry especially in oversold zone, strongest when occurring below 20 level
%K Crosses Below %D (Bearish Cross): Momentum shifting bearish, faster line falls below slower signal, consider short entry especially in overbought zone, strongest when occurring above 80 level
Crossover in Midrange (40-60): Less reliable signals, often in choppy sideways markets, require additional confirmation from trend or volume analysis
Multiple Failed Crosses: Indicates ranging market or choppy conditions, reduce position sizes or avoid trading until clear directional move
Advanced Divergence Patterns (%K Line vs Price):
Bullish Divergence: Price makes lower low while %K makes higher low, indicates weakening bearish momentum, potential trend reversal upward, more reliable when %K in oversold zone
Bearish Divergence: Price makes higher high while %K makes lower high, indicates weakening bullish momentum, potential trend reversal downward, more reliable when %K in overbought zone
Hidden Bullish Divergence: Price makes higher low while %K makes lower low, indicates trend continuation in uptrend, bullish trend strength confirmation
Hidden Bearish Divergence: Price makes lower high while %K makes higher high, indicates trend continuation in downtrend, bearish trend strength confirmation
Momentum Strength Analysis (%K Line Slope):
Steep %K Slope: Rapid momentum change, strong directional conviction, potential for extended moves but also increased reversal risk
Gradual %K Slope: Steady momentum development, sustainable trends more likely, lower probability of sharp reversals
Flat or Horizontal %K: Momentum stalling, potential reversal or consolidation ahead, wait for directional break before committing
%K Oscillation Within Range: Indicates ranging market, sideways price action, better suited for range-trading strategies than trend following
🎯 STRATEGIC APPLICATIONS
Mean Reversion Strategy (Range-Bound Markets):
Identify ranging market conditions using price action or Bollinger Bands
Wait for Stochastic to reach extreme zones (above 80 for overbought, below 20 for oversold)
Enter counter-trend position when %K crosses %D in extreme zone (sell on bearish cross above 80, buy on bullish cross below 20)
Set profit targets near opposite extreme or midline (50 level)
Use tight stop-loss above recent swing high/low to protect against breakout scenarios
Exit when Stochastic reaches opposite extreme or %K crosses %D in opposite direction
Trend Following with Momentum Confirmation:
Identify primary trend direction using higher timeframe analysis or moving averages
Wait for Stochastic pullback to oversold zone (<20) in uptrend or overbought zone (>80) in downtrend
Enter in trend direction when %K crosses %D confirming momentum shift (bullish cross in uptrend, bearish cross in downtrend)
Use wider stops to accommodate normal trend volatility
Add to position on subsequent pullbacks showing similar Stochastic pattern
Exit when Stochastic shows opposite extreme with failed cross or bearish/bullish divergence
Divergence-Based Reversal Strategy:
Scan for divergence between price and Stochastic at swing highs/lows
Confirm divergence with at least two price pivots showing divergent Stochastic readings
Wait for %K to cross %D in direction of anticipated reversal as entry trigger
Enter position in divergence direction with stop beyond recent swing extreme
Target profit at key support/resistance levels or Fibonacci retracements
Scale out as Stochastic reaches opposite extreme zone
Multi-Timeframe Momentum Alignment:
Analyze Stochastic on higher timeframe (4H or Daily) for primary trend bias
Switch to lower timeframe (1H or 15M) for precise entry timing
Only take trades where lower timeframe Stochastic signal aligns with higher timeframe momentum direction
Higher timeframe Stochastic in bullish zone (>50) = only take long entries on lower timeframe
Higher timeframe Stochastic in bearish zone (<50) = only take short entries on lower timeframe
Exit when lower timeframe shows counter-signal or higher timeframe momentum reverses
Zone Transition Strategy:
Monitor Stochastic for transitions between zones (oversold to neutral, neutral to overbought, etc.)
Enter long when Stochastic crosses above 20 (exiting oversold), signaling momentum shift from bearish to neutral/bullish
Enter short when Stochastic crosses below 80 (exiting overbought), signaling momentum shift from bullish to neutral/bearish
Use zone midpoint (50) as dynamic support/resistance for position management
Trail stops as Stochastic advances through favorable zones
Exit when Stochastic fails to maintain momentum and reverses back into prior zone
📋 DETAILED PARAMETER CONFIGURATION
%K Length (Default: 14):
Lower Values (5-9): Highly sensitive to price changes, generates more frequent signals, increased false signals in choppy markets, suitable for very short-term trading and scalping
Standard Values (10-14): Balanced sensitivity and reliability, traditional default (14) widely used,适合 swing trading and intraday strategies
Higher Values (15-21): Reduced sensitivity, smoother oscillations, fewer but potentially more reliable signals, better for position trading and lower timeframe noise reduction
Very High Values (21+): Slow response, long-term momentum measurement, fewer trading signals, suitable for weekly or monthly analysis
%K Smoothing (Default: 3):
Value 1: Fast Stochastic, uses raw %K calculation without additional smoothing, most responsive to price changes, generates earliest signals with higher noise
Value 3: Slow Stochastic (default), traditional smoothing level, reduces false signals while maintaining good responsiveness, widely accepted standard
Values 5-7: Very slow response, extremely smooth oscillations, significantly reduced whipsaws but delayed entry/exit timing
Recommendation: Default value 3 suits most trading scenarios, active short-term traders may use 1, conservative long-term positions use 5+
%D Smoothing (Default: 3):
Lower Values (1-2): Signal line closely follows %K, frequent crossover signals, useful for active trading but requires strict filtering
Standard Value (3): Traditional setting providing balanced signal line behavior, optimal for most trading applications
Higher Values (4-7): Smoother signal line, fewer crossover signals, reduced whipsaws but slower confirmation, better for trend trading
Very High Values (8+): Signal line becomes slow-moving reference, crossovers rare and highly significant, suitable for long-term position changes only
Smoothing Type Algorithm Selection:
For Trending Markets:
ZLEMA, DEMA, TEMA: Reduced lag for faster trend entry, quick response to momentum shifts, suitable for strong directional moves
HMA, ALMA: Good balance of smoothness and responsiveness, effective for clean trend following without excessive noise
EMA: Classic choice for trending markets, faster than SMA while maintaining reasonable stability
For Ranging/Choppy Markets:
Kalman Filter, Super Smoother: Superior noise filtering, reduces false signals in sideways action, helps identify genuine reversal points
Laguerre Filters: Smooth oscillations with adjustable lag, excellent for mean reversion strategies in ranges
T3, TMA: Very smooth output, filters out market noise effectively, clearer extreme zone identification
For Adaptive Market Conditions:
KAMA: Automatically adjusts to market efficiency, fast in trends and slow in congestion, reduces whipsaws during transitions
FRAMA: Adapts to fractal market structure, responsive during directional moves, conservative during uncertainty
McGinley Dynamic: Self-adjusting smoothing, follows price naturally, minimizes lag in trending markets while filtering noise in ranges
For Conservative Long-Term Analysis:
SMA: Traditional choice, predictable behavior, widely understood characteristics
RMA (Wilder's): Smooth oscillations, reduced sensitivity to outliers, consistent behavior across market conditions
Laguerre Binomial Filter: Extremely smooth output, ideal for weekly/monthly timeframe analysis, eliminates short-term noise completely
Source Selection:
Close (Default): Standard choice using closing prices, most common and widely tested
HLC3 or OHLC4: Incorporates more price information, reduces impact of sudden spikes or gaps, smoother oscillator behavior
HL2: Midpoint of high-low range, emphasizes intrabar volatility, useful for markets with wide intraday ranges
Custom Source: Can use other indicators as input (e.g., Heikin Ashi close, smoothed price), creates derivative momentum indicators
📈 PERFORMANCE ANALYSIS & COMPETITIVE ADVANTAGES
Responsiveness Characteristics:
Traditional SMA-Based Stochastic:
Fixed lag regardless of market conditions, consistent delay of approximately (K Smoothing + D Smoothing) / 2 periods
Equal treatment of trending and ranging markets, no adaptation to volatility changes
Predictable behavior but suboptimal in varying market regimes
Enhanced Version with Adaptive Algorithms:
KAMA and FRAMA reduce lag by up to 40-60% in strong trends compared to SMA while maintaining similar smoothness in ranges
ZLEMA and T3 provide near-zero lag characteristics for early entry signals with acceptable noise levels
Kalman Filter and Super Smoother offer superior noise rejection, reducing false signals in choppy conditions by estimations of 30-50% compared to SMA
Performance improvements vary by algorithm selection and market conditions
Signal Quality Improvements:
Adaptive algorithms help reduce whipsaw trades in ranging markets by adjusting sensitivity dynamically
Advanced filters (Kalman, Laguerre, Super Smoother) provide clearer extreme zone readings for mean reversion strategies
Zero-lag methods (ZLEMA, DEMA, TEMA) generate earlier crossover signals in trending markets for improved entry timing
Smoother algorithms (T3, Laguerre Binomial) reduce false extreme zone touches for more reliable overbought/oversold signals
Comparison with Standard Implementations:
Versus Basic Stochastic: Enhanced version offers 21 smoothing options versus single SMA, allowing optimization for specific market characteristics and trading styles
Versus RSI: Stochastic provides range-bound measurement (0-100) with clear extreme zones, RSI measures momentum speed, Stochastic offers clearer visual overbought/oversold identification
Versus MACD: Stochastic bounded oscillator suitable for mean reversion, MACD unbounded indicator better for trend strength, Stochastic excels in range-bound and oscillating markets
Versus CCI: Stochastic has fixed bounds (0-100) for consistent interpretation, CCI unbounded with variable extremes, Stochastic provides more standardized extreme readings across different instruments
Flexibility Advantages:
Single indicator adaptable to multiple strategies through algorithm selection rather than requiring different indicator variants
Ability to optimize smoothing characteristics for specific instruments (e.g., smoother for crypto volatility, faster for forex trends)
Multi-timeframe analysis with consistent algorithm across timeframes for coherent momentum picture
Backtesting capability with algorithm as optimization parameter for strategy development
Limitations and Considerations:
Increased complexity from multiple algorithm choices may lead to over-optimization if parameters are curve-fitted to historical data
Adaptive algorithms (KAMA, FRAMA) have adjustment periods during market regime changes where signals may be less reliable
Zero-lag algorithms sacrifice some smoothness for responsiveness, potentially increasing noise sensitivity in very choppy conditions
Performance characteristics vary significantly across algorithms, requiring understanding and testing before live implementation
Like all oscillators, Stochastic can remain in extreme zones for extended periods during strong trends, generating premature reversal signals
USAGE NOTES
This indicator is designed for technical analysis and educational purposes to provide traders with enhanced flexibility in momentum analysis. The Stochastic Oscillator has limitations and should not be used as the sole basis for trading decisions.
Important Considerations:
Algorithm performance varies with market conditions - no single smoothing method is optimal for all scenarios
Extreme zone signals (overbought/oversold) indicate potential reversal areas but not guaranteed turning points, especially in strong trends
Crossover signals may generate false entries during sideways choppy markets regardless of smoothing algorithm
Divergence patterns require confirmation from price action or additional indicators before trading
Past indicator characteristics and backtested results do not guarantee future performance
Always combine Stochastic analysis with proper risk management, position sizing, and multi-indicator confirmation
Test selected algorithm on historical data of specific instrument and timeframe before live trading
Market regime changes may require algorithm adjustment for optimal performance
The enhanced smoothing options are intended to provide tools for optimizing the indicator's behavior to match individual trading styles and market characteristics, not to create a perfect predictive tool. Responsible usage includes understanding the mathematical properties of selected algorithms and their appropriate application contexts.
Trading IQ - ICT LibraryLibrary "ICTlibrary"
Used to calculate various ICT related price levels and strategies. An ongoing project.
Hello Coders!
This library is meant for sourcing ICT related concepts. While some functions might generate more output than you require, you can specify "Lite Mode" as "true" in applicable functions to slim down necessary inputs.
isLastBar(userTF)
Identifies the last bar on the chart before a timeframe change
Parameters:
userTF (simple int) : the timeframe you wish to calculate the last bar for, must be converted to integer using 'timeframe.in_seconds()'
Returns: bool true if bar on chart is last bar of higher TF, dalse if bar on chart is not last bar of higher TF
necessaryData(atrTF)
returns necessaryData UDT for historical data access
Parameters:
atrTF (float) : user-selected timeframe ATR value.
Returns: logZ. log return Z score, used for calculating order blocks.
method gradBoxes(gradientBoxes, idColor, timeStart, bottom, top, rightCoordinate)
creates neon like effect for box drawings
Namespace types: array
Parameters:
gradientBoxes (array) : an array.new() to store the gradient boxes
idColor (color)
timeStart (int) : left point of box
bottom (float) : bottom of box price point
top (float) : top of box price point
rightCoordinate (int) : right point of box
Returns: void
checkIfTraded(tradeName)
checks if recent trade is of specific name
Parameters:
tradeName (string)
Returns: bool true if recent trade id matches target name, false otherwise
checkIfClosed(tradeName)
checks if recent closed trade is of specific name
Parameters:
tradeName (string)
Returns: bool true if recent closed trade id matches target name, false otherwise
IQZZ(atrMult, finalTF)
custom ZZ to quickly determine market direction.
Parameters:
atrMult (float) : an atr multiplier used to determine the required price move for a ZZ direction change
finalTF (string) : the timeframe used for the atr calcuation
Returns: dir market direction. Up => 1, down => -1
method drawBos(id, startPoint, getKeyPointTime, getKeyPointPrice, col, showBOS, isUp)
calculates and draws Break Of Structure
Namespace types: array
Parameters:
id (array)
startPoint (chart.point)
getKeyPointTime (int) : the actual time of startPoint, simplystartPoint.time
getKeyPointPrice (float) : the actual time of startPoint, simplystartPoint.price
col (color) : color of the BoS line / label
showBOS (bool) : whether to show label/line. This function still calculates internally for other ICT related concepts even if not drawn.
isUp (bool) : whether BoS happened during price increase or price decrease.
Returns: void
method drawMSS(id, startPoint, getKeyPointTime, getKeyPointPrice, col, showMSS, isUp, upRejections, dnRejections, highArr, lowArr, timeArr, closeArr, openArr, atrTFarr, upRejectionsPrices, dnRejectionsPrices)
calculates and draws Market Structure Shift. This data is also used to calculate Rejection Blocks.
Namespace types: array
Parameters:
id (array)
startPoint (chart.point)
getKeyPointTime (int) : the actual time of startPoint, simplystartPoint.time
getKeyPointPrice (float) : the actual time of startPoint, simplystartPoint.price
col (color) : color of the MSS line / label
showMSS (bool) : whether to show label/line. This function still calculates internally for other ICT related concepts even if not drawn.
isUp (bool) : whether MSS happened during price increase or price decrease.
upRejections (array)
dnRejections (array)
highArr (array) : array containing historical highs, should be taken from the UDT "necessaryData" defined above
lowArr (array) : array containing historical lows, should be taken from the UDT "necessaryData" defined above
timeArr (array) : array containing historical times, should be taken from the UDT "necessaryData" defined above
closeArr (array) : array containing historical closes, should be taken from the UDT "necessaryData" defined above
openArr (array) : array containing historical opens, should be taken from the UDT "necessaryData" defined above
atrTFarr (array) : array containing historical atr values (of user-selected TF), should be taken from the UDT "necessaryData" defined above
upRejectionsPrices (array) : array containing up rejections prices. Is sorted and used to determine selective looping for invalidations.
dnRejectionsPrices (array) : array containing down rejections prices. Is sorted and used to determine selective looping for invalidations.
Returns: void
method getTime(id, compare, timeArr)
gets time of inputted price (compare) in an array of data
this is useful when the user-selected timeframe for ICT concepts is greater than the chart's timeframe
Namespace types: array
Parameters:
id (array) : the array of data to search through, to find which index has the same value as "compare"
compare (float) : the target data point to find in the array
timeArr (array) : array of historical times
Returns: the time that the data point in the array was recorded
method OB(id, highArr, signArr, lowArr, timeArr, sign)
store bullish orderblock data
Namespace types: array
Parameters:
id (array)
highArr (array) : array of historical highs
signArr (array) : array of historical price direction "math.sign(close - open)"
lowArr (array) : array of historical lows
timeArr (array) : array of historical times
sign (int) : orderblock direction, -1 => bullish, 1 => bearish
Returns: void
OTEstrat(OTEstart, future, closeArr, highArr, lowArr, timeArr, longOTEPT, longOTESL, longOTElevel, shortOTEPT, shortOTESL, shortOTElevel, structureDirection, oteLongs, atrTF, oteShorts)
executes the OTE strategy
Parameters:
OTEstart (chart.point)
future (int) : future time point for drawings
closeArr (array) : array of historical closes
highArr (array) : array of historical highs
lowArr (array) : array of historical lows
timeArr (array) : array of historical times
longOTEPT (string) : user-selected long OTE profit target, please create an input.string() for this using the example below
longOTESL (int) : user-selected long OTE stop loss, please create an input.string() for this using the example below
longOTElevel (float) : long entry price of selected retracement ratio for OTE
shortOTEPT (string) : user-selected short OTE profit target, please create an input.string() for this using the example below
shortOTESL (int) : user-selected short OTE stop loss, please create an input.string() for this using the example below
shortOTElevel (float) : short entry price of selected retracement ratio for OTE
structureDirection (string) : current market structure direction, this should be "Up" or "Down". This is used to cancel pending orders if market structure changes
oteLongs (bool) : input.bool() for whether OTE longs can be executed
atrTF (float) : atr of the user-seleceted TF
oteShorts (bool) : input.bool() for whether OTE shorts can be executed
@exampleInputs
oteLongs = input.bool(defval = false, title = "OTE Longs", group = "Optimal Trade Entry")
longOTElevel = input.float(defval = 0.79, title = "Long Entry Retracement Level", options = , group = "Optimal Trade Entry")
longOTEPT = input.string(defval = "-0.5", title = "Long TP", options = , group = "Optimal Trade Entry")
longOTESL = input.int(defval = 0, title = "How Many Ticks Below Swing Low For Stop Loss", group = "Optimal Trade Entry")
oteShorts = input.bool(defval = false, title = "OTE Shorts", group = "Optimal Trade Entry")
shortOTElevel = input.float(defval = 0.79, title = "Short Entry Retracement Level", options = , group = "Optimal Trade Entry")
shortOTEPT = input.string(defval = "-0.5", title = "Short TP", options = , group = "Optimal Trade Entry")
shortOTESL = input.int(defval = 0, title = "How Many Ticks Above Swing Low For Stop Loss", group = "Optimal Trade Entry")
Returns: void (0)
displacement(logZ, atrTFreg, highArr, timeArr, lowArr, upDispShow, dnDispShow, masterCoords, labelLevels, dispUpcol, rightCoordinate, dispDncol, noBorders)
calculates and draws dispacements
Parameters:
logZ (float) : log return of current price, used to determine a "significant price move" for a displacement
atrTFreg (float) : atr of user-seleceted timeframe
highArr (array) : array of historical highs
timeArr (array) : array of historical times
lowArr (array) : array of historical lows
upDispShow (int) : amount of historical upside displacements to show
dnDispShow (int) : amount of historical downside displacements to show
masterCoords (map) : a map to push the most recent displacement prices into, useful for having key levels in one data structure
labelLevels (string) : used to determine label placement for the displacement, can be inside box, outside box, or none, example below
dispUpcol (color) : upside displacement color
rightCoordinate (int) : future time for displacement drawing, best is "last_bar_time"
dispDncol (color) : downside displacement color
noBorders (bool) : input.bool() to remove box borders, example below
@exampleInputs
labelLevels = input.string(defval = "Inside" , title = "Box Label Placement", options = )
noBorders = input.bool(defval = false, title = "No Borders On Levels")
Returns: void
method getStrongLow(id, startIndex, timeArr, lowArr, strongLowPoints)
unshift strong low data to array id
Namespace types: array
Parameters:
id (array)
startIndex (int) : the starting index for the timeArr array of the UDT "necessaryData".
this point should start from at least 1 pivot prior to find the low before an upside BoS
timeArr (array) : array of historical times
lowArr (array) : array of historical lows
strongLowPoints (array) : array of strong low prices. Used to retrieve highest strong low price and see if need for
removal of invalidated strong lows
Returns: void
method getStrongHigh(id, startIndex, timeArr, highArr, strongHighPoints)
unshift strong high data to array id
Namespace types: array
Parameters:
id (array)
startIndex (int) : the starting index for the timeArr array of the UDT "necessaryData".
this point should start from at least 1 pivot prior to find the high before a downside BoS
timeArr (array) : array of historical times
highArr (array) : array of historical highs
strongHighPoints (array)
Returns: void
equalLevels(highArr, lowArr, timeArr, rightCoordinate, equalHighsCol, equalLowsCol, liteMode)
used to calculate recent equal highs or equal lows
Parameters:
highArr (array) : array of historical highs
lowArr (array) : array of historical lows
timeArr (array) : array of historical times
rightCoordinate (int) : a future time (right for boxes, x2 for lines)
equalHighsCol (color) : user-selected color for equal highs drawings
equalLowsCol (color) : user-selected color for equal lows drawings
liteMode (bool) : optional for a lite mode version of an ICT strategy. For more control over drawings leave as "True", "False" will apply neon effects
Returns: void
quickTime(timeString)
used to quickly determine if a user-inputted time range is currently active in NYT time
Parameters:
timeString (string) : a time range
Returns: true if session is active, false if session is inactive
macros(showMacros, noBorders)
used to calculate and draw session macros
Parameters:
showMacros (bool) : an input.bool() or simple bool to determine whether to activate the function
noBorders (bool) : an input.bool() to determine whether the box anchored to the session should have borders
Returns: void
po3(tf, left, right, show)
use to calculate HTF po3 candle
@tip only call this function on "barstate.islast"
Parameters:
tf (simple string)
left (int) : the left point of the candle, calculated as bar_index + left,
right (int) : :the right point of the candle, calculated as bar_index + right,
show (bool) : input.bool() whether to show the po3 candle or not
Returns: void
silverBullet(silverBulletStratLong, silverBulletStratShort, future, userTF, H, L, H2, L2, noBorders, silverBulletLongTP, historicalPoints, historicalData, silverBulletLongSL, silverBulletShortTP, silverBulletShortSL)
used to execute the Silver Bullet Strategy
Parameters:
silverBulletStratLong (simple bool)
silverBulletStratShort (simple bool)
future (int) : a future time, used for drawings, example "last_bar_time"
userTF (simple int)
H (float) : the high price of the user-selected TF
L (float) : the low price of the user-selected TF
H2 (float) : the high price of the user-selected TF
L2 (float) : the low price of the user-selected TF
noBorders (bool) : an input.bool() used to remove the borders from box drawings
silverBulletLongTP (series silverBulletLevels)
historicalPoints (array)
historicalData (necessaryData)
silverBulletLongSL (series silverBulletLevels)
silverBulletShortTP (series silverBulletLevels)
silverBulletShortSL (series silverBulletLevels)
Returns: void
method invalidFVGcheck(FVGarr, upFVGpricesSorted, dnFVGpricesSorted)
check if existing FVGs are still valid
Namespace types: array
Parameters:
FVGarr (array)
upFVGpricesSorted (array) : an array of bullish FVG prices, used to selective search through FVG array to remove invalidated levels
dnFVGpricesSorted (array) : an array of bearish FVG prices, used to selective search through FVG array to remove invalidated levels
Returns: void (0)
method drawFVG(counter, FVGshow, FVGname, FVGcol, data, masterCoords, labelLevels, borderTransp, liteMode, rightCoordinate)
draws FVGs on last bar
Namespace types: map
Parameters:
counter (map) : a counter, as map, keeping count of the number of FVGs drawn, makes sure that there aren't more FVGs drawn
than int FVGshow
FVGshow (int) : the number of FVGs to show. There should be a bullish FVG show and bearish FVG show. This function "drawFVG" is used separately
for bearish FVG and bullish FVG.
FVGname (string) : the name of the FVG, "FVG Up" or "FVG Down"
FVGcol (color) : desired FVG color
data (FVG)
masterCoords (map) : a map containing the names and price points of key levels. Used to define price ranges.
labelLevels (string) : an input.string with options "Inside", "Outside", "Remove". Determines whether FVG labels should be inside box, outside,
or na.
borderTransp (int)
liteMode (bool)
rightCoordinate (int) : the right coordinate of any drawings. Must be a time point.
Returns: void
invalidBlockCheck(bullishOBbox, bearishOBbox, userTF)
check if existing order blocks are still valid
Parameters:
bullishOBbox (array) : an array declared using the UDT orderBlock that contains bullish order block related data
bearishOBbox (array) : an array declared using the UDT orderBlock that contains bearish order block related data
userTF (simple int)
Returns: void (0)
method lastBarRejections(id, rejectionColor, idShow, rejectionString, labelLevels, borderTransp, liteMode, rightCoordinate, masterCoords)
draws rejectionBlocks on last bar
Namespace types: array
Parameters:
id (array) : the array, an array of rejection block data declared using the UDT rejection block
rejectionColor (color) : the desired color of the rejection box
idShow (int)
rejectionString (string) : the desired name of the rejection blocks
labelLevels (string) : an input.string() to determine if labels for the block should be inside the box, outside, or none.
borderTransp (int)
liteMode (bool) : an input.bool(). True = neon effect, false = no neon.
rightCoordinate (int) : atime for the right coordinate of the box
masterCoords (map) : a map that stores the price of key levels and assigns them a name, used to determine price ranges
Returns: void
method OBdraw(id, OBshow, BBshow, OBcol, BBcol, bullishString, bearishString, isBullish, labelLevels, borderTransp, liteMode, rightCoordinate, masterCoords)
draws orderblocks and breaker blocks for data stored in UDT array()
Namespace types: array
Parameters:
id (array) : the array, an array of order block data declared using the UDT orderblock
OBshow (int) : the number of order blocks to show
BBshow (int) : the number of breaker blocks to show
OBcol (color) : color of order blocks
BBcol (color) : color of breaker blocks
bullishString (string) : the title of bullish blocks, which is a regular bullish orderblock or a bearish orderblock that's converted to breakerblock
bearishString (string) : the title of bearish blocks, which is a regular bearish orderblock or a bullish orderblock that's converted to breakerblock
isBullish (bool) : whether the array contains bullish orderblocks or bearish orderblocks. If bullish orderblocks,
the array will naturally contain bearish BB, and if bearish OB, the array will naturally contain bullish BB
labelLevels (string) : an input.string() to determine if labels for the block should be inside the box, outside, or none.
borderTransp (int)
liteMode (bool) : an input.bool(). True = neon effect, false = no neon.
rightCoordinate (int) : atime for the right coordinate of the box
masterCoords (map) : a map that stores the price of key levels and assigns them a name, used to determine price ranges
Returns: void
FVG
UDT for FVG calcualtions
Fields:
H (series float) : high price of user-selected timeframe
L (series float) : low price of user-selected timeframe
direction (series string) : FVG direction => "Up" or "Down"
T (series int) : => time of bar on user-selected timeframe where FVG was created
fvgLabel (series label) : optional label for FVG
fvgLineTop (series line) : optional line for top of FVG
fvgLineBot (series line) : optional line for bottom of FVG
fvgBox (series box) : optional box for FVG
labelLine
quickly pair a line and label together as UDT
Fields:
lin (series line) : Line you wish to pair with label
lab (series label) : Label you wish to pair with line
orderBlock
UDT for order block calculations
Fields:
orderBlockData (array) : array containing order block x and y points
orderBlockBox (series box) : optional order block box
vioCount (series int) : = 0 violation count of the order block. 0 = Order Block, 1 = Breaker Block
traded (series bool)
status (series string) : = "OB" status == "OB" => Level is order block. status == "BB" => Level is breaker block.
orderBlockLab (series label) : options label for the order block / breaker block.
strongPoints
UDT for strong highs and strong lows
Fields:
price (series float) : price of the strong high or strong low
timeAtprice (series int) : time of the strong high or strong low
strongPointLabel (series label) : optional label for strong point
strongPointLine (series line) : optional line for strong point
overlayLine (series line) : optional lines for strong point to enhance visibility
overlayLine2 (series line) : optional lines for strong point to enhance visibility
displacement
UDT for dispacements
Fields:
highPrice (series float) : high price of displacement
lowPrice (series float) : low price of displacement
timeAtPrice (series int) : time of bar where displacement occurred
displacementBox (series box) : optional box to draw displacement
displacementLab (series label) : optional label for displacement
po3data
UDT for po3 calculations
Fields:
dHigh (series float) : higher timeframe high price
dLow (series float) : higher timeframe low price
dOpen (series float) : higher timeframe open price
dClose (series float) : higher timeframe close price
po3box (series box) : box to draw po3 candle body
po3line (array) : line array to draw po3 wicks
po3Labels (array) : label array to label price points of po3 candle
macros
UDT for session macros
Fields:
sessions (array) : Array of sessions, you can populate this array using the "quickTime" function located above "export macros".
prices (matrix) : Matrix of session data -> open, high, low, close, time
sessionTimes (array) : Array of session names. Pairs with array sessions.
sessionLines (matrix) : Optional array for sesion drawings.
OTEtimes
UDT for data storage and drawings associated with OTE strategy
Fields:
upTimes (array) : time of highest point before trade is taken
dnTimes (array) : time of lowest point before trade is taken
tpLineLong (series line) : line to mark tp level long
tpLabelLong (series label) : label to mark tp level long
slLineLong (series line) : line to mark sl level long
slLabelLong (series label) : label to mark sl level long
tpLineShort (series line) : line to mark tp level short
tpLabelShort (series label) : label to mark tp level short
slLineShort (series line) : line to mark sl level short
slLabelShort (series label) : label to mark sl level short
sweeps
UDT for data storage and drawings associated with liquidity sweeps
Fields:
upSweeps (matrix) : matrix containing liquidity sweep price points and time points for up sweeps
dnSweeps (matrix) : matrix containing liquidity sweep price points and time points for down sweeps
upSweepDrawings (array) : optional up sweep box array. Pair the size of this array with the rows or columns,
dnSweepDrawings (array) : optional up sweep box array. Pair the size of this array with the rows or columns,
raidExitDrawings
UDT for drawings associated with the Liquidity Raid Strategy
Fields:
tpLine (series line) : tp line for the liquidity raid entry
tpLabel (series label) : tp label for the liquidity raid entry
slLine (series line) : sl line for the liquidity raid entry
slLabel (series label) : sl label for the liquidity raid entry
m2022
UDT for data storage and drawings associated with the Model 2022 Strategy
Fields:
mTime (series int) : time of the FVG where entry limit order is placed
mIndex (series int) : array index of FVG where entry limit order is placed. This requires an array of FVG data, which is defined above.
mEntryDistance (series float) : the distance of the FVG to the 50% range. M2022 looks for the fvg closest to 50% mark of range.
mEntry (series float) : the entry price for the most eligible fvg
fvgHigh (series float) : the high point of the eligible fvg
fvgLow (series float) : the low point of the eligible fvg
longFVGentryBox (series box) : long FVG box, used to draw the eligible FVG
shortFVGentryBox (series box) : short FVG box, used to draw the eligible FVG
line50P (series line) : line used to mark 50% of the range
line100P (series line) : line used to mark 100% (top) of the range
line0P (series line) : line used to mark 0% (bottom) of the range
label50P (series label) : label used to mark 50% of the range
label100P (series label) : label used to mark 100% (top) of the range
label0P (series label) : label used to mark 0% (bottom) of the range
sweepData (array)
silverBullet
UDT for data storage and drawings associated with the Silver Bullet Strategy
Fields:
session (series bool)
sessionStr (series string) : name of the session for silver bullet
sessionBias (series string)
sessionHigh (series float) : = high high of session // use math.max(silverBullet.sessionHigh, high)
sessionLow (series float) : = low low of session // use math.min(silverBullet.sessionLow, low)
sessionFVG (series float) : if applicable, the FVG created during the session
sessionFVGdraw (series box) : if applicable, draw the FVG created during the session
traded (series bool)
tp (series float) : tp of trade entered at the session FVG
sl (series float) : sl of trade entered at the session FVG
sessionDraw (series box) : optional draw session with box
sessionDrawLabel (series label) : optional label session with label
silverBulletDrawings
UDT for trade exit drawings associated with the Silver Bullet Strategy
Fields:
tpLine (series line) : tp line drawing for strategy
tpLabel (series label) : tp label drawing for strategy
slLine (series line) : sl line drawing for strategy
slLabel (series label) : sl label drawing for strategy
unicornModel
UDT for data storage and drawings associated with the Unicorn Model Strategy
Fields:
hPoint (chart.point)
hPoint2 (chart.point)
hPoint3 (chart.point)
breakerBlock (series box) : used to draw the breaker block required for the Unicorn Model
FVG (series box) : used to draw the FVG required for the Unicorn model
topBlock (series float) : price of top of breaker block, can be used to detail trade entry
botBlock (series float) : price of bottom of breaker block, can be used to detail trade entry
startBlock (series int) : start time of the breaker block, used to set the "left = " param for the box
includes (array) : used to store the time of the breaker block, or FVG, or the chart point sequence that setup the Unicorn Model.
entry (series float) : // eligible entry price, for longs"math.max(topBlock, FVG.get_top())",
tpLine (series line) : optional line to mark PT
tpLabel (series label) : optional label to mark PT
slLine (series line) : optional line to mark SL
slLabel (series label) : optional label to mark SL
rejectionBlocks
UDT for data storage and drawings associated with rejection blocks
Fields:
rejectionPoint (chart.point)
bodyPrice (series float) : candle body price closest to the rejection point, for "Up" rejections => math.max(open, close),
rejectionBox (series box) : optional box drawing of the rejection block
rejectionLabel (series label) : optional label for the rejection block
equalLevelsDraw
UDT for data storage and drawings associated with equal highs / equal lows
Fields:
connector (series line) : single line placed at the first high or low, y = avgerage of distinguished equal highs/lows
connectorLab (series label) : optional label to be placed at the highs or lows
levels (array) : array containing the equal highs or lows prices
times (array) : array containing the equal highs or lows individual times
startTime (series int) : the time of the first high or low that forms a sequence of equal highs or lows
radiate (array) : options label to "radiate" the label in connector lab. Can be used for anything
necessaryData
UDT for data storage of historical price points.
Fields:
highArr (array) : array containing historical high points
lowArr (array) : array containing historical low points
timeArr (array) : array containing historical time points
logArr (array) : array containing historical log returns
signArr (array) : array containing historical price directions
closeArr (array) : array containing historical close points
binaryTimeArr (array) : array containing historical time points, uses "push" instead of "unshift" to allow for binary search
binaryCloseArr (array) : array containing historical close points, uses "push" instead of "unshift" to allow the correct
binaryOpenArr (array) : array containing historical optn points, uses "push" instead of "unshift" to allow the correct
atrTFarr (array) : array containing historical user-selected TF atr points
openArr (array) : array containing historical open points
Smart Market Structure and Swing Points, version 1.0Smart Market Structure and Swing Points, Version 1.0
Overview
The Smart Market Structure and Swing Points script is designed to provide advanced insights into market structure and key swing points. This script helps identify important highs and lows, trend direction changes (structure breaks), and swing points, enhancing decision-making for both trend-following and reversal strategies. See below for detail presentation and why it has unique features.
Unique Features of the New Script
Market Structure Identification : Analyzes and marks key highs and lows to determine market structure, including higher highs, lower highs, higher lows, and lower lows.
Customizable Detection Length : Allows users to set the length for detecting highs and lows, providing flexibility to adapt to different market conditions and timeframes. Default value is 5 bars, but can be changed if needed.
Visual Signal Indicators (Labels) : Plots labels on the chart to indicate higher highs (HH), lower highs (LH), higher lows (HL), and lower lows (LL), along with corresponding RSI values, offering clear visual cues for market structure analysis. The indication of RSI values directly on high and low points enables to better judge whether the points are strong references (extreme RSI values) or weak references (middle RSI values)
Dynamic Trend Lines : Draws solid and dotted lines to connect significant highs and lows, visually representing the current trend direction and potential trend changes. Dashed lines indicates structure breaks.
Swing High and Swing Low Detection : Identifies and marks the most recent swing highs and swing lows, helping traders spot potential reversal points and key levels for setting stop losses or take profit targets .
Originality and Usefulness
This script combines market structure, trend breaks and RSI to provide a more robust view of market dynamic by indicating the strength or weakness of swing points , in that way the script is unique.
Signal Description
The script includes various signal features that highlight potential trading opportunities based on market structure:
Higher Highs (HH) and Higher Lows (HL) : These labels are plotted when new highs or lows are formed, indicating a continuation of an uptrend. The labels are positioned with consideration of the Average True Range (ATR) for better visibility.
Lower Highs (LH) and Lower Lows (LL) : These labels are plotted when new highs or lows are formed, indicating a continuation of a downtrend. The labels include RSI values to provide additional information on the strength or weakness of the points.
Trend Direction Change : Dotted lines are drawn to indicate potential trend direction changes when the script detects significant shifts in market structure.
Swing Highs and Swing Lows : These are identified based on a customizable swing length, marking recent significant highs and lows to highlight potential reversal points.
These signals help identify high-probability turning points and confirm trend direction by ensuring that the market structure aligns with the trading strategy.
Detailed Description
Input Variables
Length for High/Low Detection (`length`) : Defines the range to check for highs and lows. Default is 5.
RSI Length (`rsilength`) : The number of periods to calculate the RSI. Default is 14.
Functionality
Market Structure Calculation : The script determines the highest high and lowest low within the specified range to identify key points in market structure.
```pine
h = ta.highest(high, length * 2 + 1)
l = ta.lowest(low, length * 2 + 1)
```
Directional Logic : Variables and functions manage the state of the indicator, updating highs and lows based on the current trend direction.
```pine
var bool dirUp = false
var float lastLow = high * 100
var float lastHigh = 0.0
// Additional variables for tracking state
```
Drawing Lines and Labels : Functions draw lines and labels on the chart to visualize market structure and trend changes.
```pine
f_drawLine() =>
_li_color = dirUp ? color.red : color.lime
line.new(x1=timeHigh - length, y1=lastHigh, x2=timeLow - length, y2=lastLow, color=_li_color, width=3, style=line.style_solid, xloc=xloc.bar_index)
f_drawLastLine() =>
_li_color = dirUp ? color.blue : color.blue
if timeHigh > timeLow
line.new(x1=timeHigh - length, y1=lastHigh, x2=bar_index, y2=low, color=_li_color, width=2, style=line.style_dotted, xloc=xloc.bar_index)
else
line.new(x1=timeLow - length, y1=lastLow, x2=bar_index, y2=high, color=_li_color, width=2, style=line.style_dotted, xloc=xloc.bar_index)
```
Updating Highs and Lows : The main logic updates highs and lows based on the current trend direction, adding labels for new higher highs, lower highs, higher lows, and lower lows.
```pine
if dirUp
if f_isMin(length)
lastLow := low
// Additional logic for updating lows and labels
if f_isMax(length) and high > lastLow
lastHigh := high
// Additional logic for updating highs and labels
dirUp := false
li := f_drawLine()
```
Swing Highs and Lows : The script identifies recent swing highs and swing lows based on a customizable swing length, drawing lines to mark these points.
```pine
swingLength = 3 * length
isSwingHigh = ta.highestbars(high, swingLength) == 0
isSwingLow = ta.lowestbars(low, swingLength) == 0
if (isSwingHigh)
if (na(highLine))
highLine := line.new(bar_index, high, bar_index, high, color=color.green, style=line.style_solid, width=1)
else
line.set_xy1(highLine, bar_index, high)
line.set_xy2(highLine, bar_index + swingLength, high)
if (isSwingLow)
if (na(lowLine))
lowLine := line.new(bar_index, low, bar_index, low, color=color.red, style=line.style_solid, width=1)
else
line.set_xy1(lowLine, bar_index, low)
line.set_xy2(lowLine, bar_index + swingLength, low)
```
How to Use
Configuring Inputs : Adjust the detection length and RSI length as needed. Modify the lookback periods to suit your trading strategy. The indicator is adaptable and can be used on any timeframe.
Interpreting the Indicator : Use the labels and lines to gauge market structure and trend direction. Look for higher highs, lower highs, higher lows, and lower lows to confirm market structure.
Signal Confirmation : Pay attention to the labels and lines that provide signals for potential trend changes and swing points. Use these signals to better time entries and exits.
This script provides a detailed view of market structure and swing points, helping make more informed decisions by considering key highs and lows, trend direction changes, and the strength or weakness of swing points.