SMC + Dual UT Bot buy and sell Alerts

stephneguiroa · study · 620 行 · 点赞 653 · TradingView 原页

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

Pine Script

// This work is licensed under a Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0) https://creativecommons.org/licenses/by-nc-sa/4.0/
// © LuxAlgo
//
// MODIFICATION NOTICE:
// 1. Integrated "UT Bot Alerts".
// 2. Updated color theme to "Neon Cyberpunk".
// 3. Added "Pro" Style Badges & Dynamic TP/SL.
// 4. ADDED: Strategy Performance & Trend Dashboards.
// 5. ADDED: Multi-Timeframe (MTF) Scanner.
//
// This modified version is released under the same CC BY-NC-SA 4.0 license.
 
//@version=5
indicator('SMC + Dual UT Bot buy and sell Alerts', 'SMC + Dual UT Bot buy and sell Alerts', overlay = true, max_labels_count = 500, max_lines_count = 500, max_boxes_count = 500)
 
//---------------------------------------------------------------------------------------------------------------------}
// CONSTANTS & COLORS
//---------------------------------------------------------------------------------------------------------------------{
BULLISH_LEG                     = 1
BEARISH_LEG                     = 0
BULLISH                         = +1
BEARISH                         = -1
 
// NEON THEME
GREEN                           = #00E5FF  // Neon Cyan
RED                             = #FF2E63  // Neon Pink
BLUE                            = #FF9800  // Orange
GRAY                            = #90A4AE
TEXT_COLOR                      = color.white
BG_COLOR                        = color.new(color.black, 40)
 
// GROUPS
SMART_GROUP                     = 'Smart Money Concepts'
INTERNAL_GROUP                  = 'Real Time Internal Structure'
SWING_GROUP                     = 'Real Time Swing Structure'
BLOCKS_GROUP                    = 'Order Blocks'
EQUAL_GROUP                     = 'EQH/EQL'
GAPS_GROUP                      = 'Fair Value Gaps'
LEVELS_GROUP                    = 'Highs & Lows MTF'
ZONES_GROUP                     = 'Premium & Discount Zones'
UT_COMMON                       = 'UT Bot: Settings'
UT_MGMT                         = 'UT Bot: Trade Management'
DASH_GROUP                      = 'Dashboards'
 
//=====================================================================================================================
// >>> EMA 20 / EMA 50 / VWAP — AJOUT VISUEL UNIQUEMENT <<<
//=====================================================================================================================
EMA_VWAP_GROUP = "EMA 20 / EMA 50 & VWAP"
 
show_ema_vwap = input.bool(true, "Afficher EMA 20 / EMA 50 / VWAP", group = EMA_VWAP_GROUP)
 
ema_bull_color  = input.color(#00E5FF, "EMA Bullish", group = EMA_VWAP_GROUP)
ema_bear_color  = input.color(#FF2E63, "EMA Bearish", group = EMA_VWAP_GROUP)
ema_range_color = input.color(#90A4AE, "EMA Range", group = EMA_VWAP_GROUP)
vwap_color      = input.color(#FFD54F, "VWAP", group = EMA_VWAP_GROUP)
 
// Calculs
ema20 = ta.ema(close, 20)
ema50 = ta.ema(close, 50)
vwap_val = ta.vwap(hlc3)
 
// Coloration dynamique
ema_bull = ema20 > ema50 and close > ema50
ema_bear = ema20 < ema50 and close < ema50
 
ema_dyn_color =
     ema_bull ? ema_bull_color :
     ema_bear ? ema_bear_color :
     ema_range_color
 
// Plots
plot(show_ema_vwap ? ema20 : na, "EMA 20", color = ema_dyn_color, linewidth = 2)
plot(show_ema_vwap ? ema50 : na, "EMA 50", color = ema_dyn_color, linewidth = 2)
plot(show_ema_vwap ? vwap_val : na, "VWAP", color = vwap_color, linewidth = 2)
 
//---------------------------------------------------------------------------------------------------------------------}
// SMC INPUTS 
//---------------------------------------------------------------------------------------------------------------------{
modeInput                       = input.string( 'Historical', 'Mode', group = SMART_GROUP, options = ['Historical', 'Present'])
styleInput                      = input.string( 'Colored', 'Style', group = SMART_GROUP, options = ['Colored', 'Monochrome'])
showTrendInput                  = input(false, 'Color Candles', group = SMART_GROUP)
 
showInternalsInput              = input(true, 'Show Internal Structure', group = INTERNAL_GROUP)
showInternalBullInput           = input.string( 'All', 'Bullish Structure', group = INTERNAL_GROUP, options = ['All','BOS','CHoCH'])
internalBullColorInput          = input(#00E5FF, '', group = INTERNAL_GROUP, inline = 'ibull')
showInternalBearInput           = input.string( 'All', 'Bearish Structure' , group = INTERNAL_GROUP, options = ['All','BOS','CHoCH'])
internalBearColorInput          = input(#FF2E63, '', group = INTERNAL_GROUP, inline = 'ibear')
internalFilterConfluenceInput   = input(false, 'Confluence Filter', group = INTERNAL_GROUP)
internalStructureSize           = input.string( size.tiny, 'Internal Label Size', group = INTERNAL_GROUP, options = [size.tiny,size.small,size.normal])
 
showStructureInput              = input(true, 'Show Swing Structure', group = SWING_GROUP)
showSwingBullInput              = input.string( 'All', 'Bullish Structure', group = SWING_GROUP, inline = 'bull', options = ['All','BOS','CHoCH'])
swingBullColorInput             = input(#00E5FF, '', group = SWING_GROUP, inline = 'bull')
showSwingBearInput              = input.string( 'All', 'Bearish Structure', group = SWING_GROUP, inline = 'bear', options = ['All','BOS','CHoCH'])
swingBearColorInput             = input(#FF2E63, '', group = SWING_GROUP, inline = 'bear')
swingStructureSize              = input.string( size.small, 'Swing Label Size', group = SWING_GROUP, options = [size.tiny,size.small,size.normal])
showSwingsInput                 = input(false, 'Show Swings Points', group = SWING_GROUP, inline = 'swings')
swingsLengthInput               = input.int(50, '', group = SWING_GROUP, minval = 10, inline = 'swings')
showHighLowSwingsInput          = input(true, 'Show Strong/Weak High/Low', group = SWING_GROUP)
 
showInternalOrderBlocksInput    = input(true, 'Internal Order Blocks', group = BLOCKS_GROUP, inline = 'iob')
internalOrderBlocksSizeInput    = input.int(5, '', group = BLOCKS_GROUP, minval = 1, maxval = 20, inline = 'iob')
showSwingOrderBlocksInput       = input(false, 'Swing Order Blocks', group = BLOCKS_GROUP, inline = 'ob')
swingOrderBlocksSizeInput       = input.int(5, '', group = BLOCKS_GROUP, minval = 1, maxval = 20, inline = 'ob') 
orderBlockFilterInput           = input.string( 'Atr', 'Order Block Filter', group = BLOCKS_GROUP, options = ['Atr', 'Cumulative Mean Range'])
orderBlockMitigationInput       = input.string( 'High/Low', 'Order Block Mitigation', group = BLOCKS_GROUP, options = ['Close','High/Low'])
internalBullishOrderBlockColor  = input.color(color.new(#00B0FF, 80), 'Internal Bullish OB', group = BLOCKS_GROUP) 
internalBearishOrderBlockColor  = input.color(color.new(#FF4081, 80), 'Internal Bearish OB', group = BLOCKS_GROUP) 
swingBullishOrderBlockColor     = input.color(color.new(#2979FF, 80), 'Bullish OB', group = BLOCKS_GROUP) 
swingBearishOrderBlockColor     = input.color(color.new(#D500F9, 80), 'Bearish OB', group = BLOCKS_GROUP) 
 
showEqualHighsLowsInput         = input(true, 'Equal High/Low', group = EQUAL_GROUP)
equalHighsLowsLengthInput       = input.int(3, 'Bars Confirmation', group = EQUAL_GROUP, minval = 1)
equalHighsLowsThresholdInput    = input.float(0.1, 'Threshold', group = EQUAL_GROUP, minval = 0, maxval = 0.5, step = 0.1)
equalHighsLowsSizeInput         = input.string( size.tiny, 'Label Size', group = EQUAL_GROUP, options = [size.tiny,size.small,size.normal])
 
showFairValueGapsInput          = input(false, 'Fair Value Gaps', group = GAPS_GROUP)
fairValueGapsThresholdInput     = input(true, 'Auto Threshold', group = GAPS_GROUP)
fairValueGapsTimeframeInput     = input.timeframe('', 'Timeframe', group = GAPS_GROUP)
fairValueGapsBullColorInput     = input.color(color.new(#00E676, 70), 'Bullish FVG' , group = GAPS_GROUP) 
fairValueGapsBearColorInput     = input.color(color.new(#FF1744, 70), 'Bearish FVG' , group = GAPS_GROUP) 
fairValueGapsExtendInput        = input.int(1, 'Extend FVG', group = GAPS_GROUP, minval = 0)
 
showPremiumDiscountZonesInput   = input(false, 'Premium/Discount Zones', group = ZONES_GROUP)
premiumZoneColorInput           = input.color(#FF2E63, 'Premium Zone', group = ZONES_GROUP)
equilibriumZoneColorInput       = input.color(GRAY, 'Equilibrium Zone', group = ZONES_GROUP)
discountZoneColorInput          = input.color(#00E5FF, 'Discount Zone', group = ZONES_GROUP)
 
//---------------------------------------------------------------------------------------------------------------------}
// SMC LOGIC (Standard LuxAlgo Implementation)
//---------------------------------------------------------------------------------------------------------------------{
type alerts
    bool internalBullishBOS = false
    bool internalBearishBOS = false
    bool internalBullishCHoCH = false
    bool internalBearishCHoCH = false
    bool swingBullishBOS = false
    bool swingBearishBOS = false
    bool swingBullishCHoCH = false
    bool swingBearishCHoCH = false
    bool internalBullishOrderBlock = false
    bool internalBearishOrderBlock = false
    bool swingBullishOrderBlock = false
    bool swingBearishOrderBlock = false
    bool equalHighs = false
    bool equalLows = false
    bool bullishFairValueGap = false
    bool bearishFairValueGap = false
 
type pivot
    float currentLevel
    float lastLevel
    bool crossed
    int barTime = time
    int barIndex = bar_index
 
type orderBlock
    float barHigh
    float barLow
    int barTime
    int bias
 
type trend
    int bias    
 
type trailingExtremes
    float top
    float bottom
    int barTime
    int barIndex
    int lastTopTime
    int lastBottomTime
 
type fairValueGap
    float top
    float bottom
    int bias
    box topBox
    box bottomBox
    
var pivot swingHigh = pivot.new(na,na,false)
var pivot swingLow = pivot.new(na,na,false)
var pivot internalHigh = pivot.new(na,na,false)
var pivot internalLow = pivot.new(na,na,false)
var pivot equalHigh = pivot.new(na,na,false)
var pivot equalLow = pivot.new(na,na,false)
var trend swingTrend = trend.new(0)
var trend internalTrend = trend.new(0)
var trailingExtremes trailing = trailingExtremes.new()
var array<orderBlock> swingOrderBlocks = array.new<orderBlock>()
var array<orderBlock> internalOrderBlocks = array.new<orderBlock>()
var array<box> swingOrderBlocksBoxes = array.new<box>()
var array<box> internalOrderBlocksBoxes = array.new<box>()
var array<fairValueGap> fairValueGaps = array.new<fairValueGap>()
var array<float> parsedHighs = array.new<float>()
var array<float> parsedLows = array.new<float>()
var array<float> highs = array.new<float>()
var array<float> lows = array.new<float>()
var array<int> times = array.new<int>()
 
var swingBullishColor = swingBullColorInput
var swingBearishColor = swingBearColorInput
varip int currentBarIndex = bar_index
varip int lastBarIndex = bar_index
alerts currentAlerts = alerts.new()
var initialTime = time
 
if barstate.isfirst
    if showSwingOrderBlocksInput
        for index = 1 to swingOrderBlocksSizeInput
            swingOrderBlocksBoxes.push(box.new(na,na,na,na,xloc = xloc.bar_time,extend = extend.right))
    if showInternalOrderBlocksInput
        for index = 1 to internalOrderBlocksSizeInput
            internalOrderBlocksBoxes.push(box.new(na,na,na,na,xloc = xloc.bar_time,extend = extend.right))
 
bearishOrderBlockMitigationSource = orderBlockMitigationInput == 'Close' ? close : high
bullishOrderBlockMitigationSource = orderBlockMitigationInput == 'Close' ? close : low
atrMeasure = ta.atr(200)
volatilityMeasure = orderBlockFilterInput == 'Atr' ? atrMeasure : ta.cum(ta.tr)/bar_index
highVolatilityBar = (high - low) >= (2 * volatilityMeasure)
parsedHigh = highVolatilityBar ? low : high
parsedLow = highVolatilityBar ? high : low
 
parsedHighs.push(parsedHigh)
parsedLows.push(parsedLow)
highs.push(high)
lows.push(low)
times.push(time)
 
leg(int size) =>
    var leg = 0    
    newLegHigh = high[size] > ta.highest(size)
    newLegLow = low[size] < ta.lowest(size)
    if newLegHigh
        leg := 0
    else if newLegLow
        leg := 1
    leg
 
startOfNewLeg(int leg) => ta.change(leg) != 0
startOfBearishLeg(int leg) => ta.change(leg) == -1
startOfBullishLeg(int leg) => ta.change(leg) == +1
 
drawLabel(int labelTime, float labelPrice, string tag, color labelColor, string labelStyle) =>    
    var label l_abel = na
    if modeInput == 'Present'
        l_abel.delete()
    l_abel := label.new(chart.point.new(labelTime,na,labelPrice),tag,xloc.bar_time,color=color(na),textcolor=labelColor,style = labelStyle,size = size.small)
 
getCurrentStructure(int size,bool equalHighLow = false, bool internal = false) =>        
    currentLeg = leg(size)
    newPivot = startOfNewLeg(currentLeg)
    pivotLow = startOfBullishLeg(currentLeg)
    pivotHigh = startOfBearishLeg(currentLeg)
 
    if newPivot
        if pivotLow
            pivot p_ivot = equalHighLow ? equalLow : internal ? internalLow : swingLow    
            if equalHighLow and math.abs(p_ivot.currentLevel - low[size]) < equalHighsLowsThresholdInput * atrMeasure                
                currentAlerts.equalLows := true
            p_ivot.lastLevel := p_ivot.currentLevel
            p_ivot.currentLevel := low[size]
            p_ivot.crossed := false
            p_ivot.barTime := time[size]
            p_ivot.barIndex := bar_index[size]
            if not equalHighLow and not internal
                trailing.bottom := p_ivot.currentLevel
                trailing.barTime := p_ivot.barTime
                trailing.barIndex := p_ivot.barIndex
                trailing.lastBottomTime := p_ivot.barTime
        else
            pivot p_ivot = equalHighLow ? equalHigh : internal ? internalHigh : swingHigh
            if equalHighLow and math.abs(p_ivot.currentLevel - high[size]) < equalHighsLowsThresholdInput * atrMeasure
                currentAlerts.equalHighs := true               
            p_ivot.lastLevel := p_ivot.currentLevel
            p_ivot.currentLevel := high[size]
            p_ivot.crossed := false
            p_ivot.barTime := time[size]
            p_ivot.barIndex := bar_index[size]
            if not equalHighLow and not internal
                trailing.top := p_ivot.currentLevel
                trailing.barTime := p_ivot.barTime
                trailing.barIndex := p_ivot.barIndex
                trailing.lastTopTime := p_ivot.barTime
 
drawStructure(pivot p_ivot, string tag, color structureColor, string lineStyle, string labelStyle, string labelSize) =>    
    var line l_ine = line.new(na,na,na,na,xloc = xloc.bar_time)
    var label l_abel = label.new(na,na)
    if modeInput == 'Present'
        l_ine.delete()
        l_abel.delete()
    l_ine := line.new(chart.point.new(p_ivot.barTime,na,p_ivot.currentLevel), chart.point.new(time,na,p_ivot.currentLevel), xloc.bar_time, color=structureColor, style=lineStyle)
    l_abel := label.new(chart.point.new(na,math.round(0.5*(p_ivot.barIndex+bar_index)),p_ivot.currentLevel), tag, xloc.bar_index, color=color(na), textcolor=structureColor, style=labelStyle, size = labelSize)
 
storeOrdeBlock(pivot p_ivot,bool internal = false,int bias) =>
    if (not internal and showSwingOrderBlocksInput) or (internal and showInternalOrderBlocksInput)
        array<float> a_rray = na
        int parsedIndex = na
        if bias == BEARISH
            a_rray := parsedHighs.slice(p_ivot.barIndex,bar_index)
            parsedIndex := p_ivot.barIndex + a_rray.indexof(a_rray.max())  
        else
            a_rray := parsedLows.slice(p_ivot.barIndex,bar_index)
            parsedIndex := p_ivot.barIndex + a_rray.indexof(a_rray.min())                        
        orderBlock o_rderBlock = orderBlock.new(parsedHighs.get(parsedIndex), parsedLows.get(parsedIndex), times.get(parsedIndex),bias)
        array<orderBlock> orderBlocks = internal ? internalOrderBlocks : swingOrderBlocks
        if orderBlocks.size() >= 100
            orderBlocks.pop()
        orderBlocks.unshift(o_rderBlock)
 
drawOrderBlocks(bool internal = false) =>        
    array<orderBlock> orderBlocks = internal ? internalOrderBlocks : swingOrderBlocks
    orderBlocksSize = orderBlocks.size()
    if orderBlocksSize > 0        
        maxOrderBlocks = internal ? internalOrderBlocksSizeInput : swingOrderBlocksSizeInput
        array<orderBlock> parsedOrdeBlocks = orderBlocks.slice(0, math.min(maxOrderBlocks,orderBlocksSize))
        array<box> b_oxes = internal ? internalOrderBlocksBoxes : swingOrderBlocksBoxes        
        for [index,eachOrderBlock] in parsedOrdeBlocks
            orderBlockColor = internal ? (eachOrderBlock.bias == BEARISH ? internalBearishOrderBlockColor : internalBullishOrderBlockColor) : (eachOrderBlock.bias == BEARISH ? swingBearishOrderBlockColor : swingBullishOrderBlockColor)
            box b_ox = b_oxes.get(index)
            b_ox.set_top_left_point(chart.point.new(eachOrderBlock.barTime,na,eachOrderBlock.barHigh))
            b_ox.set_bottom_right_point(chart.point.new(last_bar_time,na,eachOrderBlock.barLow))        
            b_ox.set_border_color(internal ? na : orderBlockColor)
            b_ox.set_bgcolor(orderBlockColor)
 
displayStructure(bool internal = false) =>
    var bullishBar = true
    var bearishBar = true
    if internalFilterConfluenceInput
        bullishBar := high - math.max(close, open) > math.min(close, open - low)
        bearishBar := high - math.max(close, open) < math.min(close, open - low)
    pivot p_ivot = internal ? internalHigh : swingHigh
    trend t_rend = internal ? internalTrend : swingTrend
    lineStyle = internal ? line.style_dashed : line.style_solid
    labelSize = internal ? internalStructureSize : swingStructureSize
    extraCondition = internal ? internalHigh.currentLevel != swingHigh.currentLevel and bullishBar : true
    bullishColor = internal ? internalBullColorInput : swingBullColorInput
    if ta.crossover(close,p_ivot.currentLevel) and not p_ivot.crossed and extraCondition
        string tag = t_rend.bias == BEARISH ? 'CHoCH' : 'BOS'
        if internal
            currentAlerts.internalBullishCHoCH := tag == 'CHoCH'
            currentAlerts.internalBullishBOS := tag == 'BOS'
        else
            currentAlerts.swingBullishCHoCH := tag == 'CHoCH'
            currentAlerts.swingBullishBOS := tag == 'BOS'
        p_ivot.crossed := true
        t_rend.bias := BULLISH
        displayCondition = internal ? showInternalsInput : showStructureInput
        if displayCondition                        
            drawStructure(p_ivot,tag,bullishColor,lineStyle,label.style_label_down,labelSize)
        if (internal and showInternalOrderBlocksInput) or (not internal and showSwingOrderBlocksInput)
            storeOrdeBlock(p_ivot,internal,BULLISH)
    p_ivot := internal ? internalLow : swingLow    
    extraCondition := internal ? internalLow.currentLevel != swingLow.currentLevel and bearishBar : true
    bearishColor = internal ? internalBearColorInput : swingBearColorInput
    if ta.crossunder(close,p_ivot.currentLevel) and not p_ivot.crossed and extraCondition
        string tag = t_rend.bias == BULLISH ? 'CHoCH' : 'BOS'
        if internal
            currentAlerts.internalBearishCHoCH := tag == 'CHoCH'
            currentAlerts.internalBearishBOS := tag == 'BOS'
        else
            currentAlerts.swingBearishCHoCH := tag == 'CHoCH'
            currentAlerts.swingBearishBOS := tag == 'BOS'
        p_ivot.crossed := true
        t_rend.bias := BEARISH
        displayCondition = internal ? showInternalsInput : showStructureInput
        if displayCondition                        
            drawStructure(p_ivot,tag,bearishColor,lineStyle,label.style_label_up,labelSize)
        if (internal and showInternalOrderBlocksInput) or (not internal and showSwingOrderBlocksInput)
            storeOrdeBlock(p_ivot,internal,BEARISH)
 
updateTrailingExtremes() =>
    trailing.top := math.max(high,trailing.top)
    trailing.lastTopTime := trailing.top == high ? time : trailing.lastTopTime
    trailing.bottom := math.min(low,trailing.bottom)
    trailing.lastBottomTime := trailing.bottom == low ? time : trailing.lastBottomTime
 
// Execution of SMC
getCurrentStructure(swingsLengthInput,false)
getCurrentStructure(5,false,true)
if showEqualHighsLowsInput
    getCurrentStructure(equalHighsLowsLengthInput,true)
if showInternalsInput or showInternalOrderBlocksInput or showTrendInput
    displayStructure(true)
if showStructureInput or showSwingOrderBlocksInput or showHighLowSwingsInput
    displayStructure()
if showInternalOrderBlocksInput
    drawOrderBlocks(true)
if showSwingOrderBlocksInput
    drawOrderBlocks()
 
//---------------------------------------------------------------------------------------------------------------------}
// UT BOT + DASHBOARD INPUTS
//---------------------------------------------------------------------------------------------------------------------{
ut_h            = input.bool(false, title = "Heikin Ashi", group = UT_COMMON)
ut_src          = ut_h ? request.security(ticker.heikinashi(syminfo.tickerid), timeframe.period, close, lookahead = barmerge.lookahead_off) : close
ut_tp_rr        = input.float(1.5, title = "TP Risk:Reward", group = UT_MGMT)
ut_use_trail    = input.bool(true, title = "Use Trailing SL?", group = UT_MGMT)
show_perf_dash  = input.bool(true, title = "Show Performance Panel", group = DASH_GROUP)
show_mtf_dash   = input.bool(true, title = "Show MTF Trend Panel", group = DASH_GROUP)
dash_pos        = input.string(position.bottom_right, title = "Perf Panel Position", group = DASH_GROUP, options=[position.top_right, position.bottom_right, position.bottom_left])
 
// UT Bot 1 (Buy Only)
ut1_a = 4, ut1_c = 10
ut1_xATR = ta.atr(ut1_c)
ut1_nLoss = ut1_a * ut1_xATR
var float ut1_xATRTrailingStop = 0.0
ut1_xATRTrailingStop := if ut_src > nz(ut1_xATRTrailingStop[1], 0) and ut_src[1] > nz(ut1_xATRTrailingStop[1], 0)
    math.max(nz(ut1_xATRTrailingStop[1]), ut_src - ut1_nLoss)
else if ut_src < nz(ut1_xATRTrailingStop[1], 0) and ut_src[1] < nz(ut1_xATRTrailingStop[1], 0)
    math.min(nz(ut1_xATRTrailingStop[1]), ut_src + ut1_nLoss)
else if ut_src > nz(ut1_xATRTrailingStop[1], 0)
    ut_src - ut1_nLoss
else
    ut_src + ut1_nLoss
ut1_ema = ta.ema(ut_src, 1)
ut1_buy = ut_src > ut1_xATRTrailingStop and ta.crossover(ut1_ema, ut1_xATRTrailingStop)
 
// UT Bot 2 (Sell Only)
ut2_a = 7, ut2_c = 20
ut2_xATR = ta.atr(ut2_c)
ut2_nLoss = ut2_a * ut2_xATR
var float ut2_xATRTrailingStop = 0.0
ut2_xATRTrailingStop := if ut_src > nz(ut2_xATRTrailingStop[1], 0) and ut_src[1] > nz(ut2_xATRTrailingStop[1], 0)
    math.max(nz(ut2_xATRTrailingStop[1]), ut_src - ut2_nLoss)
else if ut_src < nz(ut2_xATRTrailingStop[1], 0) and ut_src[1] < nz(ut2_xATRTrailingStop[1], 0)
    math.min(nz(ut2_xATRTrailingStop[1]), ut_src + ut2_nLoss)
else if ut_src > nz(ut2_xATRTrailingStop[1], 0)
    ut_src - ut2_nLoss
else
    ut_src + ut2_nLoss
ut2_ema = ta.ema(ut_src, 1)
ut2_sell = ut_src < ut2_xATRTrailingStop and ta.crossover(ut2_xATRTrailingStop, ut2_ema)
 
//---------------------------------------------------------------------------------------------------------------------}
// TRADE LOGIC & BACKTESTER VARIABLES
//---------------------------------------------------------------------------------------------------------------------{
var line current_tp_line = na
var line current_sl_line = na
var float trade_tp_price = na
var float trade_sl_price = na
var string trade_dir = "none" 
 
// Stats Variables
var int total_trades = 0
var int win_trades = 0
var int loss_trades = 0
var float total_profit_p = 0.0
 
// NEW LONG
if ut1_buy
    if trade_dir != "none" // Close existing if reversal
        total_trades := total_trades + 1
        loss_trades := loss_trades + 1
        total_profit_p := total_profit_p - 1.0 // Assume 1R loss on reversal
        line.set_style(current_tp_line, line.style_dotted)
        line.set_style(current_sl_line, line.style_dotted)
 
    trade_dir := "long"
    entry_price = close
    initial_sl = ut1_xATRTrailingStop
    risk = entry_price - initial_sl
    trade_sl_price := initial_sl
    trade_tp_price := entry_price + (risk * ut_tp_rr)
    
    label.new(bar_index, low, text = "BUY 🚀\n" + str.tostring(close, format.mintick), color = GREEN, textcolor = color.black, style = label.style_label_up, size = size.normal, tooltip = "TP: " + str.tostring(trade_tp_price) + "\nSL: " + str.tostring(trade_sl_price))
    line.delete(current_tp_line), line.delete(current_sl_line)
    current_tp_line := line.new(bar_index, trade_tp_price, bar_index + 1, trade_tp_price, color = GREEN, style = line.style_solid, width = 2)
    current_sl_line := line.new(bar_index, trade_sl_price, bar_index + 1, trade_sl_price, color = RED, style = line.style_solid, width = 2)
    alert("UT Long Entry", alert.freq_once_per_bar_close)
 
// NEW SHORT
if ut2_sell
    if trade_dir != "none"
        total_trades := total_trades + 1
        loss_trades := loss_trades + 1
        total_profit_p := total_profit_p - 1.0
        line.set_style(current_tp_line, line.style_dotted)
        line.set_style(current_sl_line, line.style_dotted)
 
    trade_dir := "short"
    entry_price = close
    initial_sl = ut2_xATRTrailingStop
    risk = initial_sl - entry_price
    trade_sl_price := initial_sl
    trade_tp_price := entry_price - (risk * ut_tp_rr)
    
    label.new(bar_index, high, text = "SELL 📉\n" + str.tostring(close, format.mintick), color = RED, textcolor = color.white, style = label.style_label_down, size = size.normal, tooltip = "TP: " + str.tostring(trade_tp_price) + "\nSL: " + str.tostring(trade_sl_price))
    line.delete(current_tp_line), line.delete(current_sl_line)
    current_tp_line := line.new(bar_index, trade_tp_price, bar_index + 1, trade_tp_price, color = GREEN, style = line.style_solid, width = 2)
    current_sl_line := line.new(bar_index, trade_sl_price, bar_index + 1, trade_sl_price, color = RED, style = line.style_solid, width = 2)
    alert("UT Short Entry", alert.freq_once_per_bar_close)
 
// MANAGE ACTIVE TRADE
if trade_dir == "long" and not ut1_buy
    if ut_use_trail
        trade_sl_price := math.max(trade_sl_price, ut1_xATRTrailingStop)
    
    // Check Hit
    if high >= trade_tp_price
        trade_dir := "none"
        total_trades := total_trades + 1
        win_trades := win_trades + 1
        total_profit_p := total_profit_p + ut_tp_rr
        line.set_style(current_tp_line, line.style_dotted)
        line.set_style(current_sl_line, line.style_dotted)
        alert("Take Profit Hit", alert.freq_once_per_bar_close)
    else if low <= trade_sl_price
        trade_dir := "none"
        total_trades := total_trades + 1
        loss_trades := loss_trades + 1
        total_profit_p := total_profit_p - 1.0
        line.set_style(current_tp_line, line.style_dotted)
        line.set_style(current_sl_line, line.style_dotted)
        alert("Stop Loss Hit", alert.freq_once_per_bar_close)
    else
        line.set_xy1(current_tp_line, line.get_x1(current_tp_line), trade_tp_price)
        line.set_xy2(current_tp_line, bar_index + 1, trade_tp_price)
        line.set_xy1(current_sl_line, line.get_x1(current_sl_line), trade_sl_price)
        line.set_xy2(current_sl_line, bar_index + 1, trade_sl_price)
 
if trade_dir == "short" and not ut2_sell
    if ut_use_trail
        trade_sl_price := math.min(trade_sl_price, ut2_xATRTrailingStop)
        
    if low <= trade_tp_price
        trade_dir := "none"
        total_trades := total_trades + 1
        win_trades := win_trades + 1
        total_profit_p := total_profit_p + ut_tp_rr
        line.set_style(current_tp_line, line.style_dotted)
        line.set_style(current_sl_line, line.style_dotted)
        alert("Take Profit Hit", alert.freq_once_per_bar_close)
    else if high >= trade_sl_price
        trade_dir := "none"
        total_trades := total_trades + 1
        loss_trades := loss_trades + 1
        total_profit_p := total_profit_p - 1.0
        line.set_style(current_tp_line, line.style_dotted)
        line.set_style(current_sl_line, line.style_dotted)
        alert("Stop Loss Hit", alert.freq_once_per_bar_close)
    else
        line.set_xy1(current_tp_line, line.get_x1(current_tp_line), trade_tp_price)
        line.set_xy2(current_tp_line, bar_index + 1, trade_tp_price)
        line.set_xy1(current_sl_line, line.get_x1(current_sl_line), trade_sl_price)
        line.set_xy2(current_sl_line, bar_index + 1, trade_sl_price)
 
//---------------------------------------------------------------------------------------------------------------------}
// MTF FUNCTION
//---------------------------------------------------------------------------------------------------------------------{
get_ut_trend(a, c) =>
    _atr = ta.atr(c)
    _nLoss = a * _atr
    _src = close
    var float _xATRTrailingStop = 0.0
    _xATRTrailingStop := if _src > nz(_xATRTrailingStop[1], 0) and _src[1] > nz(_xATRTrailingStop[1], 0)
        math.max(nz(_xATRTrailingStop[1]), _src - _nLoss)
    else if _src < nz(_xATRTrailingStop[1], 0) and _src[1] < nz(_xATRTrailingStop[1], 0)
        math.min(nz(_xATRTrailingStop[1]), _src + _nLoss)
    else if _src > nz(_xATRTrailingStop[1], 0)
        _src - _nLoss
    else
        _src + _nLoss
    _pos = 0
    _pos := if _src[1] < nz(_xATRTrailingStop[1], 0) and _src > nz(_xATRTrailingStop[1], 0)
        1
    else if _src[1] > nz(_xATRTrailingStop[1], 0) and _src < nz(_xATRTrailingStop[1], 0)
        -1
    else
        nz(_pos[1], 0)
    _pos
 
// Fetch MTF Data (Using UT Bot Settings Key=5, ATR=15 as a middle ground trend filter)
t_15 = request.security(syminfo.tickerid, "15", get_ut_trend(5, 15))
t_60 = request.security(syminfo.tickerid, "60", get_ut_trend(5, 15))
t_240 = request.security(syminfo.tickerid, "240", get_ut_trend(5, 15))
t_D = request.security(syminfo.tickerid, "D", get_ut_trend(5, 15))
t_W = request.security(syminfo.tickerid, "W", get_ut_trend(5, 15))
 
//---------------------------------------------------------------------------------------------------------------------}
// DASHBOARDS
//---------------------------------------------------------------------------------------------------------------------{
// 1. STRATEGY PERF TABLE
var table perfTable = table.new(dash_pos, 2, 4, border_width = 1)
if show_perf_dash and barstate.islast
    win_rate = total_trades > 0 ? (win_trades / total_trades) * 100 : 0
   // table.cell(perfTable, 0, 0, "STRATEGY STATS", bgcolor = BG_COLOR, text_color = TEXT_COLOR, text_size = size.small)
   // table.cell(perfTable, 1, 0, "Session PnL", bgcolor = BG_COLOR, text_color = TEXT_COLOR, text_size = size.small)
    
   // table.cell(perfTable, 0, 1, "Win Rate", bgcolor = BG_COLOR, text_color = TEXT_COLOR, text_size = size.small)
   // table.cell(perfTable, 1, 1, str.tostring(win_rate, "#.##") + "%", bgcolor = win_rate > 50 ? GREEN : RED, text_color = color.black, text_size = size.small)
    
    //table.cell(perfTable, 0, 2, "Trades (W/L)", bgcolor = BG_COLOR, text_color = TEXT_COLOR, text_size = size.small)
  //  table.cell(perfTable, 1, 2, str.tostring(total_trades) + " (" + str.tostring(win_trades) + "/" + str.tostring(loss_trades) + ")", bgcolor = BG_COLOR, text_color = TEXT_COLOR, text_size = size.small)
 
    //table.cell(perfTable, 0, 3, "Net Profit (R)", bgcolor = BG_COLOR, text_color = TEXT_COLOR, text_size = size.small)
    //table.cell(perfTable, 1, 3, str.tostring(total_profit_p, "#.##") + "R", bgcolor = total_profit_p > 0 ? GREEN : RED, text_color = color.black, text_size = size.small)
 
// 2. MTF TREND DASHBOARD
var table trendTable = table.new(position.top_right, 2, 6, border_width = 1)
if show_mtf_dash and barstate.islast
    table.cell(trendTable, 0, 0, "TIMEFRAME", bgcolor = BG_COLOR, text_color = TEXT_COLOR, text_size = size.small)
    table.cell(trendTable, 1, 0, "TREND", bgcolor = BG_COLOR, text_color = TEXT_COLOR, text_size = size.small)
 
    table.cell(trendTable, 0, 1, "15m", bgcolor = BG_COLOR, text_color = TEXT_COLOR, text_size = size.small)
    table.cell(trendTable, 1, 1, t_15 == 1 ? "BULLISH" : "BEARISH", bgcolor = t_15 == 1 ? GREEN : RED, text_color = color.black, text_size = size.small)
 
    table.cell(trendTable, 0, 2, "1h", bgcolor = BG_COLOR, text_color = TEXT_COLOR, text_size = size.small)
    table.cell(trendTable, 1, 2, t_60 == 1 ? "BULLISH" : "BEARISH", bgcolor = t_60 == 1 ? GREEN : RED, text_color = color.black, text_size = size.small)
 
    table.cell(trendTable, 0, 3, "4h", bgcolor = BG_COLOR, text_color = TEXT_COLOR, text_size = size.small)
    table.cell(trendTable, 1, 3, t_240 == 1 ? "BULLISH" : "BEARISH", bgcolor = t_240 == 1 ? GREEN : RED, text_color = color.black, text_size = size.small)
 
    table.cell(trendTable, 0, 4, "Daily", bgcolor = BG_COLOR, text_color = TEXT_COLOR, text_size = size.small)
    table.cell(trendTable, 1, 4, t_D == 1 ? "BULLISH" : "BEARISH", bgcolor = t_D == 1 ? GREEN : RED, text_color = color.black, text_size = size.small)
 
    table.cell(trendTable, 0, 5, "Weekly", bgcolor = BG_COLOR, text_color = TEXT_COLOR, text_size = size.small)
    table.cell(trendTable, 1, 5, t_W == 1 ? "BULLISH" : "BEARISH", bgcolor = t_W == 1 ? GREEN : RED, text_color = color.black, text_size = size.small)
 
//---------------------------------------------------------------------------------------------------------------------}

← 返回列表