本页源码来自 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 = "Simple MA Cross Strategy",
shorttitle = "Simple MA Cross Strat",
overlay = true,
pyramiding = 0,
process_orders_on_close = false,
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) Strategy Guide / Status
guideGroup = "📘 Strategy Guide"
statusGroup = "📊 Status Panel"
guideSetup = input.text_area(
"SIMPLE MA CROSS STRATEGY\n\n" +
"STEP 1: Click the 3 dots on the settings of this strategy and adjust the pinned-to-scale settings if needed.\n" +
"STEP 2: In strategy settings > Style, turn OFF Trades on Chart for a cleaner view if desired.\n" +
"STEP 3: Read these guide sections in Inputs for a brief understanding of the strategy.\n",
"Read Me First",
group = guideGroup,
active = false,
tooltip = "General setup notes for the strategy."
)
guideOverview = input.text_area(
"OVERVIEW\n\n" +
"• Entries use the confirmed bar-close cross of Primary MA #1 and Primary MA #2.\n" +
"• Default entry setup is EMA 20 crossing EMA 200.\n" +
"• Each MA has its own type, length, source, and color inputs.\n" +
"• Optional MA #4 directional confluence can restrict trade direction.\n" +
"• When MA #4 confluence is ON, longs require MA #4 below MA #1 and MA #2, and shorts require MA #4 above MA #1 and MA #2.\n" +
"• When Exit style = Exit on MA 1+3 Cross, MA #4 also compares against the Exit MA.\n" +
"• Optional MA #4 distance filtering can require the MA1/MA2 cross to occur a minimum distance away from MA #4.\n" +
"• Optional delayed confirmation entry can hold a valid setup for X extra candles before entering.\n",
"Strategy Overview",
group = guideGroup,
active = false,
tooltip = "Overview of how entries and MA #4 confluence work."
)
guideExits = input.text_area(
"EXIT STYLES\n\n" +
"• SL / TP Engine: uses stop-loss, take-profit, and optional trailing after the base TP is touched.\n" +
"• Exit on MA 1+3 Cross: closes the trade when Primary MA #1 crosses the dedicated Exit MA.\n" +
"• Exit on MA 1+2 Cross: closes the trade when Primary MA #1 and Primary MA #2 cross in the opposite direction.\n" +
"• Chop protection can still close a trade and start chop cooldown when enabled.\n",
"Exit Styles",
group = guideGroup,
active = false,
tooltip = "Summary of the three available exit styles."
)
guideNonRepaint = input.text_area(
"NON-REPAINTING DESIGN\n\n" +
"• Confirmed bar-close signal logic only.\n" +
"• No pyramiding.\n" +
"• No intrabar signal entries.\n" +
"• No future-looking calculations for entries.\n",
"Non-Repainting Design",
group = guideGroup,
active = false,
tooltip = "Notes about how the strategy avoids repaint-style signal behavior."
)
guideMaTypes = input.text_area(
"MA TYPES\n\n" +
"• SMA (Simple Moving Average): Gives equal weight to all prices in the lookback period. Smooth and straightforward, but slower to react.\n" +
"• EMA (Exponential Moving Average): Gives more weight to recent prices. Faster to react than SMA and commonly used for crossover signals.\n" +
"• SMMA / RMA (Smoothed Moving Average): A slower, more smoothed average that holds onto older data longer. Good for filtering noise.\n" +
"• WMA (Weighted Moving Average): Gives linearly heavier weight to more recent prices. More responsive than SMA.\n" +
"• VWMA (Volume Weighted Moving Average): Weights price by volume, so higher-volume candles matter more.\n" +
"• HMA (Hull Moving Average): Designed to reduce lag while staying smooth. Often reacts quickly while keeping a cleaner shape.\n",
"MA Type Guide",
group = guideGroup,
active = false,
tooltip = "Brief explanation of how each moving average type behaves."
)
showStatusPanel = input.bool(
false,
"Show compact status panel (Takes very long time to load up)",
group = statusGroup,
tooltip = "Shows a compact live status panel summarizing the most important strategy state information."
)
statusPos = input.string(
"Top Right",
"Status panel position",
options = ["Top Right", "Top Left", "Bottom Right", "Bottom Left"],
group = statusGroup,
tooltip = "Choose where the compact status panel appears on the chart."
)
statusBg = input.color(
color.new(#000000, 50),
"Status panel background",
group = statusGroup,
tooltip = "Background color for the live status panel."
)
statusTxt = input.color(
color.rgb(43, 255, 0),
"Status panel text color",
group = statusGroup,
tooltip = "Text color for the live status panel."
)
// 2) Trade Direction
dirGroup = "🧭 Trade Direction"
tradeDirection = input.string(
"Both",
"Allowed trade direction",
options = ["Both", "Long Only", "Short Only"],
group = dirGroup,
tooltip = "Choose whether the strategy can take long trades, short trades, or both."
)
// 3) Position Sizing
sizeGroup = "💵 Position Sizing"
sizeMode = input.string(
"Lot Size",
"Sizing mode",
options = ["Lot Size", "Cash Amount"],
group = sizeGroup,
tooltip = "Choose how trade size is calculated."
)
lotSize = input.float(
0.10,
"Lot size",
minval = 0.01,
step = 0.01,
group = sizeGroup,
tooltip = "Forex lot size used when Sizing mode = Lot Size."
)
cashAmount = input.float(
500.0,
"Cash amount",
minval = 1,
step = 100,
group = sizeGroup,
tooltip = "Cash amount used when Sizing mode = Cash Amount."
)
leverageInput = input.float(
20.0,
"Leverage",
minval = 1,
step = 0.5,
group = sizeGroup,
tooltip = "Leverage multiplier used for notional sizing."
)
// 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 throughout the script."
)
// 5) Entry MAs
entryGroup = "🚀 Entry MAs"
ma1Type = input.string(
"HMA",
"Primary MA #1 type",
options = ["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA", "HMA"],
group = entryGroup,
inline = "ma1",
tooltip = "Type of the fast primary moving average used in the crossover entry logic."
)
ma1Len = input.int(
4,
"MA #1 Length",
minval = 1,
group = entryGroup,
inline = "ma1",
tooltip = "Length of Primary MA #1."
)
ma1Source = input.source(
close,
"Source",
group = entryGroup,
inline = "ma1src",
tooltip = "Source series used to calculate Primary MA #1."
)
ma1Color = input.color(
color.new(#00ff00, 0),
"Color",
group = entryGroup,
inline = "ma1src",
tooltip = "Plot color for Primary MA #1."
)
ma2Type = input.string(
"HMA",
"Primary MA #2 type",
options = ["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA", "HMA"],
group = entryGroup,
inline = "ma2",
tooltip = "Type of the slow primary moving average used in the crossover entry logic."
)
ma2Len = input.int(
60,
"MA #2 Length",
minval = 1,
group = entryGroup,
inline = "ma2",
tooltip = "Length of Primary MA #2."
)
ma2Source = input.source(
close,
"Source",
group = entryGroup,
inline = "ma2src",
tooltip = "Source series used to calculate Primary MA #2."
)
ma2Color = input.color(
color.new(#00f7ff, 0),
"Color",
group = entryGroup,
inline = "ma2src",
tooltip = "Plot color for Primary MA #2."
)
useHeldEntry = input.bool(
false,
"Use delayed confirmation entry",
group = entryGroup,
tooltip = "When enabled, after a valid entry signal the strategy waits X extra candles before entering. The setup must still hold and must not reverse during that wait."
)
heldEntryBars = input.int(
5,
"Hold setup for X extra candles",
minval = 1,
maxval = 500,
group = entryGroup,
tooltip = "Number of extra full candles the setup must survive before the strategy is allowed to enter."
)
// 6) Exit Style
exitGroup = "🛠 Exit Style"
exitStyle = input.string(
"Exit on MA 1+2 Cross",
"Exit Style",
options = ["SL / TP Engine", "Exit on MA 1+3 Cross", "Exit on MA 1+2 Cross"],
group = exitGroup,
tooltip = "SL / TP Engine uses stop-loss, take-profit, and optional trailing logic. Exit on MA 1+3 Cross exits when Primary MA #1 crosses the dedicated Exit MA. Exit on MA 1+2 Cross exits the current trade when Primary MA #1 and Primary MA #2 cross in the opposite direction."
)
alwaysInMode = input.bool(
false,
"Always-in mode (re-enter on current MA regime when flat)",
group = exitGroup,
tooltip = "When enabled, the strategy does not wait for a fresh MA #1 / MA #2 cross while flat. It enters in the direction of the current regime (MA #1 above MA #2 = long, below = short), subject to direction, MA #4, cooldown and time-block filters. Combined with 'Exit on MA 1+2 Cross' this produces an always-in-the-market flip system: each opposite cross closes the trade and the next bar re-enters the other way."
)
// 7) Exit on MA 1+3 Cross
exitMaGroup = "📉 Exit on MA 1+3 Cross"
exitMaType = input.string(
"EMA",
"Exit MA type",
options = ["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA", "HMA"],
group = exitMaGroup,
inline = "xma",
tooltip = "Type of the dedicated Exit MA used when Exit style = Exit on MA 1+3 Cross."
)
exitMaLen = input.int(
100,
"MA #3 Length",
minval = 1,
group = exitMaGroup,
inline = "xma",
tooltip = "Length of the dedicated MA #3 used by Exit on MA 1+3 Cross."
)
exitMaSource = input.source(
close,
"Source",
group = exitMaGroup,
inline = "xmasrc",
tooltip = "Source series used to calculate MA #3."
)
exitMaColor = input.color(
color.new(#e5ff00, 0),
"Color",
group = exitMaGroup,
inline = "xmasrc",
tooltip = "Plot color for the dedicated Exit MA."
)
showExitMaPlot = input.bool(
false,
"Show Exit MA on chart",
group = exitMaGroup,
tooltip = "Plots MA #3, the dedicated exit MA used by Exit on MA 1+3 Cross."
)
useExitMaLockout = input.bool(
true,
"Use entry-to-exit lockout for Exit MA",
group = exitMaGroup,
tooltip = "Ignores Exit on MA 1+3 Cross signals for a fixed number of bars after entry."
)
exitMaLockoutBars = input.int(
10,
"Ignore Exit MA for first X bars after entry",
minval = 0,
maxval = 500,
group = exitMaGroup,
tooltip = "Number of full bars after entry during which Exit on MA 1+3 Cross signals are ignored."
)
// 8) MA #4 Confluence
ma4Group = "🟠 MA #4 Confluence"
useMa4Confluence = input.bool(
true,
"Use MA #4 directional confluence",
group = ma4Group,
tooltip = "When enabled, MA #4 controls directional confluence. Longs are allowed only when MA #4 is below MA #1 and MA #2. Shorts are allowed only when MA #4 is above MA #1 and MA #2. When Exit style = Exit on MA 1+3 Cross, MA #4 must also be below or above the Exit MA."
)
ma4Type = input.string(
"SMMA (RMA)",
"MA #4 type",
options = ["SMA", "EMA", "SMMA (RMA)", "WMA", "VWMA", "HMA"],
group = ma4Group,
inline = "ma4",
tooltip = "Type of the MA #4 confluence moving average."
)
ma4Len = input.int(
1000,
"MA #4 Length",
minval = 1,
group = ma4Group,
inline = "ma4",
tooltip = "Length of MA #4."
)
ma4Source = input.source(
close,
"Source",
group = ma4Group,
inline = "ma4src",
tooltip = "Source series used to calculate MA #4."
)
ma4Color = input.color(
color.new(#ff6a00, 0),
"Color",
group = ma4Group,
inline = "ma4src",
tooltip = "Plot color for MA #4. Default is neon orange."
)
showMa4Plot = input.bool(
true,
"Show MA #4 on chart",
group = ma4Group,
tooltip = "Plots MA #4 on the chart."
)
requireCrossAwayFromMa4 = input.bool(
false,
"Require MA1/MA2 cross to be away from MA #4",
group = ma4Group,
tooltip = "When enabled, new entries are allowed only if the MA1/MA2 cross occurs at least the selected distance away from MA #4."
)
minCrossDistanceUnits = input.float(
10.0,
"Minimum cross distance from MA #4 (Pips / Units)",
minval = 0,
step = 0.1,
group = ma4Group,
tooltip = "Minimum required distance between the MA1/MA2 cross price and MA #4, measured in pips or units."
)
// 9) Stop Loss
slGroup = "🛑 Stop Loss"
slMode = input.string(
"Fixed Pips / Units",
"Stop-loss mode",
options = ["Lookback Structure", "Fixed Pips / Units", "Percent", "ATR"],
group = slGroup,
tooltip = "Method used to calculate the stop-loss when Exit style = SL / TP Engine."
)
slLookback = input.int(
5,
"Structure lookback",
minval = 1,
maxval = 200,
group = slGroup,
tooltip = "Number of completed candles used for structure-based stop-loss mode."
)
slStructureBasis = input.string(
"Wick",
"Structure basis",
options = ["Wick", "Open/Close"],
group = slGroup,
tooltip = "Wick uses prior highs or lows. Open/Close uses candle body extremes from prior 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."
)
slFixedUnits = input.float(
10.0,
"Fixed stop (Pips / Units)",
minval = 0,
step = 0.1,
group = slGroup,
tooltip = "Used when Stop-loss mode = Fixed Pips / Units."
)
slPct = input.float(
1.0,
"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-loss, take-profit, and trailing calculations."
)
slAtrMult = input.float(
1.0,
"ATR stop multiplier",
minval = 0.1,
step = 0.1,
group = slGroup,
tooltip = "Used when Stop-loss mode = ATR."
)
// 10) Take Profit
tpGroup = "🎯 Take Profit"
tpMode = input.string(
"Risk:Reward",
"Take-profit mode",
options = ["Risk:Reward", "Fixed Pips / Units", "Percent", "ATR"],
group = tpGroup,
tooltip = "Method used to calculate the base take-profit when Exit style = SL / TP Engine."
)
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 = "Used when Take-profit mode = Fixed Pips / Units."
)
tpPct = input.float(
1.0,
"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."
)
// 11) Trailing
trailGroup = "🏃 Trailing"
enableTrailing = input.bool(
false,
"Enable trailing after base TP touch",
group = trailGroup,
tooltip = "When enabled and Exit style = SL / TP Engine, the base TP acts as an activation level rather than a hard final exit."
)
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 is 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 is first touched, trailing can be prevented from moving back beyond either the base TP or a breakeven-based level."
)
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."
)
// 12) Cooldowns
cooldownGroup = "🔁 Cooldowns"
useReentryCooldown = input.bool(
false,
"Use cooldown after a trade closes",
group = cooldownGroup,
tooltip = "When enabled, the strategy waits a number of full bars after any trade closes before another entry can be taken."
)
reentryCooldownBars = input.int(
1,
"Normal cooldown bars after close",
minval = 0,
maxval = 500,
group = cooldownGroup,
tooltip = "Number of full bars to wait after a trade closes before allowing a new entry."
)
useChopProtection = input.bool(
false,
"Use chop protection",
group = cooldownGroup,
tooltip = "When enabled, an opposite MA1/MA2 cross occurring too soon after the previous opposite cross is treated as chop."
)
chopWindowBars = input.int(
20,
"Opposite cross invalid if within X bars",
minval = 1,
maxval = 1000,
group = cooldownGroup,
tooltip = "If a bullish cross occurs within this many bars of the most recent bearish cross, or vice versa, the new opposite cross is considered chopped."
)
chopCooldownBars = input.int(
50,
"Chop cooldown bars",
minval = 0,
maxval = 5000,
group = cooldownGroup,
tooltip = "Number of full bars to wait after a chopped opposite cross event."
)
// 13) Visuals
visGroup = "🎨 Visuals"
optimizerMode = input.bool(
false,
"Enable optimizer mode",
group = visGroup,
tooltip = "Aggressive low-clutter optimization mode."
)
showMaPlots = input.bool(
true,
"Show MA plots",
group = visGroup,
tooltip = "Plots the primary entry MAs, the dedicated Exit MA when relevant, and MA #4 when enabled."
)
showLiveLines = input.bool(
true,
"Show active trade lines",
group = visGroup,
tooltip = "Shows live entry, stop, target, and trailing lines for open positions."
)
showLiveTradeBox = input.bool(
true,
"Show live trade box",
group = visGroup,
tooltip = "Shows a live trade box while a position is open."
)
showTradeBoxes = input.bool(
true,
"Show recent trade boxes",
group = visGroup,
tooltip = "Draws historical trade boxes for recent closed trades."
)
showTradeLabels = input.bool(
true,
"Show recent trade labels",
group = visGroup,
tooltip = "Shows recent entry labels below price and win or 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."
)
profitBoxColor = input.color(
color.new(color.green, 80),
"Profit Fill",
group = visGroup,
inline = "profitbox",
tooltip = "Fill color for profitable trade boxes."
)
profitBoxBorder = input.color(
color.new(color.green, 90),
"Border",
group = visGroup,
inline = "profitbox",
tooltip = "Border color for profitable trade box portions."
)
riskBoxColor = input.color(
color.new(color.red, 80),
"Risk Fill",
group = visGroup,
inline = "riskbox",
tooltip = "Fill color for losing trade boxes."
)
riskBoxBorder = input.color(
color.new(color.red, 90),
"Border",
group = visGroup,
inline = "riskbox",
tooltip = "Border color for losing trade box portions."
)
// 14) Label Callouts
calloutGroup = "🧷 Label Callouts"
useCallouts = input.bool(
true,
"Offset labels from price",
group = calloutGroup,
tooltip = "Moves trade labels away from candles."
)
drawCalloutLines = input.bool(
true,
"Draw dotted connector lines",
group = calloutGroup,
tooltip = "Draws dotted connector lines between price and the offset label location."
)
calloutXBars = input.int(
2,
"Callout X offset (bars)",
minval = 0,
maxval = 50,
group = calloutGroup,
tooltip = "Horizontal label offset to the right."
)
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 or 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 profitable 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 exit labels."
)
// 15) Alerts
alertGroup = "🔔 Alerts"
alertOnLongEntry = input.bool(false, "Long entry alert", group = alertGroup, tooltip = "Enable alert() call when a long entry order is submitted.")
alertOnShortEntry = input.bool(false, "Short entry alert", group = alertGroup, tooltip = "Enable alert() call when a short entry order is submitted.")
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.")
alertOnTimeBlockExit = input.bool(false, "Time block forced-exit alert", group = alertGroup, tooltip = "Enable alert() call when a time block immediately forces the strategy out of an active trade.")
alertOnChopExit = input.bool(false, "Chop exit alert", group = alertGroup, tooltip = "Enable alert() call when chop protection exits a trade.")
alertOnExitMaExit = input.bool(false, "Exit on MA 1+3 Cross exit alert", group = alertGroup, tooltip = "Enable alert() call when the Exit on MA 1+3 Cross logic closes a trade.")
alertOnCrossExit = input.bool(false, "MA 1+2 cross exit alert", group = alertGroup, tooltip = "Enable alert() call when the Exit on MA 1+2 Cross logic closes a trade.")
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.")
alertOnTrailArm = input.bool(false, "Trailing armed alert", group = alertGroup, tooltip = "Enable alert() call when trailing becomes active after price touches the base TP.")
alertOnMa4DirBlock = input.bool(false, "MA #4 direction blocked alert", group = alertGroup, tooltip = "Enable alert() call when MA #4 directional confluence blocks a signal.")
alertOnMa4DistanceBlock = input.bool(false, "MA #4 distance blocked alert", group = alertGroup, tooltip = "Enable alert() call when the MA1/MA2 cross is too close to MA #4.")
alertOnChopCooldown = input.bool(false, "Chop cooldown started alert", group = alertGroup, tooltip = "Enable alert() call when a chopped opposite cross event starts a chop cooldown.")
// 16) 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 = "Time-block behavior."
)
w1En = input.bool(true, "Block #1", group = blockGroup, inline = "w1")
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"])
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"])
w2En = input.bool(true, "Block #2", group = blockGroup, inline = "w2")
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"])
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"])
w3En = input.bool(false, "Block #3", group = blockGroup, inline = "w3")
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"])
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"])
//══════════════════════════════════════════════════════════════════════════════
// 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, _unit) =>
_units * _unit
priceToUnits(_dist, _unit) =>
_unit != 0 ? _dist / _unit : na
isValidStop(_dir, _entryPrice, _stopPrice) =>
not na(_stopPrice) and ((_dir == 1 and _stopPrice < _entryPrice) or (_dir == -1 and _stopPrice > _entryPrice))
getQty(_price) =>
sizeMode == "Lot Size" ? (lotSize * 100000.0) : ((_price > 0) ? (strategy.convert_to_symbol(cashAmount * leverageInput) / _price) : 0.0)
trimObjects(_boxesA, _boxesB, _entryLabels, _exitLabels, _calloutLines, _keep) =>
while array.size(_boxesA) > _keep
_b = array.shift(_boxesA)
if not na(_b)
box.delete(_b)
while array.size(_boxesB) > _keep
_b = array.shift(_boxesB)
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(_boxesA, _boxesB, _entryLabels, _exitLabels, _calloutLines) =>
while array.size(_boxesA) > 0
_b = array.shift(_boxesA)
if not na(_b)
box.delete(_b)
while array.size(_boxesB) > 0
_b = array.shift(_boxesB)
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
//══════════════════════════════════════════════════════════════════════════════
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
//══════════════════════════════════════════════════════════════════════════════
ma1 = maCalc(ma1Source, ma1Len, ma1Type)
ma2 = maCalc(ma2Source, ma2Len, ma2Type)
exitMa = maCalc(exitMaSource, exitMaLen, exitMaType)
ma4 = maCalc(ma4Source, ma4Len, ma4Type)
atrSeries = ta.atr(atrLen)
bullCross = ta.crossover(ma1, ma2)
bearCross = ta.crossunder(ma1, ma2)
rawLongSignal = bullCross or (alwaysInMode and strategy.position_size == 0 and ma1 > ma2)
rawShortSignal = bearCross or (alwaysInMode and strategy.position_size == 0 and ma1 < ma2)
allowLong = tradeDirection == "Both" or tradeDirection == "Long Only"
allowShort = tradeDirection == "Both" or tradeDirection == "Short Only"
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"
useExitMaInConfluence = exitStyle == "Exit on MA 1+3 Cross"
ma4LongDirPass = not useMa4Confluence or (ma4 < ma1 and ma4 < ma2 and (not useExitMaInConfluence or ma4 < exitMa))
ma4ShortDirPass = not useMa4Confluence or (ma4 > ma1 and ma4 > ma2 and (not useExitMaInConfluence or ma4 > exitMa))
crossPrice = (ma1 + ma2) / 2.0
crossDistanceUnits = priceToUnits(math.abs(crossPrice - ma4), unitSize)
ma4DistancePass = not useMa4Confluence or not requireCrossAwayFromMa4 or (not na(crossDistanceUnits) and crossDistanceUnits >= minCrossDistanceUnits)
signalLongOk = rawLongSignal and allowLong and ma4LongDirPass and ma4DistancePass
signalShortOk = rawShortSignal and allowShort and ma4ShortDirPass and ma4DistancePass
ma4DirBlockedLong = rawLongSignal and allowLong and not ma4LongDirPass
ma4DirBlockedShort = rawShortSignal and allowShort and not ma4ShortDirPass
ma4DistanceBlocked = (rawLongSignal or rawShortSignal) and ma4DistancePass == false
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)
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 string activeExitStyle = ""
var int lastPositionCloseBar = na
var int lastCrossBar = na
var int lastCrossDir = 0
var int chopCooldownUntilBar = na
var string pendingExitReason = ""
var int pendingSnapDir = 0
var float pendingSnapEntry = na
var float pendingSnapSl = na
var float pendingSnapTp = na
var int pendingSnapEntryBar = na
var int pendingSnapEntryTime = na
var bool pendingSnapshotReady = false
var bool pendingEntryArmed = false
var int pendingEntryDir = 0
var float pendingEntrySl = na
var float pendingEntryTp = na
var float pendingEntryQty = na
var string pendingEntryTag = ""
var string pendingEntryExitStyle = ""
var bool heldEntryPending = false
var int heldEntryDir = 0
var int heldEntryStartBar = na
var string heldEntryReasonTag = ""
var string lastClosedReason = ""
var bool trailArmEvent = false
var bool chopCooldownStarted = false
var int closedSnapDir = 0
trailArmEvent := false
chopCooldownStarted := false
pos = strategy.position_size
inLong = pos > 0
inShort = pos < 0
inPosition = pos != 0
flat = pos == 0
bool exitOrderSubmitted = false
bool longEntrySubmittedThisBar = false
bool shortEntrySubmittedThisBar = false
normalCooldownActive = useReentryCooldown and not na(lastPositionCloseBar) and (bar_index - lastPositionCloseBar <= reentryCooldownBars)
chopCooldownActive = useChopProtection and not na(chopCooldownUntilBar) and bar_index <= chopCooldownUntilBar
entryBlockedByTime = blockActive
entryBlockedByCooldown = chopCooldownActive or normalCooldownActive
crossDirNow = bullCross ? 1 : bearCross ? -1 : 0
oppositeCrossTooSoon = useChopProtection and crossDirNow != 0 and lastCrossDir != 0 and crossDirNow != lastCrossDir and not na(lastCrossBar) and (bar_index - lastCrossBar <= chopWindowBars)
chopEvent = oppositeCrossTooSoon
if crossDirNow != 0
lastCrossBar := bar_index
lastCrossDir := crossDirNow
if chopEvent
chopCooldownUntilBar := bar_index + chopCooldownBars
chopCooldownStarted := true
exitMaLongSignal = ta.crossunder(ma1, exitMa)
exitMaShortSignal = ta.crossover(ma1, exitMa)
barsSinceEntry = not na(activeEntryBar) ? (bar_index - activeEntryBar) : na
exitMaLockoutActive = useExitMaLockout and not na(barsSinceEntry) and (barsSinceEntry <= exitMaLockoutBars)
whyBlocked =
entryBlockedByTime ? "Time Block" :
chopCooldownActive ? "Chop Cooldown" :
normalCooldownActive ? "Normal Cooldown" :
((rawLongSignal and allowLong and not ma4LongDirPass) or (rawShortSignal and allowShort and not ma4ShortDirPass)) ? "MA #4 Direction" :
((rawLongSignal or rawShortSignal) and useMa4Confluence and requireCrossAwayFromMa4 and not ma4DistancePass) ? "MA #4 Distance" :
(heldEntryPending ? "Holding Setup" : "Ready")
//══════════════════════════════════════════════════════════════════════════════
// Objects
//══════════════════════════════════════════════════════════════════════════════
var box[] closedBoxesA = array.new<box>()
var box[] closedBoxesB = 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(closedBoxesA, closedBoxesB, tradeEntryLabels, tradeExitLabels, tradeCalloutLines)
//══════════════════════════════════════════════════════════════════════════════
// Closed trade handling
//══════════════════════════════════════════════════════════════════════════════
closedTradeEvent = strategy.closedtrades > strategy.closedtrades[1]
if closedTradeEvent
idx = strategy.closedtrades - 1
lastPositionCloseBar := strategy.closedtrades.exit_bar_index(idx)
exitPrice = strategy.closedtrades.exit_price(idx)
plCash = strategy.closedtrades.profit(idx)
plPct = strategy.closedtrades.profit_percent(idx)
exitBarIdx = strategy.closedtrades.exit_bar_index(idx)
if pendingSnapshotReady
lastClosedReason := pendingExitReason
rewardUnits = not na(pendingSnapTp) ? priceToUnits(math.abs(pendingSnapTp - pendingSnapEntry), unitSize) : na
riskUnits = not na(pendingSnapSl) ? priceToUnits(math.abs(pendingSnapSl - pendingSnapEntry), unitSize) : na
tradeUnits = priceToUnits(math.abs(exitPrice - pendingSnapEntry), unitSize)
rrTxt = not na(rewardUnits) and not na(riskUnits) and riskUnits != 0 ? fmt2(rewardUnits / riskUnits) : "na"
if showTradeBoxesEff
box boxA = na
box boxB = na
if not na(pendingSnapSl) and not na(pendingSnapTp)
if pendingSnapDir == 1
boxA := box.new(left = pendingSnapEntryBar, top = pendingSnapTp, right = exitBarIdx, bottom = pendingSnapEntry, border_color = profitBoxBorder, bgcolor = profitBoxColor)
boxB := box.new(left = pendingSnapEntryBar, top = pendingSnapEntry, right = exitBarIdx, bottom = pendingSnapSl, border_color = riskBoxBorder, bgcolor = riskBoxColor)
else
boxA := box.new(left = pendingSnapEntryBar, top = pendingSnapEntry, right = exitBarIdx, bottom = pendingSnapTp, border_color = profitBoxBorder, bgcolor = profitBoxColor)
boxB := box.new(left = pendingSnapEntryBar, top = pendingSnapSl, right = exitBarIdx, bottom = pendingSnapEntry, border_color = riskBoxBorder, bgcolor = riskBoxColor)
else
_good = plCash >= 0
_top = math.max(pendingSnapEntry, exitPrice)
_bot = math.min(pendingSnapEntry, exitPrice)
boxA := box.new(left = pendingSnapEntryBar, top = _top, right = exitBarIdx, bottom = _bot, border_color = _good ? profitBoxBorder : riskBoxBorder, bgcolor = _good ? profitBoxColor : riskBoxColor)
array.push(closedBoxesA, boxA)
array.push(closedBoxesB, boxB)
if showTradeLabelsEff
exitBg = plCash >= 0 ? exitWinBg : exitLossBg
headTxt = plCash >= 0 ? "WIN" : "LOSS"
_txt =
headTxt + "\n" +
"PnL " + fmt2(plCash) + "\n" +
"Pct " + fmt2(plPct) + "%\n" +
"Move " + fmt2(tradeUnits) + "u\n" +
"Entry " + fmt(pendingSnapEntry) + "\n" +
"Exit " + fmt(exitPrice) + "\n" +
(not na(pendingSnapSl) ? "SL " + fmt(pendingSnapSl) + "\n" : "") +
(not na(pendingSnapTp) ? "TP " + fmt(pendingSnapTp) + "\n" : "") +
(rrTxt != "na" ? "RR " + rrTxt + "\n" : "") +
lastClosedReason
_lb = makeCallout(exitBarIdx, exitPrice, _txt, true, exitBg, exitTxtCol)
array.push(tradeExitLabels, _lb)
trimObjects(closedBoxesA, closedBoxesB, tradeEntryLabels, tradeExitLabels, tradeCalloutLines, recentTradesToDraw)
closedSnapDir := pendingSnapDir
pendingSnapshotReady := false
pendingExitReason := ""
pendingSnapDir := 0
pendingSnapEntry := na
pendingSnapSl := na
pendingSnapTp := na
pendingSnapEntryBar := na
pendingSnapEntryTime := na
if strategy.position_size == 0
activeDir := 0
activeEntryPrice := na
activeInitialSl := na
activeBaseTp := na
activeCurrentStop := na
activeCurrentTrail := na
activeRiskPrice := na
activeEntryBar := na
activeEntryTime := na
trailArmed := false
trailExtreme := na
activeExitStyle := ""
//══════════════════════════════════════════════════════════════════════════════
// Entry label helper
//══════════════════════════════════════════════════════════════════════════════
drawEntryCallout(_dir, _qty, _reasonTag) =>
_riskUnits = not na(activeRiskPrice) ? priceToUnits(activeRiskPrice, unitSize) : na
_rr = not na(activeRiskPrice) and activeRiskPrice != 0 and not na(activeBaseTp) ? math.abs(activeBaseTp - activeEntryPrice) / activeRiskPrice : na
_ma4Txt =
not useMa4Confluence ? "MA4 OFF\n" :
"MA4 Dir " + boolTxt(_dir == 1 ? ma4LongDirPass : ma4ShortDirPass) + "\n" +
"MA4 Dist " + (requireCrossAwayFromMa4 ? fmt2(crossDistanceUnits) + "u" : "OFF") + "\n"
_txt =
(_dir == 1 ? "LONG\n" : "SHORT\n") +
"Entry " + fmt(activeEntryPrice) + "\n" +
"Exit Style " + activeExitStyle + "\n" +
"Fast/Slow " + fmt(ma1) + " / " + fmt(ma2) + "\n" +
_ma4Txt +
"Size " + fmt2(_qty) + " units\n" +
(not na(activeInitialSl) ? "SL " + fmt(activeInitialSl) + "\n" : "") +
(not na(activeBaseTp) ? "TP " + fmt(activeBaseTp) + "\n" : "") +
(not na(_riskUnits) ? "Risk " + fmt2(_riskUnits) + "u\n" : "") +
(not na(_rr) ? "RR " + fmt2(_rr) + "\n" : "") +
_reasonTag
_anchorPrice = _dir == 1 ? low : high
_lb = makeCallout(bar_index, _anchorPrice, _txt, false, entryInfoBg, entryInfoTxt)
array.push(tradeEntryLabels, _lb)
trimObjects(closedBoxesA, closedBoxesB, tradeEntryLabels, tradeExitLabels, tradeCalloutLines, recentTradesToDraw)
//══════════════════════════════════════════════════════════════════════════════
// Fill sync
//══════════════════════════════════════════════════════════════════════════════
longFilledNow = strategy.position_size > 0 and strategy.position_size[1] <= 0
shortFilledNow = strategy.position_size < 0 and strategy.position_size[1] >= 0
stalePendingEntry =
pendingEntryArmed and
flat and
strategy.opentrades == 0 and
not longFilledNow and
not shortFilledNow and
pendingEntryDir != 0 and
not na(lastPositionCloseBar) and
(bar_index > lastPositionCloseBar + 1)
if stalePendingEntry
pendingEntryArmed := false
pendingEntryDir := 0
pendingEntrySl := na
pendingEntryTp := na
pendingEntryQty := na
pendingEntryTag := ""
pendingEntryExitStyle := ""
if pendingEntryArmed
fillMatched =
(pendingEntryDir == 1 and longFilledNow) or
(pendingEntryDir == -1 and shortFilledNow)
if fillMatched
openIdx = strategy.opentrades - 1
fillPrice = strategy.position_avg_price
float fillSl = pendingEntrySl
float fillTp = pendingEntryTp
if pendingEntryExitStyle == "SL / TP Engine"
fillSl := calcStopPrice(pendingEntryDir, fillPrice)
fillTp := calcTpPrice(pendingEntryDir, fillPrice, fillSl)
activeDir := pendingEntryDir
activeEntryPrice := fillPrice
activeInitialSl := fillSl
activeBaseTp := fillTp
activeCurrentStop := fillSl
activeCurrentTrail := na
activeRiskPrice := not na(fillSl) ? math.abs(fillPrice - fillSl) : na
activeEntryBar := strategy.opentrades > 0 ? strategy.opentrades.entry_bar_index(openIdx) : bar_index
activeEntryTime := strategy.opentrades > 0 ? strategy.opentrades.entry_time(openIdx) : time
trailArmed := false
trailExtreme := na
activeExitStyle := pendingEntryExitStyle
drawEntryCallout(activeDir, pendingEntryQty, pendingEntryTag)
pendingEntryArmed := false
pendingEntryDir := 0
pendingEntrySl := na
pendingEntryTp := na
pendingEntryQty := na
pendingEntryTag := ""
pendingEntryExitStyle := ""
//══════════════════════════════════════════════════════════════════════════════
// Entry / exit orchestration
//══════════════════════════════════════════════════════════════════════════════
standardCanEnterNow = not entryBlockedByTime and not entryBlockedByCooldown
standardLongSetupReady = signalLongOk and standardCanEnterNow
standardShortSetupReady = signalShortOk and standardCanEnterNow
longEntryReady = standardLongSetupReady and (not useHeldEntry or heldEntryBars <= 0)
shortEntryReady = standardShortSetupReady and (not useHeldEntry or heldEntryBars <= 0)
if (ma4DirBlockedLong or ma4DirBlockedShort) and alertOnMa4DirBlock
alert("Simple MA Cross Strategy: signal blocked by MA #4 directional confluence", alert.freq_once_per_bar_close)
if ma4DistanceBlocked and alertOnMa4DistanceBlock
alert("Simple MA Cross Strategy: signal blocked because MA1/MA2 cross is too close to MA #4", alert.freq_once_per_bar_close)
if chopCooldownStarted and alertOnChopCooldown
alert("Simple MA Cross Strategy: chop cooldown started", alert.freq_once_per_bar_close)
// Force exit by time block first.
if inPosition and flattenInBlock and blockActive and not exitOrderSubmitted
pendingExitReason := "Time Block Exit"
pendingSnapDir := activeDir
pendingSnapEntry := activeEntryPrice
pendingSnapSl := activeInitialSl
pendingSnapTp := activeBaseTp
pendingSnapEntryBar := activeEntryBar
pendingSnapEntryTime := activeEntryTime
pendingSnapshotReady := true
if inLong
strategy.close("Long", immediately = true)
if inShort
strategy.close("Short", immediately = true)
exitOrderSubmitted := true
// Chop exit next.
if inPosition and not exitOrderSubmitted and chopEvent
pendingExitReason := "Chop Exit"
pendingSnapDir := activeDir
pendingSnapEntry := activeEntryPrice
pendingSnapSl := activeInitialSl
pendingSnapTp := activeBaseTp
pendingSnapEntryBar := activeEntryBar
pendingSnapEntryTime := activeEntryTime
pendingSnapshotReady := true
if inLong
strategy.close("Long", immediately = true)
if inShort
strategy.close("Short", immediately = true)
exitOrderSubmitted := true
// SL / TP engine management.
if inPosition and not exitOrderSubmitted and exitStyle == "SL / TP Engine"
tpTouched = inLong ? (not na(activeBaseTp) and high >= activeBaseTp) : (not na(activeBaseTp) and 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
inferredReason =
enableTrailing and trailArmed and ((inLong and low <= activeCurrentStop) or (inShort and high >= activeCurrentStop)) ? "Trail Exit" :
((inLong and low <= activeCurrentStop) or (inShort and high >= activeCurrentStop)) ? "SL Exit" :
not enableTrailing and ((inLong and high >= activeBaseTp) or (inShort and low <= activeBaseTp)) ? "TP Exit" :
""
if inferredReason != ""
pendingExitReason := inferredReason
pendingSnapDir := activeDir
pendingSnapEntry := activeEntryPrice
pendingSnapSl := activeInitialSl
pendingSnapTp := activeBaseTp
pendingSnapEntryBar := activeEntryBar
pendingSnapEntryTime := activeEntryTime
pendingSnapshotReady := true
if inLong
strategy.exit("Long-X", from_entry = "Long", stop = activeCurrentStop, limit = enableTrailing ? na : activeBaseTp)
if inShort
strategy.exit("Short-X", from_entry = "Short", stop = activeCurrentStop, limit = enableTrailing ? na : activeBaseTp)
// Exit MA management.
if inPosition and not exitOrderSubmitted and exitStyle == "Exit on MA 1+3 Cross"
useExitNow = not exitMaLockoutActive
longExitNow = inLong and useExitNow and exitMaLongSignal
shortExitNow = inShort and useExitNow and exitMaShortSignal
if longExitNow or shortExitNow
pendingExitReason := "Exit on MA 1+3 Cross Exit"
pendingSnapDir := activeDir
pendingSnapEntry := activeEntryPrice
pendingSnapSl := activeInitialSl
pendingSnapTp := activeBaseTp
pendingSnapEntryBar := activeEntryBar
pendingSnapEntryTime := activeEntryTime
pendingSnapshotReady := true
if inLong
strategy.close("Long", immediately = true)
if inShort
strategy.close("Short", immediately = true)
exitOrderSubmitted := true
// Exit on opposite MA1/MA2 cross.
if inPosition and not exitOrderSubmitted and exitStyle == "Exit on MA 1+2 Cross"
longCrossExitNow = inLong and bearCross
shortCrossExitNow = inShort and bullCross
if longCrossExitNow or shortCrossExitNow
pendingExitReason := "MA1+2 Cross Exit"
pendingSnapDir := activeDir
pendingSnapEntry := activeEntryPrice
pendingSnapSl := activeInitialSl
pendingSnapTp := activeBaseTp
pendingSnapEntryBar := activeEntryBar
pendingSnapEntryTime := activeEntryTime
pendingSnapshotReady := true
if inLong
strategy.close("Long", immediately = true)
if inShort
strategy.close("Short", immediately = true)
exitOrderSubmitted := true
// Delayed confirmation entry management.
if heldEntryPending and not flat
heldEntryPending := false
heldEntryDir := 0
heldEntryStartBar := na
heldEntryReasonTag := ""
if useHeldEntry and heldEntryBars > 0 and flat and not pendingEntryArmed and not exitOrderSubmitted
if heldEntryPending
holdBarsElapsed = bar_index - heldEntryStartBar
holdComplete = holdBarsElapsed >= heldEntryBars
longHoldStillValid = heldEntryDir == 1 and ma1 > ma2 and ma4LongDirPass
shortHoldStillValid = heldEntryDir == -1 and ma1 < ma2 and ma4ShortDirPass
longHoldCancelled =
heldEntryDir == 1 and (
bearCross or
not longHoldStillValid or
entryBlockedByTime or
entryBlockedByCooldown)
shortHoldCancelled =
heldEntryDir == -1 and (
bullCross or
not shortHoldStillValid or
entryBlockedByTime or
entryBlockedByCooldown)
if longHoldCancelled or shortHoldCancelled
heldEntryPending := false
heldEntryDir := 0
heldEntryStartBar := na
heldEntryReasonTag := ""
else if holdComplete
if heldEntryDir == 1
_entry = close
_qty = getQty(_entry)
float _sl = na
float _tp = na
bool _okStop = true
bool _okTp = true
if exitStyle == "SL / TP Engine"
_sl := calcStopPrice(1, _entry)
_tp := calcTpPrice(1, _entry, _sl)
_okStop := isValidStop(1, _entry, _sl)
_okTp := not na(_tp) and _tp > _entry
if _qty > 0 and _okStop and _okTp
pendingEntryArmed := true
pendingEntryDir := 1
pendingEntrySl := _sl
pendingEntryTp := _tp
pendingEntryQty := _qty
pendingEntryTag := heldEntryReasonTag
pendingEntryExitStyle := exitStyle
strategy.entry("Long", strategy.long, qty = _qty)
longEntrySubmittedThisBar := true
heldEntryPending := false
heldEntryDir := 0
heldEntryStartBar := na
heldEntryReasonTag := ""
else if heldEntryDir == -1
_entry = close
_qty = getQty(_entry)
float _sl = na
float _tp = na
bool _okStop = true
bool _okTp = true
if exitStyle == "SL / TP Engine"
_sl := calcStopPrice(-1, _entry)
_tp := calcTpPrice(-1, _entry, _sl)
_okStop := isValidStop(-1, _entry, _sl)
_okTp := not na(_tp) and _tp < _entry
if _qty > 0 and _okStop and _okTp
pendingEntryArmed := true
pendingEntryDir := -1
pendingEntrySl := _sl
pendingEntryTp := _tp
pendingEntryQty := _qty
pendingEntryTag := heldEntryReasonTag
pendingEntryExitStyle := exitStyle
strategy.entry("Short", strategy.short, qty = _qty)
shortEntrySubmittedThisBar := true
heldEntryPending := false
heldEntryDir := 0
heldEntryStartBar := na
heldEntryReasonTag := ""
else
if standardLongSetupReady
heldEntryPending := true
heldEntryDir := 1
heldEntryStartBar := bar_index
heldEntryReasonTag := "Held Cross Entry (" + str.tostring(heldEntryBars) + " bars)"
else if standardShortSetupReady
heldEntryPending := true
heldEntryDir := -1
heldEntryStartBar := bar_index
heldEntryReasonTag := "Held Cross Entry (" + str.tostring(heldEntryBars) + " bars)"
// Standard entries when flat.
if flat and not pendingEntryArmed and not exitOrderSubmitted and (not useHeldEntry or heldEntryBars <= 0)
if longEntryReady
_entry = close
_qty = getQty(_entry)
float _sl = na
float _tp = na
bool _okStop = true
bool _okTp = true
if exitStyle == "SL / TP Engine"
_sl := calcStopPrice(1, _entry)
_tp := calcTpPrice(1, _entry, _sl)
_okStop := isValidStop(1, _entry, _sl)
_okTp := not na(_tp) and _tp > _entry
if _qty > 0 and _okStop and _okTp
pendingEntryArmed := true
pendingEntryDir := 1
pendingEntrySl := _sl
pendingEntryTp := _tp
pendingEntryQty := _qty
pendingEntryTag := "Cross Entry"
pendingEntryExitStyle := exitStyle
strategy.entry("Long", strategy.long, qty = _qty)
longEntrySubmittedThisBar := true
else if shortEntryReady
_entry = close
_qty = getQty(_entry)
float _sl = na
float _tp = na
bool _okStop = true
bool _okTp = true
if exitStyle == "SL / TP Engine"
_sl := calcStopPrice(-1, _entry)
_tp := calcTpPrice(-1, _entry, _sl)
_okStop := isValidStop(-1, _entry, _sl)
_okTp := not na(_tp) and _tp < _entry
if _qty > 0 and _okStop and _okTp
pendingEntryArmed := true
pendingEntryDir := -1
pendingEntrySl := _sl
pendingEntryTp := _tp
pendingEntryQty := _qty
pendingEntryTag := "Cross Entry"
pendingEntryExitStyle := exitStyle
strategy.entry("Short", strategy.short, qty = _qty)
shortEntrySubmittedThisBar := true
//══════════════════════════════════════════════════════════════════════════════
// Live plots and live trade box
//══════════════════════════════════════════════════════════════════════════════
liveEntryPlot = showLiveLinesEff and inPosition ? activeEntryPrice : na
liveStopPlot = showLiveLinesEff and inPosition and not na(activeCurrentStop) ? activeCurrentStop : na
liveTpPlot = showLiveLinesEff and inPosition and not na(activeBaseTp) ? activeBaseTp : na
liveTrailPlot = showLiveLinesEff and inPosition 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 inPosition and not na(activeEntryTime)
int leftTime = activeEntryTime
int rightTime = time
if not na(activeInitialSl) and not na(activeBaseTp)
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 na(liveProfitBox)
liveProfitBox := box.new(leftTime, math.max(activeEntryPrice, close), rightTime, math.min(activeEntryPrice, close), xloc = xloc.bar_time, border_color = color.new(color.white, 20), bgcolor = color.new(color.white, 93))
box.set_lefttop(liveProfitBox, leftTime, math.max(activeEntryPrice, close))
box.set_rightbottom(liveProfitBox, rightTime, math.min(activeEntryPrice, close))
else
if not na(liveProfitBox)
box.delete(liveProfitBox)
liveProfitBox := na
if not na(liveRiskBox)
box.delete(liveRiskBox)
liveRiskBox := na
//══════════════════════════════════════════════════════════════════════════════
// MA plots
//══════════════════════════════════════════════════════════════════════════════
plot(showMaPlotsEff ? ma1 : na, "Primary MA #1", ma1Color, 2)
plot(showMaPlotsEff ? ma2 : na, "Primary MA #2", ma2Color, 2)
plot(showMaPlotsEff and showExitMaPlot ? exitMa : na, "MA #3 / Exit MA", exitMaColor, 2)
plot(showMaPlotsEff and showMa4Plot ? ma4 : na, "MA #4 Confluence", ma4Color, 2)
//══════════════════════════════════════════════════════════════════════════════
// Status panel
//══════════════════════════════════════════════════════════════════════════════
var table statusTbl = na
if barstate.islast
if showStatusPanelEff
if na(statusTbl)
statusTbl := table.new(tablePosFromString(statusPos), 2, 7, border_width = 1)
else
table.set_position(statusTbl, tablePosFromString(statusPos))
holdBarsLeft = heldEntryPending and not na(heldEntryStartBar) ? math.max(heldEntryBars - (bar_index - heldEntryStartBar), 0) : na
stateRow = inPosition ? "IN TRADE" : heldEntryPending ? ("HOLD " + dirTxt(heldEntryDir) + " | " + str.tostring(holdBarsLeft) + " left") : (rawLongSignal or rawShortSignal ? "SETUP" : "WAITING")
posRow = inPosition ? (dirTxt(activeDir) + " | " + fmt(activeEntryPrice)) : "FLAT"
exitRow = inPosition ? activeExitStyle : exitStyle
blockCoolRow = blockActive ? "BLOCK ACTIVE" : chopCooldownActive ? ("CHOP " + str.tostring(chopCooldownUntilBar - bar_index) + " bars") : normalCooldownActive ? ("NORMAL " + str.tostring(reentryCooldownBars - (bar_index - lastPositionCloseBar)) + " bars") : "NONE"
ma4Row =
not useMa4Confluence ? "MA4 OFF" :
"Dir " + boolTxt((rawLongSignal ? ma4LongDirPass : rawShortSignal ? ma4ShortDirPass : true)) +
" | Dist " + (requireCrossAwayFromMa4 ? boolTxt(ma4DistancePass) : "OFF")
priceRow = inPosition ? (fmt(activeEntryPrice) + " / " + (not na(activeCurrentStop) ? fmt(activeCurrentStop) : "n/a") + " / " + (not na(activeBaseTp) ? fmt(activeBaseTp) : "n/a")) : heldEntryPending ? ("Hold " + str.tostring(holdBarsLeft) + " left") : "n/a"
blockedRow = whyBlocked
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, "Position", text_color = statusTxt, bgcolor = statusBg)
table.cell(statusTbl, 1, 1, posRow, text_color = statusTxt, bgcolor = statusBg)
table.cell(statusTbl, 0, 2, "Allowed", text_color = statusTxt, bgcolor = statusBg)
table.cell(statusTbl, 1, 2, tradeDirection, text_color = statusTxt, bgcolor = statusBg)
table.cell(statusTbl, 0, 3, "Exit Style", text_color = statusTxt, bgcolor = statusBg)
table.cell(statusTbl, 1, 3, exitRow, text_color = statusTxt, bgcolor = statusBg)
table.cell(statusTbl, 0, 4, "Block/Cooldown", text_color = statusTxt, bgcolor = statusBg)
table.cell(statusTbl, 1, 4, blockCoolRow, text_color = statusTxt, bgcolor = statusBg)
table.cell(statusTbl, 0, 5, "MA4 Filter", text_color = statusTxt, bgcolor = statusBg)
table.cell(statusTbl, 1, 5, ma4Row, text_color = statusTxt, bgcolor = statusBg)
table.cell(statusTbl, 0, 6, "Why / E-S-T", text_color = statusTxt, bgcolor = statusBg)
table.cell(statusTbl, 1, 6, blockedRow + " | " + priceRow, text_color = statusTxt, bgcolor = statusBg)
else
if not na(statusTbl)
table.delete(statusTbl)
statusTbl := na
//══════════════════════════════════════════════════════════════════════════════
// Alerts
//══════════════════════════════════════════════════════════════════════════════
if longEntrySubmittedThisBar and alertOnLongEntry
alert("Simple MA Cross Strategy: long entry", alert.freq_once_per_bar_close)
if shortEntrySubmittedThisBar and alertOnShortEntry
alert("Simple MA Cross Strategy: short entry", alert.freq_once_per_bar_close)
if trailArmEvent and alertOnTrailArm
alert("Simple MA Cross Strategy: trailing armed", alert.freq_once_per_bar_close)
if closedTradeEvent and lastClosedReason == "Exit on MA 1+3 Cross Exit" and alertOnExitMaExit
alert("Simple MA Cross Strategy: Exit on MA 1+3 Cross exit", alert.freq_once_per_bar_close)
if closedTradeEvent and closedSnapDir == 1 and alertOnLongExit
alert("Simple MA Cross Strategy: long exit", alert.freq_once_per_bar_close)
if closedTradeEvent and closedSnapDir == -1 and alertOnShortExit
alert("Simple MA Cross Strategy: short exit", alert.freq_once_per_bar_close)
if closedTradeEvent and lastClosedReason == "Time Block Exit" and alertOnTimeBlockExit
alert("Simple MA Cross Strategy: forced exit due to time block", alert.freq_once_per_bar_close)
if closedTradeEvent and lastClosedReason == "Chop Exit" and alertOnChopExit
alert("Simple MA Cross Strategy: chop exit", alert.freq_once_per_bar_close)
if closedTradeEvent and lastClosedReason == "Exit MA Exit" and alertOnExitMaExit
alert("Simple MA Cross Strategy: Exit MA exit", alert.freq_once_per_bar_close)
if closedTradeEvent and lastClosedReason == "MA1+2 Cross Exit" and alertOnCrossExit
alert("Simple MA Cross Strategy: MA 1+2 cross exit", alert.freq_once_per_bar_close)
if closedTradeEvent and (lastClosedReason == "SL Exit" or lastClosedReason == "Trail Exit") and alertOnStopHit
alert("Simple MA Cross Strategy: stop-style exit", alert.freq_once_per_bar_close)
if closedTradeEvent and lastClosedReason == "TP Exit" and alertOnTpHit
alert("Simple MA Cross Strategy: take-profit exit", alert.freq_once_per_bar_close)