ema bias is not good, is lagging, right now price is going up, but ema bias say sell, is bearish... i sell and sell, price go up and up, i lose and i lose...
Assistant
User
tell me more about:
bullishBias = close > emaValue and close > emaValue2 and close > emaValue3
bearishBias = close < emaValue and close < emaValue2 and close < emaValue3
and
bullishBias = (emaValue > emaValue2) and (emaValue2 > emaValue3) and close > emaValue
bearishBias = (emaValue < emaValue2) and (emaValue2 < emaValue3) and close < emaValue
Assistant
User
what is best to avoid this situation: right now price is going up, but ema bias say sell, is bearish... i sell and sell, price go up and up, i lose and i lose...
bullishBias = close > emaValue and close > emaValue2 and close > emaValue3
bearishBias = close < emaValue and close < emaValue2 and close < emaValue3
bullishBias = (emaValue > emaValue2) and (emaValue2 > emaValue3) and close > emaValue
bearishBias = (emaValue < emaValue2) and (emaValue2 < emaValue3) and close < emaValue
bullishBias = (emaValue > emaValue2) and (emaValue2 > emaValue3)
bearishBias = (emaValue < emaValue2) and (emaValue2 < emaValue3)
Assistant
User
bullishBias = (emaValue > emaValue2) and (emaValue2 > emaValue3) and close > emaValue
bearishBias = (emaValue < emaValue2) and (emaValue2 < emaValue3) and close < emaValue
Assistant
User
the price to be above/below which ema is best?
Assistant
User
the price to be above/below ema, but wich ema 1,2 or3 ?
Assistant
User
how about ema values 50 100 200
Assistant
User
especially on daily and higher timeframes..... wow, i daytrade on m15, maxim h1, and entries on m1 and m5
Assistant
User
i use emas only for m15, even i go on m1 or m5, ema values will be for m15 only
Assistant
User
bullishBias = (emaValue > emaValue2) and (emaValue2 > emaValue3) and (close > emaValue)
bearishBias = (emaValue < emaValue2) and (emaValue2 < emaValue3) and (close < emaValue)
i thing ill change close to emavalue3
Assistant
User
my curently bia didnt care about close, uses only ema order
Assistant
Thanks for the update—your current EMA bias is based only on EMA order, like this:
User
i have an exemple:
23516 swing high,23411 swing low, ema1=23394,ema2=23410,ema3=23460
Assistant
User
current price:23422
Assistant
User
but from swing high to swing low was a strong move leaving 3 bearish fvg
Assistant
User
i was thinking about price momentum, close><ema1, why not ema2 or ema3
Assistant
User
i trade liquidity sweeps
Assistant
User
yes
Assistant
User
i only see emas end ema bias status, no liquidiy, no swwp
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
// --- 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
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
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 is quite extensive and seems mostly well-structured and compatible with Pine Script v6. It integrates several features including liquidity detection, Fair Value Gaps (FVG), VWAP, EMA bias, previous day range, session ranges, CISD market structures, and multi-timeframe market structure analysis.
If you want me to assist with something specific—like fixing errors, adding features, optimizing it, or explaining any part—please specify your request.
Without a specific question, here are a few general remarks and tips based on your code:
1. Indicator Declaration
You correctly used //@version=6 and indicator(...) with max_lines_count = 500 to allow many lines.
2. EMA Calculation with Timeframe Option
You calculate EMA values on optionally different timeframes via request.security():
Your liquidity detection uses pivot highs/lows and tracks liquidity lines and sweeps. I confirm your logic of creating liquidity structs, managing arrays, deleting old lines, and creating dashed lines on breaks works as intended.
4. FVG Boxes and Mitigation
Your fair value gap detection and dynamic box coloring/adjustment with mitigation alerts looks functionally complete.
Just a reminder, the usage of alert() inside a function triggers alert every time the condition is met with alert.freq_once_per_bar, so ensure you want frequent alerts.
5. Prev Day Lines Drawing
Using a fixed daily timeframe with request.security() and drawing extended lines for previous day high/low is correct. Your computation of future extended line time (futureDeltaMs) looks correct.
6. Session Boxes
You implemented 4 configurable sessions with range box drawing and labels.
Minor note:
You're using var variables inside a function get_range() without proper resetting (you create var inside the function which persists across calls). This may result in wrong range values over time.
Consider storing persistent data externally or managing these variables better.
7. CISD Market Structure Logic
You handle bullish/bearish pullbacks, lines, and alerts well.
Note:
Line and label creations happen dynamically and arrays handle recent levels with optional cleanup (keepLevels).
8. Multi-Timeframe Market Structure (MSS) Section
This part processes market structure for a second timeframe, with many settings regarding display, alerts, and style.
9. Table Display
You show summary info (Current State, EMA Bias, VWAP Trend) using a table placed via input.
Potential Improvements / Issues to Look Out For:
Label/Box Cleanup:
Multiple arrays hold labels, lines, boxes, etc. Make sure elements are deleted properly to avoid hitting the max_lines_count or max_labels_count.
Variable Shadowing:
During array loops (e.g., liquidity lines), you reuse variable names (like testLiquidity). No direct issue, but avoid confusion.
Using alert() vs. alertcondition():
You use alertcondition(sweepAlert, ...) but also direct calls to alert(). The direct alert calls must be handled carefully to avoid hitting alert limits.
Session Boxes Resetting per session:
Since you create a new box on session start, you might want to delete the previous box of the same session to keep the chart clean.
var keyword scope inside functions:
Declaring variables as var inside functions means they're initialized once on script start and persist per script instance, which may not reset on new sessions.
If you want me to:
Fix errors you’re facing,
Add a feature (e.g., alerts on liquidity sweeps or improved table),
Optimize performance or line/label usage,
Help understanding a snippet or logic,
please say which part or issue you want help with, and I can focus on that.
Example Quick Fix: Session Boxes Variable Persistence
Here is a modified approach for get_range() to manage boxes and labels persistence cleanly:
var box sesa_box = na
var label sesa_label = na
get_range(session, session_name, session_css, var box b, var label l) =>
if session > session[1]
// Delete old box & label if exist
if not na(b)
box.delete(b)
if not na(l)
label.delete(l)
// Create new
b := box.new(bar_index, high, bar_index, low, bgcolor=color.new(session_css, 100 - bg_transp), border_color=show_outline ? session_css : na, border_style=line.style_dotted)
if show_txt
l := label.new(time, high, session_name, xloc=xloc.bar_time, textcolor=session_css, style=label.style_label_down, color=color.new(color.white, 100), size=size.tiny)
// Update box top and bottom during session
if session == 1 and session == session[1]
box.set_top(b, math.max(box.get_top(b), high))
box.set_bottom(b, math.min(box.get_bottom(b), low))
box.set_right(b, bar_index)
if show_txt
label.set_xy(l, (box.get_left(b) + box.get_right(b)) / 2, box.get_top(b))
// Then call:
// get_range(is_sesa, sesa_txt, sesa_css, sesa_box, sesa_label)
This pattern uses var box and label per session and updates/removes them accordingly.
If you want me to apply this fix or similar to your bigger script, just ask!
Got it.
You are using this condition to detect EMA bias (bullish or bearish):
bullishBias = (emaValue > emaValue2) and (emaValue2 > emaValue3)
bearishBias = (emaValue < emaValue2) and (emaValue2 < emaValue3)
and then:
var string emaBiasText = "Neutral"
if bullishBias
emaBiasText := "Only Buy"
else if bearishBias
emaBiasText := "Only Sell"
else
emaBiasText := "Neutral"
Why this approach can lag or fail:
EMA Crosses Are Lagging by Nature:
EMAs smooth price with more weight on recent candles, but when you check only order of three EMAs (50, 100, 200 or whatever lengths chosen), the bias updates only after these EMAs cross.
Slowest EMA (like 200) reacts very slowly.
So price may already be trending up strongly, but your EMAs still show a "bearish alignment" (largest EMA at the top).
The code only considers order of the EMAs without price position (e.g., is price above/below EMA), or momentum.
How to improve EMA bias?
Here are a few approaches:
1. Use Price vs EMA to define bias instead of just EMA cross order
For example:
bullishBias = close > emaValue and close > emaValue2 and close > emaValue3
bearishBias = close < emaValue and close < emaValue2 and close < emaValue3
This reacts faster to price vs EMA, not just EMA order.
2. Combine EMA order + price position for bias
For example:
bullishBias = (emaValue > emaValue2) and (emaValue2 > emaValue3) and close > emaValue
bearishBias = (emaValue < emaValue2) and (emaValue2 < emaValue3) and close < emaValue
3. Use a Faster EMA, or shorter lengths, or additional momentum confirmation
Sometimes 50/100/200 EMAs are just too slow for your time frame.
Try something like 20/50/100; or just 20 and 50, or include momentum indicator like RSI.
4. Use EMA slope (direction) and/or EMA crossover detection
This detects if all EMAs are moving higher or lower currently, which is more responsive.
Example Revised EMA Bias Code snippet (choose preferred logic):
// Option 1: Price vs all EMAs
bullishBias = close > emaValue and close > emaValue2 and close > emaValue3
bearishBias = close < emaValue and close < emaValue2 and close < emaValue3
// Option 2: EMA order + price above EMA1
bullishBias = (emaValue > emaValue2) and (emaValue2 > emaValue3) and (close > emaValue)
bearishBias = (emaValue < emaValue2) and (emaValue2 < emaValue3) and (close < emaValue)
// Option 3: EMA slopes positive/negative
emaSlope1 = emaValue - emaValue[1]
emaSlope2 = emaValue2 - emaValue2[1]
emaSlope3 = emaValue3 - emaValue3[1]
bullishBias = (emaSlope1 > 0) and (emaSlope2 > 0) and (emaSlope3 > 0)
bearishBias = (emaSlope1 < 0) and (emaSlope2 < 0) and (emaSlope3 < 0)
You can even combine slope + price position for more accuracy.
Additional Suggestion - Enable config in your inputs for bias calculation method:
Add input option so you can toggle behavior:
biasType = input.string("Price vs EMA", "EMA Bias Calculation Method", options=["EMA Order", "Price vs EMA", "EMA Slope"], group="Moving Average")
bullishBias = false
bearishBias = false
if biasType == "EMA Order"
bullishBias := (emaValue > emaValue2) and (emaValue2 > emaValue3)
bearishBias := (emaValue < emaValue2) and (emaValue2 < emaValue3)
else if biasType == "Price vs EMA"
bullishBias := close > emaValue and close > emaValue2 and close > emaValue3
bearishBias := close < emaValue and close < emaValue2 and close < emaValue3
else if biasType == "EMA Slope"
emaSlope1 = emaValue - emaValue[1]
emaSlope2 = emaValue2 - emaValue2[1]
emaSlope3 = emaValue3 - emaValue3[1]
bullishBias := (emaSlope1 > 0) and (emaSlope2 > 0) and (emaSlope3 > 0)
bearishBias := (emaSlope1 < 0) and (emaSlope2 < 0) and (emaSlope3 < 0)
Update your table text display accordingly.
Summary:
EMA cross order is slow and lagging especially with big lengths (200).
Price relation to EMAs (price > all EMAs or price < all EMAs) reacts faster.
EMA slope method (EMAs trending up/down) can give a smoother bias without lag.
Consider combining methods or using shorter EMA lengths.
Add user option to select bias calculation method to experiment easily.
If you'd like, I can help you generate the exact fixed snippet for your full code; just ask!
Certainly! Let's dive deeper into the two different EMA bias logics you mentioned.
1) Price above/below all EMAs
bullishBias = close > emaValue and close > emaValue2 and close > emaValue3
bearishBias = close < emaValue and close < emaValue2 and close < emaValue3
How it works:
This logic checks if the closing price is above all the EMAs (emaValue, emaValue2, emaValue3) to signal bullish bias.
Conversely, if the close is below all the EMAs, it signals bearish bias.
What does it imply?
Price above all EMAs means current price is strong enough to be above short, medium, and long-term moving averages.
Price below all EMAs means weakness — price is below all those average levels.
Advantages:
Fast Reaction: This method responds immediately as price moves, since it’s based on the current bar close, not the relative order of EMAs (which cross slower).
Clear directional signal: When price cleanly breaks above or below all EMAs, it's usually an indication of trend presence.
Disadvantages:
False Signals in Choppy Markets: Price can spike above/below EMAs temporarily and then revert, causing whipsaws.
No EMA order assessment: This method ignores the relative positions of EMAs (e.g., 50 above 100 above 200), sometimes important for trend strength.
2) EMA order + price relative to EMA
bullishBias = (emaValue > emaValue2) and (emaValue2 > emaValue3) and close > emaValue
bearishBias = (emaValue < emaValue2) and (emaValue2 < emaValue3) and close < emaValue
How it works:
Adds EMA order check on top of the price vs EMA check.
The EMAs must be in bullish order: fastest EMA > medium EMA > slow EMA (e.g., 50 > 100 > 200) for bullish bias.
The price must be above the fastest EMA (close > emaValue) as confirmation of bullish momentum.
And vice versa for bearish bias: EMAs stacked bearish and price below fastest EMA.
What does it imply?
The relative order of EMAs shows medium/long-term trend direction.
The price condition adds a short-term momentum confirmation.
Advantages:
More robust than just price: EMA order reduces false signals caused by price "spikes" — generally EMAs cross slower and confirm trend direction.
Short-term confirmation: Price above the fastest EMA shows immediate buying strength.
Disadvantages:
More lag: EMA order detection requires EMAs to physically cross, can lag current price action, especially on higher timeframes or longer EMAs.
If EMAs are flat or close, bias may flip-flop.
Price confirmation is only vs fastest EMA, sometimes price above fastest EMA but still below medium/slow EMA — borderline cases.
Summary & Which to choose?
Criteria
Price above/below all EMAs
EMA order + price vs fastest EMA
Responsiveness
Fast (reflects current price action)
Slower (awaits EMA cross + price condition)
Robustness
Can flip on price spikes (less robust)
More robust trend detection via EMA order
Trend strength info
None (ignores EMA order)
Includes medium-term to long-term trend info
Choppiness & Noise
More sensitive to noise
Smoother, better for trend following
Use case
Shorter timeframes, or faster signals
Longer term or confirm trend & momentum combo
Practical example to combine the two (optional):
Some traders combine or create tiers of signals:
// Fast bias (responsive)
fastBullishBias = close > emaValue and close > emaValue2 and close > emaValue3
fastBearishBias = close < emaValue and close < emaValue2 and close < emaValue3
// Confirmed bias (EMA order + price)
confirmedBullishBias = (emaValue > emaValue2) and (emaValue2 > emaValue3) and close > emaValue
confirmedBearishBias = (emaValue < emaValue2) and (emaValue2 < emaValue3) and close < emaValue
// Decision logic example
if confirmedBullishBias
emaBiasText := "Strong Buy"
else if fastBullishBias
emaBiasText := "Weak Buy"
else if confirmedBearishBias
emaBiasText := "Strong Sell"
else if fastBearishBias
emaBiasText := "Weak Sell"
else
emaBiasText := "Neutral"
This way, you get early warnings (fast bias) and stronger confirmations (confirmed bias).
Finally:
You can also tweak EMA lengths or add EMA slope or volume/momentum confirmation for better bias.
If you want me to prepare a working example snippet that you can integrate and test, I can do that as well. Just ask!
The problem you describe — price moving strongly up while your EMA bias signals bearish (sell) — usually happens because:
The EMA-based bias is lagging (it updates after EMAs cross, which takes time).
Or your logic doesn't account for price momentum or short-term strength well.
Or EMAs are too long and slow on the timeframe you're trading.
Best way to avoid that losing situation is to use a bias calculation method that balances:
Responsiveness to price movement
Robustness to noise and fake signals
Let's review your three candidate conditions:
1. Strict price vs all EMAs:
bullishBias = close > emaValue and close > emaValue2 and close > emaValue3
bearishBias = close < emaValue and close < emaValue2 and close < emaValue3
Very responsive because it depends on current price position.
Can flip quickly in volatile/choppy markets (= potentially fake signals).
Captures well when price decisively breaks above/below all EMAs.
2. EMA order + price > fastest EMA:
bullishBias = (emaValue > emaValue2) and (emaValue2 > emaValue3) and close > emaValue
bearishBias = (emaValue < emaValue2) and (emaValue2 < emaValue3) and close < emaValue
More conservative, requires EMAs to be sorted (representing trend direction).
Adds a momentum check by requiring price above/below fastest EMA.
Less responsive than #1, but more robust to noise.
3. Just EMA order only:
bullishBias = (emaValue > emaValue2) and (emaValue2 > emaValue3)
bearishBias = (emaValue < emaValue2) and (emaValue2 < emaValue3)
Slowest, fully depends on EMAs crossing.
Can cause delays in bias change, leading to missed moves and late entries.
May force you to trade opposite to real-time price momentum.
What is the best approach for avoiding being "stuck in a losing trade because bias lags?
Use combination or a layered approach, e.g.:
Confirm EMA order with price position AND EMA slope
Add momentum or volume confirmation (RSI, MACD, etc.)
Practical improved EMA bias example to reduce lag and increase accuracy:
// EMA slopes - check if EMAs are turning up/down (faster reaction)
emaSlope1 = emaValue - emaValue[1]
emaSlope2 = emaValue2 - emaValue2[1]
emaSlope3 = emaValue3 - emaValue3[1]
// Price vs EMAs condition
priceAboveAll = close > emaValue and close > emaValue2 and close > emaValue3
priceBelowAll = close < emaValue and close < emaValue2 and close < emaValue3
// EMA order condition
emasBullishOrder = (emaValue > emaValue2) and (emaValue2 > emaValue3)
emasBearishOrder = (emaValue < emaValue2) and (emaValue2 < emaValue3)
// Final bias logic with combined conditions
bullishBias = emasBullishOrder and (priceAboveAll or (emaSlope1 > 0 and emaSlope2 > 0 and emaSlope3 > 0))
bearishBias = emasBearishOrder and (priceBelowAll or (emaSlope1 < 0 and emaSlope2 < 0 and emaSlope3 < 0))
Explanation:
Requires EMAs stacked bullish/bearish (trend direction).
Plus either price clearly above/below all EMAs, or all EMAs are currently rising/falling (momentum via slope).
This combination helps reduce lag, because:
Sometimes price spikes first above EMAs (priceAboveAll),
Or EMAs start to slope up faster than cross-over triggers,
Both indicate early trend shifts.
Additional tips to avoid lag and bad bias signals:
1. Consider shorter EMA lengths if trading lower timeframe.
For example, 20, 50, 100 instead of 50, 100, 200.
2. Use additional indicators for confirmation:
RSI > 50 as additional bullish filter.
MACD histogram positive trend.
Volume surges on breakout.
3. Use price action confirmation (higher highs/lows) in conjunction.
Summary:
Method
Lag
Signal Robustness
Risk of missing move / being opposite
EMA order only (#3)
High
High trend confirmation
High - can lag behind price move
Price > all EMAs only (#1)
Low
Low - can be noisy
Medium - false flips in choppy market
EMA order + price + EMA slope (best)
Medium-Low
High robustness + speed
Lowest - balanced
If you want, I can generate a full snippet with the combined approach so you can test it.
Bottom line:
To avoid losing trades because of late or wrong EMA bias signals, avoid relying solely on EMA order condition (#3). Instead, use a combined condition incorporating price position and EMA momentum (slope) with stacked EMA order (#2 improved). This balances responsiveness with reliability.
Let me know if you want me to help you fully implement this combination in your script!
The conditions you wrote:
bullishBias = (emaValue > emaValue2) and (emaValue2 > emaValue3) and close > emaValue
bearishBias = (emaValue < emaValue2) and (emaValue2 < emaValue3) and close < emaValue
mean:
bullishBias is true when:
Your fast EMA (emaValue) is above the medium EMA (emaValue2),
The medium EMA is above the slow EMA (emaValue3)** (a bullish stacked order),
AND the current price (close) is above the fast EMA (emaValue) — indicating immediate price strength.
bearishBias is true when:
The fast EMA is below the medium EMA,
Medium EMA is below slow EMA (bearish stacked EMAs),
AND current price is below the fast EMA — indicating immediate downward pressure.
Why is this a pretty good bias method?
It confirms the overall trend direction via the stacked EMAs:
Fast EMA > Medium EMA > Slow EMA = uptrend
Fast EMA < Medium EMA < Slow EMA = downtrend
It requires the price to be above/below the fast EMA, which is the most responsive EMA, so it prevents you from trading against very short-term price action.
Benefits:
Robustness:
Using EMA stacked order avoids false signals caused by price noise, giving you a better sense of trend.
Responsiveness:
Checking price against fast EMA (which reacts quicker than medium or slow EMA) provides a timely confirmation of price momentum.
But be aware:
Sometimes the EMAs may be overlapping or tight, and the trend could be indecisive – bias may flip-flop if price hovers around the fast EMA.
In very volatile or sideways markets, this method may still generate some false signals.
For improved performance, you might consider adding EMA slopes (momentum):
emaSlope1 = emaValue - emaValue[1]
emaSlope2 = emaValue2 - emaValue2[1]
emaSlope3 = emaValue3 - emaValue3[1]
bullishBias = (emaValue > emaValue2) and (emaValue2 > emaValue3) and (close > emaValue) and (emaSlope1 > 0) and (emaSlope2 > 0) and (emaSlope3 > 0)
bearishBias = (emaValue < emaValue2) and (emaValue2 < emaValue3) and (close < emaValue) and (emaSlope1 < 0) and (emaSlope2 < 0) and (emaSlope3 < 0)
This requires that EMAs are stacked correctly, price is positioned favorably, and all EMAs are currently trending in the right direction (positive or negative slope).
Summary:
Your condition detects "trend" with EMA stacked order AND immediate price direction with price vs fast EMA.
This is a good balance of trend-following and momentum confirmation that reduces false bias signals and lag.
If you want, I can help generate a complete snippet with inputs to toggle bias method and proper table display update for your script. Just ask!
Great question! Choosing which EMA the price should be above or below for best and timely bias detection depends on your trading style, timeframe, and how fast you want signals.
Common EMA options to compare price with:
EMA Type
Typical Lengths
Characteristics
How price relation affects bias detection
Fast EMA
9, 12, 20
Very sensitive, fast reacts to price
Price crossing fast EMA = very early signals but more noise
Medium EMA
50, 21, 30
Balanced: smooth but responsive
Price relation provides balanced confirmations
Slow EMA
100, 200
Very smooth, trend-defining
Price relation gives strong trend confirmation but lags
Most common and recommended:
1. Price vs Fast EMA (e.g., 9, 12, or 20 EMA)
Pros:
Most responsive and captures early momentum shifts.
Less lag, so bias flips closer to price changes.
Cons:
Can produce more false signals during sideways markets.
Very small retracements can trigger bias flip.
2. Price vs Medium EMA (e.g., 50 EMA)
Pros:
Smoother than fast EMA; filters some noise.
A good "compromise" level used often as support/resistance.
Cons:
Slightly slower signals than fast EMA — can cause some lag.
3. Price vs Slow EMA (e.g., 100, 200 EMA)
Pros:
Best for confirming strong, longer-term trend.
Helps avoid false flips in noise.
Cons:
Signals tend to lag more than fast or medium EMAs.
Price often crosses slower EMA long before true trend change.
Best practice for bias detection:
Use the fastest EMA that your strategy/timeframe can tolerate for responsiveness. For example:
On shorter timeframes (5m, 15m, 1H), fast EMA like 9 or 20 is better.
On daily or higher timeframes, 50 EMA or even 100 EMA can be more reliable.
Combine price relation to fastest EMA with stacked order of medium and slow EMAs, like in your earlier condition here:
bullishBias = (emaValue > emaValue2) and (emaValue2 > emaValue3) and close > emaValue
Where:
emaValue = fast EMA (e.g., 20)
emaValue2 = medium EMA (e.g., 50)
emaValue3 = slow EMA (e.g., 100 or 200)
This way:
EMA order confirms trend direction (longer-term context)
Price > fast EMA detects momentum shifts early.
TL;DR:
If you want...
Then use price vs...
Fastest, most responsive bias
Price vs fastest EMA (9-20 EMA)
Balanced bias
Price vs fast or medium EMA (20-50)
Stable, slow bias
Price vs medium or slow EMA (50-200)
If your current bias is lagging (price going up but bias still bearish), try:
Using price vs faster EMA for price check (e.g., use 20 EMA for emaValue).
Keep longer EMAs in stack (50, 100, 200) for trend confirmation.
Example:
// Define EMAs (you can choose lengths)
fastEMA = ta.ema(close, 20)
mediumEMA = ta.ema(close, 50)
slowEMA = ta.ema(close, 200)
// Bias condition
bullishBias = (fastEMA > mediumEMA) and (mediumEMA > slowEMA) and (close > fastEMA)
bearishBias = (fastEMA < mediumEMA) and (mediumEMA < slowEMA) and (close < fastEMA)
Bonus tip:
Try visualizing these EMAs on your chart and see where price reacting to each one fits your trading style.
Let me know if you want me to help you adjust your code to apply this method!
Great clarification — when you say emaValue, emaValue2, emaValue3, you mean your three EMAs (often like EMA1=fast, EMA2=medium, EMA3=slow).
Which EMA should the price be above/below for best EMA bias?
Typical assignments in your script:
emaValue = EMA1 (fastest, e.g., 20)
emaValue2 = EMA2 (medium, e.g., 50)
emaValue3 = EMA3 (slowest, e.g., 100 or 200)
Answer:
Price should be above or below the fastest EMA (emaValue / EMA1) to determine bias.
Why price vs fastest EMA (EMA1)?
The fastest EMA reacts quickest to price changes.
If price is above the fast EMA, it means short-term momentum is bullish.
If you require price above slower EMAs too, bias signals become too slow and lag.
What about EMA order (EMA1 > EMA2 > EMA3)?
The order of all three EMAs gives you the overall trend structure (fast above medium, medium above slow = bullish trend)
But for price position to confirm immediate momentum direction, price vs fastest EMA (emaValue) is best.
So the combined logic looks like this:
// Bias conditions
bullishBias = (emaValue > emaValue2) and (emaValue2 > emaValue3) and (close > emaValue)
bearishBias = (emaValue < emaValue2) and (emaValue2 < emaValue3) and (close < emaValue)
emaValue = fastest EMA (e.g., 20)
Price above fastest EMA → momentum confirming bullish
EMA order confirms overall trend
Summary:
Condition
EMA Reference
Meaning
EMA order
Fast (EMA1) > Medium (EMA2) > Slow (EMA3)
Trend stacking condition
Price position for bias
Price > Fast EMA (EMA1)
Short-term momentum direction (timelier)
Why not price vs EMA2 or EMA3?
Price crosses medium or slow EMA later — bias will lag.
Slow EMAs represent longer-term trend, less sensitive to recent price moves.
Using price vs slow EMA risks delayed or missed short-term changes.
Optional: If you want to be even faster...
Sometimes traders compare price to the fastest EMA or even an even shorter moving average (e.g., 9 EMA), if you want the earliest signal.
TL;DR:
Use price vs EMA1 (fastest EMA) for bias momentum confirmation.
Use EMA order (EMA1 > EMA2 > EMA3) to confirm trend direction.
This minimizes lag and false bias signals.
If you want, I can help you update your code snippet accordingly!
Using EMAs with lengths 50, 100, and 200 is very common in many trading strategies, especially on daily and higher timeframes, because:
50 EMA represents intermediate-term trend (roughly about 2 months on daily charts)
100 EMA is a longer-term trend smoother
200 EMA is a widely watched major trend line (big-picture trend direction)
How to apply your bias logic with EMAs 50, 100, 200?
Assuming:
emaValue = ta.ema(close, 50) // Fast EMA
emaValue2 = ta.ema(close, 100) // Medium EMA
emaValue3 = ta.ema(close, 200) // Slow EMA
Price relation to EMA for bias?
The price should be compared to the fastest EMA (50 EMA in this case) for momentum confirmation.
bullishBias = (emaValue > emaValue2) and (emaValue2 > emaValue3) and (close > emaValue)
bearishBias = (emaValue < emaValue2) and (emaValue2 < emaValue3) and (close < emaValue)
What does this mean here?
EMA Order (50 > 100 > 200):
Your three EMAs are stacked bullish in order — indicative of a strong medium-to-long term uptrend.
Price > 50 EMA:
Price is currently above the "fastest" EMA → momentum is aligned with the trend and price is strong.
For bearish bias:
EMAs stacked 50 < 100 < 200, price below 50 EMA → downtrend, momentum bearish.
Is this combination good?
Yes! For daily or higher timeframe TV charts, this gives a good balance of:
Trend confirmation: via EMA stacking (order)
Momentum confirmation: via price position relative to 50 EMA
What about timeframe and lag?
EMAs 50, 100, 200 are longer term, so signals will be slower compared to shorter EMAs (like 9 or 20).
This reduces noise, false flips, but also means bias updates more slowly.
On higher timeframes (daily, weekly), this lag is often acceptable or desirable.
On intraday timeframes (1m, 5m, 15m), you might prefer faster EMAs like 20, 50, 100, or even 9, 21, 50.
Summary for EMAs 50, 100, 200:
Parameter
Value
Role
Fast EMA (emaValue)
50
Fastest EMA, price compared here for momentum confirmation
Medium EMA (emaValue2)
100
Intermediate trend confirmation
Slow EMA (emaValue3)
200
Long-term trend confirmation
Recommended bias logic:
bullishBias = (emaValue > emaValue2) and (emaValue2 > emaValue3) and (close > emaValue)
bearishBias = (emaValue < emaValue2) and (emaValue2 < emaValue3) and (close < emaValue)
Optional: To catch momentum shifts faster, add EMA slopes (optional):
emaSlope1 = emaValue - emaValue[1]
emaSlope2 = emaValue2 - emaValue2[1]
emaSlope3 = emaValue3 - emaValue3[1]
bullishBias = (emaValue > emaValue2) and (emaValue2 > emaValue3) and (close > emaValue) and (emaSlope1 > 0) and (emaSlope2 > 0) and (emaSlope3 > 0)
bearishBias = (emaValue < emaValue2) and (emaValue2 < emaValue3) and (close < emaValue) and (emaSlope1 < 0) and (emaSlope2 < 0) and (emaSlope3 < 0)
TL;DR
For EMAs 50, 100, 200: Compare price with 50 EMA (fastest), and use EMA order 50 > 100 > 200 to confirm trend.
If you want me to help integrate this cleanly in your full script or provide a snippet for testing, just ask!
Thanks for clarifying your timeframes — M1, M5 for entries and M15 to H1 as primary trading timeframe.
Important implications for EMA settings & bias logic on intraday lower timeframes:
1. EMAs like 50, 100, 200 on M15/H1:
On M15/H1 charts, 50, 100, 200 EMA represent:
50 EMA = last ~12.5 hours on M15 or ~50 hours on M1 (because 50 * timeframe length in minutes)
100 EMA ~ doubled that
200 EMA very long-term trend even intraday
These EMAs will be very slow and laggy for fast daytrading on these timeframes.
2. For faster, timely bias for day trading on those timeframes, prefer:
Faster EMAs, eg. 9, 20, 34, 50 — combinations common in day trading
Example popular EMA settings on intraday:
Fast: 9 or 10 EMA
Medium: 21 or 34 EMA
Slow: 50 or 100 EMA
3. Why?
Fast EMA (9 or 20) quickly follows price changes = faster bias changes, less lag
Medium and slow EMAs still confirm trend, but more responsive than 100 or 200 on intraday
4. Suggested EMA settings for your use:
EMA type
Length
Role
Fast EMA
9 or 20
Short-term momentum and quick bias
Medium EMA
21 or 34
Confirm medium trend
Slow EMA
50 or 100
Confirm longer-term trend
5. Bias logic on intraday timeframes (M15/H1):
// EMA Calculations
fastEMA = ta.ema(close, 20)
mediumEMA = ta.ema(close, 50)
slowEMA = ta.ema(close, 100)
// Bias detection
bullishBias = (fastEMA > mediumEMA) and (mediumEMA > slowEMA) and (close > fastEMA)
bearishBias = (fastEMA < mediumEMA) and (mediumEMA < slowEMA) and (close < fastEMA)
Price compared to fastEMA (20 EMA) for momentum confirmation.
6. Entries on M1/M5:
Use fastEMA (9/10/20 EMA) alone or combined with another momentum indicator (e.g., RSI) for quick entry timing.
The trend bias on higher timeframe (M15, H1) can be confirmed by bias logic above.
7. Final suggestion:
For daytrading on M15/H1 and entries on M1/M5, use shorter EMA lengths (9, 20, 50 or 20, 50, 100) instead of 50, 100, 200.
Keep price vs. fastest EMA condition.
Combine with EMA order.
Optionally add EMA slope or volume/momentum filter for robustness.
Example full bias snippet for intraday setups:
fastEMA = ta.ema(close, 20)
mediumEMA = ta.ema(close, 50)
slowEMA = ta.ema(close, 100)
emaSlope1 = fastEMA - fastEMA[1]
emaSlope2 = mediumEMA - mediumEMA[1]
emaSlope3 = slowEMA - slowEMA[1]
bullishBias = (fastEMA > mediumEMA) and (mediumEMA > slowEMA) and (close > fastEMA) and (emaSlope1 > 0) and (emaSlope2 > 0) and (emaSlope3 > 0)
bearishBias = (fastEMA < mediumEMA) and (mediumEMA < slowEMA) and (close < fastEMA) and (emaSlope1 < 0) and (emaSlope2 < 0) and (emaSlope3 < 0)
Wrap up:
For your trading style and timeframe, use shorter EMAs (9-20-50 or 20-50-100), and price relation to the fastest EMA is critical for bias detection.
If you want I can generate a modified script snippet focused on your timeframe, let me know!
Thanks for clarifying: you use EMAs calculated on the M15 timeframe even when looking for entries on M1 or M5. This is a common multi-timeframe (MTF) approach — using a higher timeframe trend (M15 EMA) to define bias, while taking entries on lower timeframes.
How does this affect EMA bias logic and price-vs-EMA comparison?
1. You're requesting EMA values on M15 and applying them on M1/M5 candles, for bias:
Your price on M1 or M5 vs M15 EMAs must be consistent.
But since price is from a different timeframe than EMAs, you should compare M1/M5 price to these M15 EMAs exactly as retrieved.
3. How to do this properly:
You want to compare lower timeframe price (close) with higher timeframe EMA values (emaValue calculated on M15).
For example:
bullishBias = (emaValue > emaValue2) and (emaValue2 > emaValue3) and (close > emaValue)
bearishBias = (emaValue < emaValue2) and (emaValue2 < emaValue3) and (close < emaValue)
close is M1 or M5 bar close (current price)
emaValue is M15 EMA at this bar time (constant or updated every 15 bars on M1)
4. Important practical note on MTF EMA vs price comparison:
The M15 EMA values update only every 15 bars on M1.
Between M15 bar closes, M15 EMA value is "flat" on M1 (doesn't change).
Price on M1/M5 can move a lot within one 15 min bar even if M15 EMA is unchanged.
Therefore, price can cross above/below M15 EMA level multiple times intrabar — causing multiple bias flips if implemented naïvely.
5. How to handle smooth MTF EMA bias with lower timeframe price?
Options:
a) Use a buffer zone (deadband) or tolerance around EMA to avoid unwanted flips due to minor price wicks intrabar.
Example:
buffer = syminfo.mintick * 5 // or some small value
bullishBias = (emaValue > emaValue2) and (emaValue2 > emaValue3) and (close > emaValue + buffer)
bearishBias = (emaValue < emaValue2) and (emaValue2 < emaValue3) and (close < emaValue - buffer)
This prevents bias flips for small price fluctuations around the EMA.
b) Use close price from M15 timeframe also for price comparison.
That is, retrieve price from M15, not from M1. This means:
priceM15 = request.security(syminfo.tickerid, "15", close)
bullishBias = (emaValue > emaValue2) and (emaValue2 > emaValue3) and (priceM15 > emaValue)
bearishBias = (emaValue < emaValue2) and (emaValue2 < emaValue3) and (priceM15 < emaValue)
Now your bias is based on M15 price and M15 EMAs, fully aligned.
Your entries on M1/M5 can be separately timed, while bias is a clean M15 trend context.
6. Summary & recommendation for your multi-timeframe bias usage:
Approach
Pros
Cons
Compare M1/M5 close vs M15 EMAs
Responsive to lower timeframe price
Can cause frequent bias flips due to price noise intrabar with flat M15 EMA
Use buffer/deadband around M15 EMA
Reduces noise bias flipping
Slight delay/insensitivity near EMA
Compare M15 close vs M15 EMAs
Clean, consistent bias without noise
Less responsive to lower timeframe price moves
My recommendation:
Use M15 price and M15 EMAs for bias calculation (fully aligned MTF).
Use lower timeframe price (M1/M5) only for entry triggers or fine timing inside that context.
If you still want to use lower timeframe price vs M15 EMA, implement a deadband/buffer to prevent whipsaws.
Example snippet with M15 price and EMAs:
// Fetch M15 EMAs
emaFastM15 = request.security(syminfo.tickerid, "15", ta.ema(close, 20))
emaMedM15 = request.security(syminfo.tickerid, "15", ta.ema(close, 50))
emaSlowM15 = request.security(syminfo.tickerid, "15", ta.ema(close, 100))
// Fetch M15 close price
priceM15 = request.security(syminfo.tickerid, "15", close)
// Bias based on M15 price and M15 EMAs (fully aligned)
bullishBias = (emaFastM15 > emaMedM15) and (emaMedM15 > emaSlowM15) and (priceM15 > emaFastM15)
bearishBias = (emaFastM15 < emaMedM15) and (emaMedM15 < emaSlowM15) and (priceM15 < emaFastM15)
Optional: Use buffer with lower timeframe price e.g.
buffer = syminfo.mintick * 10
bullishBias = (emaFastM15 > emaMedM15) and (emaMedM15 > emaSlowM15) and (close > emaFastM15 + buffer)
bearishBias = (emaFastM15 < emaMedM15) and (emaMedM15 < emaSlowM15) and (close < emaFastM15 - buffer)
If you want, I can provide you a tested full snippet that you can try on your charts with MTF bias and lower timeframe entries.
Summary:
When mixing timeframes, compare price and EMAs on the same timeframe (M15 here) for bias stability.
Use lower timeframes for entry/detals, bias remains clean and lag-reduced.
Optionally use buffer when mixing price on low TF and EMAs on high TF to avoid flip-flopping.
Let me know if you want me to create that snippet for you!
Changing your bias condition from comparing price (close) to the fastest EMA (emaValue) over to comparing price against the slowest EMA (emaValue3) is a significant shift in how your bias logic behaves.
Here's a detailed explanation and implications of such change:
Current logic:
bullishBias = (emaValue > emaValue2) and (emaValue2 > emaValue3) and (close > emaValue)
bearishBias = (emaValue < emaValue2) and (emaValue2 < emaValue3) and (close < emaValue)
EMA order check: Fast EMA > Medium EMA > Slow EMA (classic bullish stack)
Price vs Fast EMA (close > emaValue): short-term momentum confirmation
Proposed change:
bullishBias = (emaValue > emaValue2) and (emaValue2 > emaValue3) and (close > emaValue3)
bearishBias = (emaValue < emaValue2) and (emaValue2 < emaValue3) and (close < emaValue3)
Keeping the same EMA order check — which is good.
Now comparing price to the slowest EMA instead of the fastest.
What does comparing price to slowest EMA (emaValue3) imply?
Pros:
More conservative bias trigger.
Price needs to be above (or below) the slow EMA (like 200 EMA) to be bullish (or bearish).
This reduces noise and false bias flips.
Useful for filtering out short-term price noise — you only get bullish bias if price is firmly above the long-term trend EMA.
Cons:
Greater lag in bias changes.
Price can be above your fast and medium EMAs for a while (showing short-term strength), but if it remains under the slow EMA, bias stays bearish (or neutral).
You might miss early entries or trend shifts because price hasn't cleared the slow EMA yet.
For daytrading or intraday with faster timeframes, it can be too slow.
When to use price vs slow EMA for bias?
When you want very stable, long-term trend confirmation, ignoring short-term pullbacks.
When trading higher timeframes (daily / weekly).
When you want to avoid trading against major trend — only take trades favoring position of price vs the 200 EMA (slowest EMA).
Summary of price vs EMA comparison for bias:
Price vs...
Reaction Speed
Noise Sensitivity
Suitable For
Fastest EMA
Fastest, early bias
More noise
Short-term, intraday traders
Medium EMA
Medium speed
Moderate noise
Balanced traders
Slowest EMA
Slowest, lagging
Least noise
Long-term traders
Best practice in many trading strategies:
Use EMA order for trend direction (fast > medium > slow).
Use price vs fastest EMA for momentum confirmation and bias changes.
Optionally, use price vs slow EMA as a master filter — eg only consider bullish bias if price > slow EMA, else neutral or no bias.
Example:
fastBullish = (emaValue > emaValue2) and (emaValue2 > emaValue3) and (close > emaValue)
priceAboveSlow = close > emaValue3
bullishBias = fastBullish and priceAboveSlow
// similarly for bearish
fastBearish = (emaValue < emaValue2) and (emaValue2 < emaValue3) and (close < emaValue)
priceBelowSlow = close < emaValue3
bearishBias = fastBearish and priceBelowSlow
This way, your bias responds quickly to momentum changes but is only meaningful if price is also trading in the major trend direction (relative to slow EMA).
If you only use price vs slow EMA without fast EMA confirmation, the bias will be very slow and laggy, which may not suit shorter timeframes or timely entries.
TL;DR
Changing from close > emaValue (fastest EMA) to close > emaValue3 (slowest EMA) makes bias more rigid and slower to change.
Usually better as an additional filter, not sole condition.
For intraday or faster signals, keep price vs fast EMA for responsiveness.
Let me know if you want me to write a clean combined bias snippet or explain further!
bullishBias = (emaValue > emaValue2) and (emaValue2 > emaValue3)
bearishBias = (emaValue < emaValue2) and (emaValue2 < emaValue3)
Why this causes lag and poor responsiveness
EMA order changes only when EMAs cross each other,
EMAs with lengths like 50, 100, 200 are inherently slow,
So, even if price moves strongly bullish, if EMAs haven’t crossed yet, bias stays bearish — too late to react,
This leads to being “stuck” with a bearish bias despite an ongoing up move.
How to fix/improve this:
Add price relation to one EMA (usually the fastest EMA) to your bias check. For example:
bullishBias = (emaValue > emaValue2) and (emaValue2 > emaValue3) and (close > emaValue)
bearishBias = (emaValue < emaValue2) and (emaValue2 < emaValue3) and (close < emaValue)
Price > fastest EMA: confirms momentum is bullish,
Price < fastest EMA: confirms momentum is bearish.
Why is adding price condition important?
Price reacts immediately to market movements,
It can move above/below EMAs before EMAs cross,
This reduces bias lag, allowing earlier recognition of trend shifts,
Keeps you from trading against momentum or waiting until EMAs “catch up”.
Additional improvements (optional):
Add EMA slopes check to ensure EMAs are trending in the right direction:
emaSlope1 = emaValue - emaValue[1]
emaSlope2 = emaValue2 - emaValue2[1]
emaSlope3 = emaValue3 - emaValue3[1]
bullishBias = (emaValue > emaValue2) and (emaValue2 > emaValue3) and (close > emaValue) and (emaSlope1 > 0) and (emaSlope2 > 0) and (emaSlope3 > 0)
bearishBias = (emaValue < emaValue2) and (emaValue2 < emaValue3) and (close < emaValue) and (emaSlope1 < 0) and (emaSlope2 < 0) and (emaSlope3 < 0)
Summary of what to do:
Current
Recommended
Only EMA order
EMA order + price vs fast EMA (e.g., 20 EMA)
Too slow to change
Reacts faster, closer to price action
Can miss early moves
Can identify momentum shifts earlier
If you want, I can prepare a full code snippet for you based on your existing script, adding these improvements. Let me know!
Thanks for the example, let's analyze it step-by-step to understand how your EMA bias logic behaves and why adding price conditions matters.
Your example values:
Swing High: 23516
Swing Low: 23411
ema1 (fastest): 23394
ema2 (medium): 23410
ema3 (slowest): 23460
Step 1: Check EMA order conditions
ema1 = 23394
ema2 = 23410
ema3 = 23460
Check if:
Bullish order:ema1 > ema2 and ema2 > ema3?
23394 > 23410? NO (23394 < 23410)
So bullishBias condition false.
Bearish order:ema1 < ema2 and ema2 < ema3?
23394 < 23410? YES
23410 < 23460? YES
So bearish bias is potentially TRUE.
Step 2: Check current price (close) relative to fastest EMA (ema1 = 23394)
You didn't specify current price, but since:
Swing Low is 23411 (> 23394),
Swing High 23516 (> 23394),
Let's assume current price is near the swing high (e.g., ~23500).
Is close > ema1?
23500 > 23394 → TRUE
Step 3: If bias logic is only based on EMA order
You have bearish bias because EMA order is bearish (ema1 < ema2 < ema3),
But price (close) is above fastest EMA (23394), which indicates short-term bullish momentum.
Real world implication:
Your EMA order alone tells bearish bias, so your system says "sell".
But price is actually stronger than fastest EMA, showing good upward momentum and possibly continuing higher price movement.
This mismatch causes lag and false bearish bias despite price moving up.
What if you add price condition to bias?
Use this:
bullishBias = (ema1 > ema2) and (ema2 > ema3) and (close > ema1)
bearishBias = (ema1 < ema2) and (ema2 < ema3) and (close < ema1)
In your example:
EMA order says bearish (true),
Price (close) is above ema1, so close < ema1 is false,
Therefore bearishBias = false.
Your logic now:
No bearish bias,
You may treat it as neutral or bullish depending on full code.
This reflects real price momentum better and avoids premature bearish bias.
Summary:
Condition
Result in your example
EMA order only
Bearish (because ema1 < ema2 < ema3)
Price vs ema1 (close > ema1)
True (price shows bullish momentum)
Combined EMA order + price
No bearish bias (since close > ema1)
Final recommendation:
Use EMA order + price vs fastest EMA for bias to avoid lag and false signals like this.
This will let you see momentum aligned with recent price action.
If you want, I can help code this logic in Pine Script and integrate into your existing code!
Thanks for adding the current price = 23422.
Let's analyze your example again with full details:
Given:
Swing High = 23516
Swing Low = 23411
ema1 (fastest) = 23394
ema2 (medium) = 23410
ema3 (slowest) = 23460
Current price (close) = 23422
Step 1: Check EMA order (trend stack)
ema1 < ema2 < ema3?
23394 < 23410? Yes
23410 < 23460? Yes
So EMA order indicates bearish trend (bearishBias = true if using EMA order only)
Step 2: Check price vs fastest EMA (ema1)
close = 23422
ema1 = 23394
Is close > ema1? → 23422 > 23394 → Yes
This means price is trading above the fastest EMA, indicating short-term bullish momentum.
Step 3: Combined bias logic:
bullishBias = (ema1 > ema2) and (ema2 > ema3) and (close > ema1) // false (order not bullish)
bearishBias = (ema1 < ema2) and (ema2 < ema3) and (close < ema1) // close < ema1 is false, so bearishBias = false
EMA order technically bearish (ema1 < ema2 < ema3) is true.
Price is not below ema1, so bearish bias is false due to price condition.
Bullish bias fails order condition.
So the result is:
Neither bullish nor bearish bias is true if you require both EMA order and price position to confirm.
Effectively bias = Neutral or undecided.
Interpretation
Trend (EMA order) says bearish, BUT price is showing bullish momentum, trading above fastest EMA.
This means momentum could be shifting bullish, but EMAs haven't flipped yet—typical early reversal or pullback inside longer bearish trend.
What to do?
Treat this state as neutral bias and wait for confirmation (either EMA order flips or price clearly breaks EMA1 up/down).
Or use additional filter indicators (e.g., EMA slopes, RSI) to confirm momentum.
If you trust price momentum more, you can relax bearishBias condition:
bearishBias = (ema1 < ema2) and (ema2 < ema3) // Ignore price condition here
But that increases lag and false bearish bias, which you were worried about.
Final notes:
Condition
Result in example
Comment
EMA order only
Bearish (true)
Bias lags price
EMA order + price vs ema1
Neither bullish nor bearish (false)
Neutral, respects price moment
Price > ema1 only
True (bullish momentum)
Fast reaction, may be noisy
Summary recommendations for your style (M15 bias, M1/5 entries):
Use EMA order + price vs fast EMA for bias to balance trend and momentum.
Understand bias in "neutral" when price contradicts trend order.
Possibly add EMA slopes or other momentum for confirmation.
If you want, I can help you add this neutral state handling into your script or write a snippet showing this logic clearly.
Let me know!
Thanks for the additional context — you’re pointing out that from the swing high (23516) down to swing low (23411) was a strong down move which left 3 bearish FVGs (Fair Value Gaps). This is important because it means price has recently been very bearish despite what the EMAs and price comparisons may suggest.
Let’s reconcile this with your bias logic and EMA values:
Recap of key values:
Parameter
Value
Swing High
23516
Swing Low
23411
ema1 (fast)
23394
ema2 (med)
23410
ema3 (slow)
23460
Current price
23422
Price is currently above fastest EMA (23394) but below medium (23410) and slow EMA (23460).
EMAs stack bearish (23394 < 23410 < 23460).
A big bearish move recently took place leaving 3 bearish FVGs which represent unfilled liquidity areas in the market, often strong resistance areas (potential price rejection zones).
What this means contextually:
1. Price currently above fast EMA (ema1 = 23394) but still below medium (23410) and slow (23460) EMAs:
Shows short-term bounce or retracement up within an overall bearish structure.
The downtrend confirmed by EMA order and recent swing low/high is intact.
The short-term momentum (price > fast EMA) is bullish, likely a retracement leg.
2. Bearish bias from EMA order still holds:
Because EMAs are stacked bearish.
Downtrend is still primary.
Current bullish price position vs fastest EMA is a counter-trend move (retracement/pullback).
3. Bearish FVGs support sellers:
The presence of bearish FVGs (fair value gaps) adds confluence — these are known zones where price usually finds seller interest to resume downtrend.
Price approaching or still within FVGs increases probability bias remains bearish or that the retracement may fail.
How to trade or set bias logic with this info?
Option 1: Use multi-layer bias
Primary bias: Based on EMA order — still bearish.
Secondary indicator: Short-term price momentum flag (price vs fast EMA) → shows retracement.
FVG zones: Mark areas of interest for probable supply/resistance.
Example logic:
// EMA order bias
emaOrderingBearish = (ema1 < ema2) and (ema2 < ema3)
emaOrderingBullish = (ema1 > ema2) and (ema2 > ema3)
// Momentum check
momentumBullish = close > ema1
momentumBearish = close < ema1
// Combine them in bias categories
// Strong Bearish Bias = bearish EMA order + price below fast EMA
strongBearishBias = emaOrderingBearish and momentumBearish
// Bearish retracement (weak bearish or neutral bias)
bearishRetracement = emaOrderingBearish and momentumBullish
// Bullish bias (ema order bullish + momentum bullish)
strongBullishBias = emaOrderingBullish and momentumBullish
// Neutral / other combinations ignored or treated accordingly
So when EMA order bearish but price above fast EMA, label bias as retracement or neutral — don’t trade aggressively against short-term price momentum.
Option 2: Use FVGs as bias modifiers
When price is inside or near bearish FVGs during an EMA bearish bias + price > fast EMA retracement, treat as high probability short zone.
Option 3: Filter entries on lower timeframes with shorter EMAs or momentum
On M1/M5, use shorter EMAs (like 9 or 12) for entry timing — align trade with primary M15 bias but respect short-term momentum.
Summary and practical impact for your example:
Condition
Interpretation
Bias
Trade idea
EMA order bearish
Primary downtrend intact
Bearish
Bias short setups
Price > fast EMA (23394)
Short-term retracement/bounce
Neutral/weak Bullish
Wait for retracement to fail or confirm
Price near bearish FVGs
Potential strong seller interest zones
Bearish reinforced
Look for reversal signals near FVGs
Final advice:
Don’t rely on one condition only — combine EMA order, price vs fast EMA, and FVG zones.
Treat price above fastest EMA inside a bearish trend as retracement that can fail or continue.
Use FVGs to mark zones where you expect the bears to re-enter heavily.
Align entries on lower TF with these combined bias signals.
If you want I can draft a Pine Script snippet that:
Defines bias state (strong bearish, retracement, neutral, bullish) based on EMA order and price,
Highlights bearish FVG zones,
And outputs bias info for easier chart reading.
Would you like that?
Great question! Choosing which EMA to compare price (close) against for momentum depends on the balance you want between responsiveness and reliability. Let me clarify why the fastest EMA (ema1) is generally preferred for price-momentum confirmation, and why using ema2 or ema3 is less common for that.
Quick recap of your EMAs (typical example):
ema1: Fast EMA (e.g., 20)
ema2: Medium EMA (e.g., 50)
ema3: Slow EMA (e.g., 100 or 200)
Why use price vs ema1 (fast EMA) for momentum?
Fast EMA reacts quickest to price changes and reflects the short-term trend/momentum.
Since momentum is about the immediate strength or weakness in price action, comparing price to the fast EMA gives you timely signals.
If the price is above the fast EMA, it usually means bullish momentum is present now.
Conversely, price below fast EMA indicates bearish momentum.
Why not use price vs ema2 or ema3 (medium or slow EMAs)?
Medium and slow EMAs are less responsive—they smooth out price over longer periods.
Price can be above ema1 but still below ema2 or ema3 during early trend shifts or pullbacks.
Using price vs medium or slow EMAs for momentum means:
Momentum signals come late—you may miss early momentum shifts.
You may stay in losing trades longer by waiting for price to cross slow EMA.
Slow EMAs are great for defining overall trend context, not short-term momentum.
Example behavior of price relative to EMAs:
Scenario
Price vs EMAs
Interpretation
Price > ema1 only
Early momentum shift bullish
Good time to consider bullish bias
Price > ema1 & ema2
Medium-term trend strength
Momentum confirmed over longer period
Price > ema1, ema2 & ema3
Strong long-term uptrend
Very strong bullish signal
How this fits in your bias definitions:
Use EMA order (e.g., ema1 > ema2 > ema3) to confirm trend structure (direction over different time horizons).
Use price vs ema1 to confirm momentum, that is, are we currently gaining strength or weakening.
Summary recommendation:
// Bounce if price moments confirms
bullishMomentum = close > ema1 // price above fast EMA = strong short-term momentum
bearishMomentum = close < ema1 // price below fast EMA = strong short-term momentum negative
// Trend direction for higher context
emaTrendBullish = (ema1 > ema2) and (ema2 > ema3)
emaTrendBearish = (ema1 < ema2) and (ema2 < ema3)
// Combine both for Bias
bullishBias = emaTrendBullish and bullishMomentum
bearishBias = emaTrendBearish and bearishMomentum
This gives you fast bias flips with better reliability than just EMA order alone.
If you tried price vs medium or slow EMA for momentum, you’ll likely see bias flip very late, missing short-term momentum swings needed for entries or exits.
Optional: Using price vs ema2 or ema3 as additional filters
You can add conditions like "only take bullish bias if price is also above ema2 or ema3" to enforce filtering against false signals.
Example:
strictBullishBias = bullishBias and close > ema2
strictBearishBias = bearishBias and close < ema2
This makes bias less noisy but at the cost of slower reaction.
TL;DR:
For momentum, use price vs fastest EMA (ema1).
For trend structure, use EMA order (ema1 vs ema2 vs ema3).
Using price vs ema2 or ema3 for momentum causes lag and slower signals unsuitable for timely entries.
Let me know if you want a working script sample showing these principles!
Thanks for letting me know you trade Liquidity Sweeps — this is important because liquidity sweeps are typically fast, reactive price events meant to hunt stops or shakeout traders before a reversal or continuation.
How does your EMA bias/momentum logic tie into trading liquidity sweeps?
1. Liquidity sweeps usually happen on shorter timeframes and require fast reaction
Price often spikes above resistance or below support to trigger stop losses.
Speed and momentum of price are crucial to spot and confirm these sweeps.
2. Why EMA bias with price vs fast EMA is critical for liquidity sweeps:
Comparing price to the fastest EMA (ema1) gives you quick insight whether price momentum quickly favors buyers or sellers.
For example:
Price sweeps above liquidity highs + price > fast EMA + EMAs stacked bullish → strong confirmation that sweep led to continuation of uptrend.
Price sweeps below liquidity lows + price < fast EMA + EMAs stacked bearish → strong sell signal.
Using slow EMA or just EMA order alone is too lagging and reactive for fast liquidity events.
3. Suggested EMA bias approach for liquidity sweep trades
Use fast EMA (e.g., 9 or 20) for momentum check; keep medium and slow EMAs for overall trend context.
Combine with liquidity sweep detection:
Confirm that price actually swept liquidity zones (breaks above/below recent highs/lows).
Confirm momentum via price vs fast EMA and EMA order trend.
4. Example decision rules integrating liquidity sweeps and EMA bias:
// EMA calculations (choose lengths appropriate to your trading timeframe, e.g. fast=9, med=20, slow=50)
fastEMA = ta.ema(close, 9)
medEMA = ta.ema(close, 20)
slowEMA = ta.ema(close, 50)
// EMA order for trend
emaBullish = (fastEMA > medEMA) and (medEMA > slowEMA)
emaBearish = (fastEMA < medEMA) and (medEMA < slowEMA)
// Price momentum
priceAboveFastEMA = close > fastEMA
priceBelowFastEMA = close < fastEMA
// Liquidity Sweep detection (simplified example)
// Define liquidity high/low zones by recent pivots/highs/lows or custom logic
liquidityHigh = ta.pivothigh(high, 5, 5)
liquidityLow = ta.pivotlow(low, 5, 5)
// Sweep Condition - price breaks above liquidityHigh or below liquidityLow
bullSweep = not na(liquidityHigh) and high > liquidityHigh
bearSweep = not na(liquidityLow) and low < liquidityLow
// Confirm sweep with EMA bias and price momentum
strongBullSweep = bullSweep and emaBullish and priceAboveFastEMA
strongBearSweep = bearSweep and emaBearish and priceBelowFastEMA
// Plot or alert
plotshape(strongBullSweep, location=location.abovebar, color=color.green, style=shape.labelup, title="Bullish Sweep")
plotshape(strongBearSweep, location=location.belowbar, color=color.red, style=shape.labeldown, title="Bearish Sweep")
5. Tips for using EMA bias with liquidity sweeps:
Use faster EMA lengths, like 9 or 10, to detect momentum on lower timeframes common to liquidity sweeps.
Confirm liquidity sweeps with price breaking key levels + EMA bias to filter false moves.
Consider conjunction with volume spikes or VWAP confirmation for better accuracy.
6. Summary for trading liquidity sweeps with EMA bias:
Requirement
Recommendation
Detect momentum quickly
Use price vs fast EMA (9 or 20)
Confirm trend context
Use EMA order (fast > med > slow)
Confirm liquidity zones
Detect pivots or manual liquidity high/low breakouts
Combine sweeps + EMA bias
Only act if sweep + momentum/aligned trend confirmed
If you want, I can help write a full Pine Script snippet specialized for liquidity sweep detection integrated with EMA bias signals tailored to your timeframe. Just say the word!
Here's a complete Pine Script v6 example combining liquidity sweep detection with EMA bias tailored for lower timeframes (like M1, M5, M15). It uses fast/medium/slow EMAs, price vs fast EMA for momentum, and detects liquidity sweeps via recent pivots.
You can customize EMA lengths and sweep pivot lookback lengths as needed.
//@version=6
indicator("Liquidity Sweeps + EMA Bias [Custom]", overlay=true, max_lines_count=500)
// ==== INPUTS ====
// EMA lengths suitable for intraday liquidity sweep trading
fastEMALength = input.int(9, "Fast EMA Length", minval=1)
medEMALength = input.int(20, "Medium EMA Length", minval=1)
slowEMALength = input.int(50, "Slow EMA Length", minval=1)
// Liquidity pivot sensitivity (how far lookback for pivots)
pivotLen = input.int(5, "Liquidity Pivot Length", minval=1)
// ==== EMA CALCULATIONS ====
emaFast = ta.ema(close, fastEMALength)
emaMed = ta.ema(close, medEMALength)
emaSlow = ta.ema(close, slowEMALength)
// ==== EMA ORDER (Trend) ====
emaBullish = (emaFast > emaMed) and (emaMed > emaSlow)
emaBearish = (emaFast < emaMed) and (emaMed < emaSlow)
// ==== MOMENTUM (Price vs Fast EMA) ====
momentumBullish = close > emaFast
momentumBearish = close < emaFast
// ==== LIQUIDITY SWEEP DETECTION ====
// Recent pivot high and low as liquidity zones
liqHigh = ta.pivothigh(high, pivotLen, pivotLen)
liqLow = ta.pivotlow(low, pivotLen, pivotLen)
// Detect bullish sweep: price breaks above liquidity high
bullSweep = not na(liqHigh) and (high > liqHigh)
// Detect bearish sweep: price breaks below liquidity low
bearSweep = not na(liqLow) and (low < liqLow)
// ==== COMBINED STRONG SWEEP SIGNALS ====
strongBullSweep = bullSweep and emaBullish and momentumBullish
strongBearSweep = bearSweep and emaBearish and momentumBearish
// ==== PLOT EMA LINES ====
plot(emaFast, color=color.new(color.green, 0), title="Fast EMA (Momentum)")
plot(emaMed, color=color.new(color.blue, 0), title="Medium EMA")
plot(emaSlow, color=color.new(color.red, 0), title="Slow EMA")
// ==== PLOT SWEEP MARKERS ====
plotshape(strongBullSweep, title="Strong Bull Sweep", location=location.abovebar, color=color.green, style=shape.labelup, size=size.small)
plotshape(strongBearSweep, title="Strong Bear Sweep", location=location.belowbar, color=color.red, style=shape.labeldown, size=size.small)
// ==== ALERT CONDITIONS ====
alertcondition(strongBullSweep, "Strong Bull Sweep", "Bullish liquidity sweep confirmed with EMA bias")
alertcondition(strongBearSweep, "Strong Bear Sweep", "Bearish liquidity sweep confirmed with EMA bias")
// ==== TABLE to show bias status ====
var table biasTable = table.new(position.top_right, 1, 3, border_width=1)
var string biasText = "Neutral"
if strongBullSweep
biasText := "Strong Bull Sweep"
else if strongBearSweep
biasText := "Strong Bear Sweep"
else if emaBullish and momentumBullish
biasText := "Bullish Momentum"
else if emaBearish and momentumBearish
biasText := "Bearish Momentum"
else if emaBullish
biasText := "Bullish Trend"
else if emaBearish
biasText := "Bearish Trend"
table.cell(biasTable, 0, 0, "EMA Bias Status: " + biasText, text_color=color.white, bgcolor=color.black, text_size=size.small)
// ==== END SCRIPT ====
How this script works:
Detects liquidity sweeps as price breaking above recent pivot highs (bullish) or below recent pivot lows (bearish) defined by pivotLen.
Confirms sweep with EMA bias:
EMA stacked bullish + price > fast EMA for strong bullish sweeps
EMA stacked bearish + price < fast EMA for strong bearish sweeps
Plots EMAs and marks confirmed sweeps on the chart.
Provides alert conditions for both bullish and bearish sweeps.
Shows a bias summary table on top right.
To use:
Apply script on your chart with M1, M5 or M15.
Adjust EMA lengths and pivot length in inputs to fit your preference/timeframe.
Watch liquidity sweep markers and bias table.
Use alert conditions for notifications on strong sweeps.
If you want me to help integrate this into your existing indicator with your FVGs, CISD or VWAP, just say!
Thanks for testing the script!
If you're seeing the EMAs and bias status but no liquidity pivot lines or sweep markers, the likely causes are:
Pivot length too large or no recent pivots found
Pivot values (liqHigh, liqLow) are na during current bars so no sweep triggers
3) Use extended pivot line for liquidity level and sweep
Since liqHigh and liqLow are single values at pivot bar, you want to treat these as lines extending forward to current bar to detect sweep.
Add persistent array or var line to hold liquidity lines:
var line liquidityHighLine = na
var line liquidityLowLine = na
// On pivot confirmation create/update liquidity lines
if not na(liqHigh)
if na(liquidityHighLine)
liquidityHighLine := line.new(bar_index - pivotLen, liqHigh, bar_index, liqHigh, xloc=xloc.bar_index, color=color.orange, style=line.style_solid, width=1)
else
line.set_xy1(liquidityHighLine, bar_index - pivotLen, liqHigh)
line.set_xy2(liquidityHighLine, bar_index, liqHigh)
if not na(liqLow)
if na(liquidityLowLine)
liquidityLowLine := line.new(bar_index - pivotLen, liqLow, bar_index, liqLow, xloc=xloc.bar_index, color=color.purple, style=line.style_solid, width=1)
else
line.set_xy1(liquidityLowLine, bar_index - pivotLen, liqLow)
line.set_xy2(liquidityLowLine, bar_index, liqLow)
// Then you detect sweep as price crossing above/below these lines
bullSweep = not na(liquidityHighLine) and high > line.get_price(liquidityHighLine, bar_index)
bearSweep = not na(liquidityLowLine) and low < line.get_price(liquidityLowLine, bar_index)
This will dynamically track liquidity lines and detect if price sweeps them.
4) Plot sweep markers on sweeps detected this bar
plotshape(bullSweep and emaBullish and momentumBullish, location=location.abovebar, color=color.green, style=shape.triangledown, title="Bull Sweep", size=size.small)
plotshape(bearSweep and emaBearish and momentumBearish, location=location.belowbar, color=color.red, style=shape.triangleup, title="Bear Sweep", size=size.small)
Full minimal example with pivot plotting and liquidity line tracking:
//@version=6
indicator("Liquidity Sweeps + EMA Bias Debug", overlay=true)
// Inputs
pivotLen = input.int(3, "Pivot Length", minval=1)
fastEMALen = input.int(9)
medEMALen = input.int(20)
slowEMALen = input.int(50)
// EMAs
emaFast = ta.ema(close, fastEMALen)
emaMed = ta.ema(close, medEMALen)
emaSlow = ta.ema(close, slowEMALen)
// EMA order and momentum
emaBullish = (emaFast > emaMed) and (emaMed > emaSlow)
emaBearish = (emaFast < emaMed) and (emaMed < emaSlow)
momentumBullish = close > emaFast
momentumBearish = close < emaFast
// Pivots
liqHigh = ta.pivothigh(high, pivotLen, pivotLen)
liqLow = ta.pivotlow(low, pivotLen, pivotLen)
// Pivot plots
plot(liqHigh, style=plot.style_circles, color=color.orange, title="Pivot High")
plot(liqLow, style=plot.style_circles, color=color.purple, title="Pivot Low")
// Variables for liquidity lines
var line liqHighLine = na
var line liqLowLine = na
if not na(liqHigh)
if na(liqHighLine)
liqHighLine := line.new(bar_index - pivotLen, liqHigh, bar_index, liqHigh, xloc=xloc.bar_index, color=color.orange, width=2)
else
line.set_xy1(liqHighLine, bar_index - pivotLen, liqHigh)
line.set_xy2(liqHighLine, bar_index, liqHigh)
if not na(liqLow)
if na(liqLowLine)
liqLowLine := line.new(bar_index - pivotLen, liqLow, bar_index, liqLow, xloc=xloc.bar_index, color=color.purple, width=2)
else
line.set_xy1(liqLowLine, bar_index - pivotLen, liqLow)
line.set_xy2(liqLowLine, bar_index, liqLow)
// Calculate sweep by checking price crossing liquidity lines
bullSweep = not na(liqHighLine) and (high > line.get_price(liqHighLine, bar_index))
bearSweep = not na(liqLowLine) and (low < line.get_price(liqLowLine, bar_index))
// Confirm with EMA bias and momentum
strongBullSweep = bullSweep and emaBullish and momentumBullish
strongBearSweep = bearSweep and emaBearish and momentumBearish
// Sweep markers
plotshape(strongBullSweep, location=location.abovebar, color=color.green, style=shape.triangledown, title="Bull Sweep")
plotshape(strongBearSweep, location=location.belowbar, color=color.red, style=shape.triangleup, title="Bear Sweep")
// Plot EMAs
plot(emaFast, color=color.green)
plot(emaMed, color=color.blue)
plot(emaSlow, color=color.red)
Summary:
You must track liquidity lines as horizontal lines from pivot highs/lows, extending to current bar.
Then detect sweep when price breaks above (bull sweep) or below (bear sweep) those lines.
Your previous detection method checked break vs single pivot value at pivot bar, so no sweeps triggered.
Adding this dynamic line tracking fixes the detection.
Try this debug script — you will see liquidity pivot points and liquidity lines dynamically extend, with sweep markers appearing on valid breaks combined with your EMA bias.
Let me know if you want help adapting to your original full script!