Pullback with key Levels

piyacham · study · 693 行 · 点赞 46 · TradingView 原页

本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。

Pine Script

// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org
// © LuxAlgo (Trend Grading Dashboard, modified) + Supply and Demand Zones — merged
// Merged indicator: Trend Grading Dashboard V4.0 + Supply and Demand Zones + White Box Trader / Yesterday Levels (optional)
 
//@version=6
indicator("Pullback with key Levels", shorttitle = "Pullback with key Levels", overlay = true, max_boxes_count = 500, max_lines_count = 500, max_labels_count = 500)
 
// =========================================================================
// ===================  SECTION 1: TREND GRADING DASHBOARD  ==============
// =========================================================================
 
// --- Constants ---
string GRP_EMA  = "EMA Settings"
string GRP_DASH = "Dashboard Settings"
 
// --- Inputs ---
int emaLen1 = input.int(14, "EMA 1 Length", minval = 1, group = GRP_EMA, tooltip = "Length for the fast EMA")
int emaLen2 = input.int(60, "EMA 2 Length", minval = 1, group = GRP_EMA, tooltip = "Length for the slow EMA")
 
enableSignalSetting = input.bool(false, title="Enable Signal Buy/Sell when momentum shift", group = GRP_EMA)
bullSignal  = input.color(color.white, "Bullish Cross Color", tooltip = "Candle color when price crosses above EMA 14", group = GRP_EMA)
bearSignal  = input.color(color.white, "Bearish Cross Color", tooltip = "Candle color when price crosses below EMA 14", group = GRP_EMA)
 
color bullColor = input.color(#089981, "Bullish Color", group = GRP_EMA)
color bearColor = input.color(#f23645, "Bearish Color", group = GRP_EMA)
 
showDash    = input.bool(true, "Show Dashboard Table", group = GRP_DASH, tooltip = "Turn off to highly speed up Backtesting")
string tablePos    = input.string("top_right", "Dashboard Position", options = ["top_right", "bottom_right", "top_left", "bottom_left"], group = GRP_DASH)
color  textColorDash = input.color(color.white, "Text Color", group = GRP_DASH)
color  headerColor = input.color(color.gray, "Header Color", group = GRP_DASH)
 
// --- Types ---
type MarketState
    float e1
    float e2
    float price
 
// --- Calculations ---
ema14 = ta.ema(close, emaLen1)
ema60 = ta.ema(close, emaLen2)
 
priceCrossUp   = ta.crossover(close, ema14)
priceCrossDown = ta.crossunder(close, ema14)
emaCrossUp     = ema14 > ema60
 
getState() =>
    MarketState.new(ta.ema(close, emaLen1), ta.ema(close, emaLen2), close)
 
// Fetching data for multiple timeframes (only loads when dashboard is enabled)
m1  = showDash ? request.security(syminfo.tickerid, "1", getState()) : na
m3  = showDash ? request.security(syminfo.tickerid, "3", getState()) : na
m5  = showDash ? request.security(syminfo.tickerid, "5", getState()) : na
h1  = showDash ? request.security(syminfo.tickerid, "60", getState()) : na
h4  = showDash ? request.security(syminfo.tickerid, "240", getState()) : na
d1  = showDash ? request.security(syminfo.tickerid, "D", getState()) : na
 
// --- Logic Function ---
getTrendAndGrade(MarketState state) =>
    string trend = "N/A"
    string grade = "N/A"
    color  c     = color.gray
 
    if not na(state) and not na(state.e1) and not na(state.e2)
        bool isBuy = state.e1 > state.e2
        trend := isBuy ? "BUY" : "SELL"
        c     := isBuy ? bullColor : bearColor
 
        if isBuy
            grade := state.price > state.e1 ? "A" : (state.price > state.e2 ? "B" : "C")
        else
            grade := state.price < state.e1 ? "A" : (state.price < state.e2 ? "B" : "C")
 
    [trend, grade, c]
 
// Helper to fill row
fillRow(table dash, int row, string tfName, MarketState m, color txt) =>
    [t, g, c] = getTrendAndGrade(m)
    table.cell(dash, 0, row, tfName, text_color = txt)
    table.cell(dash, 1, row, t, bgcolor = c, text_color = color.white)
    table.cell(dash, 2, row, g, text_color = txt)
 
// --- Plotting ---
p1 = plot(ema14, "EMA 14", color = emaCrossUp ? bullColor : bearColor, linewidth = 2)
p2 = plot(ema60, "EMA 60", color = color.gray, linewidth = 1)
 
fill(p1, p2, ema14 > ema60 ? color.new(bullColor, 80) : color.new(bearColor, 80), "EMA Cross Shading")
 
barcolor(priceCrossUp ? bullSignal : priceCrossDown ? bearSignal : na, title = "Price Cross EMA 14")
 
// Dashboard table
var table dash = table.new(tablePos, 3, 7, frame_color = color.gray, frame_width = 1, border_color = color.gray, border_width = 1)
 
if barstate.islast and showDash
    table.cell(dash, 0, 0, "TF", bgcolor = headerColor, text_color = textColorDash)
    table.cell(dash, 1, 0, "Trend", bgcolor = headerColor, text_color = textColorDash)
    table.cell(dash, 2, 0, "Grade", bgcolor = headerColor, text_color = textColorDash)
 
    fillRow(dash, 1, "M1", m1, textColorDash)
    fillRow(dash, 2, "M3", m3, textColorDash)
    fillRow(dash, 3, "M5", m5, textColorDash)
    fillRow(dash, 4, "H1", h1, textColorDash)
    fillRow(dash, 5, "H4", h4, textColorDash)
    fillRow(dash, 6, "D1", d1, textColorDash)
 
// --- Alerts ---
alertcondition(priceCrossUp, title="Buy Alert", message="Price crossed above EMA 14 (Bullish Momentum)")
alertcondition(priceCrossDown, title="Sell Alert", message="Price crossed below EMA 14 (Bearish Momentum)")
 
if priceCrossUp
    alert("Price crossed above EMA 14 (Bullish Momentum)!", alert.freq_once_per_bar)
 
if priceCrossDown
    alert("Price crossed below EMA 14 (Bearish Momentum)!", alert.freq_once_per_bar)
 
buyCondition  = priceCrossUp and enableSignalSetting
sellCondition = priceCrossDown and enableSignalSetting
 
plotshape(series=buyCondition, title="Buy Signal", style=shape.triangleup, location=location.belowbar, color=color.green, size=size.small, text="BUY", textcolor=color.white)
plotshape(series=sellCondition, title="Sell Signal", style=shape.triangledown, location=location.abovebar, color=color.red, size=size.small, text="SELL", textcolor=color.white)
 
 
// =========================================================================
// ===================  SECTION 2: SUPPLY AND DEMAND ZONES  ==============
// =========================================================================
 
// --- Inputs ---
candleDifferenceScale = input.float(defval = 1.8, minval = 1, title = 'Zone Difference Scale', tooltip = 'The scale of how much a candle needs to be larger than a previous to be considered a zone. (candleChange / candleChange[1] > {value}, minimum value 1.0, default 1.8)', group = 'Zone Settings')
 
zoneOffset = input.int(defval = 15, minval = 0, title="Zone Extension", group = 'Display Settings', tooltip = 'How much to extend zones to the right of latest bar. (In bars)')
displayLowerTFZones = input.bool(false, title="Display Lower Timeframe Zones", group = 'Display Settings', tooltip = 'Whether to or not to display zones from a lower timeframe. ie. 2h zones on 4h timeframe (Recommended OFF).')
 
supplyEnable = input.bool(true, title = "Enable Supply Zones", group = "Zone Personalization")
supplyColor = input.color(defval = color.rgb(242, 54, 69, 70), title = 'Supply Background Color', group = 'Zone Personalization')
supplyBorderColor = input.color(defval = color.rgb(209, 212, 220, 90), title = 'Supply Border Color', group = 'Zone Personalization')
 
demandEnable = input.bool(true, title = "Enable Demand Zones", group = "Zone Personalization")
demandColor = input.color(defval = color.rgb(76, 175, 80, 70), title = 'Demand Background Color', group = 'Zone Personalization')
demandBorderColor = input.color(defval = color.rgb(209, 212, 220, 80), title = 'Demand Border Color', group = 'Zone Personalization')
 
textEnable = input.bool(true, title = "Display Text", group = 'Text Settings')
displayHL = input.bool(false, title="Display High/Low", group = 'Text Settings', tooltip = 'Whether to or not to display the tops and bottoms of a zone as text. ie. Top: 4000.00 Bottom: 3900.00.')
textColorSD = input.color(defval = color.rgb(255, 255, 255), title = 'Text Color', group = 'Text Settings')
textSizeInput = input.string("Small", title="Text Size", options=["Auto", "Tiny", "Small", "Normal", "Large", "Huge"], group = 'Text Settings')
halignInput = input.string("Right", title="Horizontal Alignment", options=["Left", "Center", "Right"], group = 'Text Settings')
supplyValignInput = input.string("Bottom", title="Vertical Alignment (Supply)", options=["Top", "Center", "Bottom"], group = 'Text Settings')
demandValignInput = input.string("Top", title="Vertical Alignment (Demand)", options=["Top", "Center", "Bottom"], group = 'Text Settings')
 
displayFormingZones = input.bool(false, title="Show Forming Zones", group = 'Timeframe Options', tooltip = 'Shows zones that could potentially form (unclosed candles)')
display30m = input.bool(false, title="Show 30m Zones", group = 'Timeframe Options')
display45m = input.bool(false, title="Show 45m Zones", group = 'Timeframe Options')
display1h = input.bool(true, title="Show 1h Zones", group = 'Timeframe Options')
display2h = input.bool(false, title="Show 2h Zones", group = 'Timeframe Options')
display3h = input.bool(false, title="Show 3h Zones", group = 'Timeframe Options')
display4h = input.bool(true, title="Show 4h Zones", group = 'Timeframe Options')
displayD = input.bool(false, title="Show Daily Zones", group = 'Timeframe Options')
displayW = input.bool(false, title="Show Weekly Zones", group = 'Timeframe Options')
 
// --- Variables ---
currentTimeframe = timeframe.period
 
if currentTimeframe == 'D'
    currentTimeframe := '1440'
if currentTimeframe == 'W'
    currentTimeframe := '10080'
if displayLowerTFZones
    currentTimeframe := '1'
 
momentCTD = math.round(time(timeframe.period) + (zoneOffset * 60000 * str.tonumber(currentTimeframe)))
 
var string textSize = size.small
if textSizeInput == 'Auto'
    textSize := size.auto
if textSizeInput == 'Tiny'
    textSize := size.tiny
if textSizeInput == 'Small'
    textSize := size.small
if textSizeInput == 'Normal'
    textSize := size.normal
if textSizeInput == 'Large'
    textSize := size.large
if textSizeInput == 'Huge'
    textSize := size.huge
 
var string halign = text.align_right
if halignInput == 'Left'
    halign := text.align_left
if halignInput == 'Center'
    halign := text.align_center
if halignInput == 'Right'
    halign := text.align_right
 
var string supplyValign = text.align_bottom
if supplyValignInput == 'Bottom'
    supplyValign := text.align_bottom
if supplyValignInput == 'Center'
    supplyValign := text.align_center
if supplyValignInput == 'Top'
    supplyValign := text.align_top
 
var string demandValign = text.align_top
if demandValignInput == 'Bottom'
    demandValign := text.align_bottom
if demandValignInput == 'Center'
    demandValign := text.align_center
if demandValignInput == 'Top'
    demandValign := text.align_top
 
var box[] supply_HT = array.new_box()
var box[] demand_HT = array.new_box()
 
// --- Plotting zones ---
createSupplyDemandZones(timeframe) =>
 
    [open_HT, high_HT, low_HT, close_HT] = request.security(syminfo.tickerid, timeframe, [open[1], high[1], low[1], close[1]], lookahead = barmerge.lookahead_on)
 
    var timeframeFormatted = ''
 
    if timeframe == '1'
        timeframeFormatted := '1m'
    else if timeframe == '3'
        timeframeFormatted := '3m'
    else if timeframe == '5'
        timeframeFormatted := '5m'
    else if timeframe == '15'
        timeframeFormatted := '15m'
    else if timeframe == '30'
        timeframeFormatted := '30m'
    else if timeframe == '45'
        timeframeFormatted := '45m'
    else if timeframe == '60'
        timeframeFormatted := '1h'
    else if timeframe == '120'
        timeframeFormatted := '2h'
    else if timeframe == '180'
        timeframeFormatted := '3h'
    else if timeframe == '240'
        timeframeFormatted := '4h'
    else if timeframe == 'D'
        timeframeFormatted := 'D'
    else if timeframe == 'W'
        timeframeFormatted := 'W'
 
    redCandle_HT = close_HT < open_HT
    greenCandle_HT = close_HT > open_HT
    neutralCandle_HT = close_HT == open_HT
    candleChange_HT = math.abs(close_HT - open_HT)
 
    var float bottomBox_HT = na
    var float topBox_HT = na
    momentCTD_HT = time(timeframe)[2]
 
    if (((redCandle_HT and greenCandle_HT[1]) or (redCandle_HT and neutralCandle_HT[1])) and (candleChange_HT / candleChange_HT[1]) >= candleDifferenceScale and (barstate.isconfirmed[1] or displayFormingZones) and supplyEnable and close_HT[1] >= close_HT and open_HT[1] <= open_HT)
        if displayFormingZones and barstate.isconfirmed[1] == false
            timeframeFormatted := timeframeFormatted + '(Forming)'
        if displayHL
            timeframeFormatted := timeframeFormatted + '\nTop: ' + str.tostring(topBox_HT) + '\nBottom: ' + str.tostring(open_HT[1])
 
        if high_HT >= high_HT[1]
            topBox_HT := high_HT
        else
            topBox_HT := high_HT[1]
 
        box supply = box.new(left=momentCTD_HT, top=topBox_HT, right=momentCTD, bgcolor=supplyColor, bottom=open_HT[1], xloc=xloc.bar_time)
        box.set_border_color(supply, supplyBorderColor)
        if textEnable
            box.set_text(supply, timeframeFormatted)
            box.set_text_size(supply, textSize)
            box.set_text_color(supply, textColorSD)
            box.set_text_halign(supply, halign)
            box.set_text_valign(supply, supplyValign)
        array.push(supply_HT, supply)
 
    if (((greenCandle_HT and redCandle_HT[1]) or (greenCandle_HT and neutralCandle_HT[1])) and (candleChange_HT / candleChange_HT[1]) >= candleDifferenceScale and (barstate.isconfirmed[1] or displayFormingZones) and demandEnable and close_HT[1] <= close_HT and open_HT[1] >= open_HT)
        if displayFormingZones and barstate.isconfirmed[1] == false
            timeframeFormatted := timeframeFormatted + ' (Forming)'
        if displayHL
            timeframeFormatted := timeframeFormatted + '\nTop: ' + str.tostring(open_HT[1]) + '\nBottom: ' + str.tostring(bottomBox_HT)
 
        if low_HT <= low_HT[1]
            bottomBox_HT := low_HT
        else
            bottomBox_HT := low_HT[1]
 
        box demand = box.new(left=momentCTD_HT, top=open_HT[1], right=momentCTD, bottom=bottomBox_HT, bgcolor=demandColor, xloc=xloc.bar_time)
        box.set_border_color(demand, demandBorderColor)
        if textEnable
            box.set_text(demand, timeframeFormatted)
            box.set_text_size(demand, textSize)
            box.set_text_color(demand, textColorSD)
            box.set_text_halign(demand, halign)
            box.set_text_valign(demand, demandValign)
        array.push(demand_HT, demand)
 
// --- Initiation ---
if display30m and str.tonumber(currentTimeframe) <= 30
    createSupplyDemandZones('30')
if display45m and str.tonumber(currentTimeframe) <= 45
    createSupplyDemandZones('45')
if display1h and str.tonumber(currentTimeframe) <= 60
    createSupplyDemandZones('60')
if display2h and str.tonumber(currentTimeframe) <= 120
    createSupplyDemandZones('120')
if display3h and str.tonumber(currentTimeframe) <= 180
    createSupplyDemandZones('180')
if display4h and str.tonumber(currentTimeframe) <= 240
    createSupplyDemandZones('240')
if displayD and str.tonumber(currentTimeframe) <= 1440
    createSupplyDemandZones('D')
if displayW and str.tonumber(currentTimeframe) <= 10080
    createSupplyDemandZones('W')
    // createSupplyDemandZones('M') // enabling this will break replay mode
 
// --- Remove broken supply zones ---
i = 0
while i < array.size(supply_HT) and array.size(supply_HT) > 0
    box currentBox = array.get(supply_HT, i)
    float breakLevel = box.get_top(currentBox)
    if high > breakLevel
        array.remove(supply_HT, i)
        box.delete(currentBox)
        int(na)
    else
        box.set_right(currentBox, momentCTD)
        i += 1
        int(na)
 
// --- Remove broken demand zones ---
i2 = 0
while i2 < array.size(demand_HT) and array.size(demand_HT) > 0
    box currentBox = array.get(demand_HT, i2)
    float breakLevel = box.get_bottom(currentBox)
    if low < breakLevel
        array.remove(demand_HT, i2)
        box.delete(currentBox)
        int(na)
    else
        box.set_right(currentBox, momentCTD)
        i2 += 1
        int(na)
 
 
// =========================================================================
// =========  SECTION 3: WHITE BOX TRADER + YESTERDAY LEVELS (OPTIONAL)  =====
// =========================================================================
 
// --- Master switch ---
string GRP_PDH = "White Box + Yesterday Levels"
enablePdhModule = input.bool(false, "เปิดใช้งานโมดูลนี้ทั้งหมด (White Box + Yesterday Levels)", group = GRP_PDH, tooltip = "เปิด/ปิด Section 3 ทั้งหมด (กรอบขาว H1, เส้นแบ่งวัน, เส้นระดับราคาของเมื่อวาน)")
showWhiteBox    = input.bool(true, "แสดงกรอบขาว H1 (White Box)", group = GRP_PDH)
 
// --- Box settings ---
boxBorderColor  = input.color(color.white, title = "Box Border Color", group = "Box Settings")
boxBgColor      = input.color(color.white, title = "Box Fill Color", group = "Box Settings")
boxTransparency = input.int(90, title = "Box Fill Transparency (0-100)", minval = 0, maxval = 100, group = "Box Settings", display = display.none)
 
// --- Yesterday levels settings ---
showYestLevels = input.bool(true, title = "แสดงเส้นระดับราคาของเมื่อวาน (ทุกวัน)", group = "Yesterday Levels Settings", display = display.none)
yestWickColor  = input.color(color.yellow, title = "สีเส้นปลายไส้ (High/Low)", group = "Yesterday Levels Settings")
yestBodyColor  = input.color(color.orange, title = "สีเส้นเนื้อเทียน (Body High/Low)", group = "Yesterday Levels Settings")
yestStyleStr   = input.string("Solid", title = "ประเภทของเส้น", options = ["Solid", "Dashed", "Dotted"], group = "Yesterday Levels Settings", display = display.none)
yestLineWidth  = input.int(1, title = "ขนาดของเส้น (ความหนา)", minval = 1, maxval = 5, group = "Yesterday Levels Settings", display = display.none)
extendBars     = input.int(10, title = "ขยายเส้นวันล่าสุดไปด้านหน้า (จำนวนแท่ง)", minval = 0, group = "Yesterday Levels Settings", display = display.none)
resText        = input.string("แนวต้าน", title = "ข้อความเมื่อราคาอยู่ใต้เส้น", group = "Yesterday Levels Settings", display = display.none)
supText        = input.string("แนวรับ", title = "ข้อความเมื่อราคาอยู่เหนือเส้น", group = "Yesterday Levels Settings", display = display.none)
yestTextColor  = input.color(color.white, title = "สีข้อความปลายเส้น", group = "Yesterday Levels Settings")
pdhText        = input.string("Old Day High", title = "Old Day High", group = "Yesterday Levels Settings", display = display.none)
pdlText        = input.string("Old Day Low", title = "Old Day Low", group = "Yesterday Levels Settings", display = display.none)
 
boxOn  = enablePdhModule and showWhiteBox
yestOn = enablePdhModule and showYestLevels
 
// ฟังก์ชันแปลงตัวเลือกประเภทเส้น
f_getLineStyle(_style) =>
    switch _style
        "Solid"  => line.style_solid
        "Dashed" => line.style_dashed
        "Dotted" => line.style_dotted
        => line.style_solid
 
// ----------------------- WHITE BOX TRADER (H1 BOX SYSTEM) -----------------------
f_calcH1Boxes() =>
    isBullish = close > open
    isBearish = close < open
    bodyMax   = math.max(close, open)
    bodyMin   = math.min(close, open)
 
    // ชั่วโมงของแท่งเทียน (เวลาไทย)
    currentHour = hour(time, "UTC+7")
 
    // ช่วงเวลาที่อนุญาตให้หาแท่งเบรก (07:00 ถึง 03:00 ของวันถัดไป)
    isInTimeWindow = (currentHour >= 7 and currentHour <= 23) or (currentHour >= 0 and currentHour <= 3)
 
    // แท่ง 03:00 เป็นจุดสิ้นสุดการยืดกรอบของวัน
    isCutoffBar = (currentHour == 3)
 
    // ขึ้นวันใหม่
    isNewDay = ta.change(time("D")) != 0
 
    // เงื่อนไขแท่งเบรก แบบ 1 และ แบบ 2
    breakType1      = (isBullish and close[1] < open[1]) or (isBearish and close[1] > open[1])
    breakType2_Up   = isBullish and (close[1] > open[1]) and (bodyMax <= high[1])
    breakType2_Down = isBearish and (close[1] < open[1]) and (bodyMin >= low[1])
    breakType2      = breakType2_Up or breakType2_Down
    isBreakCandle   = breakType1 or breakType2
 
    var bool inCycle = false
    var float bTop   = na
    var float bBot   = na
    var int startT   = na
 
    // จบรอบ: เนื้อปิดหลุดกรอบ หรือ ถึงแท่ง 03:00 น.
    bool isCycleEnded = inCycle and (bodyMax > bTop or bodyMin < bBot or isCutoffBar)
 
    bool startNewBox = false
    bool endBox      = false
 
    if isNewDay
        inCycle := false
        endBox  := true
    else if isCycleEnded
        inCycle := false
        endBox  := true
    else if isBreakCandle and not inCycle and isInTimeWindow and not isCutoffBar
        bTop        := high
        bBot        := low
        startT      := time
        inCycle     := true
        startNewBox := true
 
    [startNewBox, endBox, startT, time, bTop, bBot, isCutoffBar]
 
// รองรับ M15 / M5 และให้ H1 ประมวลผลโดยตรง
[sec_Start, sec_End, sec_StartTime, sec_EndTime, sec_Top, sec_Bot, sec_Cutoff] = request.security(syminfo.tickerid, "60", f_calcH1Boxes(), gaps = barmerge.gaps_off)
[loc_Start, loc_End, loc_StartTime, loc_EndTime, loc_Top, loc_Bot, loc_Cutoff] = f_calcH1Boxes()
 
isH1 = timeframe.period == "60"
 
h1Start     = isH1 ? loc_Start     : sec_Start
h1End       = isH1 ? loc_End       : sec_End
h1StartTime = isH1 ? loc_StartTime : sec_StartTime
h1Top       = isH1 ? loc_Top       : sec_Top
h1Bot       = isH1 ? loc_Bot       : sec_Bot
 
// --- วาด Box และเส้นแบ่งวัน ---
var box whiteBox = na
var bool isBoxActive = false
 
bool isH1TimeChanged = ta.change(h1StartTime) != 0
bool isNewDayChart   = ta.change(time("D")) != 0
 
// เมื่อเกิดกรอบใหม่ของ H1
if boxOn and h1Start and isH1TimeChanged
    whiteBox := box.new(
         left         = h1StartTime,
         top          = h1Top,
         right        = time,
         bottom       = h1Bot,
         xloc         = xloc.bar_time,
         border_color = boxBorderColor,
         border_width = 1,
         bgcolor      = color.new(boxBgColor, boxTransparency)
     )
    isBoxActive := true
 
// ขยายกรอบไปทางขวาจนจบรอบ
if boxOn and isBoxActive and not na(whiteBox)
    box.set_right(whiteBox, time)
    if h1End
        isBoxActive := false
 
// เส้นแนวตั้งแบ่งวันใหม่
if enablePdhModule and isNewDayChart
    line.new(
         x1     = time,
         y1     = low,
         x2     = time,
         y2     = high,
         xloc   = xloc.bar_time,
         extend = extend.both,
         color  = color.new(color.gray, 60),
         style  = line.style_dashed,
         width  = 1
     )
 
// ----------------------- YESTERDAY LEVELS -----------------------
f_calcYesterday() =>
    _h  = high[1]
    _l  = low[1]
    _bh = math.max(open[1], close[1])
    _bl = math.min(open[1], close[1])
    [_h, _l, _bh, _bl]
 
[yestHigh, yestLow, yestBodyHigh, yestBodyLow] = request.security(syminfo.tickerid, "D", f_calcYesterday(), gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_on)
 
// เวลาล่วงหน้าสำหรับยืดเส้นในวันล่าสุด
barTimeDiff = ta.change(time)
var int timeStep = na
if not na(barTimeDiff)
    timeStep := barTimeDiff
int futureTime = time + (nz(timeStep, 60000) * extendBars)
 
var line l_yestHigh   = na
var line l_yestLow    = na
var line l_yestBodyHi = na
var line l_yestBodyLo = na
 
// ขึ้นวันใหม่ → วาดเส้น 4 เส้นใหม่
if yestOn and isNewDayChart
    lineStyleChoice = f_getLineStyle(yestStyleStr)
 
    l_yestHigh   := line.new(x1 = time, y1 = yestHigh,     x2 = time, y2 = yestHigh,     xloc = xloc.bar_time, color = yestWickColor, style = lineStyleChoice, width = yestLineWidth)
    l_yestBodyHi := line.new(x1 = time, y1 = yestBodyHigh, x2 = time, y2 = yestBodyHigh, xloc = xloc.bar_time, color = yestBodyColor, style = lineStyleChoice, width = yestLineWidth)
    l_yestBodyLo := line.new(x1 = time, y1 = yestBodyLow,  x2 = time, y2 = yestBodyLow,  xloc = xloc.bar_time, color = yestBodyColor, style = lineStyleChoice, width = yestLineWidth)
    l_yestLow    := line.new(x1 = time, y1 = yestLow,      x2 = time, y2 = yestLow,      xloc = xloc.bar_time, color = yestWickColor, style = lineStyleChoice, width = yestLineWidth)
 
// ยืดเส้นไปทางขวา (แท่งสุดท้ายยืดไปข้างหน้าตาม extendBars)
if yestOn and not na(l_yestHigh)
    targetTime = barstate.islast ? futureTime : time
 
    line.set_x2(l_yestHigh,   targetTime)
    line.set_x2(l_yestBodyHi, targetTime)
    line.set_x2(l_yestBodyLo, targetTime)
    line.set_x2(l_yestLow,    targetTime)
 
// --- Label แนวรับ/แนวต้าน ตามราคาปัจจุบัน ---
var label lbl_yestHigh   = na
var label lbl_yestLow    = na
var label lbl_yestBodyHi = na
var label lbl_yestBodyLo = na
 
if yestOn and barstate.islast
    transBg = color.new(color.white, 100)
 
    txt_High   = pdhText
    txt_BodyHi = close > yestBodyHigh ? supText : resText
    txt_BodyLo = close > yestBodyLow  ? supText : resText
    txt_Low    = pdlText
 
    if na(lbl_yestHigh)
        lbl_yestHigh   := label.new(x = futureTime, y = yestHigh,     text = txt_High,   xloc = xloc.bar_time, textcolor = yestTextColor, color = transBg, style = label.style_label_left, size = size.normal)
        lbl_yestBodyHi := label.new(x = futureTime, y = yestBodyHigh, text = txt_BodyHi, xloc = xloc.bar_time, textcolor = yestTextColor, color = transBg, style = label.style_label_left, size = size.normal)
        lbl_yestBodyLo := label.new(x = futureTime, y = yestBodyLow,  text = txt_BodyLo, xloc = xloc.bar_time, textcolor = yestTextColor, color = transBg, style = label.style_label_left, size = size.normal)
        lbl_yestLow    := label.new(x = futureTime, y = yestLow,      text = txt_Low,    xloc = xloc.bar_time, textcolor = yestTextColor, color = transBg, style = label.style_label_left, size = size.normal)
    else
        label.set_xy(lbl_yestHigh,   futureTime, yestHigh)
        label.set_text(lbl_yestHigh, txt_High)
 
        label.set_xy(lbl_yestBodyHi, futureTime, yestBodyHigh)
        label.set_text(lbl_yestBodyHi, txt_BodyHi)
 
        label.set_xy(lbl_yestBodyLo, futureTime, yestBodyLow)
        label.set_text(lbl_yestBodyLo, txt_BodyLo)
 
        label.set_xy(lbl_yestLow,    futureTime, yestLow)
        label.set_text(lbl_yestLow,  txt_Low)
 
 
// =========================================================================
// ======  SECTION 3B: SWEEP & REJECT ALERTS (Old High / Old Low)  =========
// =========================================================================
// เงื่อนไข: ราคา sweep Old High (high > Old High) แล้วมีแท่งเทียนของ TF ที่เลือก "ปิดจบ" ใต้ Old High
//           ราคา sweep Old Low  (low  < Old Low ) แล้วมีแท่งเทียนของ TF ที่เลือก "ปิดจบ" เหนือ Old Low
// (ต้องเปิดโมดูล White Box + Yesterday Levels ด้านบนก่อน)
 
string GRP_SWEEP = "Sweep Alerts (Old High / Old Low)"
enableSweepAlert = input.bool(true, "เปิดใช้งาน Sweep Alert", group = GRP_SWEEP, tooltip = "ต้องเปิดโมดูล White Box + Yesterday Levels ด้วย")
sweepTf5         = input.bool(false, "ดูแท่งปิดจบของ M5",  group = GRP_SWEEP)
sweepTf15        = input.bool(true,  "ดูแท่งปิดจบของ M15", group = GRP_SWEEP)
sweepTf30        = input.bool(false, "ดูแท่งปิดจบของ M30", group = GRP_SWEEP)
sweepTf60        = input.bool(false, "ดูแท่งปิดจบของ H1",  group = GRP_SWEEP)
showSweepMarks   = input.bool(true, "แสดงสัญลักษณ์บนกราฟ", group = GRP_SWEEP)
showOnlyToday   = input.bool(true, "แสดงสัญลักษณ์เฉพาะวันปัจจุบัน", group = GRP_SWEEP, tooltip = "เปิด: เมื่อขึ้นวันใหม่ สัญลักษณ์ของวันก่อนจะถูกลบ เหลือเฉพาะวันปัจจุบัน (ใน Bar Replay จะเป็นวันที่ replay อยู่)")
sweepBearColor   = input.color(color.red,  "สีสัญญาณ Sweep Old High", group = GRP_SWEEP)
sweepBullColor   = input.color(color.lime, "สีสัญญาณ Sweep Old Low",  group = GRP_SWEEP)
 
// คำนวณใน TF ที่เลือก: ติดตามสถานะ sweep ของ High/Low เมื่อวาน แล้วนับครั้งที่แท่งปิดกลับ
f_sweepState() =>
    bool newDay = ta.change(time("D")) != 0
    var float dayHi = na
    var float dayLo = na
    var float pHi   = na
    var float pLo   = na
    var bool sweptHi = false
    var bool sweptLo = false
    var int bearCnt  = 0
    var int bullCnt  = 0
 
    if newDay
        pHi := dayHi
        pLo := dayLo
        dayHi := high
        dayLo := low
        sweptHi := false
        sweptLo := false
    else
        dayHi := na(dayHi) ? high : math.max(dayHi, high)
        dayLo := na(dayLo) ? low  : math.min(dayLo, low)
 
    if not na(pHi) and not na(pLo)
        if high > pHi
            sweptHi := true
        if low < pLo
            sweptLo := true
 
    // ตัดสินเฉพาะแท่งที่ปิดจบแล้ว
    if barstate.isconfirmed
        if sweptHi and close < pHi
            bearCnt += 1
            sweptHi := false
        if sweptLo and close > pLo
            bullCnt += 1
            sweptLo := false
 
    [bearCnt, bullCnt]
 
[bear5,  bull5]  = request.security(syminfo.tickerid, "5",  f_sweepState(), gaps = barmerge.gaps_off)
[bear15, bull15] = request.security(syminfo.tickerid, "15", f_sweepState(), gaps = barmerge.gaps_off)
[bear30, bull30] = request.security(syminfo.tickerid, "30", f_sweepState(), gaps = barmerge.gaps_off)
[bear60, bull60] = request.security(syminfo.tickerid, "60", f_sweepState(), gaps = barmerge.gaps_off)
 
// ตรวจว่าตัวนับเพิ่มขึ้น "ในจังหวะนี้" (varip เพื่อไม่ให้ alert ซ้ำในแท่งเดียวกัน)
f_newEvt(int cnt) =>
    varip int lastCnt = na
    bool evt = false
    if not na(cnt)
        evt := not na(lastCnt) and cnt > lastCnt
        lastCnt := cnt
    evt
 
bool evB5  = f_newEvt(bear5)
bool evB15 = f_newEvt(bear15)
bool evB30 = f_newEvt(bear30)
bool evB60 = f_newEvt(bear60)
bool evL5  = f_newEvt(bull5)
bool evL15 = f_newEvt(bull15)
bool evL30 = f_newEvt(bull30)
bool evL60 = f_newEvt(bull60)
 
// สำหรับสัญลักษณ์บนกราฟ / alertcondition (คงอยู่ตลอดแท่งบนกราฟ)
bool chB5  = ta.change(bear5)  > 0
bool chB15 = ta.change(bear15) > 0
bool chB30 = ta.change(bear30) > 0
bool chB60 = ta.change(bear60) > 0
bool chL5  = ta.change(bull5)  > 0
bool chL15 = ta.change(bull15) > 0
bool chL30 = ta.change(bull30) > 0
bool chL60 = ta.change(bull60) > 0
 
bool sweepOn = enablePdhModule and enableSweepAlert
bool bearSel = sweepOn and ((sweepTf5 and chB5) or (sweepTf15 and chB15) or (sweepTf30 and chB30) or (sweepTf60 and chB60))
bool bullSel = sweepOn and ((sweepTf5 and chL5) or (sweepTf15 and chL15) or (sweepTf30 and chL30) or (sweepTf60 and chL60))
 
// สัญลักษณ์บนกราฟ: ใช้ label เพื่อเคลียร์ของวันก่อนเมื่อขึ้นวันใหม่ได้
var array<label> sweepLbls = array.new<label>()
if showSweepMarks
    if showOnlyToday and isNewDayChart
        for lb in sweepLbls
            label.delete(lb)
        array.clear(sweepLbls)
    if bearSel
        array.push(sweepLbls, label.new(bar_index, high, "SELL\nSweep High", style = label.style_label_down, color = sweepBearColor, textcolor = color.white, size = size.small))
    if bullSel
        array.push(sweepLbls, label.new(bar_index, low, "BUY\nSweep Low", style = label.style_label_up, color = sweepBullColor, textcolor = color.black, size = size.small))
 
alertcondition(bearSel, title = "SELL: Sweep Old High + Close Below", message = "SELL | Sweep Old High แล้วแท่งปิดกลับใต้ Old High")
alertcondition(bullSel, title = "BUY: Sweep Old Low + Close Above", message = "BUY | Sweep Old Low แล้วแท่งปิดกลับเหนือ Old Low")
 
// alert() แบบระบุ TF ที่เกิดสัญญาณ (เลือก "Any alert() function call" ตอนตั้ง alert)
string tfsBear = ""
string tfsBull = ""
if sweepOn
    if sweepTf5 and evB5
        tfsBear += "M5 "
    if sweepTf15 and evB15
        tfsBear += "M15 "
    if sweepTf30 and evB30
        tfsBear += "M30 "
    if sweepTf60 and evB60
        tfsBear += "H1 "
    if sweepTf5 and evL5
        tfsBull += "M5 "
    if sweepTf15 and evL15
        tfsBull += "M15 "
    if sweepTf30 and evL30
        tfsBull += "M30 "
    if sweepTf60 and evL60
        tfsBull += "H1 "
 
if tfsBear != ""
    alert("SELL | " + syminfo.ticker + " | Sweep Old High แล้วปิดกลับใต้เส้น | TF: " + str.trim(tfsBear) + " | Old High = " + str.tostring(yestHigh, format.mintick), alert.freq_all)
 
if tfsBull != ""
    alert("BUY | " + syminfo.ticker + " | Sweep Old Low แล้วปิดกลับเหนือเส้น | TF: " + str.trim(tfsBull) + " | Old Low = " + str.tostring(yestLow, format.mintick), alert.freq_all)

← 返回列表