本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © cryptosquanch
// Modified DMI calculation and JMA smoothing are based on the open-source "DMI Modified" indicator by dman103. Credit to the original author.
//@version=6
strategy(
title = "DMI Modified Zero-Cross + MA Confluence Strategy",
shorttitle = "DMI Zero-Cross + MA Strat",
overlay = true,
pyramiding = 0,
process_orders_on_close = true,
calc_on_every_tick = false,
calc_on_order_fills = false,
initial_capital = 10000,
currency = currency.USD,
commission_type = strategy.commission.percent,
commission_value = 0.005,
slippage = 5,
margin_long = 5,
margin_short = 5,
max_labels_count = 500,
max_lines_count = 500,
max_boxes_count = 500
)
//══════════════════════════════════════════════════════════════════════════════
// Utilities
//══════════════════════════════════════════════════════════════════════════════
fmt(_x) =>
str.tostring(_x, format.mintick)
fmt2(_x) =>
str.tostring(_x, "#.##")
boolTxt(_b) =>
_b ? "YES" : "NO"
dirTxt(_dir) =>
_dir == 1 ? "LONG" : _dir == -1 ? "SHORT" : "FLAT"
tablePosFromString(_pos) =>
switch _pos
"Top Right" => position.top_right
"Top Left" => position.top_left
"Bottom Right" => position.bottom_right
"Bottom Left" => position.bottom_left
=> position.top_right
timeStrToMinutes(_s) =>
_parts = str.split(_s, ":")
_h = array.size(_parts) > 0 ? int(str.tonumber(array.get(_parts, 0))) : 0
_m = array.size(_parts) > 1 ? int(str.tonumber(array.get(_parts, 1))) : 0
_h * 60 + _m
inWindowHHMM(_enabled, _startHHMM, _endHHMM, _tz) =>
if not _enabled
false
else
_nowH = hour(time, _tz)
_nowM = minute(time, _tz)
_now = _nowH * 60 + _nowM
_st = timeStrToMinutes(_startHHMM)
_en = timeStrToMinutes(_endHHMM)
_st <= _en ? (_now >= _st and _now < _en) : (_now >= _st or _now < _en)
maCalc(_source, _length, _type) =>
switch _type
"SMA" => ta.sma(_source, _length)
"EMA" => ta.ema(_source, _length)
"SMMA (RMA)" => ta.rma(_source, _length)
"WMA" => ta.wma(_source, _length)
"VWMA" => ta.vwma(_source, _length)
"HMA" => ta.hma(_source, _length)
=> ta.ema(_source, _length)
jmaCalc(_src, _length) =>
_len = math.max(_length, 1)
_beta = 0.45 * (_len - 1) / (0.45 * (_len - 1) + 2)
_alpha = _beta
var float _tmp0 = na
var float _tmp1 = na
var float _tmp2 = na
var float _tmp3 = na
var float _tmp4 = na
_tmp0 := (1 - _alpha) * _src + _alpha * nz(_tmp0[1])
_tmp1 := (_src - _tmp0) * (1 - _beta) + _beta * nz(_tmp1[1])
_tmp2 := _tmp0 + _tmp1
_tmp3 := (_tmp2 - nz(_tmp4[1])) * ((1 - _alpha) * (1 - _alpha)) + (_alpha * _alpha) * nz(_tmp3[1])
_tmp4 := nz(_tmp4[1]) + _tmp3
_tmp4
dmiSmooth(_src, _length, _type) =>
switch _type
"NONE" => _src
"SMA" => ta.sma(_src, _length)
"SMMA" => ta.rma(_src, _length)
"EMA" => ta.ema(_src, _length)
"WMA" => ta.wma(_src, _length)
"HMA" => ta.hma(_src, _length)
"JMA" => jmaCalc(_src, _length)
=> _src
unitToPrice(_units, _unitMode, _pipSizeFX, _pointSize) =>
_unitMode == "Pips (FX)" ? _units * _pipSizeFX : _unitMode == "Points" ? _units * _pointSize : _units * syminfo.mintick
priceToUnits(_priceDist, _unitMode, _pipSizeFX, _pointSize) =>
_div = _unitMode == "Pips (FX)" ? _pipSizeFX : _unitMode == "Points" ? _pointSize : syminfo.mintick
_div != 0 ? _priceDist / _div : na
isValidStop(_dir, _entryPrice, _stopPrice) =>
not na(_stopPrice) and ((_dir == 1 and _stopPrice < _entryPrice) or (_dir == -1 and _stopPrice > _entryPrice))
//══════════════════════════════════════════════════════════════════════════════
// Inputs
//══════════════════════════════════════════════════════════════════════════════
// 1) Help / Status
helpGroup = "📘 Help / Status"
showHelpPanel = input.bool(
false,
"Show centered help panel",
group = helpGroup,
tooltip = "Displays a startup help panel that explains how the strategy works, reminds the user to add the separate DMI Modified indicator by dman103 to the chart, and summarizes the main settings."
)
helpBg = input.color(
color.new(#000000, 0),
"Help panel background",
group = helpGroup,
tooltip = "Background color for the centered help panel. Default is solid black."
)
helpTxt = input.color(
color.rgb(51, 255, 0),
"Help panel text color",
group = helpGroup,
tooltip = "Text color for the centered help panel."
)
showStatusPanel = input.bool(
true,
"Show compact live status panel",
group = helpGroup,
tooltip = "Shows a compact live panel with setup state, DMI state, MA state, active trade data, and block status."
)
statusPos = input.string(
"Top Right",
"Status panel position",
options = ["Top Right", "Top Left", "Bottom Right", "Bottom Left"],
group = helpGroup,
tooltip = "Choose where the compact live status panel is displayed."
)
statusBg = input.color(
color.new(#000000, 26),
"Status panel background",
group = helpGroup,
tooltip = "Background color of the live status panel."
)
statusTxt = input.color(
color.rgb(9, 255, 0),
"Status panel text color",
group = helpGroup,
tooltip = "Text color of the live status panel."
)
// 2) Trade Direction
dirGroup = "🧭 Trade Direction"
tradeDirection = input.string(
"Both",
"Allowed trade direction",
options = ["Both", "Long Only", "Short Only"],
group = dirGroup,
tooltip = "Choose whether the strategy can take long trades, short trades, or both."
)
closeOnOppCross = input.bool(
false,
"Close active trade on opposite DMI zero-line cross",
group = dirGroup,
tooltip = "When enabled, an open long closes immediately on a confirmed cross below 0, and an open short closes immediately on a confirmed cross above 0."
)
closeOnDmiWeaken = input.bool(
false,
"Close active trade when DMI weakens on confirmed bar close",
group = dirGroup,
tooltip = "For longs: closes when DMI remains above 0 but is lower than the previous bar. For shorts: closes when DMI remains below 0 but is higher than the previous bar."
)
closeOnDmiMagnitude = input.bool(
false,
"Close active trade when DMI magnitude reaches threshold",
group = dirGroup,
tooltip = "When enabled, longs close when DMI >= threshold and shorts close when DMI <= negative threshold."
)
dmiMagnitudeLevel = input.float(
30.0,
"DMI magnitude threshold",
minval = 0.1,
step = 0.1,
group = dirGroup,
tooltip = "Example: 30 means longs close when DMI >= +30 and shorts close when DMI <= -30."
)
// 3) Position Sizing
sizeGroup = "💵 Position Sizing"
sizeMode = input.string(
"Cash",
"Order size mode",
options = ["Cash", "Percent of Equity"],
group = sizeGroup,
tooltip = "Sizing method used for orders. Cash and Percent of Equity are converted into an approximate quantity using price."
)
orderCash = input.float(
10000,
"Cash amount",
minval = 0,
step = 50,
group = sizeGroup,
tooltip = "Cash value used when Order size mode = Cash."
)
orderPctEq = input.float(
100.0,
"Percent of equity",
minval = 0.01,
step = 0.25,
group = sizeGroup,
tooltip = "Percent of current equity used when Order size mode = Percent of Equity."
)
// 4) Units
unitGroup = "📐 Units"
unitMode = input.string(
"Pips (FX)",
"Unit mode",
options = ["Pips (FX)", "Ticks", "Points"],
group = unitGroup,
tooltip = "Choose how stop, target, and trailing distances are measured."
)
pipSizeFX = input.float(
0.01,
"Pip size (FX)",
minval = 0.00001,
step = 0.00001,
group = unitGroup,
tooltip = "Size of one pip for FX mode. Default 0.01 is appropriate for many JPY pairs such as USDJPY."
)
pointSize = input.float(
0.01,
"Point size",
minval = 0.00001,
step = 0.00001,
group = unitGroup,
tooltip = "Used only when Unit mode = Points."
)
// 5) DMI Modified Core
dmiGroup = "📊 DMI Modified Core"
dmiLen = input.int(
7,
"DMI length",
minval = 1,
group = dmiGroup,
tooltip = "Main DMI lookback length."
)
dmiSmoothLen = input.int(
3,
"Smoothing length",
minval = 1,
group = dmiGroup,
tooltip = "Smoothing length applied to the modified DMI result."
)
dmiSmoothType = input.string(
"JMA",
"Smoothing type",
options = ["NONE", "SMA", "SMMA", "EMA", "WMA", "HMA", "JMA"],
group = dmiGroup,
tooltip = "Smoothing type used on the modified DMI result."
)
holdBars = input.int(
0,
"Hold bars after cross",
minval = 0,
group = dmiGroup,
tooltip = "How many additional confirmed bars the modified DMI must remain on the crossed side of 0 after the initial confirmed cross."
)
useMinDmiMag = input.bool(
false,
"Use minimum DMI magnitude filter",
group = dmiGroup,
tooltip = "When enabled, the trade is only allowed if the modified DMI value is far enough away from 0 on the actual entry-confirmation bar."
)
minDmiMag = input.float(
2.0,
"Minimum |DMI| after confirmation",
minval = 0,
step = 0.1,
group = dmiGroup,
tooltip = "Minimum required modified DMI magnitude on the entry-confirmation bar."
)
useAdxFilter = input.bool(
false,
"Use ADX strength filter",
group = dmiGroup,
tooltip = "When enabled, a trade is only allowed if ADX is at or above the chosen threshold on the entry-confirmation bar."
)
adxLen = input.int(
14,
"ADX length",
minval = 1,
group = dmiGroup,
tooltip = "ADX lookback used by the optional ADX strength filter."
)
minAdx = input.float(
20.0,
"Minimum ADX",
minval = 0,
step = 0.1,
group = dmiGroup,
tooltip = "Minimum ADX required when the ADX filter is enabled."
)
showDmiMarkers = input.bool(
false,
"Show DMI zero-cross markers on price chart",
group = dmiGroup,
tooltip = "Optional lightweight on-chart markers for internal DMI zero-line crosses."
)
// 6) MA Confluence
maGroup = "📈 MA Confluence"
useMaConfluence = input.bool(
false,
"Use MA stack confluence",
group = maGroup,
tooltip = "When enabled, entry is only allowed if the selected MAs are strictly stacked in the same direction on the entry-confirmation bar."
)
maSource = input.source(
close,
"MA source",
group = maGroup,
tooltip = "Source used for all moving averages."
)
maCount = input.int(
4,
"Number of MAs",
minval = 2,
maxval = 5,
group = maGroup,
tooltip = "Number of active moving averages used in the stack check."
)
ma1Type = input.string("EMA", "MA #1", options = ["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA", "HMA"], group = maGroup, inline = "ma1", tooltip = "Type for MA #1.")
ma1Len = input.int(20, "", minval = 1, group = maGroup, inline = "ma1", tooltip = "Length for MA #1.")
ma1Color = input.color(color.new(#00ff00, 0), "", group = maGroup, inline = "ma1", tooltip = "Color for MA #1.")
ma2Type = input.string("EMA", "MA #2", options = ["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA", "HMA"], group = maGroup, inline = "ma2", tooltip = "Type for MA #2.")
ma2Len = input.int(50, "", minval = 1, group = maGroup, inline = "ma2", tooltip = "Length for MA #2.")
ma2Color = input.color(color.new(#39ff14, 0), "", group = maGroup, inline = "ma2", tooltip = "Color for MA #2.")
ma3Type = input.string("EMA", "MA #3", options = ["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA", "HMA"], group = maGroup, inline = "ma3", tooltip = "Type for MA #3.")
ma3Len = input.int(100, "", minval = 1, group = maGroup, inline = "ma3", tooltip = "Length for MA #3.")
ma3Color = input.color(color.new(#66ff66, 0), "", group = maGroup, inline = "ma3", tooltip = "Color for MA #3.")
ma4Type = input.string("EMA", "MA #4", options = ["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA", "HMA"], group = maGroup, inline = "ma4", tooltip = "Type for MA #4.")
ma4Len = input.int(200, "", minval = 1, group = maGroup, inline = "ma4", tooltip = "Length for MA #4.")
ma4Color = input.color(color.new(#7dff7d, 0), "", group = maGroup, inline = "ma4", tooltip = "Color for MA #4.")
ma5Type = input.string("EMA", "MA #5", options = ["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA", "HMA"], group = maGroup, inline = "ma5", tooltip = "Type for MA #5.")
ma5Len = input.int(400, "", minval = 1, group = maGroup, inline = "ma5", tooltip = "Length for MA #5.")
ma5Color = input.color(color.new(#a0ffa0, 0), "", group = maGroup, inline = "ma5", tooltip = "Color for MA #5.")
// 7) Stop Loss
slGroup = "🛑 Stop Loss"
slMode = input.string(
"Signal Bar Offset",
"Stop-loss mode",
options = ["Signal Bar Offset", "Fixed Units / Pips", "Percent", "ATR"],
group = slGroup,
tooltip = "Choose how the stop-loss is calculated."
)
slSignalOffsetUnits = input.float(
3.0,
"Signal-bar offset (units)",
minval = 0,
step = 0.1,
group = slGroup,
tooltip = "Used when Stop-loss mode = Signal Bar Offset."
)
slFixedUnits = input.float(
10.0,
"Fixed stop distance (units)",
minval = 0,
step = 0.1,
group = slGroup,
tooltip = "Used when Stop-loss mode = Fixed Units / Pips."
)
slPct = input.float(
0.25,
"Stop distance (%)",
minval = 0.01,
step = 0.01,
group = slGroup,
tooltip = "Used when Stop-loss mode = Percent."
)
slAtrLen = input.int(
14,
"ATR length",
minval = 1,
group = slGroup,
tooltip = "ATR length used for ATR-based stop-loss, take-profit, and trailing calculations."
)
slAtrMult = input.float(
1.0,
"ATR stop multiplier",
minval = 0.1,
step = 0.1,
group = slGroup,
tooltip = "Used when Stop-loss mode = ATR."
)
// 8) Take Profit
tpGroup = "🎯 Take Profit"
tpMode = input.string(
"Risk:Reward",
"Take-profit mode",
options = ["Risk:Reward", "Fixed Units / Pips", "Percent", "ATR", "Signal Bar Range Extension"],
group = tpGroup,
tooltip = "Choose how the base take-profit is calculated. When trailing is enabled, this base TP becomes the activation threshold."
)
rrMultiple = input.float(
2.0,
"Risk:Reward multiple",
minval = 0.1,
step = 0.1,
group = tpGroup,
tooltip = "Used when Take-profit mode = Risk:Reward."
)
tpFixedUnits = input.float(
20.0,
"Fixed TP distance (units)",
minval = 0,
step = 0.1,
group = tpGroup,
tooltip = "Used when Take-profit mode = Fixed Units / Pips."
)
tpPct = input.float(
0.50,
"Take-profit (%)",
minval = 0.01,
step = 0.01,
group = tpGroup,
tooltip = "Used when Take-profit mode = Percent."
)
tpAtrMult = input.float(
2.0,
"ATR TP multiplier",
minval = 0.1,
step = 0.1,
group = tpGroup,
tooltip = "Used when Take-profit mode = ATR."
)
signalRangeMult = input.float(
1.0,
"Signal-bar range extension multiplier",
minval = 0.1,
step = 0.1,
group = tpGroup,
tooltip = "Used when Take-profit mode = Signal Bar Range Extension."
)
// 9) Trailing / Post-TP Protection
trailGroup = "🏃 Trailing / Post-TP Protection"
enableTrailing = input.bool(
false,
"Enable trailing after base TP is touched",
group = trailGroup,
tooltip = "When enabled, the base TP becomes an activation threshold instead of a hard limit target."
)
trailMode = input.string(
"Fixed Units / Pips",
"Trailing mode",
options = ["Fixed Units / Pips", "Percent", "ATR", "Bottom/Top of Last X Candles", "Open/Close of Last X Candles"],
group = trailGroup,
tooltip = "Trailing method used after the base TP has been touched."
)
trailFixedUnits = input.float(
5.0,
"Trailing distance (units)",
minval = 0,
step = 0.1,
group = trailGroup,
tooltip = "Used when Trailing mode = Fixed Units / Pips."
)
trailPct = input.float(
0.20,
"Trailing distance (%)",
minval = 0.01,
step = 0.01,
group = trailGroup,
tooltip = "Used when Trailing mode = Percent."
)
trailAtrMult = input.float(
1.0,
"Trailing ATR multiplier",
minval = 0.1,
step = 0.1,
group = trailGroup,
tooltip = "Used when Trailing mode = ATR."
)
trailLookback = input.int(
3,
"Trailing structure lookback",
minval = 1,
group = trailGroup,
tooltip = "Used by the candle-structure trailing modes."
)
protectFloorMode = input.string(
"Base TP Level",
"Post-TP protection floor",
options = ["Base TP Level", "Breakeven Level"],
group = trailGroup,
tooltip = "After the base TP is touched, trailing can be prevented from moving back beyond either the base TP level or a breakeven level."
)
breakevenOffsetUnits = input.float(
0.0,
"Breakeven offset (units)",
minval = 0,
step = 0.1,
group = trailGroup,
tooltip = "Used when Post-TP protection floor = Breakeven Level."
)
// 10) Time Blocks
blockGroup = "⏰ Time Blocks"
tzOpt = input.string(
"America/New_York",
"Time zone",
options = [
"America/New_York", "America/Chicago", "America/Denver", "America/Los_Angeles",
"UTC", "Etc/UTC",
"Europe/London", "Europe/Paris",
"Asia/Tokyo", "Asia/Hong_Kong", "Asia/Singapore",
"Australia/Sydney"
],
group = blockGroup,
tooltip = "Timezone used by all time blocks."
)
blockMode = input.string(
"Block new entries only",
"Block behavior",
options = ["Block new entries only", "Block new entries + exit current trades"],
group = blockGroup,
tooltip = "Default blocks only new entries. The other mode also closes open trades immediately when a block is active."
)
w1En = input.bool(true, "Block #1", group = blockGroup, inline = "w1", tooltip = "Enable/disable time block #1.")
w1St = input.string("16:45", "Start", group = blockGroup, inline = "w1", options = ["00:00","00:15","00:30","00:45","01:00","01:15","01:30","01:45","02:00","02:15","02:30","02:45","03:00","03:15","03:30","03:45","04:00","04:15","04:30","04:45","05:00","05:15","05:30","05:45","06:00","06:15","06:30","06:45","07:00","07:15","07:30","07:45","08:00","08:15","08:30","08:45","09:00","09:15","09:30","09:45","10:00","10:15","10:30","10:45","11:00","11:15","11:30","11:45","12:00","12:15","12:30","12:45","13:00","13:15","13:30","13:45","14:00","14:15","14:30","14:45","15:00","15:15","15:30","15:45","16:00","16:15","16:30","16:45","17:00","17:15","17:30","17:45","18:00","18:15","18:30","18:45","19:00","19:15","19:30","19:45","20:00","20:15","20:30","20:45","21:00","21:15","21:30","21:45","22:00","22:15","22:30","22:45","23:00","23:15","23:30","23:45"], tooltip = "Start time for block #1.")
w1EnT = input.string("18:15", "End", group = blockGroup, inline = "w1", options = ["00:00","00:15","00:30","00:45","01:00","01:15","01:30","01:45","02:00","02:15","02:30","02:45","03:00","03:15","03:30","03:45","04:00","04:15","04:30","04:45","05:00","05:15","05:30","05:45","06:00","06:15","06:30","06:45","07:00","07:15","07:30","07:45","08:00","08:15","08:30","08:45","09:00","09:15","09:30","09:45","10:00","10:15","10:30","10:45","11:00","11:15","11:30","11:45","12:00","12:15","12:30","12:45","13:00","13:15","13:30","13:45","14:00","14:15","14:30","14:45","15:00","15:15","15:30","15:45","16:00","16:15","16:30","16:45","17:00","17:15","17:30","17:45","18:00","18:15","18:30","18:45","19:00","19:15","19:30","19:45","20:00","20:15","20:30","20:45","21:00","21:15","21:30","21:45","22:00","22:15","22:30","22:45","23:00","23:15","23:30","23:45"], tooltip = "End time for block #1.")
w2En = input.bool(true, "Block #2", group = blockGroup, inline = "w2", tooltip = "Enable/disable time block #2.")
w2St = input.string("08:15", "Start", group = blockGroup, inline = "w2", options = ["00:00","00:15","00:30","00:45","01:00","01:15","01:30","01:45","02:00","02:15","02:30","02:45","03:00","03:15","03:30","03:45","04:00","04:15","04:30","04:45","05:00","05:15","05:30","05:45","06:00","06:15","06:30","06:45","07:00","07:15","07:30","07:45","08:00","08:15","08:30","08:45","09:00","09:15","09:30","09:45","10:00","10:15","10:30","10:45","11:00","11:15","11:30","11:45","12:00","12:15","12:30","12:45","13:00","13:15","13:30","13:45","14:00","14:15","14:30","14:45","15:00","15:15","15:30","15:45","16:00","16:15","16:30","16:45","17:00","17:15","17:30","17:45","18:00","18:15","18:30","18:45","19:00","19:15","19:30","19:45","20:00","20:15","20:30","20:45","21:00","21:15","21:30","21:45","22:00","22:15","22:30","22:45","23:00","23:15","23:30","23:45"], tooltip = "Start time for block #2.")
w2EnT = input.string("09:30", "End", group = blockGroup, inline = "w2", options = ["00:00","00:15","00:30","00:45","01:00","01:15","01:30","01:45","02:00","02:15","02:30","02:45","03:00","03:15","03:30","03:45","04:00","04:15","04:30","04:45","05:00","05:15","05:30","05:45","06:00","06:15","06:30","06:45","07:00","07:15","07:30","07:45","08:00","08:15","08:30","08:45","09:00","09:15","09:30","09:45","10:00","10:15","10:30","10:45","11:00","11:15","11:30","11:45","12:00","12:15","12:30","12:45","13:00","13:15","13:30","13:45","14:00","14:15","14:30","14:45","15:00","15:15","15:30","15:45","16:00","16:15","16:30","16:45","17:00","17:15","17:30","17:45","18:00","18:15","18:30","18:45","19:00","19:15","19:30","19:45","20:00","20:15","20:30","20:45","21:00","21:15","21:30","21:45","22:00","22:15","22:30","22:45","23:00","23:15","23:30","23:45"], tooltip = "End time for block #2.")
w3En = input.bool(false, "Block #3", group = blockGroup, inline = "w3", tooltip = "Enable/disable time block #3.")
w3St = input.string("00:00", "Start", group = blockGroup, inline = "w3", options = ["00:00","00:15","00:30","00:45","01:00","01:15","01:30","01:45","02:00","02:15","02:30","02:45","03:00","03:15","03:30","03:45","04:00","04:15","04:30","04:45","05:00","05:15","05:30","05:45","06:00","06:15","06:30","06:45","07:00","07:15","07:30","07:45","08:00","08:15","08:30","08:45","09:00","09:15","09:30","09:45","10:00","10:15","10:30","10:45","11:00","11:15","11:30","11:45","12:00","12:15","12:30","12:45","13:00","13:15","13:30","13:45","14:00","14:15","14:30","14:45","15:00","15:15","15:30","15:45","16:00","16:15","16:30","16:45","17:00","17:15","17:30","17:45","18:00","18:15","18:30","18:45","19:00","19:15","19:30","19:45","20:00","20:15","20:30","20:45","21:00","21:15","21:30","21:45","22:00","22:15","22:30","22:45","23:00","23:15","23:30","23:45"], tooltip = "Start time for block #3.")
w3EnT = input.string("00:00", "End", group = blockGroup, inline = "w3", options = ["00:00","00:15","00:30","00:45","01:00","01:15","01:30","01:45","02:00","02:15","02:30","02:45","03:00","03:15","03:30","03:45","04:00","04:15","04:30","04:45","05:00","05:15","05:30","05:45","06:00","06:15","06:30","06:45","07:00","07:15","07:30","07:45","08:00","08:15","08:30","08:45","09:00","09:15","09:30","09:45","10:00","10:15","10:30","10:45","11:00","11:15","11:30","11:45","12:00","12:15","12:30","12:45","13:00","13:15","13:30","13:45","14:00","14:15","14:30","14:45","15:00","15:15","15:30","15:45","16:00","16:15","16:30","16:45","17:00","17:15","17:30","17:45","18:00","18:15","18:30","18:45","19:00","19:15","19:30","19:45","20:00","20:15","20:30","20:45","21:00","21:15","21:30","21:45","22:00","22:15","22:30","22:45","23:00","23:15","23:30","23:45"], tooltip = "End time for block #3.")
// 11) Re-entry Control
reentryGroup = "🔁 Re-entry Control"
useReentryCooldown = input.bool(
true,
"Use re-entry cooldown after a trade closes",
group = reentryGroup,
tooltip = "When enabled, the strategy waits a number of full bars after a position closes before allowing a new entry."
)
reentryCooldownBars = input.int(
1,
"Cooldown bars after close",
minval = 0,
maxval = 50,
group = reentryGroup,
tooltip = "Number of bars to wait after a position closes before another entry is allowed."
)
// 13) Visuals / Optimizer
visGroup = "🎨 Visuals"
optimizerMode = input.bool(
false,
"Enable optimizer mode (hide most visual objects)",
group = visGroup,
tooltip = "Turns off most labels, lines, boxes, MA plots, tables, and chart clutter to make optimization cleaner and lighter."
)
showMaPlots = input.bool(
true,
"Show MA ribbon",
group = visGroup,
tooltip = "Plots the active moving averages used for MA stack confluence."
)
showLiveLines = input.bool(
true,
"Show active-trade lines",
group = visGroup,
tooltip = "Shows live entry, stop, target, and trail lines while a trade is open."
)
showLiveTradeBox = input.bool(
true,
"Show live trade box",
group = visGroup,
tooltip = "Draws a live risk/reward box while a trade is open."
)
showTradeBoxes = input.bool(
true,
"Show recent closed-trade boxes",
group = visGroup,
tooltip = "Draws historical risk/reward boxes for recent closed trades."
)
showTradeLabels = input.bool(
true,
"Show recent trade labels",
group = visGroup,
tooltip = "Shows entry and exit callout labels for recent trades."
)
recentTradesToDraw = input.int(
20,
"Max recent trades to keep",
minval = 1,
maxval = 50,
group = visGroup,
tooltip = "Maximum number of recent trades to keep on the chart."
)
// 14) Label Callouts
calloutGroup = "🧷 Label Callouts"
useCallouts = input.bool(true, "Offset trade callouts from price", group = calloutGroup, tooltip = "Moves trade labels away from candles for cleaner reading.")
drawCalloutLines = input.bool(true, "Draw dotted connector lines", group = calloutGroup, tooltip = "Draws dotted connector lines between price and the offset trade callout labels.")
calloutXBars = input.int(2, "Callout X offset (bars)", minval = 0, maxval = 50, group = calloutGroup, tooltip = "Horizontal offset of callout labels in bars.")
calloutBaseAtr = input.float(20.0, "Base separation from price (ATR)", step = 0.1, group = calloutGroup, tooltip = "Base vertical separation of callout labels from price, measured in ATR multiples.")
calloutMemory = input.int(20, "Callout memory", minval = 0, maxval = 50, group = calloutGroup, tooltip = "How many historical callout placements the engine remembers.")
entryInfoBg = input.color(color.new(color.black, 15), "Entry label background", group = calloutGroup, tooltip = "Background color of entry labels.")
entryInfoTxt = input.color(color.rgb(0, 255, 13), "Entry label text", group = calloutGroup, tooltip = "Text color of entry labels.")
exitWinBg = input.color(color.new(color.lime, 35), "Winning exit label background", group = calloutGroup, tooltip = "Background color for winning closed-trade labels.")
exitLossBg = input.color(color.new(color.red, 35), "Losing exit label background", group = calloutGroup, tooltip = "Background color for losing closed-trade labels.")
exitTxtCol = input.color(color.white, "Exit label text", group = calloutGroup, tooltip = "Text color used on exit labels.")
//══════════════════════════════════════════════════════════════════════════════
// Effective toggles
//══════════════════════════════════════════════════════════════════════════════
showHelpPanelEff = showHelpPanel and not optimizerMode
showStatusPanelEff = showStatusPanel and not optimizerMode
showMaPlotsEff = showMaPlots and not optimizerMode
showLiveLinesEff = showLiveLines and not optimizerMode
showLiveTradeBoxEff = showLiveTradeBox and not optimizerMode
showTradeBoxesEff = showTradeBoxes and not optimizerMode
showTradeLabelsEff = showTradeLabels and not optimizerMode
showDmiMarkersEff = showDmiMarkers and not optimizerMode
useCalloutsEff = useCallouts and not optimizerMode
drawCalloutLinesEff = drawCalloutLines and not optimizerMode
//══════════════════════════════════════════════════════════════════════════════
// Core Calculations
//══════════════════════════════════════════════════════════════════════════════
atrSeries = ta.atr(slAtrLen)
// DMI Modified by dman103 logic core
upMove = ta.change(ta.highest(high, dmiLen))
downMove = -ta.change(ta.lowest(low, dmiLen))
trueRangeDmi = ta.rma(ta.tr(true), dmiLen)
plusDI = nz(100 * ta.rma(upMove > downMove and upMove > 0 ? upMove : 0, dmiLen) / trueRangeDmi)
minusDI = nz(100 * ta.rma(downMove > upMove and downMove > 0 ? downMove : 0, dmiLen) / trueRangeDmi)
dmiRaw = plusDI - minusDI
dmiValue = dmiSmooth(dmiRaw, dmiSmoothLen, dmiSmoothType)
// ADX filter source
[adxPlus, adxMinus, adxValue] = ta.dmi(adxLen, adxLen)
dmiBullCross = ta.crossover(dmiValue, 0)
dmiBearCross = ta.crossunder(dmiValue, 0)
dmiLongWeak = dmiValue > 0 and dmiValue < dmiValue[1]
dmiShortWeak = dmiValue < 0 and dmiValue > dmiValue[1]
dmiLongMagnitudeExit = closeOnDmiMagnitude and dmiValue >= dmiMagnitudeLevel
dmiShortMagnitudeExit = closeOnDmiMagnitude and dmiValue <= -dmiMagnitudeLevel
// MA ribbon
ma1 = maCalc(maSource, ma1Len, ma1Type)
ma2 = maCalc(maSource, ma2Len, ma2Type)
ma3 = maCalc(maSource, ma3Len, ma3Type)
ma4 = maCalc(maSource, ma4Len, ma4Type)
ma5 = maCalc(maSource, ma5Len, ma5Type)
maBull =
maCount == 2 ? (ma1 > ma2) :
maCount == 3 ? (ma1 > ma2 and ma2 > ma3) :
maCount == 4 ? (ma1 > ma2 and ma2 > ma3 and ma3 > ma4) :
(ma1 > ma2 and ma2 > ma3 and ma3 > ma4 and ma4 > ma5)
maBear =
maCount == 2 ? (ma1 < ma2) :
maCount == 3 ? (ma1 < ma2 and ma2 < ma3) :
maCount == 4 ? (ma1 < ma2 and ma2 < ma3 and ma3 < ma4) :
(ma1 < ma2 and ma2 < ma3 and ma3 < ma4 and ma4 < ma5)
// Time blocks
blockActive =
inWindowHHMM(w1En, w1St, w1EnT, tzOpt) or
inWindowHHMM(w2En, w2St, w2EnT, tzOpt) or
inWindowHHMM(w3En, w3St, w3EnT, tzOpt)
flattenInBlock = blockMode == "Block new entries + exit current trades"
// Trade direction
allowLong = tradeDirection == "Both" or tradeDirection == "Long Only"
allowShort = tradeDirection == "Both" or tradeDirection == "Short Only"
// Current position state
pos = strategy.position_size
posPrev = strategy.position_size[1]
inLong = pos > 0
inShort = pos < 0
flat = pos == 0
newPositionOpened = pos != 0 and posPrev == 0
positionClosed = pos == 0 and posPrev != 0
//══════════════════════════════════════════════════════════════════════════════
// Pending strict zero-cross state
//══════════════════════════════════════════════════════════════════════════════
var int pendingDir = 0
var int pendingHoldProgress = 0
var int pendingStartBar = na
var float pendingCrossValue = na
var string setupReason = "Waiting for fresh DMI zero-line cross"
// Start new pending signal only when flat
if flat
if dmiBullCross
pendingDir := 1
pendingHoldProgress := 0
pendingStartBar := bar_index
pendingCrossValue := dmiValue
setupReason := holdBars == 0 ? "Fresh bullish DMI cross confirmed" : "Bullish DMI cross confirmed — holding above 0"
else if dmiBearCross
pendingDir := -1
pendingHoldProgress := 0
pendingStartBar := bar_index
pendingCrossValue := dmiValue
setupReason := holdBars == 0 ? "Fresh bearish DMI cross confirmed" : "Bearish DMI cross confirmed — holding below 0"
// Cancel/replace pending if opposite cross appears before entry
if flat and pendingDir == 1 and dmiBearCross
pendingDir := -1
pendingHoldProgress := 0
pendingStartBar := bar_index
pendingCrossValue := dmiValue
setupReason := holdBars == 0 ? "New bearish cross replaced pending long" : "New bearish cross replaced pending long — holding below 0"
if flat and pendingDir == -1 and dmiBullCross
pendingDir := 1
pendingHoldProgress := 0
pendingStartBar := bar_index
pendingCrossValue := dmiValue
setupReason := holdBars == 0 ? "New bullish cross replaced pending short" : "New bullish cross replaced pending short — holding above 0"
// Continue or cancel hold phase
if flat and pendingDir == 1 and not dmiBullCross
if dmiValue > 0
if pendingHoldProgress < holdBars
pendingHoldProgress += 1
else
pendingDir := 0
pendingHoldProgress := 0
pendingStartBar := na
pendingCrossValue := na
setupReason := "Pending long cancelled — DMI fell back below 0"
if flat and pendingDir == -1 and not dmiBearCross
if dmiValue < 0
if pendingHoldProgress < holdBars
pendingHoldProgress += 1
else
pendingDir := 0
pendingHoldProgress := 0
pendingStartBar := na
pendingCrossValue := na
setupReason := "Pending short cancelled — DMI rose back above 0"
entryReadyLong = flat and pendingDir == 1 and pendingHoldProgress >= holdBars
entryReadyShort = flat and pendingDir == -1 and pendingHoldProgress >= holdBars
//══════════════════════════════════════════════════════════════════════════════
// Entry/Exit helper functions
//══════════════════════════════════════════════════════════════════════════════
calcStopPrice(_dir, _entryPrice, _atrNow) =>
float _out = na
if slMode == "Signal Bar Offset"
float _off = unitToPrice(slSignalOffsetUnits, unitMode, pipSizeFX, pointSize)
_out := _dir == 1 ? low - _off : high + _off
else if slMode == "Fixed Units / Pips"
float _dist = unitToPrice(slFixedUnits, unitMode, pipSizeFX, pointSize)
_out := _dir == 1 ? _entryPrice - _dist : _entryPrice + _dist
else if slMode == "Percent"
float _dist = _entryPrice * (slPct / 100.0)
_out := _dir == 1 ? _entryPrice - _dist : _entryPrice + _dist
else
float _dist = _atrNow * slAtrMult
_out := _dir == 1 ? _entryPrice - _dist : _entryPrice + _dist
_out
calcTpPrice(_dir, _entryPrice, _stopPrice, _atrNow) =>
float _out = na
if tpMode == "Risk:Reward"
_risk = not na(_stopPrice) ? math.abs(_entryPrice - _stopPrice) : na
_out := not na(_risk) ? (_dir == 1 ? _entryPrice + _risk * rrMultiple : _entryPrice - _risk * rrMultiple) : na
else if tpMode == "Fixed Units / Pips"
_dist = unitToPrice(tpFixedUnits, unitMode, pipSizeFX, pointSize)
_out := _dir == 1 ? _entryPrice + _dist : _entryPrice - _dist
else if tpMode == "Percent"
_dist = _entryPrice * (tpPct / 100.0)
_out := _dir == 1 ? _entryPrice + _dist : _entryPrice - _dist
else if tpMode == "ATR"
_dist = _atrNow * tpAtrMult
_out := _dir == 1 ? _entryPrice + _dist : _entryPrice - _dist
else
_range = high - low
_dist = _range * signalRangeMult
_out := _dir == 1 ? _entryPrice + _dist : _entryPrice - _dist
_out
lowestLowTrail = ta.lowest(low, trailLookback)
highestHighTrail = ta.highest(high, trailLookback)
ocLowSeries = math.min(open, close)
ocHighSeries = math.max(open, close)
lowestOcTrail = ta.lowest(ocLowSeries, trailLookback)
highestOcTrail = ta.highest(ocHighSeries, trailLookback)
//══════════════════════════════════════════════════════════════════════════════
// Callout engine
//══════════════════════════════════════════════════════════════════════════════
var int[] _co_entry_dn_x = array.new<int>()
var float[] _co_entry_dn_y = array.new<float>()
var label[] _co_entry_dn_lb = array.new<label>()
var line[] _co_entry_dn_ln = array.new<line>()
var int[] _co_entry_up_x = array.new<int>()
var float[] _co_entry_up_y = array.new<float>()
var label[] _co_entry_up_lb = array.new<label>()
var line[] _co_entry_up_ln = array.new<line>()
var int[] _co_exit_up_x = array.new<int>()
var float[] _co_exit_up_y = array.new<float>()
var label[] _co_exit_up_lb = array.new<label>()
var line[] _co_exit_up_ln = array.new<line>()
var int[] _co_exit_dn_x = array.new<int>()
var float[] _co_exit_dn_y = array.new<float>()
var label[] _co_exit_dn_lb = array.new<label>()
var line[] _co_exit_dn_ln = array.new<line>()
_coEnsureSpace(_xs, _ys, _lbs, _lns) =>
while array.size(_xs) >= calloutMemory
array.shift(_xs)
array.shift(_ys)
_oldLb = array.shift(_lbs)
if not na(_oldLb)
label.delete(_oldLb)
_oldLn = array.shift(_lns)
if not na(_oldLn)
line.delete(_oldLn)
_coMark(_xs, _ys, _lbs, _lns, _xPlaced, _yPlaced, _lb, _ln) =>
array.push(_xs, _xPlaced)
array.push(_ys, _yPlaced)
array.push(_lbs, _lb)
array.push(_lns, _ln)
makeCallout(_bucket, _dir, _xAnchor, _yAnchor, _text, _bg, _style, _txtCol) =>
label _lb = na
if not optimizerMode and showTradeLabelsEff
baseSep = math.max(atrSeries * calloutBaseAtr, syminfo.mintick * 20)
doOffset = useCalloutsEff
xPlaced = doOffset ? (_xAnchor + calloutXBars) : _xAnchor
yPlaced = doOffset ? (_dir == "UP" ? _yAnchor + baseSep : _yAnchor - baseSep) : _yAnchor
if _bucket == "ENTRY_DN"
_coEnsureSpace(_co_entry_dn_x, _co_entry_dn_y, _co_entry_dn_lb, _co_entry_dn_ln)
else if _bucket == "ENTRY_UP"
_coEnsureSpace(_co_entry_up_x, _co_entry_up_y, _co_entry_up_lb, _co_entry_up_ln)
else if _bucket == "EXIT_UP"
_coEnsureSpace(_co_exit_up_x, _co_exit_up_y, _co_exit_up_lb, _co_exit_up_ln)
else
_coEnsureSpace(_co_exit_dn_x, _co_exit_dn_y, _co_exit_dn_lb, _co_exit_dn_ln)
line _ln = na
if doOffset and drawCalloutLinesEff
_ln := line.new(
x1 = _xAnchor, y1 = _yAnchor,
x2 = xPlaced, y2 = yPlaced,
xloc = xloc.bar_index,
extend = extend.none,
style = line.style_dotted,
width = 2,
color = color.new(color.white, 0)
)
_lb := label.new(
x = xPlaced,
y = yPlaced,
text = _text,
xloc = xloc.bar_index,
yloc = yloc.price,
style = _style,
textcolor = _txtCol,
color = _bg,
size = size.small
)
if _bucket == "ENTRY_DN"
_coMark(_co_entry_dn_x, _co_entry_dn_y, _co_entry_dn_lb, _co_entry_dn_ln, xPlaced, yPlaced, _lb, _ln)
else if _bucket == "ENTRY_UP"
_coMark(_co_entry_up_x, _co_entry_up_y, _co_entry_up_lb, _co_entry_up_ln, xPlaced, yPlaced, _lb, _ln)
else if _bucket == "EXIT_UP"
_coMark(_co_exit_up_x, _co_exit_up_y, _co_exit_up_lb, _co_exit_up_ln, xPlaced, yPlaced, _lb, _ln)
else
_coMark(_co_exit_dn_x, _co_exit_dn_y, _co_exit_dn_lb, _co_exit_dn_ln, xPlaced, yPlaced, _lb, _ln)
_lb
//══════════════════════════════════════════════════════════════════════════════
// Trade object storage
//══════════════════════════════════════════════════════════════════════════════
var box[] closedProfitBoxes = array.new<box>()
var box[] closedRiskBoxes = array.new<box>()
var label[] tradeEntryLabels = array.new<label>()
var label[] tradeExitLabels = array.new<label>()
trimObjects() =>
while array.size(closedProfitBoxes) > recentTradesToDraw
_b = array.shift(closedProfitBoxes)
if not na(_b)
box.delete(_b)
while array.size(closedRiskBoxes) > recentTradesToDraw
_b = array.shift(closedRiskBoxes)
if not na(_b)
box.delete(_b)
while array.size(tradeEntryLabels) > recentTradesToDraw
_l = array.shift(tradeEntryLabels)
if not na(_l)
label.delete(_l)
while array.size(tradeExitLabels) > recentTradesToDraw
_l = array.shift(tradeExitLabels)
if not na(_l)
label.delete(_l)
//══════════════════════════════════════════════════════════════════════════════
// Active trade snapshots
//══════════════════════════════════════════════════════════════════════════════
var int activeDir = 0
var float activeEntryPrice = na
var float activeInitialSl = na
var float activeBaseTp = na
var float activeCurrentStop = na
var float activeCurrentTrail = na
var float activeRiskPrice = na
var float activeEntryDmi = na
var string activeEntryReason = ""
var int activeEntryBar = na
var int activeEntryTime = na
var bool trailArmed = false
var float trailExtreme = na
var string lastClosedReason = ""
var bool exitTriggeredByClose = false
var int lastPositionCloseBar = na
var float snapEntryPrice = na
var float snapInitialSl = na
var float snapBaseTp = na
var float snapEntryDmi = na
var int snapDir = 0
var int snapEntryBar = na
var box liveProfitBox = na
var box liveRiskBox = na
//══════════════════════════════════════════════════════════════════════════════
// Entry logic
//══════════════════════════════════════════════════════════════════════════════
entryPriceCandidate = close
maOkLong = useMaConfluence ? maBull : true
maOkShort = useMaConfluence ? maBear : true
magOkLong = useMinDmiMag ? dmiValue >= minDmiMag : true
magOkShort = useMinDmiMag ? dmiValue <= -minDmiMag : true
adxOk = useAdxFilter ? adxValue >= minAdx : true
blockOk = not blockActive
cooldownOk = not useReentryCooldown or na(lastPositionCloseBar) or (bar_index - lastPositionCloseBar > reentryCooldownBars)
bool enterLongNow = false
bool enterShortNow = false
float thisStop = na
float thisTp = na
string thisReason = ""
if entryReadyLong
float candidateStop = calcStopPrice(1, entryPriceCandidate, atrSeries)
float candidateTp = calcTpPrice(1, entryPriceCandidate, candidateStop, atrSeries)
stopPlacementOk = isValidStop(1, entryPriceCandidate, candidateStop)
tpPlacementOk = not na(candidateTp) and candidateTp > entryPriceCandidate
if not allowLong
pendingDir := 0
pendingHoldProgress := 0
pendingStartBar := na
setupReason := "Long trades disabled"
else if not blockOk
pendingDir := 0
pendingHoldProgress := 0
pendingStartBar := na
setupReason := "Long entry blocked by active time block"
else if not maOkLong
pendingDir := 0
pendingHoldProgress := 0
pendingStartBar := na
setupReason := "Long entry blocked — MAs not bullishly stacked"
else if not magOkLong
pendingDir := 0
pendingHoldProgress := 0
pendingStartBar := na
setupReason := "Long entry blocked — DMI magnitude too weak"
else if not adxOk
pendingDir := 0
pendingHoldProgress := 0
pendingStartBar := na
setupReason := "Long entry blocked — ADX below threshold"
else if na(candidateStop)
pendingDir := 0
pendingHoldProgress := 0
pendingStartBar := na
setupReason := "Long entry blocked — stop unavailable"
else if not stopPlacementOk
pendingDir := 0
pendingHoldProgress := 0
pendingStartBar := na
setupReason := "Long entry blocked — stop not below entry"
else if not tpPlacementOk
pendingDir := 0
pendingHoldProgress := 0
pendingStartBar := na
setupReason := "Long entry blocked — TP not above entry"
else if not cooldownOk
pendingDir := 0
pendingHoldProgress := 0
pendingStartBar := na
setupReason := "Long entry blocked — re-entry cooldown active"
else
enterLongNow := true
thisStop := candidateStop
thisTp := candidateTp
thisReason := "DMI cross + 0" + (holdBars > 0 ? " + hold " + str.tostring(holdBars) : "") + (useMaConfluence ? " + bullish MA stack" : "")
pendingDir := 0
pendingHoldProgress := 0
pendingStartBar := na
pendingCrossValue := na
setupReason := "Long entered"
if entryReadyShort
float candidateStop = calcStopPrice(-1, entryPriceCandidate, atrSeries)
float candidateTp = calcTpPrice(-1, entryPriceCandidate, candidateStop, atrSeries)
stopPlacementOk = isValidStop(-1, entryPriceCandidate, candidateStop)
tpPlacementOk = not na(candidateTp) and candidateTp < entryPriceCandidate
if not allowShort
pendingDir := 0
pendingHoldProgress := 0
pendingStartBar := na
setupReason := "Short trades disabled"
else if not blockOk
pendingDir := 0
pendingHoldProgress := 0
pendingStartBar := na
setupReason := "Short entry blocked by active time block"
else if not maOkShort
pendingDir := 0
pendingHoldProgress := 0
pendingStartBar := na
setupReason := "Short entry blocked — MAs not bearishly stacked"
else if not magOkShort
pendingDir := 0
pendingHoldProgress := 0
pendingStartBar := na
setupReason := "Short entry blocked — DMI magnitude too weak"
else if not adxOk
pendingDir := 0
pendingHoldProgress := 0
pendingStartBar := na
setupReason := "Short entry blocked — ADX below threshold"
else if na(candidateStop)
pendingDir := 0
pendingHoldProgress := 0
pendingStartBar := na
setupReason := "Short entry blocked — stop unavailable"
else if not stopPlacementOk
pendingDir := 0
pendingHoldProgress := 0
pendingStartBar := na
setupReason := "Short entry blocked — stop not above entry"
else if not tpPlacementOk
pendingDir := 0
pendingHoldProgress := 0
pendingStartBar := na
setupReason := "Short entry blocked — TP not below entry"
else if not cooldownOk
pendingDir := 0
pendingHoldProgress := 0
pendingStartBar := na
setupReason := "Short entry blocked — re-entry cooldown active"
else
enterShortNow := true
thisStop := candidateStop
thisTp := candidateTp
thisReason := "DMI cross - 0" + (holdBars > 0 ? " + hold " + str.tostring(holdBars) : "") + (useMaConfluence ? " + bearish MA stack" : "")
pendingDir := 0
pendingHoldProgress := 0
pendingStartBar := na
pendingCrossValue := na
setupReason := "Short entered"
// Quantity approximation
getQty() =>
float qty = 0.0
if sizeMode == "Cash"
qty := close != 0 ? strategy.convert_to_symbol(orderCash) / close : 0.0
else
qty := close != 0 ? strategy.convert_to_symbol(strategy.equity * orderPctEq / 100.0) / close : 0.0
qty
entryQty = getQty()
if enterLongNow and entryQty > 0
activeDir := 1
activeEntryPrice := close
activeInitialSl := thisStop
activeBaseTp := thisTp
activeCurrentStop := thisStop
activeCurrentTrail := na
activeRiskPrice := math.abs(activeEntryPrice - activeInitialSl)
activeEntryDmi := dmiValue
activeEntryReason := thisReason
activeEntryBar := bar_index
activeEntryTime := time
trailArmed := false
trailExtreme := na
exitTriggeredByClose := false
strategy.entry("Long", strategy.long, qty = entryQty)
if showTradeLabelsEff
tLong =
"LONG ENTRY\n" +
"Reason: " + activeEntryReason + "\n" +
"Entry: " + fmt(activeEntryPrice) + "\n" +
"DMI: " + fmt2(activeEntryDmi) + "\n" +
"SL: " + fmt(activeInitialSl) + "\n" +
"TP: " + fmt(activeBaseTp) + "\n" +
"Risk: " + fmt2(priceToUnits(activeRiskPrice, unitMode, pipSizeFX, pointSize)) + " " + (unitMode == "Pips (FX)" ? "pips" : unitMode == "Points" ? "pts" : "ticks")
_lb = makeCallout("ENTRY_DN", "DN", bar_index, low, tLong, entryInfoBg, label.style_label_up, entryInfoTxt)
array.push(tradeEntryLabels, _lb)
trimObjects()
if enterShortNow and entryQty > 0
activeDir := -1
activeEntryPrice := close
activeInitialSl := thisStop
activeBaseTp := thisTp
activeCurrentStop := thisStop
activeCurrentTrail := na
activeRiskPrice := math.abs(activeEntryPrice - activeInitialSl)
activeEntryDmi := dmiValue
activeEntryReason := thisReason
activeEntryBar := bar_index
activeEntryTime := time
trailArmed := false
trailExtreme := na
exitTriggeredByClose := false
strategy.entry("Short", strategy.short, qty = entryQty)
if showTradeLabelsEff
tShort =
"SHORT ENTRY\n" +
"Reason: " + activeEntryReason + "\n" +
"Entry: " + fmt(activeEntryPrice) + "\n" +
"DMI: " + fmt2(activeEntryDmi) + "\n" +
"SL: " + fmt(activeInitialSl) + "\n" +
"TP: " + fmt(activeBaseTp) + "\n" +
"Risk: " + fmt2(priceToUnits(activeRiskPrice, unitMode, pipSizeFX, pointSize)) + " " + (unitMode == "Pips (FX)" ? "pips" : unitMode == "Points" ? "pts" : "ticks")
_lb = makeCallout("ENTRY_DN", "DN", bar_index, low, tShort, entryInfoBg, label.style_label_up, entryInfoTxt)
array.push(tradeEntryLabels, _lb)
trimObjects()
//══════════════════════════════════════════════════════════════════════════════
// Position sync
//══════════════════════════════════════════════════════════════════════════════
if newPositionOpened
activeEntryPrice := strategy.position_avg_price
activeRiskPrice := not na(activeInitialSl) ? math.abs(activeEntryPrice - activeInitialSl) : na
if activeDir == 0
activeDir := pos > 0 ? 1 : pos < 0 ? -1 : 0
if flat
trailArmed := false
trailExtreme := na
activeCurrentTrail := na
//══════════════════════════════════════════════════════════════════════════════
// Live trade management
//══════════════════════════════════════════════════════════════════════════════
lastClosedReason := bar_index > 0 ? lastClosedReason[1] : ""
if pos != 0
tpTouched = inLong ? high >= activeBaseTp : low <= activeBaseTp
if enableTrailing
if not trailArmed and tpTouched
trailArmed := true
trailExtreme := inLong ? high : low
if trailArmed
if inLong
trailExtreme := math.max(nz(trailExtreme, high), high)
if inShort
trailExtreme := math.min(nz(trailExtreme, low), low)
float rawTrail = na
if trailMode == "Fixed Units / Pips"
_dist = unitToPrice(trailFixedUnits, unitMode, pipSizeFX, pointSize)
rawTrail := inLong ? trailExtreme - _dist : trailExtreme + _dist
else if trailMode == "Percent"
_dist = activeEntryPrice * (trailPct / 100.0)
rawTrail := inLong ? trailExtreme - _dist : trailExtreme + _dist
else if trailMode == "ATR"
_dist = atrSeries * trailAtrMult
rawTrail := inLong ? trailExtreme - _dist : trailExtreme + _dist
else if trailMode == "Bottom/Top of Last X Candles"
rawTrail := inLong ? lowestLowTrail : highestHighTrail
else
rawTrail := inLong ? lowestOcTrail : highestOcTrail
protectFloor = protectFloorMode == "Base TP Level" ? activeBaseTp : (inLong ? activeEntryPrice + unitToPrice(breakevenOffsetUnits, unitMode, pipSizeFX, pointSize) : activeEntryPrice - unitToPrice(breakevenOffsetUnits, unitMode, pipSizeFX, pointSize))
activeCurrentTrail := inLong ? math.max(rawTrail, protectFloor) : math.min(rawTrail, protectFloor)
activeCurrentStop := activeCurrentTrail
else
activeCurrentStop := activeInitialSl
activeCurrentTrail := na
else
activeCurrentStop := activeInitialSl
activeCurrentTrail := na
// Pre-infer likely exit reason
if pos != 0 and flattenInBlock and blockActive
lastClosedReason := "Blocked window exit"
else if pos != 0 and closeOnOppCross and ((inLong and dmiBearCross) or (inShort and dmiBullCross))
lastClosedReason := "Opposite DMI zero-line cross exit"
else if pos != 0 and closeOnDmiWeaken and ((inLong and dmiLongWeak) or (inShort and dmiShortWeak))
lastClosedReason := "DMI weakened exit"
else if pos != 0 and ((inLong and dmiLongMagnitudeExit) or (inShort and dmiShortMagnitudeExit))
lastClosedReason := "DMI magnitude target exit"
else if pos != 0 and enableTrailing and trailArmed and ((inLong and low <= activeCurrentStop) or (inShort and high >= activeCurrentStop))
lastClosedReason := "Trailing exit"
else if pos != 0 and ((inLong and low <= activeCurrentStop) or (inShort and high >= activeCurrentStop))
lastClosedReason := "Stop-loss exit"
else if pos != 0 and not enableTrailing and ((inLong and high >= activeBaseTp) or (inShort and low <= activeBaseTp))
lastClosedReason := "Take-profit exit"
// Apply exits
longExitReady =
inLong and
not na(activeCurrentStop) and
(enableTrailing or not na(activeBaseTp))
shortExitReady =
inShort and
not na(activeCurrentStop) and
(enableTrailing or not na(activeBaseTp))
if inLong
if flattenInBlock and blockActive
exitTriggeredByClose := true
strategy.close("Long", immediately = true)
else if closeOnOppCross and dmiBearCross
exitTriggeredByClose := true
strategy.close("Long", immediately = true)
else if closeOnDmiWeaken and dmiLongWeak
exitTriggeredByClose := true
strategy.close("Long", immediately = true)
else if dmiLongMagnitudeExit
exitTriggeredByClose := true
strategy.close("Long", immediately = true)
else if longExitReady
strategy.exit("Long-X", from_entry = "Long", stop = activeCurrentStop, limit = enableTrailing ? na : activeBaseTp)
else
lastClosedReason := "Emergency close — invalid long exit state"
strategy.close("Long", immediately = true)
if inShort
if flattenInBlock and blockActive
exitTriggeredByClose := true
strategy.close("Short", immediately = true)
else if closeOnOppCross and dmiBullCross
exitTriggeredByClose := true
strategy.close("Short", immediately = true)
else if closeOnDmiWeaken and dmiShortWeak
exitTriggeredByClose := true
strategy.close("Short", immediately = true)
else if dmiShortMagnitudeExit
exitTriggeredByClose := true
strategy.close("Short", immediately = true)
else if shortExitReady
strategy.exit("Short-X", from_entry = "Short", stop = activeCurrentStop, limit = enableTrailing ? na : activeBaseTp)
else
lastClosedReason := "Emergency close — invalid short exit state"
strategy.close("Short", immediately = true)
//══════════════════════════════════════════════════════════════════════════════
// Closed trade handling
//══════════════════════════════════════════════════════════════════════════════
if positionClosed
lastPositionCloseBar := bar_index
snapEntryPrice := activeEntryPrice
snapInitialSl := activeInitialSl
snapBaseTp := activeBaseTp
snapEntryDmi := activeEntryDmi
snapDir := activeDir
snapEntryBar := activeEntryBar
idx = strategy.closedtrades - 1
if idx >= 0
exitPrice = strategy.closedtrades.exit_price(idx)
plCash = strategy.closedtrades.profit(idx)
plPct = strategy.closedtrades.profit_percent(idx)
if showTradeBoxesEff
box profitBox = na
box riskBox = na
if snapDir == 1
profitBox := box.new(left = snapEntryBar, top = snapBaseTp, right = bar_index, bottom = snapEntryPrice, border_color = color.new(color.green, 0), bgcolor = color.new(color.green, 82))
riskBox := box.new(left = snapEntryBar, top = snapEntryPrice, right = bar_index, bottom = snapInitialSl, border_color = color.new(color.red, 0), bgcolor = color.new(color.red, 84))
else if snapDir == -1
profitBox := box.new(left = snapEntryBar, top = snapEntryPrice, right = bar_index, bottom = snapBaseTp, border_color = color.new(color.green, 0), bgcolor = color.new(color.green, 82))
riskBox := box.new(left = snapEntryBar, top = snapInitialSl, right = bar_index, bottom = snapEntryPrice, border_color = color.new(color.red, 0), bgcolor = color.new(color.red, 84))
array.push(closedProfitBoxes, profitBox)
array.push(closedRiskBoxes, riskBox)
if showTradeLabelsEff
txt =
dirTxt(snapDir) + " CLOSED\n" +
"Entry: " + fmt(snapEntryPrice) + "\n" +
"Exit: " + fmt(exitPrice) + "\n" +
"Init SL: " + fmt(snapInitialSl) + "\n" +
"Base TP: " + fmt(snapBaseTp) + "\n" +
"P/L: " + fmt2(plCash) + "\n" +
"P/L %: " + fmt2(plPct) + "%\n" +
"Reason: " + lastClosedReason
exitBg = plCash >= 0 ? exitWinBg : exitLossBg
_lb = makeCallout("EXIT_UP", "UP", bar_index, exitPrice, txt, exitBg, label.style_label_down, exitTxtCol)
array.push(tradeExitLabels, _lb)
trimObjects()
activeDir := 0
activeEntryPrice := na
activeInitialSl := na
activeBaseTp := na
activeCurrentStop := na
activeCurrentTrail := na
activeRiskPrice := na
activeEntryDmi := na
activeEntryReason := ""
activeEntryBar := na
activeEntryTime := na
trailArmed := false
trailExtreme := na
exitTriggeredByClose := false
//══════════════════════════════════════════════════════════════════════════════
// Live lines + live box
//══════════════════════════════════════════════════════════════════════════════
liveEntryPlot = showLiveLinesEff and pos != 0 ? activeEntryPrice : na
liveStopPlot = showLiveLinesEff and pos != 0 ? activeCurrentStop : na
liveTpPlot = showLiveLinesEff and pos != 0 ? activeBaseTp : na
liveTrailPlot = showLiveLinesEff and pos != 0 and enableTrailing and trailArmed ? activeCurrentTrail : na
plot(liveEntryPlot, "Active Entry", color.new(color.white, 0), 2, plot.style_linebr)
plot(liveStopPlot, "Active Stop", color.new(color.red, 0), 2, plot.style_linebr)
plot(liveTpPlot, "Active TP", color.new(color.lime, 0), 2, plot.style_linebr)
plot(liveTrailPlot, "Active Trail", color.new(color.orange, 0), 2, plot.style_linebr)
if showLiveTradeBoxEff and pos != 0 and not na(activeEntryTime)
int leftTime = activeEntryTime
int rightTime = time
if na(liveProfitBox)
liveProfitBox := box.new(leftTime, math.max(activeEntryPrice, activeBaseTp), rightTime, math.min(activeEntryPrice, activeBaseTp), xloc = xloc.bar_time, border_color = color.new(color.green, 0), bgcolor = color.new(color.green, 85))
if na(liveRiskBox)
liveRiskBox := box.new(leftTime, math.max(activeEntryPrice, activeInitialSl), rightTime, math.min(activeEntryPrice, activeInitialSl), xloc = xloc.bar_time, border_color = color.new(color.red, 0), bgcolor = color.new(color.red, 85))
if activeDir == 1
box.set_lefttop(liveProfitBox, leftTime, activeBaseTp)
box.set_rightbottom(liveProfitBox, rightTime, activeEntryPrice)
box.set_lefttop(liveRiskBox, leftTime, activeEntryPrice)
box.set_rightbottom(liveRiskBox, rightTime, activeInitialSl)
else if activeDir == -1
box.set_lefttop(liveProfitBox, leftTime, activeEntryPrice)
box.set_rightbottom(liveProfitBox, rightTime, activeBaseTp)
box.set_lefttop(liveRiskBox, leftTime, activeInitialSl)
box.set_rightbottom(liveRiskBox, rightTime, activeEntryPrice)
else
if not na(liveProfitBox)
box.delete(liveProfitBox)
liveProfitBox := na
if not na(liveRiskBox)
box.delete(liveRiskBox)
liveRiskBox := na
//══════════════════════════════════════════════════════════════════════════════
// Plots / markers
//══════════════════════════════════════════════════════════════════════════════
plot(showMaPlotsEff ? ma1 : na, "MA1", ma1Color, 2)
plot(showMaPlotsEff ? ma2 : na, "MA2", ma2Color, 2)
plot(showMaPlotsEff and maCount >= 3 ? ma3 : na, "MA3", ma3Color, 2)
plot(showMaPlotsEff and maCount >= 4 ? ma4 : na, "MA4", ma4Color, 2)
plot(showMaPlotsEff and maCount >= 5 ? ma5 : na, "MA5", ma5Color, 2)
if showDmiMarkersEff and dmiBullCross
label.new(
bar_index,
low,
"DMI↑0\n" + fmt2(dmiValue),
xloc = xloc.bar_index,
yloc = yloc.belowbar,
style = label.style_label_up,
color = color.new(color.lime, 0),
textcolor = color.black,
size = size.tiny
)
if showDmiMarkersEff and dmiBearCross
label.new(
bar_index,
high,
"DMI↓0\n" + fmt2(dmiValue),
xloc = xloc.bar_index,
yloc = yloc.abovebar,
style = label.style_label_down,
color = color.new(color.red, 0),
textcolor = color.white,
size = size.tiny
)
//══════════════════════════════════════════════════════════════════════════════
// Help Panel
//══════════════════════════════════════════════════════════════════════════════
var table helpTbl = na
if barstate.islast
if showHelpPanelEff
if na(helpTbl)
helpTbl := table.new(position.middle_center, 1, 1, border_width = 1)
helpText =
"DMI ZERO-CROSS + MA CONFLUENCE STRATEGY\n\n" +
"HOW IT WORKS\n" +
"• The strategy waits for a fresh zero-line cross in the modified DMI.\n" +
"• Longs need a confirmed cross from below 0 to above 0.\n" +
"• Shorts need a confirmed cross from above 0 to below 0.\n" +
"• If Hold Bars > 0, the DMI must stay on that side for the required extra confirmed bars before entry is evaluated.\n" +
"• Optional filters can then check minimum DMI magnitude, ADX strength, and bullish/bearish MA stacking.\n" +
"• Only one trade can be open at a time. No pyramiding.\n\n" +
"EXITS\n" +
"• SL modes: Signal Bar Offset, Fixed Units/Pips, Percent, ATR.\n" +
"• TP modes: R:R, Fixed Units/Pips, Percent, ATR, Signal Bar Range Extension.\n" +
"• Optional trailing activates only after the base TP is touched.\n" +
"• Optional opposite-cross exit can immediately close an open trade.\n" +
"• Optional weakened-DMI exit can close a trade before the opposite zero-line cross.\n" +
"• Optional DMI magnitude exit can close at a chosen DMI threshold.\n\n" +
"IMPORTANT DMI NOTE\n" +
"• Please also add the separate indicator: 'DMI Modified' by dman103.\n" +
"• In TradingView: Indicators → search for 'DMI Modified' → add the script by dman103 to your chart.\n" +
"• This strategy calculates the same modified DMI logic internally for trading, but the separate indicator is still recommended for the dedicated visual pane and proper reference.\n" +
"• Credit and shoutout to dman103 for the DMI Modified indicator concept.\n\n" +
"NON-REPAINTING DESIGN\n" +
"• Bar-close confirmation only.\n" +
"• No intrabar signal dependency.\n" +
"• Entry is only allowed from a fresh confirmed zero-line cross, not from DMI simply remaining above/below 0.\n\n" +
"TIME BLOCKS\n" +
"• Default behavior blocks new entries only.\n" +
"• Optional mode can also close open trades immediately during blocked windows.\n\n" +
"TIP\n" +
"• Review this panel once, then turn it off for a cleaner chart."
table.cell(helpTbl, 0, 0, helpText, text_color = helpTxt, bgcolor = helpBg)
else
if not na(helpTbl)
table.delete(helpTbl)
helpTbl := na
//══════════════════════════════════════════════════════════════════════════════
// Status Panel
//══════════════════════════════════════════════════════════════════════════════
var table statusTbl = na
if barstate.islast
if showStatusPanelEff
if na(statusTbl)
statusTbl := table.new(tablePosFromString(statusPos), 2, 5, border_width = 1)
else
table.set_position(statusTbl, tablePosFromString(statusPos))
stateRow = pos != 0 ? "IN TRADE" : pendingDir == 0 ? "WAITING" : "SETUP"
dirRow = pos != 0 ? dirTxt(activeDir) : pendingDir == 1 ? "LONG" : pendingDir == -1 ? "SHORT" : "NONE"
trailRow = pos != 0 ? (enableTrailing ? (trailArmed ? "ACTIVE" : "ARMED") : "OFF") : "n/a"
blockRow = boolTxt(blockActive)
pricesRow = pos != 0 ? fmt(activeEntryPrice) + " / " + fmt(activeCurrentStop) + " / " + fmt(activeBaseTp) : "n/a"
dmiRow = closeOnDmiMagnitude ? fmt2(dmiValue) + " / " + fmt2(dmiMagnitudeLevel) : fmt2(dmiValue)
table.cell(statusTbl, 0, 0, "State", text_color = statusTxt, bgcolor = statusBg)
table.cell(statusTbl, 1, 0, stateRow, text_color = statusTxt, bgcolor = statusBg)
table.cell(statusTbl, 0, 1, "Direction", text_color = statusTxt, bgcolor = statusBg)
table.cell(statusTbl, 1, 1, dirRow, text_color = statusTxt, bgcolor = statusBg)
table.cell(statusTbl, 0, 2, "DMI", text_color = statusTxt, bgcolor = statusBg)
table.cell(statusTbl, 1, 2, dmiRow, text_color = statusTxt, bgcolor = statusBg)
table.cell(statusTbl, 0, 3, "Entry / SL / TP", text_color = statusTxt, bgcolor = statusBg)
table.cell(statusTbl, 1, 3, pricesRow, text_color = statusTxt, bgcolor = statusBg)
table.cell(statusTbl, 0, 4, "Trail / Blocked", text_color = statusTxt, bgcolor = statusBg)
table.cell(statusTbl, 1, 4, trailRow + " / " + blockRow, text_color = statusTxt, bgcolor = statusBg)
else
if not na(statusTbl)
table.delete(statusTbl)
statusTbl := na
//══════════════════════════════════════════════════════════════════════════════
// Alerts
//══════════════════════════════════════════════════════════════════════════════
if enterLongNow
alert("DMI strategy long entry", alert.freq_once_per_bar_close)
if enterShortNow
alert("DMI strategy short entry", alert.freq_once_per_bar_close)
if positionClosed and snapDir == 1
alert("DMI strategy long exit", alert.freq_once_per_bar_close)
if positionClosed and snapDir == -1
alert("DMI strategy short exit", alert.freq_once_per_bar_close)
if pos != 0 and flattenInBlock and blockActive
alert("DMI strategy forced exit due to active time block", alert.freq_once_per_bar_close)