本页源码来自 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
//@version=6
strategy(
title = "Candlestick Momentum + MA Stack Strategy",
shorttitle = "Candle Momentum + 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
)
//══════════════════════════════════════════════════════════════════════════════
// Inputs
//══════════════════════════════════════════════════════════════════════════════
// 1) Help / Status
helpGroup = "📘 Help / Status"
showHelpPanel = input.bool(
false,
"Show centered help panel",
group = helpGroup,
tooltip = "Displays a startup help panel with a full summary of how the strategy works."
)
helpBg = input.color(
color.new(#000000, 0),
"Help panel background",
group = helpGroup,
tooltip = "Background color for the centered help panel."
)
helpTxt = input.color(
color.new(#2bff00, 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 strategy state, momentum state, MA state, and active trade prices."
)
statusPos = input.string(
"Top Right",
"Status panel position",
options = ["Top Right", "Top Left", "Bottom Right", "Bottom Left"],
group = helpGroup,
tooltip = "Choose where the live status panel is displayed."
)
statusBg = input.color(
color.new(#000000, 33),
"Status panel background",
group = helpGroup,
tooltip = "Background color for the live status panel. Default is black with heavy transparency."
)
statusTxt = input.color(
color.rgb(38, 255, 0),
"Status panel text color",
group = helpGroup,
tooltip = "Text color of the live status panel. Default is neon green."
)
// 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."
)
// 3) Position Sizing
sizeGroup = "💵 Position Sizing"
lotSize = input.float(
0.10,
"Lot size",
minval = 0.01,
step = 0.01,
group = sizeGroup,
tooltip = "Forex lot size. 0.10 = 10,000 units (mini lot). 1.00 = 100,000 units (standard lot)."
)
// 4) Pips / Units
unitGroup = "📐 Pips / Units"
unitSize = input.float(
0.01,
"1 Pip / Unit size",
minval = 0.00001,
step = 0.00001,
group = unitGroup,
tooltip = "Distance conversion used everywhere in the script. Default 0.01 is appropriate for USDJPY if you want 1 pip = 0.01. Side note: 0.01 lot size is often roughly equal to about $1,000 notional trade size and may require roughly $50+ account value at 20:1 leverage, depending on broker rules and margin requirements."
)
// 5) Entry: Momentum
entryGroup = "🚀 Entry: Momentum"
moveMode = input.string(
"Pips / Units",
"Movement measurement",
options = ["Pips / Units", "Percent"],
group = entryGroup,
tooltip = "Choose whether the required momentum move is measured in Pips / Units or as a percent move across the selected candle window."
)
requiredMoveUnits = input.float(
50.0,
"Required move (Pips / Units)",
minval = 0,
step = 0.1,
group = entryGroup,
tooltip = "Required movement across the selected candle window when Movement measurement = Pips / Units. (Please Note: This value should be changed based on the candlestick size being viewed)"
)
requiredMovePct = input.float(
2.00,
"Required move (%)",
minval = 0,
step = 0.01,
group = entryGroup,
tooltip = "Required movement across the selected candle window when Movement measurement = Percent. (Please Note: This value should be changed based on the candlestick size being viewed)"
)
moveCandles = input.int(
3,
"Candles in move window",
minval = 1,
maxval = 100,
group = entryGroup,
tooltip = "Number of consecutive completed candles used to evaluate the move."
)
priceMode = input.string(
"Body (Open to Close)",
"Price basis",
options = ["Body (Open to Close)", "Wicks (Low to High)"],
group = entryGroup,
tooltip = "Body mode measures movement from the first candle open to the last candle close. Wick mode measures directional wick movement from the first candle extreme to the last candle extreme."
)
gapMode = input.string(
"Include Gaps",
"Gap treatment",
options = ["Include Gaps", "Exclude Gaps"],
group = entryGroup,
tooltip = "Include Gaps uses the direct window endpoints. Exclude Gaps ignores jump discontinuities between candles and measures candle-by-candle internal movement instead."
)
candleDirMode = input.string(
"All Same Direction",
"Candle direction filter",
options = ["All Same Direction", "Mixed Allowed"],
group = entryGroup,
tooltip = "All Same Direction requires every candle in the move window to close in the signal direction. Mixed Allowed removes that filter."
)
useMovePerCandleFilter = input.bool(
false,
"Use minimum move-per-candle filter",
group = entryGroup,
tooltip = "Optional quality filter. Requires the average move per candle in the window to be at or above the selected minimum."
)
minMovePerCandleUnits = input.float(
10.0,
"Min move per candle (Pips / Units)",
minval = 0,
step = 0.1,
group = entryGroup,
tooltip = "Minimum average move per candle when the move-per-candle filter is enabled and Movement measurement = Pips / Units."
)
minMovePerCandlePct = input.float(
0.05,
"Min move per candle (%)",
minval = 0,
step = 0.01,
group = entryGroup,
tooltip = "Minimum average move per candle when the move-per-candle filter is enabled and Movement measurement = Percent."
)
// 6) MA Confluence
maGroup = "📈 MA Confluence"
useMaConfluence = input.bool(
false,
"Use MA stack confluence",
group = maGroup,
tooltip = "(Make sure you turn on the MA ribbon visuals in settings below if you want to use the MA ribbon filter) When enabled, entry is only allowed if the selected moving averages are stacked in the same direction on the signal bar close."
)
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(
"Lookback Structure",
"Stop-loss mode",
options = ["Lookback Structure", "Fixed Pips / Units", "Percent", "ATR"],
group = slGroup,
tooltip = "Choose how the stop-loss is calculated."
)
slLookback = input.int(
5,
"Structure lookback",
minval = 1,
maxval = 100,
group = slGroup,
tooltip = "Number of completed candles used by Lookback Structure stop-loss mode."
)
slStructureBasis = input.string(
"Wick",
"Structure basis",
options = ["Wick", "Open/Close"],
group = slGroup,
tooltip = "Wick uses highest high or lowest low from prior completed bars. Open/Close uses candle body extremes from prior completed bars."
)
slStructureBuffer = input.float(
2.0,
"Structure buffer (Pips / Units)",
minval = 0,
step = 0.1,
group = slGroup,
tooltip = "Extra distance added beyond the selected structure stop so the stop is not placed exactly on the structure point."
)
slFixedUnits = input.float(
15.0,
"Fixed stop (Pips / Units)",
minval = 0,
step = 0.1,
group = slGroup,
tooltip = "Used when Stop-loss mode = Fixed Pips / Units."
)
slPct = input.float(
0.20,
"Stop (%)",
minval = 0.01,
step = 0.01,
group = slGroup,
tooltip = "Used when Stop-loss mode = Percent."
)
atrLen = input.int(
14,
"ATR length",
minval = 1,
group = slGroup,
tooltip = "ATR length used by ATR-based stop, target, 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 Pips / Units", "Percent", "ATR"],
group = tpGroup,
tooltip = "Choose how the base take-profit is calculated. If trailing is enabled, this base TP becomes the activation level for the trailing logic."
)
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(
10.0,
"Fixed TP (Pips / Units)",
minval = 0,
step = 0.1,
group = tpGroup,
tooltip = "Simple fixed target from entry. Example: 10 means TP is 10 Pips / Units from entry."
)
tpPct = input.float(
0.30,
"TP (%)",
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."
)
// 9) Trailing
trailGroup = "🏃 Trailing"
enableTrailing = input.bool(
false,
"Enable trailing after base TP touch",
group = trailGroup,
tooltip = "When enabled, the base TP is no longer treated as a hard final exit. Instead, once price touches the base TP level, trailing is armed and the trade is managed by the selected trailing method."
)
trailMode = input.string(
"Fixed Pips / Units",
"Trailing mode",
options = ["Fixed Pips / Units", "Percent", "ATR", "Last X Wicks", "Last X Opens/Closes"],
group = trailGroup,
tooltip = "Trailing method used only after the base TP level has been touched."
)
trailFixedUnits = input.float(
5.0,
"Trail distance (Pips / Units)",
minval = 0,
step = 0.1,
group = trailGroup,
tooltip = "Used when Trailing mode = Fixed Pips / Units."
)
trailPct = input.float(
0.15,
"Trail distance (%)",
minval = 0.01,
step = 0.01,
group = trailGroup,
tooltip = "Used when Trailing mode = Percent."
)
trailAtrMult = input.float(
1.0,
"Trail ATR multiplier",
minval = 0.1,
step = 0.1,
group = trailGroup,
tooltip = "Used when Trailing mode = ATR."
)
trailLookback = input.int(
3,
"Trail lookback",
minval = 1,
maxval = 100,
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 level is touched, trailing can be prevented from moving back beyond either the base TP level or breakeven."
)
breakevenOffsetUnits = input.float(
0.0,
"Breakeven offset (Pips / Units)",
minval = 0,
step = 0.1,
group = trailGroup,
tooltip = "Used when Post-TP protection floor = Breakeven Level."
)
// 10) Re-entry Cooldown
reentryGroup = "🔁 Re-entry Cooldown"
useReentryCooldown = input.bool(
true,
"Use cooldown after 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 = 100,
group = reentryGroup,
tooltip = "Number of full bars to wait after a trade closes before another entry can be taken."
)
// 11) Visuals
visGroup = "🎨 Visuals"
// Box appearance
profitBoxColor = input.color(
color.new(color.green, 95),
"Profit Fill",
group = visGroup,
inline = "profitbox",
tooltip = "Fill color for profit portion of trade boxes."
)
profitBoxBorder = input.color(
color.new(color.green, 90),
"Border",
group = visGroup,
inline = "profitbox",
tooltip = "Border color for profit portion of trade boxes."
)
riskBoxColor = input.color(
color.new(color.red, 95),
"Risk Fill",
group = visGroup,
inline = "riskbox",
tooltip = "Fill color for risk portion of trade boxes."
)
riskBoxBorder = input.color(
color.new(color.red, 90),
"Border",
group = visGroup,
inline = "riskbox",
tooltip = "Border color for risk portion of trade boxes."
)
optimizerMode = input.bool(
false,
"Enable optimizer mode",
group = visGroup,
tooltip = "Aggressive low-clutter mode for optimization. Hides help panel, status panel, MA ribbon, labels, connector lines, trade boxes, and most chart objects."
)
showMaPlots = input.bool(
false,
"Show MA ribbon",
group = visGroup,
tooltip = "(Make sure you turn on the MA ribbon in settings above if you want to use the MA ribbon filter) 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 trade box while a position is open."
)
showTradeBoxes = input.bool(
true,
"Show recent trade boxes",
group = visGroup,
tooltip = "Draws historical red and green trade boxes for recent closed trades."
)
showTradeLabels = input.bool(
true,
"Show recent trade labels",
group = visGroup,
tooltip = "Shows entry labels below price and win/loss labels above price."
)
recentTradesToDraw = input.int(
20,
"Recent trades to keep",
minval = 0,
maxval = 50,
group = visGroup,
tooltip = "Maximum number of recent closed trades to keep plotted. 0 means plot nothing historically."
)
// 12) Label Callouts
calloutGroup = "🧷 Label Callouts"
useCallouts = input.bool(
true,
"Offset labels 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 labels."
)
calloutXBars = input.int(
2,
"Callout X offset (bars)",
minval = 0,
maxval = 50,
group = calloutGroup,
tooltip = "Horizontal label offset to the right, measured in bars."
)
entryYOffsetUnits = input.float(
100.0,
"Entry Y offset (Pips / Units)",
minval = 0,
step = 0.1,
group = calloutGroup,
tooltip = "Vertical offset used for entry labels below price."
)
exitYOffsetUnits = input.float(
100.0,
"Exit Y offset (Pips / Units)",
minval = 0,
step = 0.1,
group = calloutGroup,
tooltip = "Vertical offset used for win/loss labels above price."
)
entryInfoBg = input.color(
color.new(color.black, 10),
"Entry label background",
group = calloutGroup,
tooltip = "Background color for entry labels."
)
entryInfoTxt = input.color(
color.rgb(57, 255, 20),
"Entry label text",
group = calloutGroup,
tooltip = "Text color for entry labels."
)
exitWinBg = input.color(
color.new(color.green, 25),
"Winning exit label background",
group = calloutGroup,
tooltip = "Background color for winning exit labels."
)
exitLossBg = input.color(
color.new(color.red, 25),
"Losing exit label background",
group = calloutGroup,
tooltip = "Background color for losing exit labels."
)
exitTxtCol = input.color(
color.white,
"Exit label text",
group = calloutGroup,
tooltip = "Text color used on win/loss exit labels."
)
// 13) Alerts
alertGroup = "🔔 Alerts"
alertOnLongEntry = input.bool(false, "Long entry alert", group = alertGroup, tooltip = "Enable alert() call when a long entry is triggered.")
alertOnShortEntry = input.bool(false, "Short entry alert", group = alertGroup, tooltip = "Enable alert() call when a short entry is triggered.")
alertOnLongExit = input.bool(false, "Long exit alert", group = alertGroup, tooltip = "Enable alert() call when a long trade closes.")
alertOnShortExit = input.bool(false, "Short exit alert", group = alertGroup, tooltip = "Enable alert() call when a short trade closes.")
alertOnForcedBlockExit= input.bool(false, "Time block forced-exit alert", group = alertGroup, tooltip = "Enable alert() call when a time block forces an exit.")
alertOnTrailArm = input.bool(false, "Trailing armed alert", group = alertGroup, tooltip = "Enable alert() call when trailing becomes active after price touches the base TP.")
alertOnStopHit = input.bool(false, "Stop-loss style exit alert", group = alertGroup, tooltip = "Enable alert() call when the pre-inferred exit reason is stop-loss or trailing stop.")
alertOnTpHit = input.bool(false, "Take-profit style exit alert", group = alertGroup, tooltip = "Enable alert() call when the pre-inferred exit reason is take-profit.")
// 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", "Europe/Lisbon",
"Asia/Tokyo", "Asia/Hong_Kong", "Asia/Singapore",
"Australia/Sydney"
],
group = blockGroup,
tooltip = "Timezone used by all time blocks."
)
blockMode = input.string(
"Block new trades only",
"Block behavior",
options = ["Block new trades only", "Immediately exit current trades and block new trades"],
group = blockGroup,
tooltip = "Default blocks only new entries. The other option immediately exits any active trade and also blocks new trades while the time block is active."
)
w1En = input.bool(true, "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(true, "Block #2", group = blockGroup, inline = "w2", tooltip = "Enable or 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 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.")
//══════════════════════════════════════════════════════════════════════════════
// Utilities
//══════════════════════════════════════════════════════════════════════════════
fmt(_x) =>
str.tostring(_x, format.mintick)
fmt2(_x) =>
str.tostring(_x, "#.##")
boolTxt(_b) =>
_b ? "ON" : "OFF"
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)
unitToPrice(_units, _unitSize) =>
_units * _unitSize
priceToUnits(_dist, _unitSize) =>
_unitSize != 0 ? _dist / _unitSize : na
isBullBar(_i) =>
close[_i] > open[_i]
isBearBar(_i) =>
close[_i] < open[_i]
allBullishBars(_len) =>
_ok = true
for i = 0 to _len - 1
_ok := _ok and isBullBar(i)
_ok
allBearishBars(_len) =>
_ok = true
for i = 0 to _len - 1
_ok := _ok and isBearBar(i)
_ok
sumLongBodies(_len) =>
_sum = 0.0
for i = 0 to _len - 1
_sum += math.max(close[i] - open[i], 0)
_sum
sumShortBodies(_len) =>
_sum = 0.0
for i = 0 to _len - 1
_sum += math.max(open[i] - close[i], 0)
_sum
sumWickRanges(_len) =>
_sum = 0.0
for i = 0 to _len - 1
_sum += high[i] - low[i]
_sum
getWindowLowestLow(_len) =>
ta.lowest(low, _len)
getWindowHighestHigh(_len) =>
ta.highest(high, _len)
calcLongMovePrice(_bars, _priceMode, _gapMode) =>
float _out = na
int _first = _bars - 1
if bar_index >= _first
if _gapMode == "Include Gaps"
if _priceMode == "Body (Open to Close)"
_out := close - open[_first]
else
_out := getWindowHighestHigh(_bars) - low[_first]
else
if _priceMode == "Body (Open to Close)"
_out := sumLongBodies(_bars)
else
_out := sumWickRanges(_bars)
_out
calcShortMovePrice(_bars, _priceMode, _gapMode) =>
float _out = na
int _first = _bars - 1
if bar_index >= _first
if _gapMode == "Include Gaps"
if _priceMode == "Body (Open to Close)"
_out := open[_first] - close
else
_out := high[_first] - getWindowLowestLow(_bars)
else
if _priceMode == "Body (Open to Close)"
_out := sumShortBodies(_bars)
else
_out := sumWickRanges(_bars)
_out
calcLongMovePct(_bars, _priceMode, _gapMode) =>
float _out = na
int _first = _bars - 1
if bar_index >= _first
if _gapMode == "Include Gaps"
if _priceMode == "Body (Open to Close)"
_base = open[_first]
_out := _base != 0 ? ((close - _base) / _base) * 100.0 : na
else
_base = low[_first]
_move = getWindowHighestHigh(_bars) - _base
_out := _base != 0 ? (_move / _base) * 100.0 : na
else
if _priceMode == "Body (Open to Close)"
_base = open[_first]
_out := _base != 0 ? (sumLongBodies(_bars) / _base) * 100.0 : na
else
_base = low[_first]
_out := _base != 0 ? (sumWickRanges(_bars) / _base) * 100.0 : na
_out
calcShortMovePct(_bars, _priceMode, _gapMode) =>
float _out = na
int _first = _bars - 1
if bar_index >= _first
if _gapMode == "Include Gaps"
if _priceMode == "Body (Open to Close)"
_base = open[_first]
_out := _base != 0 ? ((_base - close) / _base) * 100.0 : na
else
_base = high[_first]
_move = _base - getWindowLowestLow(_bars)
_out := _base != 0 ? (_move / _base) * 100.0 : na
else
if _priceMode == "Body (Open to Close)"
_base = open[_first]
_out := _base != 0 ? (sumShortBodies(_bars) / _base) * 100.0 : na
else
_base = high[_first]
_out := _base != 0 ? (sumWickRanges(_bars) / _base) * 100.0 : na
_out
isValidStop(_dir, _entryPrice, _stopPrice) =>
not na(_stopPrice) and ((_dir == 1 and _stopPrice < _entryPrice) or (_dir == -1 and _stopPrice > _entryPrice))
getQty(_price) =>
lotSize * 100000
trimObjects(_profitBoxes, _riskBoxes, _entryLabels, _exitLabels, _calloutLines, _keep) =>
while array.size(_profitBoxes) > _keep
_b = array.shift(_profitBoxes)
if not na(_b)
box.delete(_b)
while array.size(_riskBoxes) > _keep
_b = array.shift(_riskBoxes)
if not na(_b)
box.delete(_b)
while array.size(_entryLabels) > _keep
_l = array.shift(_entryLabels)
if not na(_l)
label.delete(_l)
while array.size(_exitLabels) > _keep
_l = array.shift(_exitLabels)
if not na(_l)
label.delete(_l)
while array.size(_calloutLines) > _keep * 2
_ln = array.shift(_calloutLines)
if not na(_ln)
line.delete(_ln)
clearAllObjects(_profitBoxes, _riskBoxes, _entryLabels, _exitLabels, _calloutLines) =>
while array.size(_profitBoxes) > 0
_b = array.shift(_profitBoxes)
if not na(_b)
box.delete(_b)
while array.size(_riskBoxes) > 0
_b = array.shift(_riskBoxes)
if not na(_b)
box.delete(_b)
while array.size(_entryLabels) > 0
_l = array.shift(_entryLabels)
if not na(_l)
label.delete(_l)
while array.size(_exitLabels) > 0
_l = array.shift(_exitLabels)
if not na(_l)
label.delete(_l)
while array.size(_calloutLines) > 0
_ln = array.shift(_calloutLines)
if not na(_ln)
line.delete(_ln)
//══════════════════════════════════════════════════════════════════════════════
// 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 and recentTradesToDraw > 0
showTradeLabelsEff = showTradeLabels and not optimizerMode and recentTradesToDraw > 0
useCalloutsEff = useCallouts and not optimizerMode
drawCalloutLinesEff = drawCalloutLines and not optimizerMode
//══════════════════════════════════════════════════════════════════════════════
// Core Calculations
//══════════════════════════════════════════════════════════════════════════════
atrSeries = ta.atr(atrLen)
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)
blockActive =
inWindowHHMM(w1En, w1St, w1EnT, tzOpt) or
inWindowHHMM(w2En, w2St, w2EnT, tzOpt) or
inWindowHHMM(w3En, w3St, w3EnT, tzOpt)
flattenInBlock = blockMode == "Immediately exit current trades and block new trades"
allowLong = tradeDirection == "Both" or tradeDirection == "Long Only"
allowShort = tradeDirection == "Both" or tradeDirection == "Short Only"
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
enoughBars = bar_index >= moveCandles - 1
longMovePrice = calcLongMovePrice(moveCandles, priceMode, gapMode)
shortMovePrice = calcShortMovePrice(moveCandles, priceMode, gapMode)
longMovePct = calcLongMovePct(moveCandles, priceMode, gapMode)
shortMovePct = calcShortMovePct(moveCandles, priceMode, gapMode)
longMoveUnits = priceToUnits(longMovePrice, unitSize)
shortMoveUnits = priceToUnits(shortMovePrice, unitSize)
longMomentumTxt = "Momentum " + fmt2(longMoveUnits) + "u | " + fmt2(longMovePct) + "%"
shortMomentumTxt = "Momentum " + fmt2(shortMoveUnits) + "u | " + fmt2(shortMovePct) + "%"
reqMoveOkLong = moveMode == "Pips / Units" ? longMoveUnits >= requiredMoveUnits : longMovePct >= requiredMovePct
reqMoveOkShort = moveMode == "Pips / Units" ? shortMoveUnits >= requiredMoveUnits : shortMovePct >= requiredMovePct
avgMovePerCandleLong = moveMode == "Pips / Units" ? (longMoveUnits / moveCandles) : (longMovePct / moveCandles)
avgMovePerCandleShort = moveMode == "Pips / Units" ? (shortMoveUnits / moveCandles) : (shortMovePct / moveCandles)
minMoveFilterOkLong = not useMovePerCandleFilter or (moveMode == "Pips / Units" ? avgMovePerCandleLong >= minMovePerCandleUnits : avgMovePerCandleLong >= minMovePerCandlePct)
minMoveFilterOkShort = not useMovePerCandleFilter or (moveMode == "Pips / Units" ? avgMovePerCandleShort >= minMovePerCandleUnits : avgMovePerCandleShort >= minMovePerCandlePct)
dirFilterOkLong = candleDirMode == "Mixed Allowed" or allBullishBars(moveCandles)
dirFilterOkShort = candleDirMode == "Mixed Allowed" or allBearishBars(moveCandles)
rawLongSignal = enoughBars and reqMoveOkLong and dirFilterOkLong and minMoveFilterOkLong
rawShortSignal = enoughBars and reqMoveOkShort and dirFilterOkShort and minMoveFilterOkShort
maOkLong = useMaConfluence ? maBull : true
maOkShort = useMaConfluence ? maBear : true
blockOk = not blockActive
var int lastPositionCloseBar = na
cooldownOk = not useReentryCooldown or na(lastPositionCloseBar) or (bar_index - lastPositionCloseBar > reentryCooldownBars)
// Avoid simultaneous long and short entries on the same bar.
bothSignals = rawLongSignal and rawShortSignal
// Normal preference when one side is larger
preferLong = moveMode == "Pips / Units" ? longMoveUnits > shortMoveUnits : longMovePct > shortMovePct
preferShort = moveMode == "Pips / Units" ? shortMoveUnits > longMoveUnits : shortMovePct > longMovePct
// Tie-break for 1-candle wick mode:
// use candle direction so one candle cannot qualify as both directions with no winner.
wickOneBarTie = moveCandles == 1 and priceMode == "Wicks (Low to High)" and bothSignals
tieBreakLong = wickOneBarTie and close > open
tieBreakShort = wickOneBarTie and close < open
enterLongNow =
flat and allowLong and maOkLong and blockOk and cooldownOk and
(
(rawLongSignal and not rawShortSignal) or
(bothSignals and preferLong) or
tieBreakLong
)
enterShortNow =
flat and allowShort and maOkShort and blockOk and cooldownOk and
(
(rawShortSignal and not rawLongSignal) or
(bothSignals and preferShort) or
tieBreakShort
)
//══════════════════════════════════════════════════════════════════════════════
// Structure stop source series (must calculate on EVERY bar)
//══════════════════════════════════════════════════════════════════════════════
bodyLowSource = math.min(open[1], close[1])
bodyHighSource = math.max(open[1], close[1])
structureWickLowPrev = ta.lowest(low[1], slLookback)
structureWickHighPrev = ta.highest(high[1], slLookback)
structureBodyLowPrev = ta.lowest(bodyLowSource, slLookback)
structureBodyHighPrev = ta.highest(bodyHighSource, slLookback)
//══════════════════════════════════════════════════════════════════════════════
// Stop / TP Helpers
//══════════════════════════════════════════════════════════════════════════════
calcStructureStop(_dir) =>
_buffer = unitToPrice(slStructureBuffer, unitSize)
float _out = na
if slStructureBasis == "Wick"
_out := _dir == 1 ? (structureWickLowPrev - _buffer) : (structureWickHighPrev + _buffer)
else
_out := _dir == 1 ? (structureBodyLowPrev - _buffer) : (structureBodyHighPrev + _buffer)
_out
calcStopPrice(_dir, _entryPrice) =>
float _out = na
if slMode == "Lookback Structure"
_out := calcStructureStop(_dir)
else if slMode == "Fixed Pips / Units"
_dist = unitToPrice(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
_dist = atrSeries * slAtrMult
_out := _dir == 1 ? _entryPrice - _dist : _entryPrice + _dist
_out
calcTpPrice(_dir, _entryPrice, _stopPrice) =>
float _out = na
if tpMode == "Risk:Reward"
_risk = math.abs(_entryPrice - _stopPrice)
_out := _dir == 1 ? _entryPrice + _risk * rrMultiple : _entryPrice - _risk * rrMultiple
else if tpMode == "Fixed Pips / Units"
_dist = unitToPrice(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
_dist = atrSeries * tpAtrMult
_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)
//══════════════════════════════════════════════════════════════════════════════
// Trade state
//══════════════════════════════════════════════════════════════════════════════
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 int activeEntryBar = na
var int activeEntryTime = na
var bool trailArmed = false
var float trailExtreme = na
var float snapEntryPrice = na
var float snapInitialSl = na
var float snapBaseTp = na
var int snapDir = 0
var int snapEntryBar = na
var string exitReasonCandidate = ""
var string lastClosedReason = ""
var bool trailArmEvent = false
trailArmEvent := false
//══════════════════════════════════════════════════════════════════════════════
// Objects
//══════════════════════════════════════════════════════════════════════════════
var box[] closedProfitBoxes = array.new<box>()
var box[] closedRiskBoxes = array.new<box>()
var label[] tradeEntryLabels = array.new<label>()
var label[] tradeExitLabels = array.new<label>()
var line[] tradeCalloutLines = array.new<line>()
makeCallout(_xAnchor, _yAnchor, _txt, _isExit, _bg, _txtCol) =>
label _lb = na
if showTradeLabelsEff
_xPlaced = useCalloutsEff ? (_xAnchor + calloutXBars) : _xAnchor
_off = unitToPrice(_isExit ? exitYOffsetUnits : entryYOffsetUnits, unitSize)
_yPlaced = useCalloutsEff ? (_isExit ? _yAnchor + _off : _yAnchor - _off) : _yAnchor
if useCalloutsEff 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 = 1,
color = color.new(color.white, 0)
)
array.push(tradeCalloutLines, _ln)
_lb := label.new(
x = _xPlaced,
y = _yPlaced,
text = _txt,
xloc = xloc.bar_index,
yloc = yloc.price,
style = _isExit ? label.style_label_down : label.style_label_up,
textcolor = _txtCol,
color = _bg,
size = size.small
)
_lb
if recentTradesToDraw == 0 and barstate.islast
clearAllObjects(closedProfitBoxes, closedRiskBoxes, tradeEntryLabels, tradeExitLabels, tradeCalloutLines)
//══════════════════════════════════════════════════════════════════════════════
// Closed trade handling
//══════════════════════════════════════════════════════════════════════════════
if positionClosed
lastPositionCloseBar := bar_index
lastClosedReason := exitReasonCandidate
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)
rewardUnits = priceToUnits(math.abs(snapBaseTp - snapEntryPrice), unitSize)
riskUnits = priceToUnits(math.abs(snapInitialSl - snapEntryPrice), unitSize)
rrTxt = riskUnits != 0 ? fmt2(rewardUnits / riskUnits) : "na"
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 =profitBoxBorder, bgcolor = profitBoxColor)
riskBox := box.new(left = snapEntryBar, top = snapInitialSl, right = bar_index, bottom = snapEntryPrice, border_color = riskBoxBorder, bgcolor = riskBoxColor)
else if snapDir == -1
profitBox := box.new(left = snapEntryBar, top = snapEntryPrice, right = bar_index, bottom = snapBaseTp, border_color = profitBoxBorder, bgcolor = profitBoxColor)
riskBox := box.new(left = snapEntryBar, top = snapInitialSl, right = bar_index, bottom = snapEntryPrice, border_color = riskBoxBorder, bgcolor = riskBoxColor)
array.push(closedProfitBoxes, profitBox)
array.push(closedRiskBoxes, riskBox)
if showTradeLabelsEff
exitBg = plCash >= 0 ? exitWinBg : exitLossBg
headTxt = plCash >= 0 ? "WIN" : "LOSS"
_txt =
headTxt + "\n" +
"PnL " + fmt2(plCash) + "\n" +
"Pct " + fmt2(plPct) + "%\n" +
"Entry " + fmt(snapEntryPrice) + "\n" +
"Exit " + fmt(exitPrice) + "\n" +
"SL " + fmt(snapInitialSl) + "\n" +
"TP " + fmt(snapBaseTp) + "\n" +
"RR " + rrTxt + "\n" +
lastClosedReason
_lb = makeCallout(bar_index, exitPrice, _txt, true, exitBg, exitTxtCol)
array.push(tradeExitLabels, _lb)
trimObjects(closedProfitBoxes, closedRiskBoxes, tradeEntryLabels, tradeExitLabels, tradeCalloutLines, recentTradesToDraw)
activeDir := 0
activeEntryPrice := na
activeInitialSl := na
activeBaseTp := na
activeCurrentStop := na
activeCurrentTrail := na
activeRiskPrice := na
activeEntryBar := na
activeEntryTime := na
trailArmed := false
trailExtreme := na
exitReasonCandidate := ""
//══════════════════════════════════════════════════════════════════════════════
// Entry logic
//══════════════════════════════════════════════════════════════════════════════
if enterLongNow
_entry = close
_sl = calcStopPrice(1, _entry)
_tp = calcTpPrice(1, _entry, _sl)
_okStop = isValidStop(1, _entry, _sl)
_okTp = not na(_tp) and _tp > _entry
_qty = getQty(_entry)
if _qty > 0 and _okStop and _okTp
activeDir := 1
activeEntryPrice := _entry
activeInitialSl := _sl
activeBaseTp := _tp
activeCurrentStop := _sl
activeCurrentTrail := na
activeRiskPrice := math.abs(_entry - _sl)
activeEntryBar := bar_index
activeEntryTime := time
trailArmed := false
trailExtreme := na
exitReasonCandidate := ""
strategy.entry("Long", strategy.long, qty = _qty)
_rr = activeRiskPrice != 0 ? math.abs(activeBaseTp - activeEntryPrice) / activeRiskPrice : na
_txt =
"LONG\n" +
longMomentumTxt + "\n" +
"Entry " + fmt(activeEntryPrice) + "\n" +
"SL " + fmt(activeInitialSl) + "\n" +
"TP " + fmt(activeBaseTp) + "\n" +
"Risk " + fmt2(priceToUnits(activeRiskPrice, unitSize)) + "\n" +
"RR " + fmt2(_rr)
_lb = makeCallout(bar_index, low, _txt, false, entryInfoBg, entryInfoTxt)
array.push(tradeEntryLabels, _lb)
trimObjects(closedProfitBoxes, closedRiskBoxes, tradeEntryLabels, tradeExitLabels, tradeCalloutLines, recentTradesToDraw)
if enterShortNow
_entry = close
_sl = calcStopPrice(-1, _entry)
_tp = calcTpPrice(-1, _entry, _sl)
_okStop = isValidStop(-1, _entry, _sl)
_okTp = not na(_tp) and _tp < _entry
_qty = getQty(_entry)
if _qty > 0 and _okStop and _okTp
activeDir := -1
activeEntryPrice := _entry
activeInitialSl := _sl
activeBaseTp := _tp
activeCurrentStop := _sl
activeCurrentTrail := na
activeRiskPrice := math.abs(_entry - _sl)
activeEntryBar := bar_index
activeEntryTime := time
trailArmed := false
trailExtreme := na
exitReasonCandidate := ""
strategy.entry("Short", strategy.short, qty = _qty)
_rr = activeRiskPrice != 0 ? math.abs(activeEntryPrice - activeBaseTp) / activeRiskPrice : na
_txt =
"SHORT\n" +
shortMomentumTxt + "\n" +
"Entry " + fmt(activeEntryPrice) + "\n" +
"SL " + fmt(activeInitialSl) + "\n" +
"TP " + fmt(activeBaseTp) + "\n" +
"Risk " + fmt2(priceToUnits(activeRiskPrice, unitSize)) + "\n" +
"RR " + fmt2(_rr)
_lb = makeCallout(bar_index, high, _txt, false, entryInfoBg, entryInfoTxt)
array.push(tradeEntryLabels, _lb)
trimObjects(closedProfitBoxes, closedRiskBoxes, tradeEntryLabels, tradeExitLabels, tradeCalloutLines, recentTradesToDraw)
if newPositionOpened
activeEntryPrice := strategy.position_avg_price
activeRiskPrice := math.abs(activeEntryPrice - activeInitialSl)
//══════════════════════════════════════════════════════════════════════════════
// Live trade management
//══════════════════════════════════════════════════════════════════════════════
if pos != 0
tpTouched = inLong ? high >= activeBaseTp : low <= activeBaseTp
if enableTrailing
if not trailArmed and tpTouched
trailArmed := true
trailExtreme := inLong ? high : low
trailArmEvent := true
if trailArmed
if inLong
trailExtreme := math.max(nz(trailExtreme, high), high)
else
trailExtreme := math.min(nz(trailExtreme, low), low)
float rawTrail = na
if trailMode == "Fixed Pips / Units"
_dist = unitToPrice(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 == "Last X Wicks"
rawTrail := inLong ? lowestLowTrail : highestHighTrail
else
rawTrail := inLong ? lowestOcTrail : highestOcTrail
protectFloor = protectFloorMode == "Base TP Level" ? activeBaseTp : (inLong ? activeEntryPrice + unitToPrice(breakevenOffsetUnits, unitSize) : activeEntryPrice - unitToPrice(breakevenOffsetUnits, unitSize))
activeCurrentTrail := inLong ? math.max(rawTrail, protectFloor) : math.min(rawTrail, protectFloor)
activeCurrentStop := activeCurrentTrail
else
activeCurrentStop := activeInitialSl
activeCurrentTrail := na
else
activeCurrentStop := activeInitialSl
activeCurrentTrail := na
if flattenInBlock and blockActive
exitReasonCandidate := "Time Block Exit"
else if enableTrailing and trailArmed and ((inLong and low <= activeCurrentStop) or (inShort and high >= activeCurrentStop))
exitReasonCandidate := "Trail Exit"
else if (inLong and low <= activeCurrentStop) or (inShort and high >= activeCurrentStop)
exitReasonCandidate := "SL Exit"
else if not enableTrailing and ((inLong and high >= activeBaseTp) or (inShort and low <= activeBaseTp))
exitReasonCandidate := "TP Exit"
else
exitReasonCandidate := ""
// 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)
//══════════════════════════════════════════════════════════════════════════════
// Live plots and live trade 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)
var box liveProfitBox = na
var box liveRiskBox = na
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 = profitBoxBorder, bgcolor = profitBoxColor)
if na(liveRiskBox)
liveRiskBox := box.new(leftTime, math.max(activeEntryPrice, activeInitialSl), rightTime, math.min(activeEntryPrice, activeInitialSl), xloc = xloc.bar_time, border_color = riskBoxBorder, bgcolor = riskBoxColor)
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
//══════════════════════════════════════════════════════════════════════════════
// MA Ribbon
//══════════════════════════════════════════════════════════════════════════════
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)
//══════════════════════════════════════════════════════════════════════════════
// 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 =
"CANDLESTICK MOMENTUM + MA STACK STRATEGY\n\n" +
"HOW IT WORKS\n" +
"• Entry is evaluated only on confirmed bar close.\n" +
"• The strategy checks a rolling candle window for a required move.\n" +
"• Move can be measured in Pips / Units or Percent.\n" +
"• Body mode uses first open to last close.\n" +
"• Wick mode uses directional wick movement.\n" +
"• Gap mode can include or exclude jump discontinuities.\n" +
"• Optional candle-direction filter can require all candles in the window to close in the same direction.\n" +
"• Optional minimum move-per-candle filter rejects weak momentum bursts.\n" +
"• Optional MA confluence requires the active MAs to be stacked on the signal bar close.\n\n" +
"EXITS\n" +
"• Stop options: Lookback Structure, Fixed Pips / Units, Percent, ATR.\n" +
"• Structure stop can use Wick or Open and includes a buffer.\n" +
"• TP options: Risk:Reward, Fixed Pips / Units, Percent, ATR.\n" +
"• If trailing is enabled, the base TP becomes a trigger, not a hard final exit.\n" +
"• Once price touches the base TP, trailing is armed and manages the trade from there.\n\n" +
"NON-REPAINTING DESIGN\n" +
"• Confirmed bar-close logic only.\n" +
"• No pyramiding.\n" +
"• No intrabar signal logic.\n" +
"• No future-looking entry conditions.\n\n" +
"TIME BLOCKS\n" +
"• Default behavior blocks new trades only.\n" +
"• Optional mode immediately exits current trades and blocks new trades.\n\n" +
"TIP\n" +
"• Read this 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, 6, border_width = 1)
else
table.set_position(statusTbl, tablePosFromString(statusPos))
stateRow = pos != 0 ? "IN TRADE" : rawLongSignal or rawShortSignal ? "SETUP" : "WAITING"
dirRow = pos != 0 ? dirTxt(activeDir) : enterLongNow ? "LONG" : enterShortNow ? "SHORT" : "NONE"
allowRow = tradeDirection
moveRow = moveMode == "Pips / Units" ? ("L " + fmt2(longMoveUnits) + " | S " + fmt2(shortMoveUnits)) : ("L " + fmt2(longMovePct) + "% | S " + fmt2(shortMovePct) + "%")
maRow = useMaConfluence ? ("L " + boolTxt(maOkLong) + " | S " + boolTxt(maOkShort)) : "OFF"
pricesRow = pos != 0 ? (fmt(activeEntryPrice) + " / " + fmt(activeCurrentStop) + " / " + fmt(activeBaseTp)) : "n/a"
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, "Dir", text_color = statusTxt, bgcolor = statusBg)
table.cell(statusTbl, 1, 1, dirRow, text_color = statusTxt, bgcolor = statusBg)
table.cell(statusTbl, 0, 2, "Allow", text_color = statusTxt, bgcolor = statusBg)
table.cell(statusTbl, 1, 2, allowRow, text_color = statusTxt, bgcolor = statusBg)
table.cell(statusTbl, 0, 3, "Move", text_color = statusTxt, bgcolor = statusBg)
table.cell(statusTbl, 1, 3, moveRow, text_color = statusTxt, bgcolor = statusBg)
table.cell(statusTbl, 0, 4, "MA", text_color = statusTxt, bgcolor = statusBg)
table.cell(statusTbl, 1, 4, maRow, text_color = statusTxt, bgcolor = statusBg)
table.cell(statusTbl, 0, 5, "Entry / SL / TP", text_color = statusTxt, bgcolor = statusBg)
table.cell(statusTbl, 1, 5, pricesRow, text_color = statusTxt, bgcolor = statusBg)
else
if not na(statusTbl)
table.delete(statusTbl)
statusTbl := na
//══════════════════════════════════════════════════════════════════════════════
// Alerts
//══════════════════════════════════════════════════════════════════════════════
if enterLongNow and alertOnLongEntry
alert("Momentum strat long entry", alert.freq_once_per_bar_close)
if enterShortNow and alertOnShortEntry
alert("Momentum strat short entry", alert.freq_once_per_bar_close)
if trailArmEvent and alertOnTrailArm
alert("Momentum strat trailing armed", alert.freq_once_per_bar_close)
if positionClosed and snapDir == 1 and alertOnLongExit
alert("Momentum strat long exit", alert.freq_once_per_bar_close)
if positionClosed and snapDir == -1 and alertOnShortExit
alert("Momentum strat short exit", alert.freq_once_per_bar_close)
if positionClosed and lastClosedReason == "Time Block Exit" and alertOnForcedBlockExit
alert("Momentum strat forced exit due to time block", alert.freq_once_per_bar_close)
if positionClosed and (lastClosedReason == "SL Exit" or lastClosedReason == "Trail Exit") and alertOnStopHit
alert("Momentum strat stop-style exit", alert.freq_once_per_bar_close)
if positionClosed and lastClosedReason == "TP Exit" and alertOnTpHit
alert("Momentum strat TP-style exit", alert.freq_once_per_bar_close)