本页源码来自 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
// The five-pivot HH / HL / LH / LL classification follows the open-source "Higher High Lower Low Strategy (With Source Code)" by LonesomeTheBlue. Credit to the original author.
//@version=6
strategy(
title = "HH-HL / LL-LH Structure + MA Confluence Strategy",
shorttitle = "HH-HL/LL-LH + MA Confluence 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,
default_qty_type = strategy.cash,
default_qty_value = 10000,
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 = 200
)
//──────────────────────────────────────────────────────────────────────────────
// Utilities
//──────────────────────────────────────────────────────────────────────────────
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)
=> na
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)
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
fmt(_x) =>
str.tostring(_x, format.mintick)
dirTxt(_dir) =>
_dir == 1 ? "LONG" : _dir == -1 ? "SHORT" : "FLAT"
//──────────────────────────────────────────────────────────────────────────────
// INPUTS
//──────────────────────────────────────────────────────────────────────────────
// 1) HELP / STATUS
helpGroup = "📘 Help / Status"
showHelpPanel = input.bool(
false,
"Show centered help panel",
group = helpGroup,
tooltip = "Displays a centered overview of how the strategy works. Turn this off after reviewing it if you want a cleaner chart."
)
helpBg = input.color(
color.new(#000000, 0),
"Help panel background",
group = helpGroup,
tooltip = "Background color of the centered help panel."
)
helpTxt = input.color(
color.white,
"Help panel text color",
group = helpGroup,
tooltip = "Text color of the centered help panel."
)
showStatusPanel = input.bool(
true,
"Show compact live status panel",
group = helpGroup,
tooltip = "Shows the current setup state or live trade-management state in the chosen chart corner."
)
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 appears."
)
statusBg = input.color(
color.new(color.black, 30),
"Status panel background",
group = helpGroup,
tooltip = "Background color of the compact live status panel."
)
statusTxt = input.color(
color.rgb(9, 255, 0),
"Status panel text color",
group = helpGroup,
tooltip = "Text color used in the compact live status panel. Default is bright green."
)
// 2) TRADE DIRECTION
modeGroup = "🧭 Trade Direction"
tradeDirection = input.string(
"Both",
"Allowed trade direction",
options = ["Both", "Long Only", "Short Only"],
group = modeGroup,
tooltip = "Choose whether the strategy can take long trades, short trades, or both."
)
orderCash = input.float(
10000,
"Order size ($ cash)",
minval = 0,
step = 50,
group = modeGroup,
tooltip = "Cash size used for each trade. This strategy is single-entry only and does not scale in."
)
// 3) UNITS
unitGroup = "📐 Units"
unitMode = input.string(
"Pips (FX)",
"Unit mode",
options = ["Pips (FX)", "Ticks", "Points"],
group = unitGroup,
tooltip = "Choose how distance settings are measured. For USDJPY, pips are typically the most natural choice. (0.01 lot size is = to $1000 trade size and requires $50 in account for a 20:1 leverage)"
)
pipSizeFX = input.float(
0.01,
"Pip size (FX)",
minval = 0.00001,
step = 0.00001,
group = unitGroup,
tooltip = "The size of one pip. Default 0.01 is appropriate for many JPY forex pairs like USDJPY."
)
pointSize = input.float(
0.01,
"Point size",
minval = 0.00001,
step = 0.00001,
group = unitGroup,
tooltip = "Used only when Unit mode = Points."
)
unitSize =
unitMode == "Pips (FX)" ? pipSizeFX :
unitMode == "Points" ? pointSize :
syminfo.mintick
// 4) SIGNAL SOURCE TF
tfGroup = "🕒 Signal Source TF"
signalTfMode = input.string(
"Current Chart",
"Structure signal timeframe",
options = ["Current Chart", "Higher TF"],
group = tfGroup,
tooltip = "Choose whether HH/HL/LH/LL structure comes from the current chart timeframe or a higher timeframe."
)
signalHtfLabel = input.string(
"1 hour",
"Higher TF for structure",
options = [
"1 second",
"1 minute",
"5 minute",
"10 minute",
"15 minute",
"30 minute",
"1 hour",
"4 hour",
"6 hour",
"8 hour",
"12 hour",
"1 day",
"1 week",
"1 month"
],
group = tfGroup,
tooltip = "Used only when Structure signal timeframe = Higher TF."
)
signalHtf =
signalHtfLabel == "1 second" ? "1S" :
signalHtfLabel == "1 minute" ? "1" :
signalHtfLabel == "5 minute" ? "5" :
signalHtfLabel == "10 minute" ? "10" :
signalHtfLabel == "15 minute" ? "15" :
signalHtfLabel == "30 minute" ? "30" :
signalHtfLabel == "1 hour" ? "60" :
signalHtfLabel == "4 hour" ? "240" :
signalHtfLabel == "6 hour" ? "360" :
signalHtfLabel == "8 hour" ? "480" :
signalHtfLabel == "12 hour" ? "720" :
signalHtfLabel == "1 day" ? "D" :
signalHtfLabel == "1 week" ? "W" :
"M"
// 5) HH/HL / LL/LH LOGIC
structGroup = "🏗️ HH/HL / LL/LH Logic"
leftBarsLtf = input.int(
25,
"Left bars (current TF)",
minval = 1,
group = structGroup,
tooltip = "Pivot left strength used on the current chart timeframe. Larger values create more significant but slower pivot confirmations."
)
rightBarsLtf = input.int(
25,
"Right bars (current TF)",
minval = 1,
group = structGroup,
tooltip = "Pivot right strength used on the current chart timeframe. This also controls the confirmation delay of pivots."
)
leftBarsHtf = input.int(
25,
"Left bars (HTF)",
minval = 1,
group = structGroup,
tooltip = "Pivot left strength used when structure is sourced from the higher timeframe."
)
rightBarsHtf = input.int(
25,
"Right bars (HTF)",
minval = 1,
group = structGroup,
tooltip = "Pivot right strength used when structure is sourced from the higher timeframe."
)
maxBarsFirstToSecond = input.int(
0,
"Max bars from 1st signal to 2nd signal (0 = off)",
minval = 0,
group = structGroup,
tooltip = "Optional timeout for a setup. Example: if HH appears but HL does not confirm within this many bars, the setup resets."
)
minEntryDistToFirstPivotUnits = input.float(
3.0,
"Min entry distance from HH/LL (units)",
minval = 0,
step = 0.1,
group = structGroup,
tooltip = "Invalidates entries that occur too close to the first pivot anchor. Longs require enough room below the HH; shorts require enough room above the LL."
)
// 6) MA CONFLUENCE
maGroup = "📈 MA Confluence"
useMaConfluence = input.bool(
true,
"Use MA stack confluence",
group = maGroup,
tooltip = "When enabled, the second structure signal must confirm while the chosen moving averages are properly stacked. If they are crossed or out of order at that moment, the setup is invalid."
)
maTfMode = input.string(
"Current Chart",
"MA logic timeframe",
options = ["Current Chart", "Higher TF"],
group = maGroup,
tooltip = "Choose whether MA stacking is evaluated on the current chart timeframe or a separate higher timeframe."
)
maHtf = input.timeframe(
"60",
"Higher TF for MAs",
group = maGroup,
tooltip = "Used only when MA logic timeframe = Higher TF."
)
maSource = input.source(
close,
"MA source",
group = maGroup,
tooltip = "Shared source used for all moving averages."
)
maCount = input.int(
4,
"Number of MAs",
minval = 2,
maxval = 5,
group = maGroup,
tooltip = "Minimum 2, maximum 5. All active MAs must be strictly stacked with no crossing for a valid MA-confluence setup."
)
ma1Type = input.string("EMA", "MA #1", options = ["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA"], group = maGroup, inline = "ma1", tooltip = "Type for MA #1. Usually the fastest MA.")
ma1Len = input.int(20, "", minval = 1, group = maGroup, inline = "ma1", tooltip = "Length for MA #1.")
ma1Color = input.color(color.new(#f6c309, 0), "", group = maGroup, inline = "ma1", tooltip = "Color for MA #1.")
ma2Type = input.string("EMA", "MA #2", options = ["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA"], 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(#fb9800, 0), "", group = maGroup, inline = "ma2", tooltip = "Color for MA #2.")
ma3Type = input.string("EMA", "MA #3", options = ["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA"], 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(color.blue, 0), "", group = maGroup, inline = "ma3", tooltip = "Color for MA #3.")
ma4Type = input.string("EMA", "MA #4", options = ["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA"], 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(color.green, 0), "", group = maGroup, inline = "ma4", tooltip = "Color for MA #4.")
ma5Type = input.string("EMA", "MA #5", options = ["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA"], 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(color.red, 0), "", group = maGroup, inline = "ma5", tooltip = "Color for MA #5.")
// 7) ENTRY RULES
entryGroup = "✅ Entry Rules"
useMinStopDistance = input.bool(
false,
"Use minimum stop distance filter",
group = entryGroup,
tooltip = "Optional safety filter. If enabled, trades are invalid when the stop distance from entry is too small."
)
minStopDistanceUnits = input.float(
1.0,
"Minimum stop distance (units)",
minval = 0,
step = 0.1,
group = entryGroup,
tooltip = "Used only when the minimum stop distance filter is enabled."
)
// 8) STOP LOSS
slGroup = "🛑 Stop Loss"
slMode = input.string(
"Signal Pivot Offset",
"Stop-loss mode",
options = ["Signal Pivot Offset", "Fixed Units / Pips", "Percent", "ATR", "Recent Swing"],
group = slGroup,
tooltip = "Choose how the stop-loss is calculated."
)
slSignalOffsetUnits = input.float(
3.0,
"Signal pivot offset (units)",
minval = 0,
step = 0.1,
group = slGroup,
tooltip = "For longs: X units below the HL wick low. For shorts: X units above the LH wick high."
)
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 and take-profit calculations."
)
slAtrMult = input.float(
1.0,
"ATR stop multiplier",
minval = 0.1,
step = 0.1,
group = slGroup,
tooltip = "Used when Stop-loss mode = ATR."
)
swingLookback = input.int(
20,
"Recent swing lookback",
minval = 1,
group = slGroup,
tooltip = "Used when Stop-loss mode = Recent Swing."
)
swingBufferUnits = input.float(
0.0,
"Recent swing buffer (units)",
minval = 0,
step = 0.1,
group = slGroup,
tooltip = "Extra buffer added beyond the recent swing stop level."
)
// 9) TAKE PROFIT
tpGroup = "🎯 Take Profit"
tpMode = input.string(
"Signal Pivot Offset",
"Take-profit mode",
options = ["Signal Pivot Offset", "Fixed Units / Pips", "Percent", "ATR", "Risk:Reward"],
group = tpGroup,
tooltip = "Choose how the base take-profit is calculated. When trailing is enabled, this TP becomes the trail activation threshold."
)
tpSignalOffsetUnits = input.float(
10.0,
"Signal pivot offset (units)",
minval = 0,
step = 0.1,
group = tpGroup,
tooltip = "For longs: X units above the HH wick high. For shorts: X units below the LL wick low."
)
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.5,
"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."
)
rrMultiple = input.float(
2.0,
"Risk:Reward multiple",
minval = 0.1,
step = 0.1,
group = tpGroup,
tooltip = "Used when Take-profit mode = Risk:Reward. TP = entry plus/minus risk distance × this multiple."
)
// 10) TRAILING
trailGroup = "🏃 Trailing"
enableTrailing = input.bool(
false,
"Enable trailing after TP is touched",
group = trailGroup,
tooltip = "When enabled, the base TP becomes the trail activation threshold instead of a hard limit target. After activation, the trail cannot move back beyond the TP threshold."
)
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 = "Choose how the trailing stop moves after the base TP is 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.2,
"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. Longs trail from the bottom/lowest OC of the last X candles. Shorts trail from the top/highest OC of the last X candles."
)
// 11) OPTIMIZER MODE
optGroup = "⚡ Optimizer"
optimizerMode = input.bool(
false,
"Enable optimizer mode (hide visual objects)",
group = optGroup,
tooltip = "Turns off labels, lines, boxes, tables, MA plots, structure markers, and other chart visuals so optimization runs with less chart clutter and overhead."
)
// 12) VISUALS
visGroup = "🎨 Visuals"
showCurrentTfMarkers = input.bool(true, "Show current-TF HH/HL/LH/LL markers", group = visGroup, tooltip = "Plots current chart timeframe structure labels and confirmation labels.")
showHtfMarkers = input.bool(true, "Show HTF HH/HL/LH/LL markers", group = visGroup, tooltip = "Plots higher-timeframe structure labels and confirmation labels when HTF events occur.")
showMaPlots = input.bool(true, "Show MA ribbon", group = visGroup, tooltip = "Plots the active MA ribbon used for MA-confluence validation.")
showTradeLabels = input.bool(true, "Show recent trade labels", group = visGroup, tooltip = "Draws detailed labels for recent closed trades.")
showTradeBoxes = input.bool(true, "Show recent trade risk/reward boxes", group = visGroup, tooltip = "Draws custom forecast-style boxes for the most recent closed trades.")
recentTradesToDraw = input.int(30, "Max recent trades to draw", minval = 1, maxval = 30, group = visGroup, tooltip = "Maximum number of recent closed trades to keep drawn on the chart.")
showLiveLines = input.bool(true, "Show active-trade lines", group = visGroup, tooltip = "Plots live entry, stop, target, and trailing lines while a trade is open.")
// 13) LABEL CALLOUTS
calloutGroup = "🧷 Label Callouts"
useCallouts = input.bool(true, "Offset trade callouts from price", group = calloutGroup, tooltip = "Moves trade info labels away from candles so they are easier to read.")
drawCalloutLines = input.bool(true, "Draw dotted connector lines", group = calloutGroup, tooltip = "Draws dotted lines from price to the offset callout labels.")
calloutXBars = input.int(2, "Callout X offset (bars)", minval = 0, maxval = 50, group = calloutGroup, tooltip = "How many bars to the right the callout label should be placed.")
calloutBaseAtr = input.float(7.0, "Base separation from price (ATR)", step = 0.1, group = calloutGroup, tooltip = "Base distance between the price anchor and the callout label.")
calloutStepAtr = input.float(1.2, "Vertical stack step (ATR)", step = 0.1, group = calloutGroup, tooltip = "Extra spacing used when multiple labels cluster together.")
calloutDetectAtr = input.float(0.35, "Detect overlap distance (ATR)", step = 0.05, group = calloutGroup, tooltip = "How close labels can be before the script stacks them.")
calloutDetectBars = input.int(8, "Detect overlap within X bars", minval = 0, maxval = 100, group = calloutGroup, tooltip = "Bar window used to detect nearby labels for stacking.")
calloutMaxStack = input.int(12, "Max stacked callouts per cluster", minval = 1, maxval = 50, group = calloutGroup, tooltip = "Maximum number of stacked labels allowed in a cluster.")
calloutMemory = input.int(250, "Callout memory", minval = 50, maxval = 2000, group = calloutGroup, tooltip = "How many historical callout placements to keep in memory.")
entryInfoBg = input.color(color.new(color.black, 25), "Entry label background", group = calloutGroup, tooltip = "Background color of entry callout labels.")
entryInfoTxt = input.color(color.rgb(0, 255, 13), "Entry label text", group = calloutGroup, tooltip = "Text color of entry callout labels.")
exitWinBg = input.color(color.new(color.lime, 35), "Winning exit label background", group = calloutGroup, tooltip = "Background color for profitable 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 closed-trade callout labels.")
// 14) 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 no-new-entry 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. Optional mode will also close any open trade while a block window is active."
)
w1En = input.bool(false, "Block #1", group = blockGroup, inline = "w1", tooltip = "Enable or 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(false, "Block #2", group = blockGroup, inline = "w2", tooltip = "Enable or disable time block #2.")
w2St = input.string("00:00", "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("00:00", "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 or 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.")
//──────────────────────────────────────────────────────────────────────────────
// Effective visual toggles
//──────────────────────────────────────────────────────────────────────────────
showHelpPanelEff = showHelpPanel and not optimizerMode
showStatusPanelEff = showStatusPanel and not optimizerMode
showCurrentTfMarkersEff = showCurrentTfMarkers and not optimizerMode
showHtfMarkersEff = showHtfMarkers and not optimizerMode
showMaPlotsEff = showMaPlots and not optimizerMode
showTradeLabelsEff = showTradeLabels and not optimizerMode
showTradeBoxesEff = showTradeBoxes and not optimizerMode
showLiveLinesEff = showLiveLines and not optimizerMode
useCalloutsEff = useCallouts and not optimizerMode
drawCalloutLinesEff = drawCalloutLines and not optimizerMode
showReadinessDotsEff = not optimizerMode
//──────────────────────────────────────────────────────────────────────────────
// Current TF structure engine
//──────────────────────────────────────────────────────────────────────────────
ph = ta.pivothigh(leftBarsLtf, rightBarsLtf)
pl = ta.pivotlow(leftBarsLtf, rightBarsLtf)
int dirNew = na
float valNew = na
dirNew := not na(ph) ? 1 : not na(pl) ? -1 : na
valNew := not na(ph) ? ph : not na(pl) ? pl : na
var int d0 = na
var int d1 = na
var int d2 = na
var int d3 = na
var int d4 = na
var float p0 = na
var float p1 = na
var float p2 = na
var float p3 = na
var float p4 = na
bool newPivotAccepted = false
if not na(dirNew) and not na(valNew)
if na(d0)
d0 := dirNew
p0 := valNew
newPivotAccepted := true
else
if dirNew == d0
bool moreExtreme = dirNew == 1 ? (valNew > p0) : (valNew < p0)
if moreExtreme
p0 := valNew
newPivotAccepted := true
else
d4 := d3
p4 := p3
d3 := d2
p3 := p2
d2 := d1
p2 := p1
d1 := d0
p1 := p0
d0 := dirNew
p0 := valNew
newPivotAccepted := true
a = p0
b = p1
c = p2
d = p3
e = p4
have5 = not na(a) and not na(b) and not na(c) and not na(d) and not na(e)
ltfHh = newPivotAccepted and have5 and (a > b and a > c and c > b and c > d)
ltfLl = newPivotAccepted and have5 and (a < b and a < c and c < b and c < d)
ltfHl = newPivotAccepted and have5 and ((a >= c and (b > c and b > d and d > c and d > e)) or (a < b and a > c and b < d))
ltfLh = newPivotAccepted and have5 and ((a <= c and (b < c and b < d and d < c and d < e)) or (a > b and a < c and b > d))
ltfEventType = ltfHh ? 1 : ltfHl ? 2 : ltfLh ? 3 : ltfLl ? 4 : 0
ltfEventPrice = ltfEventType != 0 ? p0 : na
ltfEventTime = ltfEventType != 0 ? time[rightBarsLtf] : na
plotshape(showCurrentTfMarkersEff and ltfHl, title = "HL (LTF)", style = shape.labelup, location = location.belowbar, offset = -rightBarsLtf, color = color.lime, text = "HL", textcolor = color.rgb(0, 0, 0), size = size.tiny)
plotshape(showCurrentTfMarkersEff and ltfHh, title = "HH (LTF)", style = shape.labeldown, location = location.abovebar, offset = -rightBarsLtf, color = color.lime, text = "HH", textcolor = color.rgb(0, 0, 0), size = size.tiny)
plotshape(showCurrentTfMarkersEff and ltfLh, title = "LH (LTF)", style = shape.labeldown, location = location.abovebar, offset = -rightBarsLtf, color = color.red, text = "LH", textcolor = color.white, size = size.tiny)
plotshape(showCurrentTfMarkersEff and ltfLl, title = "LL (LTF)", style = shape.labelup, location = location.belowbar, offset = -rightBarsLtf, color = color.red, text = "LL", textcolor = color.white, size = size.tiny)
if showCurrentTfMarkersEff and ltfHh
label.new(bar_index, high, "+" + str.tostring(rightBarsLtf), style = label.style_label_down, color = color.new(color.lime, 0), textcolor = color.rgb(0, 0, 0), size = size.tiny)
if showCurrentTfMarkersEff and ltfHl
label.new(bar_index, low, "+" + str.tostring(rightBarsLtf), style = label.style_label_up, color = color.new(color.lime, 0), textcolor = color.rgb(0, 0, 0), size = size.tiny)
if showCurrentTfMarkersEff and ltfLh
label.new(bar_index, high, "+" + str.tostring(rightBarsLtf), style = label.style_label_down, color = color.new(color.red, 0), textcolor = color.white, size = size.tiny)
if showCurrentTfMarkersEff and ltfLl
label.new(bar_index, low, "+" + str.tostring(rightBarsLtf), style = label.style_label_up, color = color.new(color.red, 0), textcolor = color.white, size = size.tiny)
//──────────────────────────────────────────────────────────────────────────────
// HTF structure engine
//──────────────────────────────────────────────────────────────────────────────
fHtfEventType() =>
_ph = ta.pivothigh(leftBarsHtf, rightBarsHtf)
_pl = ta.pivotlow(leftBarsHtf, rightBarsHtf)
int _dirNew = na
float _valNew = na
_dirNew := not na(_ph) ? 1 : not na(_pl) ? -1 : na
_valNew := not na(_ph) ? _ph : not na(_pl) ? _pl : na
var int _d0 = na
var int _d1 = na
var int _d2 = na
var int _d3 = na
var int _d4 = na
var float _p0 = na
var float _p1 = na
var float _p2 = na
var float _p3 = na
var float _p4 = na
bool _newAcc = false
if not na(_dirNew) and not na(_valNew)
if na(_d0)
_d0 := _dirNew
_p0 := _valNew
_newAcc := true
else
if _dirNew == _d0
bool _moreExtreme = _dirNew == 1 ? (_valNew > _p0) : (_valNew < _p0)
if _moreExtreme
_p0 := _valNew
_newAcc := true
else
_d4 := _d3
_p4 := _p3
_d3 := _d2
_p3 := _p2
_d2 := _d1
_p2 := _p1
_d1 := _d0
_p1 := _p0
_d0 := _dirNew
_p0 := _valNew
_newAcc := true
_a = _p0
_b = _p1
_c = _p2
_d = _p3
_e = _p4
_have5 = not na(_a) and not na(_b) and not na(_c) and not na(_d) and not na(_e)
_hh = _newAcc and _have5 and (_a > _b and _a > _c and _c > _b and _c > _d)
_ll = _newAcc and _have5 and (_a < _b and _a < _c and _c < _b and _c < _d)
_hl = _newAcc and _have5 and ((_a >= _c and (_b > _c and _b > _d and _d > _c and _d > _e)) or (_a < _b and _a > _c and _b < _d))
_lh = _newAcc and _have5 and ((_a <= _c and (_b < _c and _b < _d and _d < _c and _d < _e)) or (_a > _b and _a < _c and _b > _d))
_hh ? 1 : _hl ? 2 : _lh ? 3 : _ll ? 4 : 0
fHtfPivotTime() =>
_et = fHtfEventType()
_et != 0 ? time[rightBarsHtf] : na
fHtfPivotPrice() =>
_ph = ta.pivothigh(leftBarsHtf, rightBarsHtf)
_pl = ta.pivotlow(leftBarsHtf, rightBarsHtf)
_zz = not na(_ph) ? _ph : not na(_pl) ? _pl : na
_et = fHtfEventType()
_et != 0 ? _zz : na
htfEventType = request.security(syminfo.tickerid, signalHtf, fHtfEventType(), barmerge.gaps_off, barmerge.lookahead_off)
htfEventTime = request.security(syminfo.tickerid, signalHtf, fHtfPivotTime(), barmerge.gaps_off, barmerge.lookahead_off)
htfEventPrice = request.security(syminfo.tickerid, signalHtf, fHtfPivotPrice(), barmerge.gaps_off, barmerge.lookahead_off)
newHtfEvent = signalTfMode == "Higher TF" and htfEventType != 0 and not na(htfEventTime) and (htfEventTime != htfEventTime[1])
if showHtfMarkersEff and newHtfEvent and not na(htfEventPrice) and not na(htfEventTime)
string txt = htfEventType == 1 ? "HTF HH" : htfEventType == 2 ? "HTF HL" : htfEventType == 3 ? "HTF LH" : "HTF LL"
bool isUp = htfEventType == 2 or htfEventType == 4
color bg = htfEventType == 1 or htfEventType == 2 ? color.new(color.lime, 60) : color.new(color.red, 60)
color tc = htfEventType == 1 or htfEventType == 2 ? color.black : color.white
label.new(htfEventTime, htfEventPrice, txt, xloc = xloc.bar_time, yloc = yloc.price, style = isUp ? label.style_label_up : label.style_label_down, color = bg, textcolor = tc, size = size.tiny)
if showHtfMarkersEff and newHtfEvent
bool isUp2 = htfEventType == 2 or htfEventType == 4
float y2 = isUp2 ? low : high
label.new(bar_index, y2, "+" + str.tostring(rightBarsHtf), style = isUp2 ? label.style_label_up : label.style_label_down, color = (htfEventType == 1 or htfEventType == 2) ? color.new(color.lime, 50) : color.new(color.red, 50), textcolor = (htfEventType == 1 or htfEventType == 3) ? color.white : color.black, size = size.tiny)
//──────────────────────────────────────────────────────────────────────────────
// Signal source selection
//──────────────────────────────────────────────────────────────────────────────
sigEventType = signalTfMode == "Current Chart" ? ltfEventType : htfEventType
sigEventPrice = signalTfMode == "Current Chart" ? ltfEventPrice : htfEventPrice
sigEventTime = signalTfMode == "Current Chart" ? ltfEventTime : htfEventTime
sigNew = signalTfMode == "Current Chart" ? (ltfEventType != 0) : newHtfEvent
//──────────────────────────────────────────────────────────────────────────────
// MA logic
//──────────────────────────────────────────────────────────────────────────────
maTf = maTfMode == "Current Chart" ? timeframe.period : maHtf
ma1 = request.security(syminfo.tickerid, maTf, maCalc(maSource, ma1Len, ma1Type), barmerge.gaps_off, barmerge.lookahead_off)
ma2 = request.security(syminfo.tickerid, maTf, maCalc(maSource, ma2Len, ma2Type), barmerge.gaps_off, barmerge.lookahead_off)
ma3 = request.security(syminfo.tickerid, maTf, maCalc(maSource, ma3Len, ma3Type), barmerge.gaps_off, barmerge.lookahead_off)
ma4 = request.security(syminfo.tickerid, maTf, maCalc(maSource, ma4Len, ma4Type), barmerge.gaps_off, barmerge.lookahead_off)
ma5 = request.security(syminfo.tickerid, maTf, maCalc(maSource, ma5Len, ma5Type), barmerge.gaps_off, barmerge.lookahead_off)
atrSeries = ta.atr(slAtrLen)
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)
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)
//──────────────────────────────────────────────────────────────────────────────
// 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"
//──────────────────────────────────────────────────────────────────────────────
// Callout engine
//──────────────────────────────────────────────────────────────────────────────
var int[] _co_up_x = array.new<int>()
var float[] _co_up_y = array.new<float>()
var label[] _co_up_lb = array.new<label>()
var line[] _co_up_ln = array.new<line>()
var int[] _co_dn_x = array.new<int>()
var float[] _co_dn_y = array.new<float>()
var label[] _co_dn_lb = array.new<label>()
var line[] _co_dn_ln = array.new<line>()
_coEnsureSpace(_xs, _ys, _lbs, _lns) =>
while array.size(_xs) >= calloutMemory
array.shift(_xs)
array.shift(_ys)
label _oldLb = array.shift(_lbs)
if not na(_oldLb)
label.delete(_oldLb)
line _oldLn = array.shift(_lns)
if not na(_oldLn)
line.delete(_oldLn)
_coCount(_xs, _ys, _x0, _y0, _barsWin, _yThresh) =>
int n = math.min(array.size(_xs), array.size(_ys))
if n <= 0
0
else
int cnt = 0
for i = 0 to n - 1
int xi = array.get(_xs, i)
float yi = array.get(_ys, i)
bool nearX = math.abs(xi - _x0) <= _barsWin
bool nearY = math.abs(yi - _y0) <= _yThresh
if nearX and nearY
cnt += 1
cnt
_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(_dir, _xAnchor, _yAnchor, _text, _bg, _style, _txtCol) =>
if optimizerMode
na
else
float yThresh = atrSeries * calloutDetectAtr
float step = atrSeries * calloutStepAtr
float baseSep = atrSeries * calloutBaseAtr
int barsWin = calloutDetectBars
bool doOffset = useCalloutsEff
int cnt = 0
if doOffset
if _dir == "UP"
cnt := _coCount(_co_up_x, _co_up_y, _xAnchor, _yAnchor, barsWin, yThresh)
else
cnt := _coCount(_co_dn_x, _co_dn_y, _xAnchor, _yAnchor, barsWin, yThresh)
cnt := math.min(cnt, calloutMaxStack)
int xPlaced = doOffset ? (_xAnchor + calloutXBars) : _xAnchor
float yPlaced = na
if doOffset
if _dir == "UP"
yPlaced := _yAnchor + baseSep + (cnt * step)
else
yPlaced := _yAnchor - baseSep - (cnt * step)
else
yPlaced := _yAnchor
if _dir == "UP"
_coEnsureSpace(_co_up_x, _co_up_y, _co_up_lb, _co_up_ln)
else
_coEnsureSpace(_co_dn_x, _co_dn_y, _co_dn_lb, _co_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)
)
label 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 _dir == "UP"
_coMark(_co_up_x, _co_up_y, _co_up_lb, _co_up_ln, xPlaced, yPlaced, lb, ln)
else
_coMark(_co_dn_x, _co_dn_y, _co_dn_lb, _co_dn_ln, xPlaced, yPlaced, lb, ln)
lb
//──────────────────────────────────────────────────────────────────────────────
// 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
allowLong = tradeDirection == "Both" or tradeDirection == "Long Only"
allowShort = tradeDirection == "Both" or tradeDirection == "Short Only"
//──────────────────────────────────────────────────────────────────────────────
// Setup state machine
//──────────────────────────────────────────────────────────────────────────────
var int setupSide = 0
var int setupStep = 0
var float firstPivotPrice = na
var float secondPivotPrice = na
var int firstSignalBar = na
var string setupReason = "Waiting for first signal"
//──────────────────────────────────────────────────────────────────────────────
// Active trade snapshots
//──────────────────────────────────────────────────────────────────────────────
var int activeDir = 0
var string activeEntryReason = ""
var float activeEntryPrice = na
var float activeInitialSl = na
var float activeBaseTp = na
var float activeCurrentStop = na
var float activeCurrentTrail = na
var float activeFirstPivot = na
var float activeSecondPivot = na
var int activeEntryBar = na
var bool trailArmed = false
var float trailExtreme = na
var string lastClosedReason = ""
var float snapEntryPrice = na
var float snapInitialSl = na
var float snapBaseTp = na
var int snapDir = 0
var int snapEntryBar = na
//──────────────────────────────────────────────────────────────────────────────
// Trade drawing storage
//──────────────────────────────────────────────────────────────────────────────
var box[] profitBoxes = array.new<box>()
var box[] riskBoxes = array.new<box>()
trimBoxes() =>
while array.size(profitBoxes) > recentTradesToDraw
box _pb = array.shift(profitBoxes)
if not na(_pb)
box.delete(_pb)
while array.size(riskBoxes) > recentTradesToDraw
box _rb = array.shift(riskBoxes)
if not na(_rb)
box.delete(_rb)
//──────────────────────────────────────────────────────────────────────────────
// Entry / exit helpers
//──────────────────────────────────────────────────────────────────────────────
calcStopPrice(_dir, _entryPrice, _secondPivot, _atrNow) =>
float _out = na
if slMode == "Signal Pivot Offset"
_out := _dir == 1 ? (_secondPivot - slSignalOffsetUnits * unitSize) : (_secondPivot + slSignalOffsetUnits * unitSize)
else if slMode == "Fixed Units / Pips"
_dist = slFixedUnits * unitSize
_out := _dir == 1 ? (_entryPrice - _dist) : (_entryPrice + _dist)
else if slMode == "Percent"
_dist = _entryPrice * (slPct / 100.0)
_out := _dir == 1 ? (_entryPrice - _dist) : (_entryPrice + _dist)
else if slMode == "ATR"
_dist = _atrNow * slAtrMult
_out := _dir == 1 ? (_entryPrice - _dist) : (_entryPrice + _dist)
else
_out := _dir == 1 ? (ta.lowest(low, swingLookback) - swingBufferUnits * unitSize) : (ta.highest(high, swingLookback) + swingBufferUnits * unitSize)
_out
calcTpPrice(_dir, _entryPrice, _firstPivot, _stopPrice, _atrNow) =>
float _out = na
if tpMode == "Signal Pivot Offset"
_out := _dir == 1 ? (_firstPivot + tpSignalOffsetUnits * unitSize) : (_firstPivot - tpSignalOffsetUnits * unitSize)
else if tpMode == "Fixed Units / Pips"
_dist = tpFixedUnits * unitSize
_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
_risk = math.abs(_entryPrice - _stopPrice)
_out := _dir == 1 ? (_entryPrice + _risk * rrMultiple) : (_entryPrice - _risk * rrMultiple)
_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)
//──────────────────────────────────────────────────────────────────────────────
// Setup timeout
//──────────────────────────────────────────────────────────────────────────────
if flat and setupStep == 1 and maxBarsFirstToSecond > 0 and not na(firstSignalBar)
if (bar_index - firstSignalBar) > maxBarsFirstToSecond
setupSide := 0
setupStep := 0
firstPivotPrice := na
secondPivotPrice := na
firstSignalBar := na
setupReason := "Setup timed out before second signal"
//──────────────────────────────────────────────────────────────────────────────
// Setup processing + entries
//──────────────────────────────────────────────────────────────────────────────
bool enterLongNow = false
bool enterShortNow = false
string thisEntryReason = ""
float thisStop = na
float thisTp = na
float thisEntry = close
float setupFirstPivotSnapshot = na
float setupSecondPivotSnapshot = na
if flat and sigNew and sigEventType != 0
if sigEventType == 1
setupSide := 1
setupStep := 1
firstPivotPrice := sigEventPrice
secondPivotPrice := na
firstSignalBar := bar_index
setupReason := "HH confirmed — waiting for HL"
else if sigEventType == 4
setupSide := -1
setupStep := 1
firstPivotPrice := sigEventPrice
secondPivotPrice := na
firstSignalBar := bar_index
setupReason := "LL confirmed — waiting for LH"
else
if setupSide == 1 and sigEventType == 3
setupSide := 0
setupStep := 0
firstPivotPrice := na
secondPivotPrice := na
firstSignalBar := na
setupReason := "Long setup invalidated by opposite second signal"
else if setupSide == -1 and sigEventType == 2
setupSide := 0
setupStep := 0
firstPivotPrice := na
secondPivotPrice := na
firstSignalBar := na
setupReason := "Short setup invalidated by opposite second signal"
if setupStep == 1 and setupSide == 1 and sigEventType == 2
secondPivotPrice := sigEventPrice
float candidateStop = calcStopPrice(1, thisEntry, secondPivotPrice, atrSeries)
float candidateTp = calcTpPrice(1, thisEntry, firstPivotPrice, candidateStop, atrSeries)
bool maOk = useMaConfluence ? maBull : true
bool dirOk = allowLong
bool blockOk = not blockActive
bool roomOk = (firstPivotPrice - thisEntry) >= (minEntryDistToFirstPivotUnits * unitSize)
bool stopDistanceOk = useMinStopDistance ? ((thisEntry - candidateStop) >= (minStopDistanceUnits * unitSize)) : true
bool stopPlacementOk = candidateStop < thisEntry
bool tpPlacementOk = candidateTp > thisEntry
if not dirOk
setupSide := 0
setupStep := 0
firstPivotPrice := na
secondPivotPrice := na
firstSignalBar := na
setupReason := "Long trades disabled"
else if not maOk
setupSide := 0
setupStep := 0
firstPivotPrice := na
secondPivotPrice := na
firstSignalBar := na
setupReason := "HL confirmed but MAs not bullishly stacked"
else if not blockOk
setupSide := 0
setupStep := 0
firstPivotPrice := na
secondPivotPrice := na
firstSignalBar := na
setupReason := "Entry blocked by active time window"
else if not roomOk
setupSide := 0
setupStep := 0
firstPivotPrice := na
secondPivotPrice := na
firstSignalBar := na
setupReason := "Entry too close to HH anchor"
else if not stopDistanceOk
setupSide := 0
setupStep := 0
firstPivotPrice := na
secondPivotPrice := na
firstSignalBar := na
setupReason := "Stop distance too small"
else if not stopPlacementOk
setupSide := 0
setupStep := 0
firstPivotPrice := na
secondPivotPrice := na
firstSignalBar := na
setupReason := "Stop not below entry"
else if not tpPlacementOk
setupSide := 0
setupStep := 0
firstPivotPrice := na
secondPivotPrice := na
firstSignalBar := na
setupReason := "Take-profit not above entry"
else
enterLongNow := true
thisStop := candidateStop
thisTp := candidateTp
thisEntryReason := "HH → HL confirmed" + (useMaConfluence ? " + bullish MA stack" : "")
setupFirstPivotSnapshot := firstPivotPrice
setupSecondPivotSnapshot := secondPivotPrice
setupSide := 0
setupStep := 0
firstPivotPrice := na
secondPivotPrice := na
firstSignalBar := na
setupReason := "Long entered"
if setupStep == 1 and setupSide == -1 and sigEventType == 3
secondPivotPrice := sigEventPrice
float candidateStop = calcStopPrice(-1, thisEntry, secondPivotPrice, atrSeries)
float candidateTp = calcTpPrice(-1, thisEntry, firstPivotPrice, candidateStop, atrSeries)
bool maOk = useMaConfluence ? maBear : true
bool dirOk = allowShort
bool blockOk = not blockActive
bool roomOk = (thisEntry - firstPivotPrice) >= (minEntryDistToFirstPivotUnits * unitSize)
bool stopDistanceOk = useMinStopDistance ? ((candidateStop - thisEntry) >= (minStopDistanceUnits * unitSize)) : true
bool stopPlacementOk = candidateStop > thisEntry
bool tpPlacementOk = candidateTp < thisEntry
if not dirOk
setupSide := 0
setupStep := 0
firstPivotPrice := na
secondPivotPrice := na
firstSignalBar := na
setupReason := "Short trades disabled"
else if not maOk
setupSide := 0
setupStep := 0
firstPivotPrice := na
secondPivotPrice := na
firstSignalBar := na
setupReason := "LH confirmed but MAs not bearishly stacked"
else if not blockOk
setupSide := 0
setupStep := 0
firstPivotPrice := na
secondPivotPrice := na
firstSignalBar := na
setupReason := "Entry blocked by active time window"
else if not roomOk
setupSide := 0
setupStep := 0
firstPivotPrice := na
secondPivotPrice := na
firstSignalBar := na
setupReason := "Entry too close to LL anchor"
else if not stopDistanceOk
setupSide := 0
setupStep := 0
firstPivotPrice := na
secondPivotPrice := na
firstSignalBar := na
setupReason := "Stop distance too small"
else if not stopPlacementOk
setupSide := 0
setupStep := 0
firstPivotPrice := na
secondPivotPrice := na
firstSignalBar := na
setupReason := "Stop not above entry"
else if not tpPlacementOk
setupSide := 0
setupStep := 0
firstPivotPrice := na
secondPivotPrice := na
firstSignalBar := na
setupReason := "Take-profit not below entry"
else
enterShortNow := true
thisStop := candidateStop
thisTp := candidateTp
thisEntryReason := "LL → LH confirmed" + (useMaConfluence ? " + bearish MA stack" : "")
setupFirstPivotSnapshot := firstPivotPrice
setupSecondPivotSnapshot := secondPivotPrice
setupSide := 0
setupStep := 0
firstPivotPrice := na
secondPivotPrice := na
firstSignalBar := na
setupReason := "Short entered"
if enterLongNow and orderCash > 0
activeDir := 1
activeEntryReason := thisEntryReason
activeEntryPrice := close
activeInitialSl := thisStop
activeBaseTp := thisTp
activeCurrentStop := thisStop
activeCurrentTrail := na
activeFirstPivot := setupFirstPivotSnapshot
activeSecondPivot := setupSecondPivotSnapshot
activeEntryBar := bar_index
trailArmed := false
trailExtreme := na
strategy.entry("Long", strategy.long, qty = strategy.convert_to_symbol(orderCash) / close)
string tLong =
"LONG ENTRY\n" +
"Reason: " + activeEntryReason + "\n" +
"Entry: " + fmt(activeEntryPrice) + "\n" +
"SL: " + fmt(activeInitialSl) + "\n" +
"TP: " + fmt(activeBaseTp)
makeCallout("DN", bar_index, close, tLong, entryInfoBg, label.style_label_up, entryInfoTxt)
if enterShortNow and orderCash > 0
activeDir := -1
activeEntryReason := thisEntryReason
activeEntryPrice := close
activeInitialSl := thisStop
activeBaseTp := thisTp
activeCurrentStop := thisStop
activeCurrentTrail := na
activeFirstPivot := setupFirstPivotSnapshot
activeSecondPivot := setupSecondPivotSnapshot
activeEntryBar := bar_index
trailArmed := false
trailExtreme := na
strategy.entry("Short", strategy.short, qty = strategy.convert_to_symbol(orderCash) / close)
string tShort =
"SHORT ENTRY\n" +
"Reason: " + activeEntryReason + "\n" +
"Entry: " + fmt(activeEntryPrice) + "\n" +
"SL: " + fmt(activeInitialSl) + "\n" +
"TP: " + fmt(activeBaseTp)
makeCallout("DN", bar_index, close, tShort, entryInfoBg, label.style_label_down, entryInfoTxt)
//──────────────────────────────────────────────────────────────────────────────
// Live trade management
//──────────────────────────────────────────────────────────────────────────────
if newPositionOpened
activeEntryPrice := strategy.position_avg_price
if flat
trailArmed := false
trailExtreme := na
activeCurrentTrail := na
if pos != 0
if enableTrailing
bool tpTouched = inLong ? (high >= activeBaseTp) : (low <= activeBaseTp)
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 = trailFixedUnits * unitSize
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
activeCurrentTrail := inLong ? math.max(rawTrail, activeBaseTp) : math.min(rawTrail, activeBaseTp)
activeCurrentStop := activeCurrentTrail
else
activeCurrentStop := activeInitialSl
activeCurrentTrail := na
else
activeCurrentStop := activeInitialSl
activeCurrentTrail := na
//──────────────────────────────────────────────────────────────────────────────
// Exit reason pre-inference
//──────────────────────────────────────────────────────────────────────────────
lastClosedReason := bar_index > 0 ? lastClosedReason[1] : ""
if pos != 0 and flattenInBlock and blockActive
lastClosedReason := "Blocked window 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
//──────────────────────────────────────────────────────────────────────────────
if inLong
if flattenInBlock and blockActive
strategy.close("Long", immediately = true)
else
strategy.exit("Long-X", from_entry = "Long", stop = activeCurrentStop, limit = enableTrailing ? na : activeBaseTp)
if inShort
if flattenInBlock and blockActive
strategy.close("Short", immediately = true)
else
strategy.exit("Short-X", from_entry = "Short", stop = activeCurrentStop, limit = enableTrailing ? na : activeBaseTp)
//──────────────────────────────────────────────────────────────────────────────
// Closed trade handling
//──────────────────────────────────────────────────────────────────────────────
if positionClosed
snapEntryPrice := activeEntryPrice
snapInitialSl := activeInitialSl
snapBaseTp := activeBaseTp
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(profitBoxes, profitBox)
array.push(riskBoxes, riskBox)
trimBoxes()
if showTradeLabelsEff
string 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: " + str.tostring(plCash, "#.##") + "\n" +
"P/L %: " + str.tostring(plPct, "#.##") + "%\n" +
"Reason: " + lastClosedReason
color exitBg = plCash >= 0 ? exitWinBg : exitLossBg
makeCallout("UP", bar_index, exitPrice, txt, exitBg, label.style_label_down, exitTxtCol)
activeDir := 0
activeEntryReason := ""
activeEntryPrice := na
activeInitialSl := na
activeBaseTp := na
activeCurrentStop := na
activeCurrentTrail := na
activeFirstPivot := na
activeSecondPivot := na
activeEntryBar := na
trailArmed := false
trailExtreme := na
//──────────────────────────────────────────────────────────────────────────────
// Live lines
//──────────────────────────────────────────────────────────────────────────────
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)
//──────────────────────────────────────────────────────────────────────────────
// Center 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)
string helpText =
"STRUCTURE + MA STRATEGY\n\n" +
"LONG PREMISE\n" +
"• Wait for HH to confirm.\n" +
"• Then wait for HL to confirm.\n" +
"• On the bar where HL confirms, the trade is taken at the close only if the MA stack is valid (unless MA confluence is disabled).\n" +
"• If MAs are crossed / not properly stacked at HL confirmation, the setup is invalid immediately and resets.\n\n" +
"SHORT PREMISE\n" +
"• Wait for LL to confirm.\n" +
"• Then wait for LH to confirm.\n" +
"• On the bar where LH confirms, the trade is taken at the close only if the MA stack is valid (unless MA confluence is disabled).\n" +
"• If MAs are crossed / not properly stacked at LH confirmation, the setup is invalid immediately and resets.\n\n" +
"ANCHOR RULES\n" +
"• The newest HH or LL replaces the previous first anchor.\n" +
"• Long SL can be based below the HL wick low.\n" +
"• Short SL can be based above the LH wick high.\n" +
"• Long TP can be based above the HH wick high.\n" +
"• Short TP can be based below the LL wick low.\n" +
"• Trades are invalid if entry is too close to the HH/LL anchor.\n\n" +
"NON-REPAINTING DESIGN\n" +
"• Entries are evaluated only on confirmed bars.\n" +
"• HTF requests use lookahead-off logic.\n" +
"• No delayed entry after second-signal confirmation: it is either valid now or invalid now.\n\n" +
"TRAILING\n" +
"• If enabled, the base TP becomes a trail-activation threshold.\n" +
"• Once activated, the trailing stop cannot move back past the base TP threshold.\n\n" +
"TIME BLOCKS\n" +
"• Default behavior blocks new entries only.\n" +
"• Optional mode can also close current trades during blocked windows.\n\n" +
"TIP\n" +
"• Review this panel once, then turn it off in settings 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
//──────────────────────────────────────────────────────────────────────────────
// Compact live status panel
//──────────────────────────────────────────────────────────────────────────────
var table statusTbl = na
if barstate.islast
if showStatusPanelEff
if na(statusTbl)
statusTbl := table.new(tablePosFromString(statusPos), 2, 9, border_width = 1)
else
table.set_position(statusTbl, tablePosFromString(statusPos))
string stateRow = pos != 0 ? "IN TRADE" : setupStep == 0 ? "WAITING 1ST" : "WAITING 2ND"
string dirRow = pos != 0 ? dirTxt(activeDir) : setupSide == 1 ? "LONG SETUP" : setupSide == -1 ? "SHORT SETUP" : "NONE"
string reasonRow = pos != 0 ? activeEntryReason : setupReason
string blockRow = blockActive ? "YES" : "NO"
string trailRow = pos != 0 ? (enableTrailing ? (trailArmed ? "ACTIVE" : "ARM AT TP") : "OFF") : "n/a"
string maRow = useMaConfluence ? (setupSide == 1 ? (maBull ? "BULL READY" : "NOT READY") : setupSide == -1 ? (maBear ? "BEAR READY" : "NOT READY") : "WAIT") : "DISABLED"
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, "Reason", text_color = statusTxt, bgcolor = statusBg)
table.cell(statusTbl, 1, 2, reasonRow, text_color = statusTxt, bgcolor = statusBg)
table.cell(statusTbl, 0, 3, "Blocked", text_color = statusTxt, bgcolor = statusBg)
table.cell(statusTbl, 1, 3, blockRow, text_color = statusTxt, bgcolor = statusBg)
table.cell(statusTbl, 0, 4, "MA Gate", text_color = statusTxt, bgcolor = statusBg)
table.cell(statusTbl, 1, 4, maRow, text_color = statusTxt, bgcolor = statusBg)
table.cell(statusTbl, 0, 5, "Entry", text_color = statusTxt, bgcolor = statusBg)
table.cell(statusTbl, 1, 5, pos != 0 ? fmt(activeEntryPrice) : "n/a", text_color = statusTxt, bgcolor = statusBg)
table.cell(statusTbl, 0, 6, "SL", text_color = statusTxt, bgcolor = statusBg)
table.cell(statusTbl, 1, 6, pos != 0 ? fmt(activeCurrentStop) : "n/a", text_color = statusTxt, bgcolor = statusBg)
table.cell(statusTbl, 0, 7, "TP", text_color = statusTxt, bgcolor = statusBg)
table.cell(statusTbl, 1, 7, pos != 0 ? fmt(activeBaseTp) : "n/a", text_color = statusTxt, bgcolor = statusBg)
table.cell(statusTbl, 0, 8, "Trail", text_color = statusTxt, bgcolor = statusBg)
table.cell(statusTbl, 1, 8, trailRow, text_color = statusTxt, bgcolor = statusBg)
else
if not na(statusTbl)
table.delete(statusTbl)
statusTbl := na
//──────────────────────────────────────────────────────────────────────────────
// Tiny readiness dots
//──────────────────────────────────────────────────────────────────────────────
plotshape(showReadinessDotsEff and setupSide == 1 and setupStep == 1, title = "Waiting HL", style = shape.circle, location = location.bottom, color = color.new(color.lime, 0), textcolor = color.lime, size = size.tiny, text = "L")
plotshape(showReadinessDotsEff and setupSide == -1 and setupStep == 1, title = "Waiting LH", style = shape.circle, location = location.top, color = color.new(color.red, 0), textcolor = color.red, size = size.tiny, text = "S")