// --- True range for label positioning ---
tr = ta.tr(true)
// --- Bias Detection for EMA (no chart labels now) ---
bullishBias = (emaValue > emaValue2) and (emaValue2 > emaValue3)
bearishBias = (emaValue < emaValue2) and (emaValue2 < emaValue3)
// === FVG SETTINGS ===
isFvgToShow = input(true, title='Display FVG', group="Fair Value Gap")
bullishFvgColor = input.color(color.new(color.green, 50), 'Bullish FVG Color', group="Fair Value Gap")
bearishFvgColor = input.color(color.new(color.red, 50), 'Bearish FVG Color', group="Fair Value Gap")
mitigatedFvgColor = input.color(color.new(color.gray, 50), 'Mitigated FVG Color', group="Fair Value Gap")
fvgHistoryNbr = input.int(5, 'Number of FVG to show', minval=1, maxval=50, group="Fair Value Gap")
isMitigatedFvgToReduce = input(false, title='Reduce mitigated FVG', group="Fair Value Gap")
// === DATA STRUCTURES ===
// For Liquidity
type liquidity
float value
int barStart
int barEnd
line liquidityLine
bool broken
label sweep
var array bullishLiquidity = array.new()
var array bearishLiquidity = array.new()
// For FVG
var array fvgBoxes = array.new_box(0)
var array fvgTypes = array.new_bool(0)
var array fvgLabels = array.new_label(0)
var array isFvgMitigated = array.new_bool(0)
// === FVG FUNCTIONS ===
FVGDraw(_boxes, _fvgTypes, _isFvgMitigated, _fvgLabels) =>
for [index, value] in _boxes
// Processing bullish FVG
if array.get(_fvgTypes, index)
if low <= box.get_bottom(value)
array.remove(_boxes, index)
array.remove(_fvgTypes, index)
array.remove(_isFvgMitigated, index)
label.delete(array.get(_fvgLabels, index))
array.remove(_fvgLabels, index)
box.delete(value)
else
if low < box.get_top(value)
box.set_bgcolor(value, mitigatedFvgColor)
if not array.get(_isFvgMitigated, index)
alert("FVG has been mitigated", alert.freq_once_per_bar)
array.set(_isFvgMitigated, index, true)
if isMitigatedFvgToReduce
box.set_top(value, low)
box.set_right(value, bar_index)
label.set_x(array.get(_fvgLabels, index), (box.get_left(value) + box.get_right(value)) / 2 )
label.set_y(array.get(_fvgLabels, index), box.get_top(value) - (box.get_top(value) - box.get_bottom(value)) / 2)
// Processing bearish FVG
else
if high >= box.get_top(value)
array.remove(_boxes, index)
array.remove(_fvgTypes, index)
array.remove(_isFvgMitigated, index)
label.delete(array.get(_fvgLabels, index))
array.remove(_fvgLabels, index)
box.delete(value)
else
if high > box.get_bottom(value)
box.set_bgcolor(value, mitigatedFvgColor)
if not array.get(_isFvgMitigated, index)
alert("FVG has been mitigated", alert.freq_once_per_bar)
array.set(_isFvgMitigated, index, true)
if isMitigatedFvgToReduce
box.set_bottom(value, high)
box.set_right(value, bar_index)
label.set_x(array.get(_fvgLabels, index), (box.get_left(value) + box.get_right(value)) / 2 )
label.set_y(array.get(_fvgLabels, index), box.get_top(value) - (box.get_top(value) - box.get_bottom(value)) / 2)
// === UPDATE VISUALS ===
// Update Liquidity Lines and Sweeps
var bool sweepAlert = false
if array.size(bearishLiquidity) > 0
liquidity testLiquidity = na
for i = array.size(bearishLiquidity) - 1 to 0 by 1
testLiquidity := array.get(bearishLiquidity, i)
if high > testLiquidity.value
testLiquidity.liquidityLine.set_x2(time)
testLiquidity.liquidityLine.set_style(line.style_dashed)
array.remove(bearishLiquidity, i)
if close < testLiquidity.value
testLiquidity.sweep := label.new(x = time, y = high, text = 'x', xloc = xloc.bar_time, style = label.style_label_down, size = size.normal, textcolor = color.new(color.purple, 0), color = color.new(color.white, 100))
sweepAlert := true
else
testLiquidity.liquidityLine.set_x2(time)
if array.size(bullishLiquidity) > 0
liquidity testLiquidity = na
for i = array.size(bullishLiquidity) - 1 to 0 by 1
testLiquidity := array.get(bullishLiquidity, i)
if low < testLiquidity.value
testLiquidity.liquidityLine.set_x2(time)
testLiquidity.liquidityLine.set_style(line.style_dashed)
array.remove(bullishLiquidity, i)
if close > testLiquidity.value
testLiquidity.sweep := label.new(x = time, y = low, text = 'x', xloc = xloc.bar_time, style = label.style_label_up, size = size.normal, textcolor = color.new(color.teal, 0), color = color.new(color.white, 100))
sweepAlert := true
else
testLiquidity.liquidityLine.set_x2(time)
// === ALERTS ===
alertcondition(sweepAlert, title = "Liquidity Sweep", message = "A liquidity zone has been swept.")
sweepAlert := false
// === PREVIOUS DAY HIGH/LOW SETTINGS ===
showPrevDayRange = input.bool(true, 'Show Previous Day High/Low', group='Previous Day Range')
prevDayColorHigh = input.color(color.new(color.red, 0), 'Previous Day High Color', group='Previous Day Range')
prevDayColorLow = input.color(color.new(color.red, 0), 'Previous Day Low Color', group='Previous Day Range')
prevDayLineWidth = input.int(1, 'Previous Day Line Width', minval=1, maxval=5, group='Previous Day Range')
prevDayLineStyle = input.string('Dashed', 'Previous Day Line Style', options=['Dashed', 'Dotted'], group='Previous Day Range')
// Convert line style string to line.style constant
lineStyle = prevDayLineStyle == 'Dotted' ? line.style_dotted : line.style_dashed
// Get previous day timeframe string or use 'D'
dailyTF = "D" // fixed daily timeframe
// Request previous daily data (high/low) and previous day start timestamp (session start)
prevDayHigh = request.security(syminfo.tickerid, dailyTF, high[1], lookahead=barmerge.lookahead_on)
prevDayLow = request.security(syminfo.tickerid, dailyTF, low[1], lookahead=barmerge.lookahead_on)
prevDayTime = request.security(syminfo.tickerid, dailyTF, time[1], lookahead=barmerge.lookahead_on) // Timestamp of previous daily bar start
// Variables to hold lines just once (persistent)
var line prevHighLine = na
var line prevLowLine = na
// Overlays - Range Only
//-----------------------------------------------------------------------------{
if show_sesa
get_range(is_sesa, sesa_txt, sesa_css)
if show_sesb
get_range(is_sesb, sesb_txt, sesb_css)
if show_sesc
get_range(is_sesc, sesc_txt, sesc_css)
if show_sesd
get_range(is_sesd, sesd_txt, sesd_css)
//-----------------------------------------------------------------------------}
// User Inputs for Customization
bullishBreakColor = input.color(color.white, "Bull CISD", inline = "bup")
bearishBreakColor = input.color(color.white, "Bear CISD", inline = "bep")
bullStr = input.string("+CISD", " ", tooltip = "Text to be displayed next to the CISD level.", inline = "bup")
bearStr = input.string("-CISD", " ", tooltip = "Text to be displayed next to the CISD level.", inline = "bep")
bullishAlerts = input.bool(false, "Alert?", "When set up through Tradingview, the script will send an alert when price closes ABOVE the current '+CISD' level.", inline = "bup")
bearishAlerts = input.bool(false, "Alert?", "When set up through Tradingview, the script will send an alert when price closes ABOVE the current '-CISD' level.", inline = "bep")
// Variable Declarations
var line lastTopLine = na
var line lastBottomLine = na
var MarketStructure currentStructure = MarketStructure.new(0, 0, false)
var cisdLevelsBu = array.new()
var cisdLevelsBe = array.new()
var bool isBullishPullback = false
var bool isBearishPullback = false
var float potentialTopPrice = na
var float potentialBottomPrice = na
var int bullishBreakIndex = na
var int bearishBreakIndex = na
var float bullishChangeLevel = na
var float bearishChangeLevel = na
// Bearish Pullback Logic
if bearishPullbackDetected and not isBearishPullback
isBearishPullback := true
potentialTopPrice := open[1]
bullishBreakIndex := bar_index[1]
// Bullish Pullback Logic
if bullishPullbackDetected and not isBullishPullback
isBullishPullback := true
potentialBottomPrice := open[1]
bearishBreakIndex := bar_index[1]
// Update Potential Levels During Pullbacks
if isBullishPullback
if open < potentialBottomPrice
potentialBottomPrice := open
bearishBreakIndex := bar_index
if (close < open) and (open > potentialBottomPrice)
potentialBottomPrice := open
bearishBreakIndex := bar_index
if isBearishPullback
if open > potentialTopPrice
potentialTopPrice := open
bullishBreakIndex := bar_index
if (close > open) and open < potentialTopPrice
potentialTopPrice := open
bullishBreakIndex := bar_index
if array.size(cisdLevelsBu) > 1 and not keepLevels
latest = array.shift(cisdLevelsBu)
line.delete(latest.level)
label.delete(latest.txt)
if array.size(cisdLevelsBe) > 1 and not keepLevels
latest = array.shift(cisdLevelsBe)
line.delete(latest.level)
label.delete(latest.txt)
if array.size(cisdLevelsBu) >= 1
latest = array.get(cisdLevelsBu,0)
if not (close < latest.level.get_y2()) and not latest.completed
line.set_x2(latest.level, bar_index+lookAheadBars)
label.set_x(latest.txt, bar_index+lookAheadBars)
if close < latest.level.get_y2() and not latest.completed
latest.completed := true
alert("Bearish CISD Formed")
if array.size(cisdLevelsBe) >= 1 and not keepLevels
latest = array.get(cisdLevelsBe,0)
if not (close > latest.level.get_y2()) and not latest.completed
line.set_x2(latest.level, bar_index+lookAheadBars)
label.set_x(latest.txt, bar_index+lookAheadBars)
if close > latest.level.get_y2() and not latest.completed
latest.completed := true
alert("Bullish CISD Formed")
// Groups
General_Settings_group = '-------MSS General Settings-------'
Timeframe_1_Group = '-------Timeframe 1 Settings--------'
// Tooltips
Hide_MS_Tooltip = 'If true will hide all MS plots such as "HH 2H" or "HH 15min"'
Hide_Breaks_Tooltip = 'If true will hide all MS breaks such as "BOS 1H" or "MSS 15min"'
Timeframe_Tooltip = 'If set to chart is true no need to alter these two inputs.'
Set_To_Chart_Tooltip = 'If set to chart is set to true, there is no need to alter the Timeframe inputs, it will automatically configure itself to the charts timeframe.'
Lower_Timeframe_Tooltip = 'If set to true and chart timeframe is higher than the choosen timeframe, structure will not display. Note plotting ltf structure on a htf will provide inaccurate plots.'
Use_High_Low_Tooltip = 'If set to true high and low values will be used to confirm market structure else if set to false close will be used.'
Display_TF_Pivots = 'If true the script will display the timeframe declared in the TF inputs'
Display_TF_MS = 'If true the script will display the timeframe's market structure declared in the TF inputs if Hide all Market Structure is false in general settings.'
BOS_Alert_Tooltip = 'Set to true to activate BOS alerts then proceed to set the any alert function specifically on this script.'
MSS_Alert_Tooltip = 'Set to true to activate MSS alerts then proceed to set the any alert function specifically on this script.'
BOS_Plot_Tooltip = 'If set to true the TF BOS plots will be plotted else if false they will be hidden.'
MSS_Plot_Tooltip = 'If set to true the TF MSS plots will be plotted else if false they will be hidden.'
// General Settings
Hide_All_MS = input.bool(defval = true, title = 'Hide all Market Structure', group = General_Settings_group, tooltip = Hide_MS_Tooltip)
Hide_All_Breaks = input.bool(defval = false, title = 'Hide all Structure Breaks', group = General_Settings_group, tooltip = Hide_Breaks_Tooltip)
Show_Only_On_Lower_Timeframes = input.bool(defval = true, title = 'Show Structure only on a lower Timeframe', group = General_Settings_group, tooltip = Lower_Timeframe_Tooltip)
// User Inputs
// Timeframe 1 Settings
TF_1_Use_Bos_Plot = input.bool(defval = false, title = 'Show TF 1 BOS Plots', group = Timeframe_1_Group, tooltip = BOS_Plot_Tooltip)
TF_1_Use_MSS_Plot = input.bool(defval = true, title = 'Show TF 1 MSS Plots', group = Timeframe_1_Group, tooltip = MSS_Plot_Tooltip)
TF_1_Chart_Feature = input.bool(defval = true, title = 'Set Timeframe to Chart', group = Timeframe_1_Group, tooltip = Set_To_Chart_Tooltip)
TF_1_Use_High_Low = input.bool(defval = false, title = 'Use High/Low for Bos & Mss', group = Timeframe_1_Group, tooltip = Use_High_Low_Tooltip)
TF_1_Display_Pivots = input.bool(defval = true, title = 'Display Market Structure', group = Timeframe_1_Group, tooltip = Display_TF_MS)
TF_1_Display_Timeframe = input.bool(defval = true, title = 'Display Timeframe', group = Timeframe_1_Group, tooltip = Display_TF_Pivots)
TF_1_BOS_Alert = input.bool(defval = true, title = 'Use TF 1 BOS Alert', group = Timeframe_1_Group, tooltip = BOS_Alert_Tooltip)
TF_1_MSS_Alert = input.bool(defval = true, title = 'Use TF 1 MSS Alert', group = Timeframe_1_Group, tooltip = MSS_Alert_Tooltip)
TF_1_Multip = input.int(defval = 15, minval = 1, maxval = 1440, title = 'Timeframe 1', group = Timeframe_1_Group, inline = 'T1')
TF_1_Period = input.string(defval = 'Minute', title = '', options = ['Minute', 'Hour', 'Day', 'Week', 'Month'], group = Timeframe_1_Group, inline = 'T1', tooltip = Timeframe_Tooltip)
TF_1_Swing_Length = input.int(defval = 4, title = 'Swing Length', minval = 1, group = Timeframe_1_Group)
TF_1_Line_Type = input.string(defval = 'Solid', title = 'Border Type', options = ['Solid', 'Dashed', 'Dotted'], group = Timeframe_1_Group)
TF_1_Line_Width = input.int(defval = 2, title = 'Line Width', group = Timeframe_1_Group)
TF_1_Text_Size = input.string(defval = 'Small', title = 'Text Size', options = ['Normal', 'Tiny', 'Small', 'Large', 'Huge', 'Auto'], group = Timeframe_1_Group)
TF_1_Bul_Bos_Col = input.color(defval = color.green, title = 'Bullish Bos/Mss Color', group = Timeframe_1_Group, inline = 'TF 1 Color')
TF_1_Bear_Bos_Col = input.color(defval = color.red, title = 'Bearish Bos/Mss Color', group = Timeframe_1_Group, inline = 'TF 1 Color')
TF_1_Bul_MS_Col = input.color(defval = color.white, title = 'Bullish Text MS Color', group = Timeframe_1_Group, inline = 'TF 1 Ms Color')
TF_1_Bear_MS_Col = input.color(defval = color.white, title = 'Bearish Text MS Color', group = Timeframe_1_Group, inline = 'TF 1 Ms Color')
// General functions
// Getting the line type from the user.
Line_Type_Control(Type) =>
Line_Functionality = switch Type
'Solid' => line.style_solid
'Dashed' => line.style_dashed
'Dotted' => line.style_dotted
code
Line_Functionality
// Text size from the user
Text_Size_Switch(Text_Size) =>
Text_Type = switch Text_Size
'Normal' => size.normal
'Tiny' => size.tiny
'Small' => size.small
'Large' => size.large
'Huge' => size.huge
'Auto' => size.auto
Text_Type
TF_Period == 'Month' and timeframe.isweekly and 5 / (TF_Multip * 1440 * 5 / timeframe.multiplier) * 1440 == timeframe.multiplier => TF_Multip * 1440 * 5 / 1440 * Swing_Length
TF_Period == 'Month' and timeframe.isdaily and 5 * 5 / (TF_Multip * 1440 * 5 * 5 / timeframe.multiplier) * 1440 == timeframe.multiplier => TF_Multip * 1440 * 5 * 5 / 1440 * Swing_Length
timeframe.ismonthly and timeframe.multiplier == TF_Multip and TF_Period == 'Month' => Swing_Length
TF_Period == 'Week' and timeframe.isminutes and timeframe.multiplier % 60 == 0 and 24 * 5 / (TF_Multip * 1440 * 5 / timeframe.multiplier) * 60 == timeframe.multiplier => TF_Multip * 1440 * 5 / timeframe.multiplier * Swing_Length
TF_Period == 'Week' and timeframe.isdaily and 5 / (TF_Multip * 1440 * 5 / timeframe.multiplier) * 1440 == timeframe.multiplier => TF_Multip * 1440 * 5 / 1440 * Swing_Length
timeframe.isweekly and timeframe.multiplier == TF_Multip and TF_Period == 'Week' => Swing_Length
TF_Period == 'Day' and timeframe.isminutes and timeframe.multiplier % 60 == 0 and 24 / (TF_Multip * 1440 / timeframe.multiplier) * 60 == timeframe.multiplier => TF_Multip * 1440 / timeframe.multiplier * Swing_Length
timeframe.isdaily and timeframe.multiplier == TF_Multip and TF_Period == 'Day' => Swing_Length
timeframe.isminutes and timeframe.multiplier % 60 != 0 and TF_Period == 'Minute' and TF_Multip == timeframe.multiplier => Swing_Length
timeframe.isminutes and timeframe.multiplier % 60 != 0 and TF_Period == 'Minute' and TF_Multip != timeframe.multiplier => TF_Multip / 60 * 60 / timeframe.multiplier * Swing_Length
timeframe.isminutes and timeframe.multiplier % 60 != 0 and TF_Period == 'Hour' and TF_Multip != timeframe.multiplier => TF_Multip * 60 / 60 * 60 / timeframe.multiplier * Swing_Length
timeframe.isminutes and timeframe.multiplier % 60 != 0 and TF_Period == 'Hour' and TF_Multip == timeframe.multiplier and timeframe.multiplier * 60 == 60 => TF_Multip * 60 / 60 * 60 / timeframe.multiplier * Swing_Length
timeframe.isminutes and timeframe.multiplier % 60 != 0 and TF_Period == 'Day' and TF_Multip != timeframe.multiplier => TF_Multip * 1440 / 60 * 60 / timeframe.multiplier * Swing_Length
timeframe.isminutes and timeframe.multiplier % 60 == 0 and TF_Period == 'Hour' and TF_Multip * 60 == timeframe.multiplier => Swing_Length
timeframe.isminutes and timeframe.multiplier % 60 == 0 and TF_Period == 'Hour' and TF_Multip * 60 != timeframe.multiplier => TF_Multip * 60 / timeframe.multiplier * Swing_Length
HTF_Structure_Control(Chart_as_Timeframe, TF_Period, TF_Multip) =>
if Chart_as_Timeframe == true
true
else if Show_Only_On_Lower_Timeframes == false
true
else
switch
TF_Period == 'Minute' and TF_Multip < timeframe.multiplier and timeframe.isminutes => false
TF_Period == 'Minute' and TF_Multip >= timeframe.multiplier and timeframe.isminutes => true
TF_Period == 'Minute' and timeframe.isdaily => false
TF_Period == 'Minute' and timeframe.isweekly => false
TF_Period == 'Minute' and timeframe.ismonthly => false
TF_Period == 'Hour' and TF_Multip * 60 < timeframe.multiplier and timeframe.isminutes => false
TF_Period == 'Hour' and TF_Multip * 60 >= timeframe.multiplier and timeframe.isminutes => true
TF_Period == 'Hour' and timeframe.isdaily => false
TF_Period == 'Hour' and timeframe.isweekly => false
TF_Period == 'Hour' and timeframe.ismonthly => false
TF_Period == 'Day' and timeframe.isdaily or timeframe.isminutes => true
TF_Period == 'Week' and timeframe.isweekly or timeframe.isdaily or timeframe.isminutes => true
TF_Period == 'Month' and timeframe.ismonthly or timeframe.isweekly or timeframe.isdaily or timeframe.isminutes => true
// Calculating the Mtf BOS and MSS
// Getting the high and low values
[TF_1_SH, TF_1_SL] = request.security(symbol = syminfo.tickerid, timeframe = TF_1_Chart_Feature ? timeframe.period : TF(TF_1_Period, TF_1_Multip), expression = [ta.pivothigh(high, TF_1_Swing_Length, TF_1_Swing_Length), ta.pivotlow(low, TF_1_Swing_Length, TF_1_Swing_Length)], gaps = barmerge.gaps_on)
Count_Candles_For_Structure(Direction, Condition) =>
var int High_Count = 0
var int Low_Count = 0
code
if Direction == 'Bullish'
for i = 0 to Condition by 1
High_Count := i
High_Count
High_Count
else if Direction == 'Bearish'
for i = 0 to Condition by 1
Low_Count := i
Low_Count
Low_Count
Your provided Pine Script code is quite extensive and advanced, combining multiple concepts including liquidity sweeps, EMAs, VWAP, Fair Value Gaps (FVG), daily high/low, session ranges, Custom CISD levels (Change in Structure Detection), and Market Structure Shifts (MSS) with multi-timeframe features and alerts.
What the code does overall:
Plots EMAs and VWAP with configurable parameters.
Detects liquidity sweeps and draws liquidity lines.
Detects and draws Fair Value Gaps (FVG) boxes.
Plots previous day high/low as horizontal lines extending into the future.
Draws session range boxes for different markets: New York, London, Tokyo, Asia.
Implements a CISD logic, which detects bullish and bearish pullbacks and marks Change of Structure levels with lines and labels.
Draws a status table summarizing EMA bias, VWAP trend, and overall state.
Implements Market Structure Shift (MSS) detection on a specified timeframe, with multi-timeframe support, plotting of breaks of structure (BOS) and market structure shifts, with alerts.
Some important notes & suggestions for improvement or to address potential issues:
1. Initialization of mutable variables and arrays in Pine v6:
You have many var arrays and variables, which is good practice, but I’d recommend verifying all array.new<type>() have consistent element types, especially for user-defined type elements.
2. Potential logical issues with CISD pullback detection:
The pullback detection is based on candle open/close relationships, which can generate false positives on small bars or inside bars.
The logic for updating potentialBottomPrice and potentialTopPrice updates them during the pullback based on open/close comparisons and bar height, which may get complicated if you use low/high instead of open/close.
If you intend to trigger alerts for CISD formations, make sure that opening more than one identical line does not confuse the alert handler.
3. Remove unnecessary or unreachable code:
In Market_Structure function:
pinescript
User
My strategy, I wait for a liquidity sweep on m15, then change to m5 or m1. Open position only in a trading session London or New York if price show signs of reverse after sweep, by changing cisd and specialty forming fvg
Assistant
Thanks for clarifying your trading strategy! Here’s a practical approach and some tradingview Pine Script guidance based on your workflow:
Your strategy summary:
Wait for liquidity sweep on M15 timeframe.
Upon sweep occurrence, switch to M5 or M1 chart for entry.
Trade only during London or New York sessions.
Enter position when price shows signs of reversal after sweep:
Confirmed by CISD (Change in Structure Detection) change (bullish or bearish).
Optionally confirmed by formation or presence of Fair Value Gap (FVG) (or its mitigation).
How to implement this workflow:
Liquidity Sweep detection on M15:
Since your main script does liquidity sweep detection, you can modify or add a variable storing when sweep happens on M15.
Confirm trading session:
Use your existing session code or build simple helper function to confirm if current bar is within London or New York trading session. Those are defined in your script and can be simplified like:
Pine scripts can only access higher or same timeframes using request.security. You cannot dynamically switch the chart itself or downscale from M15 to M5/M1 inside code automatically - that’s a manual chart action by the user.
However, you can:
Run this strategy on M5 or M1 timeframe
Use request.security call with 15-min timeframe to get liquidity sweep signals on M15
Then your entry signals can be generated on M5 or M1 based on this M15 sweep info + session + price structure.
Detect CISD change for sign of reversal
Your CISD logic already detects changes in Market Structure and draws lines and labels. You can expose a bool variable when a CISD change occurs—like a bullish or bearish CISD is formed.
Check existence or formation of FVG
You already detect FVGs with boxes and flags like isFvgMitigated. In your logic, you can track formation of bullish or bearish FVG overlapping current price range or after sweep to confirm reversal.
User
I want to ask you about Ema bias
Assistant
Certainly! Regarding EMA Bias — it’s a popular concept in trading to identify the general market trend or directional bias using Exponential Moving Averages (EMAs).
What is EMA Bias?
EMA Bias is the determination of market bias (bullish, bearish, or neutral) based on the relative positioning of one or multiple EMAs.
Common setups include:
Bullish bias when a shorter EMA is above a longer EMA (e.g. EMA 50 > EMA 100 > EMA 200).
Bearish bias when a shorter EMA is below a longer EMA (e.g. EMA 50 < EMA 100 < EMA 200).
Neutral bias when EMAs are crossing over or intertwined — no clear directional bias.
In your script:
You defined EMA bias as:
pinescript
bullishBias = (emaValue > emaValue2) and (emaValue2 > emaValue3)
bearishBias = (emaValue < emaValue2) and (emaValue2 < emaValue3)
Where:
emaValue is your EMA 1 (e.g., EMA 50)
emaValue2 is EMA 2 (e.g., EMA 100)
emaValue3 is EMA 3 (e.g., EMA 200)
So:
Bullish bias: EMA 50 > EMA 100 > EMA 200 → price is trending upwards.
Bearish bias: EMA 50 < EMA 100 < EMA 200 → price is trending downwards.
Else → Neutral.
How to use EMA bias practically
Trade with the bias: Enter only long trades when bullish bias, and short trades when bearish bias.
Filter signals: Combine EMA bias with price action, volume, or other indicators to reduce false entries.
Dynamic stop or take profit: Place stops based on EMA lines or adapt position sizing to bias strength.
Important considerations:
Timeframes matter — EMA bias on M15 might differ from H1 or D1.
EMAs lag by nature — so bias can change late after price movement.
Change lengths depending on volatility or asset type.
You can look at crossovers or EMA slope for confirmation.
Your table shows EMA bias:
pinescript
var string emaBiasText = "Neutral"
if bullishBias
emaBiasText := "Only Buy"
else if bearishBias
emaBiasText := "Only Sell"
else
emaBiasText := "Neutral"
This lets you quickly see if the indicator deems market bias bullish, bearish, or neutral.
Summary
EMA bias is a quantitative gauge of trend direction based on selected EMAs' relative position. It’s commonly used as a trend filter or context for strategy execution.
If you want, I can help you:
Customize or extend your EMA bias logic
Add slope or momentum filters to bias
Visualize EMA bias more clearly on your chart or alerts
Just ask!
User
According to my strategy I told about, what Ema values I should use
Assistant
Great question! Choosing the right EMA values for your strategy depends on your timeframes and trading style. Since your strategy workflow is:
Detect liquidity sweeps on M15
Then drop down to M5 or M1 for entries (looking for reversal signals via CISD and FVG)
Trade only during London/New York sessions
Use EMA bias as a filter/context to trade in the direction of the "trend"
Recommended EMA periods for your multi-timeframe setup:
Timeframe
EMA Length Suggestions
Reasoning
M15
EMA 50, EMA 100, EMA 200
These are classic medium-term EMAs capturing trend and bias on 15-min bars. Good for liquidity sweep confirmation and bias direction.
M5 or M1
EMA 20 or EMA 21, EMA 50
Shorter EMAs better catch quicker reversals and local momentum on lower timeframes. Use as confirmation overlays alongside M15 bias.
Why these values?
EMA 50 / EMA 100 / EMA 200 on M15
EMA 50 is fast enough to capture intermediate momentum.
EMA 100 and 200 confirm broader trend direction.
Perfect to define bullish/bearish bias on your main liquidity sweep timeframe.
Your current script’s defaults (50, 100, 200) are good standard choices here.
EMA 20 or 21 + EMA 50 on M5/M1
EMA 20-21 reacts quicker to price changes on lower timeframes
EMA 50 on small timeframes adds a smoother trend context
Combining these allows you to filter reversal signals near liquidity sweep zones.
Practical incorporation in your strategy:
Use EMA 50/100/200 on M15 to define trend bias and the sweep confirmation.
On M5 or M1, you can either:
Use the same EMA 50/100/200 but expecting a more choppy appearance because of the smaller bars, or
Use EMA 21 and EMA 50 for tighter, more sensitive trend following during your entry assessment.
Confirm your entry only if:
M15 EMA bias is bullish and on M5/M1 you see reversal aligned with bullish CISD and FVG near the liquidity sweep.
Similarly for bearish bias.
User
I use Ema only in m15, or should I use it on h1?
Assistant
Great question! Whether to use EMA bias only on M15 or also on H1 depends on your overall trading style and how much multi-timeframe confirmation you want.
Using EMA bias only on M15 (your liquidity sweep timeframe):
Pros:
EMA bias directly aligns with the timeframe where you detect liquidity sweeps.
Simpler and faster to compute.
Reflects near-term trend context that is most relevant for your entry signals on M5/M1.
Easier to manage and interpret without over-complicating with conflicting signals from higher TF.
Cons:
May sometimes generate whipsaws during volatile periods.
Less broader trend context.
Using EMA bias also on H1 (higher timeframe):
Pros:
Adds higher timeframe trend context, filtering signals more robustly.
Helps avoid counter-trend trades in bigger swings or news-driven moves.
Can improve trade quality by only taking trades aligned with both M15 and H1 trend.
Cons:
Adds complexity.
Higher TF EMA signals can lag more.
May reduce the number of trading opportunities if higher TF and M15 are often opposed.
Recommended approach for your strategy:
Start using EMA bias on M15 only, since liquidity sweeps and your entries revolve largely around M15 events.
If after backtesting you find too many false signals or wish to better filter trades:
Add H1 EMA bias overlay as a trend filter.
This means:
Require both M15 and H1 EMA bias to agree for a trade signal.
For example, only take long entries if M15 and H1 EMA biases are bullish.
How to add H1 EMA bias easily in your script:
pinescript
User
M15 or h1, not both
Assistant
Got it! You want to choose either M15 or H1 EMA bias, not both combined.
Which one to pick for your strategy?
Since your liquidity sweep detection and main event is on M15, here are the considerations:
Use EMA bias on M15 IF:
Your main triggering event (liquidity sweep) is detected on the M15 timeframe.
You want your bias to closely reflect the timeframe where you plan entries (M5/M1 after the sweep).
You prefer more frequent signals aligned with the near-term trend.
You want better alignment between liquidity sweep events and bias.
Use EMA bias on H1 IF:
You prefer to trade with a bigger, slower trend context.
You want to avoid "noise" or quick reversals often seen on M15.
You want fewer but potentially higher-probability signals.
Your research shows better profitability or fewer false signals by trading aligned with H1 trend.
Summary for your strategy:
Option
Pros
Cons
Best for
EMA on M15
More aligned with sweep signals, faster reaction, more entries
More noise / false signals possible
Traders focusing on medium-short swings and faster reactivity
Traders focusing on swing/trend-following with bigger timeframes
My recommendation:
Use EMA bias on M15 since your whole edge centers on liquidity sweeps on M15 timeframe, and then you look for entries on M5/M1.
This keeps everything in close timeframe proximity and avoids conflicts. Your reversal signals and CISD formation will feel more natural and timely with M15 bias.
Tip if picking M15 EMA bias:
Use EMAs like 50, 100, 200 on M15, which suits well for medium-term context.
Avoid too short EMAs that may flicker too much.
Optionally, check EMA slope or price positioning around EMA for even better bias filtering.
If you want, I can help create or optimize the EMA bias logic specifically for M15 only with your existing script style. Just say the word!
User
Help me decide m15 emas, 9/21/50, 20/50/100, 50/100/200
Assistant
Choosing between those three EMA sets on M15 depends on your strategy’s trade frequency, noise tolerance, and how far you want to gauge trend strength.
Here’s a comparison of the three common EMA combos on M15:
1. EMA 9 / 21 / 50
Type: Fast EMAs
Pros:
Very responsive to price changes, good for catching quick momentum shifts and sharp reversals.
Better for scalping or fast intra-session trading with more entry opportunities.
Cons:
Can generate more false signals in choppy or sideways markets.
May be too sensitive for spotting "macro" bias on M15.
Use case:
If you want to aggressively follow momentum on M15 and your entries rely on quick reaction to CISD and FVG signals.
Great for fast-paced intraday setups.
2. EMA 20 / 50 / 100
Type: Medium EMAs
Pros:
Smoother than 9/21/50, less noise.
Good balance between responsiveness and trend stability.
Often used by many swing and day traders on 15-min timeframe.
Cons:
Might miss some very fast short-term reversals but better filters noise.
Use case:
If you want solid trend context without too much false noise.
Good middle-ground for intraday setups mixed with swing tendencies.
3. EMA 50 / 100 / 200
Type: Slow EMAs
Pros:
Best for identifying the overall medium-to-longer-term trend on M15 bars.
Very smooth, avoids whipsaws.
Good filter to avoid counter-trend trades.
Cons:
Less responsive to short-term reversals or quick changes.
Might lag and cause late signals for very fast setups.
Use case:
If your strategy prefers trading only with the broader trend, using CISD and FVG as fine-tuned entry confirmations.
Suitable when you want fewer trades but higher confidence bias.
Which should YOU choose for your strategy?
User
Ok 20/50/100 it is in m15
Assistant
Great choice! EMA 20/50/100 on M15 provides a nice balance between responsiveness and trend reliability—ideal for your liquidity sweep + CISD + FVG strategy.
What’s next?
Implement your EMA bias logic on M15 with those EMAs.
Use that bias as a filter for your entries on lower timeframes (M5/M1).
Combine with your liquidity sweep detection on M15 and CISD/FVG reversals on lower TF for higher confidence.
Restrict trades to London and New York sessions as you planned.
Use bullishBias and bearishBias bools to filter your entries.
Pro tip
You can also add EMA slope checks or require confirmation via price action near these EMAs before taking trades.
If you want help integrating this EMA bias cleanly into your existing full script (liquidity sweeps, session checks, CISD, FVG, alerts, table), just ask!
Happy trading! 🚀
User
How about vwap
Assistant
Great question! VWAP (Volume Weighted Average Price) is a powerful trend and value tool, especially for intraday trading like your M15-focused strategy.
How VWAP fits your strategy:
VWAP shows the average price weighted by volume over the current trading day—a dynamic intraday value reference.
Traders view price above VWAP as bullish (buyers in control) and price below VWAP as bearish (sellers in control).
VWAP often acts as dynamic support or resistance.
Combining VWAP with your EMA bias and liquidity sweeps can improve entry timing and risk management.
How to use VWAP in your specific workflow:
Confirm trend context:
Use VWAP alongside EMA bias on M15 to confirm or filter trades.
For example, only take long entries when price is above VWAP and EMA bias is bullish.
Take short entries when price is below VWAP and EMA bias is bearish.
Enhance entry precision:
When liquidity sweep + CISD + FVG indicate reversal, check if price is near or bouncing off VWAP line.
VWAP “touches” are often good confluence points for entries or stops.
Session-based VWAP:
Since you trade mostly London and New York sessions, consider session VWAPs if your platform/script supports it (session VWAPs reset VWAP at session start).
And your table displays VWAP trend as bullish/bearish based on:
pinescript
vwapTrendText = "Neutral"
if close > vwapValue
vwapTrendText := "Bullish"
else if close < vwapValue
vwapTrendText := "Bearish"
Recommended VWAP usage:
Combine VWAP trend (price above/below VWAP) with EMA bias for stronger directional confirmation.
Use VWAP as a dynamic support/resistance tool. For example:
User
Example: price just swept 23565 high, vwap 23444, current price 23559,m15 Ema bias 20/50/100 neutral, 9:53
Assistant
Thanks for the detailed example; let’s break down what it means and how you might interpret it within your strategy:
Your example details:
Liquidity sweep: Price just swept high of 23565
VWAP: 23444 (current VWAP level)
Current price: 23559 (below the swept liquidity high but well above VWAP)
M15 EMA bias (20/50/100): Neutral
Time: 9:53 (presumably during session, e.g., London or New York)
Interpretation in your strategy context:
Liquidity sweep occurred—price broke above previous liquidity high 23565, but currently pulled back slightly below it (23559).
Price is well above VWAP (23559 vs 23444)—this typically hints at bullish volume-weighted value zone, suggesting buyers dominate overall so far.
EMA bias is neutral on M15 (no clear short-medium trend in EMAs) implying no strong directional bias currently.
Session context (9:53) likely within London or New York session—your active trading periods.
What signals or considerations does this suggest?
Price is trading above VWAP, generally bullish context from volume-weighted perspective.
But, EMA bias is neutral, so there’s no strong trend to accompany price action.
You just had a liquidity sweep (price breaking above 23565 high), which can indicate stop runs or trap of liquidity hunters.
Current price pulled back to 23559, below the sweep high.
Entry or trade decision hints:
The fact that EMA bias is neutral makes you cautious — no strong trend confirmation.
Price staying above VWAP favors buyers slightly.
After a liquidity sweep, look for signs of reversal or continuation:
Does a bullish CISD form after sweep? Do you see Fair Value Gaps forming that support bullish retracement?
Is there a rejection candle or price holding above key liquidity zone?
If pullback respects VWAP and CISD + FVG align bullishly, this is a potential long entry setup.
Otherwise, if the price fails to hold or EMA bias turns bearish, consider sitting out or waiting for clearer confirmation.
User
Before session, London start at 10:00
Assistant
Thanks for clarifying London session start time as 10:00 (presumably your chart's timezone or adjusted for exchange timezone).
How does this affect your example?
At 9:53, price and conditions occur before London session open.
Your strategy only takes trades during London or New York sessions.
So even if price swept the high and VWAP is bullish, your rule says no entries yet because session not started.
This filters out potentially noisy or low-volume moves before major session liquidity kicks in.
How to handle this in your Pine Script
You can define a boolean that detects if the current bar is inside the London session (or NY session), based on your input session times and timezone, for example:
pinescript
// Example: London session 10:00 - 13:00 exchange time or UTC offset adjusted
// Using your sesb_ses input: "1000-1300"
tz = use_exchange ? syminfo.timezone : str.format('UTC{0}{1}', tz_incr >= 0 ? '+' : '-', math.abs(tz_incr))
inLondonSession = ta.session.isin(sesb_ses, tz)
inNewYorkSession = ta.session.isin(sesa_ses, tz)
inTradeSession = inLondonSession or inNewYorkSession
Before session block in logic
Simply prevent signals before session like:
pinescript
if not inTradeSession
// no entries
longEntry := false
shortEntry := false
In your example:
At 9:53 (before London open 10:00):
inLondonSession == false
inNewYorkSession == false (assuming NY session start at 15:00 or so)
So no entries should trigger, regardless of price sweep or VWAP bias.
Summary:
Your no-trade zone before 10:00 London start works as a filter for quality.
Even if liquidity sweep and price action look interesting at 9:53, wait patiently.
Wait for sessions to open to get true institutional liquidity flow and better follow-through.
This avoids false signals in thin market periods.
If you want me to help you add a clean session filter block or time-of-day checks in code, just say so!
User
Open day price or Asia low 23308
Assistant
Got it! You mentioned an “Open day price or Asia low 23308” in the context of your example with liquidity sweeps, VWAP, EMA bias, and trading sessions.
Let me explain how you can use key reference levels like the day open or the Asia session low (23308) in your strategy and code:
Why track Day Open and Asia Low?
Day Open: Often acts as an important psychological & institutional reference during the trading day. Price above day open can signal bullish bias; below signals bearish bias.
Asia Low (23308): A significant session high/low (in your case low) from a prior session (Asia). These levels often act as support or resistance zones and liquidity points.
Your liquidity sweep might occur around these levels, or price reversals after sweep may respect these as confluence zones.
How to incorporate these levels into your trading logic:
1. Use Day Open as a reference:
You can fetch the daily open price using request.security for the daily timeframe:
priceAboveDayOpen = close > dailyOpen
priceBelowDayOpen = close < dailyOpen
Use it as additional filter for entries or bias context.
2. Use Asia Low (23308) as a fixed or dynamic level:
If fixed level known ahead (like 23308), store it as a constant input:
pinescript
asiaLow = input.float(23308, "Asia Low Level")
If you want to detect Asia session lows dynamically, you can calculate the low of your Asia session bars:
pinescript
// Assuming Asia session defined as 00:00 - 09:00 UTC+X, adjust tz_incr accordingly
asiaSessionLow = ta.lowest(low, timeframe.in_seconds('09:00') / timeframe.in_seconds(timeframe.period)) // Approximate low during Asia session
Not yet included in a published release.
//Tracking whether previous levels have been broken
var bool TF_High_Present = false
var bool TF_Low_Present = false
//Tracking prev breakout
var int Prev_Breakout_Type = 0
//Varibales for generating BOS and CHOCH
bool High_Broken = false
bool Low_Broken = false
End_High_Time = 0
End_Low_Time = 0
// Variables for Market Structure
bool HH = false
bool LH = false
bool HL = false
bool LL = false
TF_High_Close_Price = request.security(symbol = syminfo.tickerid, timeframe = Chart_as_Timeframe ? timeframe.period : TF(TF_Period, TF_Multip), expression = Use_High_Low ? high : close)
TF_Low_Close_Price = request.security(symbol = syminfo.tickerid, timeframe = Chart_as_Timeframe ? timeframe.period : TF(TF_Period, TF_Multip), expression = Use_High_Low ? low : close)
if not na(TF_SH)
if TF_SH >= TF_Prev_High
HH := true
HH
else
LH := true
LH
TF_Prev_High := TF_SH
TF_Prev_High_Time := TF_Prev_High != TF_Prev_High[1] ? time[MTF_MS_Display(Chart_as_Timeframe, TF_Period, TF_Multip, Swing_Length)] : TF_Prev_High_Time[1]
TF_High_Present := true
TF_High_Present
if not na(TF_SL)
if TF_SL >= TF_Prev_Low
HL := true
HL
else
LL := true
LL
TF_Prev_Low := TF_SL
TF_Prev_Low_Time := TF_Prev_Low != TF_Prev_Low[1] ? time[MTF_MS_Display(Chart_as_Timeframe, TF_Period, TF_Multip, Swing_Length)] : TF_Prev_Low_Time[1]
TF_Low_Present := true
TF_Low_Present
if TF_High_Close_Price > TF_Prev_High and TF_High_Present
High_Broken := true
TF_High_Present := false
End_High_Time := time
End_High_Time
if TF_Low_Close_Price < TF_Prev_Low and TF_Low_Present
Low_Broken := true
TF_Low_Present := false
End_Low_Time := time
End_Low_Time
// Displaying Swing Levels
if HH and Display_Timeframe and Display_Structure and not Hide_All_MS
label.new(TF_Prev_High_Time, TF_Prev_High, 'HH \n' + TF_Display(Chart_as_Timeframe, TF_Period, TF_Multip), xloc = xloc.bar_time, color = Transparent_Color, style = label.style_label_down, textcolor = Bul_Ms_Col, size = Text_Size_Switch(TF_Text_Size))
if HL and Display_Timeframe and Display_Structure and not Hide_All_MS
label.new(TF_Prev_Low_Time, TF_Prev_Low, 'HL \n' + TF_Display(Chart_as_Timeframe, TF_Period, TF_Multip), xloc = xloc.bar_time, color = Transparent_Color, style = label.style_label_up, textcolor = Bul_Ms_Col, size = Text_Size_Switch(TF_Text_Size))
if LH and Display_Timeframe and Display_Structure and not Hide_All_MS
label.new(TF_Prev_High_Time, TF_Prev_High, 'LH \n' + TF_Display(Chart_as_Timeframe, TF_Period, TF_Multip), xloc = xloc.bar_time, color = Transparent_Color, style = label.style_label_down, textcolor = Bear_Ms_Col, size = Text_Size_Switch(TF_Text_Size))
if LL and Display_Timeframe and Display_Structure and not Hide_All_MS
label.new(TF_Prev_Low_Time, TF_Prev_Low, 'LL \n' + TF_Display(Chart_as_Timeframe, TF_Period, TF_Multip), xloc = xloc.bar_time, color = Transparent_Color, style = label.style_label_up, textcolor = Bear_Ms_Col, size = Text_Size_Switch(TF_Text_Size))
High_Count := ta.barssince(HH == true or LH == true) + MTF_MS_Display(Chart_as_Timeframe, TF_Period, TF_Multip, Swing_Length)
Low_Count := ta.barssince(HL == true or LL == true) + MTF_MS_Display(Chart_as_Timeframe, TF_Period, TF_Multip, Swing_Length)
High_Count_Function = Count_Candles_For_Structure('Bullish', High_Count)
Low_Count_Function = Count_Candles_For_Structure('Bearish', Low_Count)
//Generating the BOS Lines
if High_Broken and Display_Timeframe and not Hide_All_Breaks and HTF_Structure_Control(Chart_as_Timeframe, TF_Period, TF_Multip)
if Prev_Breakout_Type == 1 and Use_Bos_Plot
line.new(x1 = time[High_Count_Function], y1 = TF_Prev_High, x2 = End_High_Time, y2 = TF_Prev_High, xloc = xloc.bar_time, color = Bul_Bos_Col, style = Line_Type_Control(Line_Type), width = Line_Width)
label.new(x = time[High_Count_Function / 2], y = TF_Prev_High, xloc = xloc.bar_time, text = 'BOS \n' + TF_Display(Chart_as_Timeframe, TF_Period, TF_Multip), color = Transparent_Color, style = label.style_label_down, textcolor = Bul_Bos_Col, size = Text_Size_Switch(TF_Text_Size))
else if Prev_Breakout_Type == -1 and Use_MSS_Plot
line.new(x1 = time[High_Count_Function], y1 = TF_Prev_High, x2 = End_High_Time, y2 = TF_Prev_High, xloc = xloc.bar_time, color = Bul_Bos_Col, style = Line_Type_Control(Line_Type), width = Line_Width)
label.new(x = time[High_Count_Function / 2], y = TF_Prev_High, xloc = xloc.bar_time, text = 'MSS \n' + TF_Display(Chart_as_Timeframe, TF_Period, TF_Multip), color = Transparent_Color, style = label.style_label_down, textcolor = Bul_Bos_Col, size = Text_Size_Switch(TF_Text_Size))
if Prev_Breakout_Type == -1 and Use_MSS_Alert
alert(message = 'New bullish MSS formed on ' + TF_Display(Chart_as_Timeframe, TF_Period, TF_Multip), freq = alert.freq_once_per_bar_close)
else if Prev_Breakout_Type == 1 and Use_BOS_Alert
alert(message = 'New bullish BOS formed on ' + TF_Display(Chart_as_Timeframe, TF_Period, TF_Multip), freq = alert.freq_once_per_bar_close)
Prev_Breakout_Type := 1
Prev_Breakout_Type
if Low_Broken and Display_Timeframe and not Hide_All_Breaks and HTF_Structure_Control(Chart_as_Timeframe, TF_Period, TF_Multip)
if Prev_Breakout_Type == -1 and Use_Bos_Plot
line.new(x1 = time[Low_Count_Function], y1 = TF_Prev_Low, x2 = End_Low_Time, y2 = TF_Prev_Low, xloc = xloc.bar_time, color = Bear_Bos_Col, style = Line_Type_Control(Line_Type), width = Line_Width)
label.new(x = time[Low_Count_Function / 2], y = TF_Prev_Low, xloc = xloc.bar_time, text = 'BOS \n' + TF_Display(Chart_as_Timeframe, TF_Period, TF_Multip), color = Transparent_Color, textcolor = Bear_Bos_Col, style = label.style_label_up, size = Text_Size_Switch(TF_Text_Size))
else if Prev_Breakout_Type == 1 and Use_MSS_Plot
line.new(x1 = time[Low_Count_Function], y1 = TF_Prev_Low, x2 = End_Low_Time, y2 = TF_Prev_Low, xloc = xloc.bar_time, color = Bear_Bos_Col, style = Line_Type_Control(Line_Type), width = Line_Width)
label.new(x = time[Low_Count_Function / 2], y = TF_Prev_Low, xloc = xloc.bar_time, text = 'MSS \n' + TF_Display(Chart_as_Timeframe, TF_Period, TF_Multip), color = Transparent_Color, textcolor = Bear_Bos_Col, style = label.style_label_up, size = Text_Size_Switch(TF_Text_Size))
if Prev_Breakout_Type == 1 and Use_MSS_Alert
alert(message = 'New bearish MSS formed on ' + TF_Display(Chart_as_Timeframe, TF_Period, TF_Multip), freq = alert.freq_once_per_bar_close)
else if Prev_Breakout_Type == -1 and Use_BOS_Alert
alert(message = 'New bearish BOS formed on ' + TF_Display(Chart_as_Timeframe, TF_Period, TF_Multip), freq = alert.freq_once_per_bar_close)
Prev_Breakout_Type := -1
Prev_Breakout_Type
Requesting high or low conditionally as Use_High_Low might request incomplete data if used improperly.
4. Potential runtime error in session ranges get_range function:
pinescript
if session > session[1]
...
if session == 1 and session == session[1]
...
This condition:
pinescript
if session == 1 and session == session[1]
Logs an odd behavior. Typically, when accumulating session highs/lows for the session, consider adding more robust state tracking or use var variables to retain values across bars.
You may want to rewrite this function to handle session open/close cleanly.
5. Managing line/label objects lifetime:
You create many lines and labels, especially in the Market Structure and CISD parts. To avoid leaking graphical objects and exceeding Pine limits:
Use arrays or variables to keep track.
Delete old or completed items, which your script already partially does via arrays and array.shift.
Limit persists to reasonable amounts. Consider setting maximum history length user-configurable.
6. Alert conditions
Your main alert condition on sweep:
pinescript
alertcondition(sweepAlert, title = "Liquidity Sweep", message = "A liquidity zone has been swept.")
This will trigger an alert once per bar when a sweep is detected. Make sure alert condition usage matches intended behavior in TradingView alert dialog.
7. VWAP value alias fix:
Your VWAP calculation:
pinescript
vwapValue = ta.vwap
Should be:
pinescript
vwapValue = ta.vwap()
because ta.vwap is a function, not a variable.
8. Plotting multiple EMAs safely:
If your indicator runs on lower timeframe but you request EMAs on higher timeframe (request.security), the plot will lag. Users should be aware of that, which your input parameter clarifies.
9. Any debug or cleanup tips:
Some variables (e.g., bullishChangeLevel, bearishChangeLevel, etc.) are declared but never used in the shared code snippet; consider cleaning unused variables.
The script is quite comprehensive and mixes many advanced price action, multi-timeframe, and liquidity concepts.
Verify using ta.vwap() (function call).
Review and enhance session range function logic.
Watch line and label creation/deletion carefully to avoid hitting Pine’s object creation limits.
Consider adding more comments for complex logic parts (MSS, CISD).
Alert management seems appropriate; do extensive backtesting on alerts to ensure no misses or spams.
Adjust lookahead, time zones, sessions, and timeframe inputs based on actual chart trading hours for context accuracy.
If you want help refactoring or isolating a particular block (like MSS, CISD, session ranges), feel free to ask!
Implementation tips for Pine Script:
Here is a conceptual snippet to integrate these ideas inside your script:
pinescript
//@version=6
indicator("Liquidity Sweep + CISD + FVG Strategy", overlay=true)
// === INPUTS ===
show_london = input.bool(true, "Trade in London session")
show_ny = input.bool(true, "Trade in NY session")
// Sessions - from your existing code or simplified (example)
tz = str.format('UTC{0}{1}', tz_incr >= 0 ? '+' : '-', math.abs(tz_incr))
inLondon = ta.session.isin(sesb_ses, tz)
inNewYork = ta.session.isin(sesa_ses, tz)
inTradeSession = (show_london and inLondon) or (show_ny and inNewYork)
// --- Fetch liquidity sweep signal from M15 using security ---
liquiditySweepM15 = request.security(syminfo.tickerid, "15", sweepAlert ? 1 : 0, lookahead=barmerge.lookahead_off) == 1
// You must ensure 'sweepAlert' is set properly on M15 in the inner script.
// --- CISD reversal signal (simplified) ---
// Assuming you have a bool variable `bullishCISDFormed` and `bearishCISDFormed`
// You can create these by detecting when a CISD line/label is created or when 'completed' set true
// For example (simplified):
bullishCISDFormed = false
bearishCISDFormed = false
// Example pseudo detection based on your cisdLevels arrays
if array.size(cisdLevelsBu) > 0
lb = array.get(cisdLevelsBu, 0)
if lb.completed and bar_index == lb.level.get_x2() // On formation bar
bullishCISDFormed := true
if array.size(cisdLevelsBe) > 0
be = array.get(cisdLevelsBe, 0)
if be.completed and bar_index == be.level.get_x2()
bearishCISDFormed := true
// --- Check FVG presence near price ---
// For simplicity, check if there is an unmitigated bullish or bearish FVG nearby price
fvgBullPresent = false
fvgBearPresent = false
for i = 0 to array.size(fvgBoxes)-1
box_ = array.get(fvgBoxes, i)
fvgType = array.get(fvgTypes, i)
mitigated = array.get(isFvgMitigated, i)
if not mitigated
if fvgType // bullish FVG
if low <= box.get_top(box_) and high >= box.get_bottom(box_)
fvgBullPresent := true
else // bearish FVG
if low <= box.get_top(box_) and high >= box.get_bottom(box_)
fvgBearPresent := true
// --- Entry Conditions ---
longEntry = liquiditySweepM15 and inTradeSession and bullishCISDFormed and fvgBullPresent
shortEntry = liquiditySweepM15 and inTradeSession and bearishCISDFormed and fvgBearPresent
// --- Plot entry signals ---
plotshape(longEntry, title="Long Entry", location=location.belowbar, color=color.green, style=shape.labelup, text="Long", size=size.small)
plotshape(shortEntry, title="Short Entry", location=location.abovebar, color=color.red, style=shape.labeldown, text="Short", size=size.small)
// Optional: Alert conditions
alertcondition(longEntry, title="Long Entry Alert", message="Long Entry signal after liquidity sweep")
alertcondition(shortEntry, title="Short Entry Alert", message="Short Entry signal after liquidity sweep")
Important points:
The liquiditySweepM15 variable depends on proper detection and setting of sweepAlert in your existing liquidity sweep code, run on 15-minute timeframe via request.security.
CISD states (bullishCISDFormed, bearishCISDFormed) should be flagged carefully where CISD is confirmed.
FVG presence check iterates your FVG boxes. You might want to add some buffer or tolerance to 'near price' detection.
Session detection uses TradingView session feature with your TZ adjustment.
This script will plot signals on M5/M1 (or whatever timeframe you apply), but signals are based on liquidity sweep detected on M15 through request.security.
You cannot auto switch the chart timeframe from M15 to M5/M1 but the idea is to run this combined script on the smaller timeframe and leverage M15 info internally for liquidity sweep.
How to trade with this logic:
Keep your chart on M5 or M1.
The indicator will monitor M15 liquidity sweeps and signal entries when conditions align.
Only signals during desired sessions will be indicated.
Use alerts to get notifications.
Extra recommendations:
Add some filters like price consolidation, confirmation candlestick patterns, volume spike, or volatility squeeze near the sweep and CISD levels for more robust signals.
Always backtest your conditions with historical data.
Make your line and label drawings optional or removables for cleaner charts.
Optimize lookahead parameters and manage object counts carefully.
If you want, I can help you create a dedicated reusable function or a specialized lightweight indicator script focusing only on the sweep + CISD + FVG + session combo for M5/M1 timeframe. Just let me know!
Avoid counter-trend trades, e.g., don’t take a bullish reversal signal on M5/M1 if M15 EMA bias strongly bearish.
Example adjustment for your inputs:
pinescript
// On M15 (run on any timeframe, or called via request.security)
ema1Length_m15 = 50
ema2Length_m15 = 100
ema3Length_m15 = 200
// On M5 or M1
emaFastLength_lowTF = 21
emaSlowLength_lowTF = 50
Optional enhancements:
You can also use EMA slope or crossovers as additional filters. For example:
Confirm EMA50 is sloping upward on M15 for bullish bias (dEMA50 = ta.ema(src, 50) - ta.ema(src[1], 50) > 0)
You may also test:
EMA 9 or 13 on M1 for even faster reaction.
WMA or Hull Moving Average for less lag.
Quick tips:
Backtest these EMA settings with your liquidity sweep + CISD + FVG setup to see what combination reduces false signals.
Start with the classic 50/100/200 on M15 since your script is already designed for these.
For entries on lower TF, try 21 + 50 EMA — good balance between noise and trend.
If you want, I can help you code the multi-timeframe EMA bias check and align it with your liquidity sweep + CISD + FVG combo for exact integration — just ask!
// EMA lengths for H1 – can match M15 or use longer EMAs like 100, 200, 300
emaLength1_H1 = 50
emaLength2_H1 = 100
emaLength3_H1 = 200
// Get EMA values from H1 timeframe
ema1_h1 = request.security(syminfo.tickerid, "60", ta.ema(close, emaLength1_H1))
ema2_h1 = request.security(syminfo.tickerid, "60", ta.ema(close, emaLength2_H1))
ema3_h1 = request.security(syminfo.tickerid, "60", ta.ema(close, emaLength3_H1))
// Define H1 EMA bias
bullishBias_H1 = (ema1_h1 > ema2_h1) and (ema2_h1 > ema3_h1)
bearishBias_H1 = (ema1_h1 < ema2_h1) and (ema2_h1 < ema3_h1)
// Use final bias only if both agree
finalBullishBias = bullishBias and bullishBias_H1
finalBearishBias = bearishBias and bearishBias_H1
Then use finalBullishBias / finalBearishBias as your main signal filter.
Summary
EMA Bias on...
When to use
Benefit
M15 only
Simple, fast, focused on your main timeframe
Quick signals, fewer delays
M15 + H1 combined
If looking for better overall trend alignment
Reduce false signals, filter trades
My recommendation:
Start with M15 only EMA bias since it directly matches your liquidity sweep timeframe, keeping your setup simpler. Later, consider adding H1 EMA bias as an additional trend filter if you want stronger confirmation and trades aligned with bigger picture trends.
If you want, I can help you write a snippet that combines these EMA biases properly into your existing script!
Your strategy:
Waits for liquidity sweep on M15 (a medium-term event)
Drops down to M5 or M1 for entry signals with CISD and FVG
Trades only during London or New York sessions
Wants to trade in the direction of EMA bias
Recommendation:
Go with EMA 20 / 50 / 100 on M15
It’s a good balance between being smooth enough to reflect reliable bias on M15 and still responsive enough to catch meaningful changes during your key trading sessions.
EMA 9/21/50 might be too noisy and cause conflicting bias on M15 for your style.
EMA 50/100/200 slows down too much on M15 for your timeframe and might miss timely bias shifts important around liquidity sweeps.
Extra tip:
You can always add an EMA slope or crossover confirmation, e.g., confirm bias change only if EMA 20 crosses EMA 50 or EMA 20 is trending consistently.
Backtest your choice for at least several weeks/months of historical price action to see which works best combined with your liquidity sweeps, CISD & FVG signals.
If you want, here’s a quick snippet for EMA 20/50/100 bias check on M15 inside your script:
Fast (9/21/50): For quick reaction and more trades — riskier
Medium (20/50/100): Balanced, recommended for your M15-based workflow
Slow (50/100/200): Strong trend filter, slower trades, less signals
Pick 20/50/100 for a solid, practical balance in your setup.
Need help coding it all in or testing? I’m here!
In a bullish EMA bias, if price dips near VWAP and FVG + CISD bullish signals appear, this can be a strong setup.
Optionally add alerts when price crosses VWAP aligned with your bias and sweep signals.
Simple example integrating VWAP with EMA bias and your entry logic:
pinescript
// Assume you have:
bullishBias = (ema20 > ema50) and (ema50 > ema100)
bearishBias = (ema20 < ema50) and (ema50 < ema100)
vwapValue = ta.vwap()
// VWAP trend
bullishVWAP = close > vwapValue
bearishVWAP = close < vwapValue
// Entry conditions
longEntry = liquiditySweepM15 and inTradeSession and bullishBias and bullishVWAP and bullishCISDFormed and fvgBullPresent
shortEntry = liquiditySweepM15 and inTradeSession and bearishBias and bearishVWAP and bearishCISDFormed and fvgBearPresent
Summary
VWAP Use Case
Benefit
Confirm EMA bias trend
Reduces false entries against volume flow
Support/resistance area
Helps pinpoint entries or stop-loss levels
Session VWAP filter
Filters for active session price behavior
Would you like help adding session VWAP or multi-session VWAPs? Or deeper trading rules combining VWAP with your overall signals? Just ask!
Practical example of your logic for such scenario:
pinescript
// Check if price is above VWAP
priceAboveVwap = close > vwapValue
// M15 EMA bias - neutral means neither bullish nor bearish
emaNeutral = not bullishBias and not bearishBias
// Liquidity sweep just happened: price pierced above 23565 recently
justSwept = (high > 23565) and ta.barssince(high > 23565) <= 2 // swept in last 2 bars
// Suppose you also detect reversal signs with CISD / FVG here (boolean signals)
bullishCISDReversal = ... // your boolean condition
bullishFvgPresence = ... // your boolean condition
// Entry condition example:
longEntry = justSwept and priceAboveVwap and emaNeutral and bullishCISDReversal and bullishFvgPresence and inTradeSession
if (longEntry)
label.new(bar_index, low, "Potential Long Entry", style=label.style_label_up, color=color.green)
Summary:
Your example shows price pulling back slightly after an upside liquidity sweep with volume bias bullish (price > VWAP) but no clear EMA trend.
You want to wait for confirmations like CISD bullish break + supportive FVG before entering.
Neutral EMA bias suggests caution — avoid chasing until trend clarity.
VWAP above means look for buyers defending value zone, which supports bullish setups.
Use time (sessions) and price action to confirm reversals after sweep.
If you want, I can help you build exact code for detecting these conditions around sweep + VWAP + neutral EMA bias + CISD + FVG for your entry signals in Pine!
Your script already includes sessions, so you can narrow to bars in Asia session and track the session low with something like:
pinescript
var float asiaLowSession = na
inAsiaSession = ta.session.isin(sesc_ses, tz)
if inAsiaSession
asiaLowSession := math.min(nz(asiaLowSession, low), low)
else
asiaLowSession := na
3. Combine these levels in your trade signals:
For example, if price is approaching or respecting Asia Low (23308), this can be:
Support zone for bullish reversal after liquidity sweep.
A stop-loss or take-profit level.
Likewise, price vs Day Open helps confirm bias or bias flips.
Example of combined condition snippet:
pinescript
// Inputs for fixed Asia Low, or use dynamic asiaLowSession from above
asiaLowLevel = input.float(23308, "Asia Low Level")
// Check confluence with liquidity sweep & CISD reversal
nearAsiaLow = math.abs(close - asiaLowLevel) <= syminfo.mintick * 10 // within small ticks distance
priceAboveDayOpen = close > dailyOpen
longEntry = liquiditySweepM15 and inTradeSession and bullishBias and bullishCISDReversal and fvgBullPresent and nearAsiaLow and priceAboveDayOpen
Summary of how your example fits:
Open Day price and Asia Low (23308) are key reference support zones.
Price trading near or above these levels after a liquidity sweep and combined with bullish EMA bias + VWAP + CISD + FVG signals = High-probability setup.
If price dipped below Asia low or day open, cautious or consider short bias setups.
If you want, I can assist you coding these session lows and day open detection dynamically into your existing script for more automated multi-level confluence!