本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
//@version=6
indicator("Buy/Sell Signals XL", overlay=true, max_lines_count=500, max_labels_count=500, max_boxes_count=500)
// ── Inputs ────────────────────────────────────────────────
nrMode = input.string("Entries + Exits", "Non-repaint", options=["Entries + Exits", "Entries Only", "Off"], tooltip="Entries + Exits: signals and SL/TP exits are confirmed only after the bar closes and never disappear or move (same as the old ON). Entries Only: signals wait for the bar close, but the SL or TP is registered the moment price touches it, like a real stop or limit order. This applies to Wick exit trigger only. With Close exit trigger, exits still wait for the bar close, because a live close can come and go. If the SL and TP are both touched on the same bar, the SL is assumed first, so a TP shown early in the bar can flip to an SL before the bar closes. Off: everything is live. Signals can appear while the bar is still forming and may vanish or flip before the bar closes (repainting), and entries, stops and targets can move. The scanner is not affected by this setting, it always reads closed bars. Alerts and the info box statistics are most reliable with Entries + Exits.")
mode = input.string("OC", "Signal mode", options=["OC", "Breakout", "Donchian", "MA Cross", "Supertrend"], tooltip="Chooses the signal engine. Only one mode runs at a time, and everything else (trade lines, lookback statistics, info box, scanner, alerts) is shared. OC: a large candle that closes beyond the prior candle's body. Breakout: a close or wick beyond a tight consolidation base. Donchian: a close beyond the Donchian channel (the highest high or lowest low of the last N bars). MA Cross: the fast moving average crosses the slow one. Supertrend: the Supertrend line flips from down to up (BUY) or from up to down (SELL). Each mode has its own settings group below, including its own stop loss and take profit settings, and the groups of the other modes are ignored. Enable SL/TP, Exit trigger and ATR length are shared by every mode and sit in the Stop Loss / Take Profit group.")
grpOC = "OC Mode"
bodyLen = input.int(50, "Average body length", minval=1, group=grpOC, tooltip="Number of bars used to calculate the average candle body (absolute distance between open and close). The signal candle's body is compared against this average. No signals can appear until this many bars of history exist. The same length is used for the average volume.")
bodyMult = input.float(3.0, "Min body vs average (x)", minval=0.0, step=0.5, group=grpOC, tooltip="Minimum size of the signal candle's body as a multiple of the average body. 3.0 means the body must be at least 3 times the average. Higher values give fewer, stronger signals. Set to 0 to remove the size filter.")
ocVol = input.float(0.0, "Min volume vs average (x)", minval=0.0, step=0.5, group=grpOC, tooltip="Minimum volume of the signal candle as a multiple of its average volume (same averaging length as the body average). 1.5 means the signal bar needs at least 1.5 times average volume. Set to 0 to turn the volume filter off. Needs volume data on the symbol: if none is available, no signals appear while this is above 0.")
ocAlt = input.bool(true, "Alternate signals", group=grpOC, tooltip="ON: signals alternate BUY, SELL, BUY and so on. A signal in the same direction as the open trade is skipped. OFF: every qualifying candle fires a signal. A bullish breakout candle always gives a BUY and a bearish one always gives a SELL, even if the previous signal went the same way. A repeat signal in the same direction closes the open trade at the signal bar's close (counted as a Signal exit) and opens a new one with a fresh entry, SL and TP.")
ocNoOvl = input.bool(true, "Ignore signals while a trade is open", group=grpOC, tooltip="ON: no new BUY or SELL fires while a trade is still open, so setups never overlap. The next signal can only appear after the open trade has hit its SL or TP. OFF: a new signal can fire inside an open trade and closes it at the signal bar's close (counted as a Signal exit). Applies only when Enable SL/TP is ON and the trade has a way to end on its own. If the Stop loss mode is None or the Take profit mode is Opposite signal, the trade can also end on a signal, so only same-direction signals are blocked and an opposite signal still closes the trade and opens a new one. If neither a stop nor a target is active, the toggle does nothing.")
ocSlMode = input.string("Candle wick", "Stop loss mode", options=["ATR", "Candle wick", "Candle body", "None"], group=grpOC, tooltip="ATR: the stop is placed at entry +/- ATR x the stop loss multiple. Candle wick: the stop is placed at the extreme of the signal candle, its low for a BUY and its high for a SELL. Candle body: the stop is placed at the signal candle's open (the far edge of its body). Candle modes give a different stop distance on every trade and ignore the Stop loss (x ATR) setting. The Stop buffer (x ATR) setting moves the candle stops further out. The info box shows the latest trade's stop size in ATR units (CW = candle wick, CB = candle body). None: no stop loss at all. No SL line or shading is drawn and trades are never stopped out. Take profit mode ATR target still works as a target only, and SL multiple has no stop distance to multiply so it behaves like Opposite signal. With None and Opposite signal, trades behave like Enable SL/TP OFF (stop-and-reverse), but the Entry line and label are still drawn for the open trade. Ignored when Enable SL/TP is OFF.")
ocSlBuf = input.float(0.0, "Stop buffer (x ATR)", minval=0.0, step=0.05, group=grpOC, tooltip="Extra distance added beyond the stop in the Candle wick and Candle body stop loss modes, in ATR: below the stop for a BUY and above it for a SELL. 0 places the stop exactly on the candle wick or body edge. Uses the ATR length in the Stop Loss / Take Profit group. Ignored by the ATR and None stop loss modes, and when Enable SL/TP is OFF.")
ocTpMode = input.string("SL multiple", "Take profit mode", options=["ATR target", "SL multiple", "Opposite signal"], group=grpOC, tooltip="ATR target: the take profit is placed at entry +/- ATR x the take profit (x ATR) multiple. SL multiple: the take profit is placed at entry +/- the stop distance x the take profit (x SL) multiple, so 2.0 means a reward of 2 times the risk, whichever Stop loss mode is used. Opposite signal: no fixed take profit. The trade stays open until the opposite BUY/SELL signal fires (or the stop loss is hit), and no TP line is drawn. Ignored when Enable SL/TP is OFF.")
ocSlMult = input.float(1.5, "Stop loss (x ATR)", minval=0.1, step=0.1, group=grpOC, tooltip="Used only when Stop loss mode is ATR. Stop loss distance from entry as a multiple of ATR. Long: entry minus this distance. Short: entry plus this distance.")
ocTpMult = input.float(3.0, "Take profit (x ATR)", minval=0.1, step=0.1, group=grpOC, tooltip="Used only when Enable SL/TP is ON and Take profit mode is ATR target. Take profit distance from entry as a multiple of ATR. Long: entry plus this distance. Short: entry minus this distance.")
ocTpRMult = input.float(1.0, "Take profit (x SL)", minval=0.1, step=0.1, group=grpOC, tooltip="Used only when Enable SL/TP is ON and Take profit mode is SL multiple. Take profit distance from entry as a multiple of the stop loss distance. Long: entry plus this distance. Short: entry minus this distance.")
grpBrk = "Breakout Mode"
baseMode = input.string("Fixed", "Base mode", options=["Fixed", "Variable"], group=grpBrk, tooltip="Fixed: the base is exactly Base length bars. Variable: the base is the longest run of bars before the signal candle, from Variable min base up to Variable max base, whose height still fits within Max base height (x ATR). A longer tight base then qualifies. The base box, the Base height take profit and the fresh-base rule all use the length actually found.")
baseLen = input.int(10, "Fixed base length (bars)", minval=3, group=grpBrk, tooltip="Number of candles before the signal candle that form the base. The base is the highest high and lowest low of these candles. A BUY fires when a candle closes above the base high, a SELL when it closes below the base low. No signals can appear until this many bars of history exist. Used in Fixed base mode only. Variable base mode uses the Variable min base and Variable max base settings instead.")
varMin = input.int(5, "Variable min base (bars)", minval=3, maxval=200, group=grpBrk, tooltip="Used only when Base mode is Variable: the shortest base that counts, in bars. A base shorter than this is never accepted.")
varMax = input.int(30, "Variable max base (bars)", minval=3, maxval=200, group=grpBrk, tooltip="Used only when Base mode is Variable: the longest base the script will look for, in bars. A value below Variable min base is treated as equal to it.")
baseMult = input.float(3.0, "Max base height (x ATR)", minval=0.1, step=0.1, group=grpBrk, tooltip="A base counts as tight when its height (highest high minus lowest low of the base length) is no more than this many ATR. Smaller values mean only very tight bases qualify and give fewer signals. Uses the ATR length from the Stop Loss / Take Profit group.")
brkMode = input.string("Bar Close (Edge)", "Breakout entry mode", options=["Bar Close (Edge)", "Bar Close (Entry)", "Bar Wick (Edge)"], group=grpBrk, tooltip="Bar Close (Edge): the signal needs a bar to close beyond the base edge, and the entry, stop and target are measured from the base edge price (the breakout point), where a stop order at the edge would have filled. You get the cleaner signals of a close with the entry marked at the breakout. Bar Close (Entry): the signal needs a bar to close beyond the base edge, and the entry is that bar's close. Bar Wick (Edge): a breakout counts as soon as a bar's high goes above the base high (BUY) or its low goes below the base low (SELL), even if it closes back inside, and the entry is the base edge price (plus or minus the Min breakout strength) where price crossed. Bar Wick gives more signals and more false ones. If one bar pokes through both edges in Bar Wick mode, its color decides: a green bar gives a BUY and a red one a SELL. Signals still wait for the bar to close when Non-repaint is ON.")
minBreak = input.float(0.0, "Min breakout strength (x ATR)", minval=0.0, step=0.1, group=grpBrk, tooltip="The close must clear the base edge by at least this many ATR. 0 means any close beyond the base counts. Higher values filter out weak breakouts that barely poke through the edge.")
brkVol = input.float(0.0, "Min volume vs average (x)", minval=0.0, step=0.5, group=grpBrk, tooltip="Minimum volume of the signal candle as a multiple of its average volume. 1.5 means the signal bar needs at least 1.5 times average volume. Set to 0 to turn the volume filter off. Needs volume data on the symbol: if none is available, no signals appear while this is above 0.")
brkVolLen = input.int(50, "Average volume length", minval=1, group=grpBrk, tooltip="Number of bars used to calculate the average volume. Used only when Min volume vs average is above 0.")
brkTrend = input.bool(false, "Trend filter", group=grpBrk, tooltip="ON: BUY only fires when the close is above the trend EMA and SELL only when it is below it. OFF: no trend filter.")
brkTrendLen = input.int(200, "Trend EMA length", minval=2, group=grpBrk, tooltip="Length of the EMA used by the trend filter. Used only when Trend filter is ON.")
brkShowTrend = input.bool(false, "Show trend EMA", group=grpBrk, tooltip="Plots the trend EMA on the chart. Used only for display: the Trend filter setting controls whether it affects signals.")
brkEmaCol = input.color(color.orange, "Trend EMA color", group=grpBrk, tooltip="Color of the trend EMA line. Used only when Show trend EMA is ON.")
brkEmaW = input.int(1, "Trend EMA width", minval=1, maxval=5, group=grpBrk, tooltip="Thickness of the trend EMA line. Used only when Show trend EMA is ON.")
brkAlt = input.bool(true, "Alternate signals", group=grpBrk, tooltip="ON: signals alternate BUY, SELL, BUY and so on. A signal in the same direction as the open trade is skipped. OFF: every qualifying breakout fires. A repeat signal in the same direction closes the open trade at the signal bar's close (counted as a Signal exit) and opens a new one with a fresh entry, SL and TP. Either way, a new signal needs a fresh base: the base window must not contain the previous signal candle.")
brkNoOvl = input.bool(true, "Ignore signals while a trade is open", group=grpBrk, tooltip="ON: no new BUY or SELL fires while a trade is still open, so setups never overlap. The next signal can only appear after the open trade has hit its SL or TP. OFF: a new signal can fire inside an open trade and closes it at the signal bar's close (counted as a Signal exit). Only applies when Enable SL/TP is ON and at least one of the stop loss or take profit is active, because otherwise a trade only ends on a new signal and every signal would be blocked.")
noBaseInTrade = input.bool(true, "Ignore base development while a trade is open", group=grpBrk, tooltip="ON: a base only counts if all of its candles formed after the last trade ended (hit its SL or TP). Candles that printed while a trade was open cannot be part of the next base, so a setup cannot be built from the very candles of the trade before it. After a trade ends, a full base length of new bars (the Variable min base in Variable mode) must pass before the next signal. OFF: the base can include candles from inside a previous trade. Only applies when Enable SL/TP is ON, because only then does a trade end on its own at its SL or TP.")
brkShowBase = input.bool(true, "Show base zones", group=grpBrk, tooltip="Draws a box around the base (highest high to lowest low of the base length) behind each BUY or SELL.")
brkSlMode = input.string("Base edge", "Stop loss mode", options=["ATR", "Base edge"], group=grpBrk, tooltip="ATR: the stop is placed at entry +/- ATR x the stop loss multiple. Base edge: the stop is placed at the far side of the base, its low (minus the stop buffer) for a BUY and its high (plus the buffer) for a SELL. Base edge gives a different stop distance on every trade and ignores the Stop loss (x ATR) setting. If the base stop would not be beyond the entry price, the signal is skipped and no trade is opened. The info box shows the latest trade's stop size in ATR units (BE = base edge). Ignored when Enable SL/TP is OFF.")
brkSlBuf = input.float(0.0, "Stop buffer (x ATR)", minval=0.0, step=0.05, group=grpBrk, tooltip="Extra distance added beyond the base edge, in ATR. Used only when Stop loss mode is Base edge.")
brkTpMode = input.string("Base height", "Take profit mode", options=["ATR target", "SL multiple", "Base height"], group=grpBrk, tooltip="ATR target: the take profit is placed at entry +/- ATR x the take profit (x ATR) multiple. SL multiple: the take profit is placed at entry +/- the stop distance x the take profit (x SL) multiple, so 2.0 means a reward of 2 times the risk, whichever Stop loss mode is used. Base height: the take profit is placed at entry +/- the base height x the take profit (x base height) multiple. Ignored when Enable SL/TP is OFF.")
brkSlMult = input.float(1.5, "Stop loss (x ATR)", minval=0.1, step=0.1, group=grpBrk, tooltip="Used when Stop loss mode is ATR. Stop loss distance from entry as a multiple of ATR. Long: entry minus this distance. Short: entry plus this distance.")
brkTpMult = input.float(3.0, "Take profit (x ATR)", minval=0.1, step=0.1, group=grpBrk, tooltip="Used only when Enable SL/TP is ON and Take profit mode is ATR target. Take profit distance from entry as a multiple of ATR. Long: entry plus this distance. Short: entry minus this distance.")
brkTpRMult = input.float(2.0, "Take profit (x SL)", minval=0.1, step=0.1, group=grpBrk, tooltip="Used only when Enable SL/TP is ON and Take profit mode is SL multiple. Take profit distance from entry as a multiple of the stop loss distance. Long: entry plus this distance. Short: entry minus this distance.")
brkTpBMult = input.float(1.0, "Take profit (x base height)", minval=0.1, step=0.1, group=grpBrk, tooltip="Used only when Enable SL/TP is ON and Take profit mode is Base height. Take profit distance from entry as a multiple of the base's height. Long: entry plus this distance. Short: entry minus this distance.")
grpDon = "Donchian Mode"
donLen = input.int(20, "Channel length", minval=2, group=grpDon, tooltip="Number of bars in the Donchian channel. The upper band is the highest high of the previous bars and the lower band is the lowest low of the previous bars (the signal bar itself is not included). A BUY fires when a bar closes above the upper band and a SELL when a bar closes below the lower band. Longer lengths give fewer, slower signals. Shorter lengths give more, faster signals. No signals can appear until this many bars of history exist. The same length is used for the volume average.")
donEntMode = input.string("Bar Close (Edge)", "Entry mode", options=["Bar Close (Entry)", "Bar Close (Edge)"], group=grpDon, tooltip="Bar Close (Entry): the entry is the close of the signal candle. Bar Close (Edge): the signal still needs a bar to close beyond the channel, but the entry is the channel band that price broke (the upper band for a BUY, the lower band for a SELL). The stop loss and take profit are measured from the entry in both modes.")
donVol = input.float(0.0, "Min volume vs average (x)", minval=0.0, step=0.5, group=grpDon, tooltip="Minimum volume of the signal candle as a multiple of its average volume (averaged over the channel length). 1.5 means the signal bar needs at least 1.5 times average volume. Set to 0 to turn the volume filter off. Needs volume data on the symbol: if none is available, no signals appear while this is above 0.")
donAlt = input.bool(true, "Alternate signals", group=grpDon, tooltip="ON: signals alternate BUY, SELL, BUY and so on. A signal in the same direction as the open trade is skipped. OFF: every bar that closes beyond a band fires a signal. A close above the upper band always gives a BUY and a close below the lower band always gives a SELL, even if the previous signal went the same way. In a strong trend that can mean a signal on every new high or low. A repeat signal in the same direction closes the open trade at the signal bar's close (counted as a Signal exit) and opens a new one with a fresh entry, SL and TP.")
donNoOvl = input.bool(true, "Ignore signals while a trade is open", group=grpDon, tooltip="ON: no new BUY or SELL fires while a trade is still open, so setups never overlap. The next signal can only appear after the open trade has hit its SL or TP. OFF: a new signal can fire inside an open trade and closes it at the signal bar's close (counted as a Signal exit). Applies only when Enable SL/TP is ON and the trade has a way to end on its own. If the Stop loss mode is None or the Take profit mode is Opposite signal, the trade can also end on a signal, so only same-direction signals are blocked and an opposite signal still closes the trade and opens a new one. If neither a stop nor a target is active, the toggle does nothing.")
donShowChan = input.bool(true, "Show Donchian channel", group=grpDon, tooltip="Plots the upper and lower channel bands. Signals, alerts and the info box are not affected.")
donChanCol = input.color(#787B86, "Channel color", group=grpDon, tooltip="Color of the upper and lower bands. Used only when Show Donchian channel is ON.")
donShade = input.bool(true, "Show channel shading", group=grpDon, tooltip="Shades the area between the upper and lower bands. Used only when Show Donchian channel is ON.")
donShadeCol = input.color(color.new(#787B86, 92), "Channel shading color", group=grpDon, tooltip="Color and transparency of the shading between the bands. Used only when Show Donchian channel and Show channel shading are ON.")
donShowMid = input.bool(true, "Show middle line", group=grpDon, tooltip="Plots the middle line of the channel (the average of the upper and lower bands). Used only when Show Donchian channel is ON. The Channel middle stop loss mode uses this line whether or not it is shown.")
donSlMode = input.string("Channel opposite", "Stop loss mode", options=["ATR", "Channel opposite", "Channel middle", "Candle wick", "Candle body", "None"], group=grpDon, tooltip="ATR: the stop is placed at entry +/- ATR x the stop loss multiple. Channel opposite: the stop is placed at the opposite band of the channel on the signal bar (the lower band for a BUY, the upper band for a SELL). Channel middle: the stop is placed at the middle line of the channel on the signal bar. Candle wick: the stop is placed at the extreme of the signal candle, its low for a BUY and its high for a SELL. Candle body: the stop is placed at the signal candle's open (the far edge of its body). The channel and candle modes give a different stop distance on every trade and ignore the Stop loss (x ATR) setting. The Stop buffer (x ATR) setting moves them further out. The info box shows the latest trade's stop size in ATR units (CO = channel opposite, CM = channel middle, CW = candle wick, CB = candle body). None: no stop loss at all. No SL line or shading is drawn and trades are never stopped out. Take profit mode ATR target still works as a target only, and SL multiple has no stop distance to multiply so it behaves like Opposite signal. With None and Opposite signal, trades behave like Enable SL/TP OFF (stop-and-reverse), but the Entry line and label are still drawn for the open trade. Ignored when Enable SL/TP is OFF.")
donSlBuf = input.float(0.0, "Stop buffer (x ATR)", minval=0.0, step=0.05, group=grpDon, tooltip="Extra distance added beyond the stop in the Channel opposite, Channel middle, Candle wick and Candle body stop loss modes, in ATR: below the stop for a BUY and above it for a SELL. 0 places the stop exactly on the band, middle line, wick or body edge. Uses the ATR length in the Stop Loss / Take Profit group. Ignored by the ATR and None stop loss modes, and when Enable SL/TP is OFF.")
donTpMode = input.string("SL multiple", "Take profit mode", options=["ATR target", "SL multiple", "Opposite signal"], group=grpDon, tooltip="ATR target: the take profit is placed at entry +/- ATR x the take profit (x ATR) multiple. SL multiple: the take profit is placed at entry +/- the stop distance x the take profit (x SL) multiple, so 2.0 means a reward of 2 times the risk, whichever Stop loss mode is used. Opposite signal: no fixed take profit. The trade stays open until the opposite BUY/SELL signal fires (or the stop loss is hit), and no TP line is drawn. Ignored when Enable SL/TP is OFF.")
donSlMult = input.float(2.0, "Stop loss (x ATR)", minval=0.1, step=0.1, group=grpDon, tooltip="Used only when Stop loss mode is ATR. Stop loss distance from entry as a multiple of ATR. Long: entry minus this distance. Short: entry plus this distance.")
donTpMult = input.float(3.0, "Take profit (x ATR)", minval=0.1, step=0.1, group=grpDon, tooltip="Used only when Enable SL/TP is ON and Take profit mode is ATR target. Take profit distance from entry as a multiple of ATR. Long: entry plus this distance. Short: entry minus this distance.")
donTpRMult = input.float(0.5, "Take profit (x SL)", minval=0.1, step=0.1, group=grpDon, tooltip="Used only when Enable SL/TP is ON and Take profit mode is SL multiple. Take profit distance from entry as a multiple of the stop loss distance. Long: entry plus this distance. Short: entry minus this distance.")
grpMA = "MA Cross Mode"
fastLen = input.int(9, "Fast MA length", minval=1, group=grpMA, tooltip="Length of the fast moving average. A BUY fires when the fast MA crosses above the slow MA and a SELL when it crosses below. Shorter lengths react faster and give more signals. Keep it below the slow MA length.")
slowLen = input.int(21, "Slow MA length", minval=2, group=grpMA, tooltip="Length of the slow moving average. Longer lengths give fewer, slower signals. No signals can appear until this many bars of history exist. The same length is used for the volume average.")
maType = input.string("EMA", "MA type", options=["SMA", "EMA", "WMA", "HMA", "RMA"], group=grpMA, tooltip="Type of moving average used for both lines (and the trend filter). SMA: simple average. EMA: gives more weight to recent bars. WMA: weighted average. HMA: Hull, very fast and smooth. RMA: Wilder smoothing, slow and steady.")
maSrc = input.string("Close", "MA source", options=["Close", "Open", "High", "Low", "HL2", "HLC3", "OHLC4"], group=grpMA, tooltip="Price used to calculate the moving averages. Close is the usual choice. HL2 is the average of the high and low, HLC3 adds the close, and OHLC4 is the average of all four prices.")
minSep = input.float(0.0, "Min cross strength (x ATR)", minval=0.0, step=0.05, group=grpMA, tooltip="Filter for weak crosses. On the signal bar the gap between the fast and slow MA must be at least this many ATR. Right after a cross the gap is small, so useful values are small, for example 0.05 to 0.3. A cross of two lines that barely separate is skipped. 0 turns the filter off. Uses the ATR length in the Stop Loss / Take Profit group.")
maTrend = input.bool(false, "Trend filter", group=grpMA, tooltip="ON: BUY signals fire only when the close is above the trend MA and SELL signals only when it is below. This skips crosses against the bigger trend. The trend MA uses the MA type above and the length below. OFF: no trend filter.")
maTrendLen = input.int(200, "Trend MA length", minval=2, group=grpMA, tooltip="Length of the trend MA. Used only when Trend filter is ON. No signals can appear until this many bars of history exist while the filter is ON.")
maEntMode = input.string("Bar Close (Edge)", "Entry mode", options=["Bar Close (Entry)", "Bar Close (Edge)"], group=grpMA, tooltip="Bar Close (Entry): the entry is the close of the signal candle. Bar Close (Edge): the signal still needs a bar to close with the fast MA across the slow MA, but the entry is the slow MA price, kept inside the signal candle's high and low range so it is always a price the bar traded at. The stop loss and take profit are measured from the entry in both modes.")
maVol = input.float(0.0, "Min volume vs average (x)", minval=0.0, step=0.5, group=grpMA, tooltip="Minimum volume of the signal candle as a multiple of its average volume (averaged over the slow MA length). 1.5 means the signal bar needs at least 1.5 times average volume. Set to 0 to turn the volume filter off. Needs volume data on the symbol: if none is available, no signals appear while this is above 0.")
maAlt = input.bool(false, "Alternate signals", group=grpMA, tooltip="ON: signals alternate BUY, SELL, BUY and so on. A signal in the same direction as the open trade is skipped. OFF: every qualifying crossover fires a signal. Crossovers alternate by nature, so a repeat in the same direction only happens when a filter removed the crossover in between. A repeat signal in the same direction closes the open trade at the signal bar's close (counted as a Signal exit) and opens a new one with a fresh entry, SL and TP.")
maNoOvl = input.bool(true, "Ignore signals while a trade is open", group=grpMA, tooltip="ON: no new BUY or SELL fires while a trade is still open, so setups never overlap. The next signal can only appear after the open trade has hit its SL or TP. OFF: a new signal can fire inside an open trade and closes it at the signal bar's close (counted as a Signal exit). Applies only when Enable SL/TP is ON and the trade has a way to end on its own. If the Stop loss mode is None or the Take profit mode is Opposite signal, the trade can also end on a signal, so only same-direction signals are blocked and an opposite signal still closes the trade and opens a new one. If neither a stop nor a target is active, the toggle does nothing.")
maShowMAs = input.bool(true, "Show moving averages", group=grpMA, tooltip="Plots the fast and slow moving averages. Signals, alerts and the info box are not affected.")
maFastCol = input.color(#FF9800, "Fast MA color", group=grpMA, tooltip="Color of the fast MA line. Used only when Show moving averages is ON.")
maSlowCol = input.color(#9C27B0, "Slow MA color", group=grpMA, tooltip="Color of the slow MA line. Used only when Show moving averages is ON.")
maShowFill = input.bool(true, "Show MA shading", group=grpMA, tooltip="Shades the area between the fast and slow MA with the Buy color when the fast MA is above the slow MA and the Sell color when it is below. Used only when Show moving averages is ON.")
maTrendCol = input.color(#787B86, "Trend MA color", group=grpMA, tooltip="Color of the trend MA line. It is plotted only when Trend filter is ON.")
maSlMode = input.string("ATR", "Stop loss mode", options=["ATR", "Swing", "Candle wick", "Candle body", "None"], group=grpMA, tooltip="ATR: the stop is placed at entry +/- ATR x the stop loss multiple. Swing: the stop is placed at the lowest low (BUY) or highest high (SELL) of the last Swing length bars, including the signal bar. Candle wick: the stop is placed at the extreme of the signal candle, its low for a BUY and its high for a SELL. Candle body: the stop is placed at the signal candle's open (the far edge of its body). The swing and candle modes give a different stop distance on every trade and ignore the Stop loss (x ATR) setting. The Stop buffer (x ATR) setting moves them further out and the Min stop distance (x ATR) setting keeps them a minimum distance from the entry. The info box shows the latest trade's stop size in ATR units (SW = swing, CW = candle wick, CB = candle body). None: no stop loss at all. No SL line or shading is drawn and trades are never stopped out. Take profit mode ATR target still works as a target only, and SL multiple has no stop distance to multiply so it behaves like Opposite signal. With None and Opposite signal, trades behave like Enable SL/TP OFF (stop-and-reverse), but the Entry line and label are still drawn for the open trade. Ignored when Enable SL/TP is OFF.")
swingLen = input.int(5, "Swing length (bars)", minval=1, group=grpMA, tooltip="Number of bars used to find the swing low or high for the Swing stop loss mode, including the signal bar. Used only when Stop loss mode is Swing. Ignored when Enable SL/TP is OFF.")
maSlBuf = input.float(0.0, "Stop buffer (x ATR)", minval=0.0, step=0.05, group=grpMA, tooltip="Extra distance added beyond the stop in the Swing, Candle wick and Candle body stop loss modes, in ATR: below the stop for a BUY and above it for a SELL. 0 places the stop exactly on the swing level, wick or body edge. Uses the ATR length in the Stop Loss / Take Profit group. Ignored by the ATR and None stop loss modes, and when Enable SL/TP is OFF.")
slMin = input.float(1.0, "Min stop distance (x ATR)", minval=0.0, step=0.05, group=grpMA, tooltip="Minimum distance between the entry and the stop in the Swing, Candle wick and Candle body stop loss modes, in ATR. If the stop would sit closer than this to the entry, or on the wrong side of it, it is pushed out to this distance. This keeps the Entry, SL and TP lines from stacking on each other, which can happen with Bar Close (Edge) entries or doji candles, where the entry can sit right on the candle wick or body edge. The take profit in SL multiple mode is measured from the final stop distance. 0 turns the minimum off. Uses the ATR length in the Stop Loss / Take Profit group. Ignored by the ATR and None stop loss modes, and when Enable SL/TP is OFF.")
maTpMode = input.string("SL multiple", "Take profit mode", options=["ATR target", "SL multiple", "Opposite signal"], group=grpMA, tooltip="ATR target: the take profit is placed at entry +/- ATR x the take profit (x ATR) multiple. SL multiple: the take profit is placed at entry +/- the stop distance x the take profit (x SL) multiple, so 2.0 means a reward of 2 times the risk, whichever Stop loss mode is used. Opposite signal: no fixed take profit. The trade stays open until the opposite BUY/SELL signal fires (or the stop loss is hit), and no TP line is drawn. Ignored when Enable SL/TP is OFF.")
maSlMult = input.float(2.0, "Stop loss (x ATR)", minval=0.1, step=0.1, group=grpMA, tooltip="Used only when Stop loss mode is ATR. Stop loss distance from entry as a multiple of ATR. Long: entry minus this distance. Short: entry plus this distance.")
maTpMult = input.float(3.0, "Take profit (x ATR)", minval=0.1, step=0.1, group=grpMA, tooltip="Used only when Enable SL/TP is ON and Take profit mode is ATR target. Take profit distance from entry as a multiple of ATR. Long: entry plus this distance. Short: entry minus this distance.")
maTpRMult = input.float(1.0, "Take profit (x SL)", minval=0.1, step=0.1, group=grpMA, tooltip="Used only when Enable SL/TP is ON and Take profit mode is SL multiple. Take profit distance from entry as a multiple of the stop loss distance. Long: entry plus this distance. Short: entry minus this distance.")
grpST = "Supertrend Mode"
stLen = input.int(10, "Supertrend ATR length", minval=1, group=grpST, tooltip="Number of bars used for the ATR inside the Supertrend calculation. Shorter values make the line follow price more closely and flip more often. Longer values make it smoother and slower. This is separate from the ATR length in the Stop Loss / Take Profit group, which only sizes the stop and target. No signals can appear until the Supertrend has enough bars of history.")
stMult = input.float(3.0, "Supertrend factor", minval=0.1, step=0.1, group=grpST, tooltip="How far the Supertrend line sits from price, as a multiple of its ATR. Higher values keep the line further away, so it flips less often and gives fewer, slower signals. Lower values keep it close and give more, faster signals. A BUY fires when price closes above the line and the trend flips to up. A SELL fires when price closes below the line and the trend flips to down.")
stEntMode = input.string("Bar Close (Entry)", "Entry mode", options=["Bar Close (Entry)", "Bar Close (Edge)"], group=grpST, tooltip="Bar Close (Entry): the entry is the close of the signal candle. Bar Close (Edge): the signal still needs a bar to close beyond the Supertrend line, but the entry is the line price that price broke (the Supertrend value from the bar before the flip), kept inside the signal candle's high and low range so it is always a price the bar traded at. The stop loss and take profit are measured from the entry in both modes.")
stNoOvl = input.bool(true, "Ignore signals while a trade is open", group=grpST, tooltip="ON: no new BUY or SELL fires while a trade is still open, so setups never overlap. The next signal can only appear after the open trade has hit its SL or TP. A flip on the same bar where the open trade hits its SL or TP still fires. OFF: a new signal can fire inside an open trade and closes it at the signal bar's close (counted as a Signal exit). Applies only when Enable SL/TP is ON and the trade has a way to end on its own. If the Stop loss mode is None or the Take profit mode is Opposite signal, the trade can also end on a signal, so only same-direction signals are blocked and an opposite signal still closes the trade and opens a new one. If neither a stop nor a target is active, the toggle does nothing.")
stShowLine = input.bool(true, "Show Supertrend line", group=grpST, tooltip="Draws the Supertrend line on the chart: the Buy color while the trend is up and the Sell color while it is down. Signals, alerts and the info box are not affected.")
stLineW = input.int(2, "Supertrend line width", minval=1, maxval=4, group=grpST, tooltip="Thickness of the Supertrend line. Used only when Show Supertrend line is ON.")
stSlMode = input.string("Supertrend line", "Stop loss mode", options=["Supertrend line", "ATR", "Candle wick", "Candle body", "None"], group=grpST, tooltip="Supertrend line: the stop is placed on the Supertrend line value at the signal bar. The line sits below price for a BUY and above it for a SELL. The stop is locked in for the trade and does not trail. ATR: the stop is placed at entry +/- ATR x the stop loss multiple. Candle wick: the stop is placed at the extreme of the signal candle, its low for a BUY and its high for a SELL. Candle body: the stop is placed at the signal candle's open (the far edge of its body). The Supertrend line and candle modes give a different stop distance on every trade and ignore the Stop loss (x ATR) setting. The Stop buffer (x ATR) setting moves them further out. The info box shows the latest trade's stop size in ATR units (ST = Supertrend line, CW = candle wick, CB = candle body). None: no stop loss at all. No SL line or shading is drawn and trades are never stopped out. Take profit mode ATR target still works as a target only, and SL multiple has no stop distance to multiply so it behaves like Opposite signal. With None and Opposite signal, trades behave like Enable SL/TP OFF (stop-and-reverse), but the Entry line and label are still drawn for the open trade. Ignored when Enable SL/TP is OFF.")
stSlBuf = input.float(0.0, "Stop buffer (x ATR)", minval=0.0, step=0.05, group=grpST, tooltip="Extra distance added beyond the stop in the Supertrend line, Candle wick and Candle body stop loss modes, in ATR: below the stop for a BUY and above it for a SELL. 0 places the stop exactly on the line, wick or body edge. Uses the ATR length in the Stop Loss / Take Profit group. Ignored by the ATR and None stop loss modes, and when Enable SL/TP is OFF.")
stTpMode = input.string("SL multiple", "Take profit mode", options=["ATR target", "SL multiple", "Opposite signal"], group=grpST, tooltip="ATR target: the take profit is placed at entry +/- ATR x the take profit (x ATR) multiple. SL multiple: the take profit is placed at entry +/- the stop distance x the take profit (x SL) multiple, so 2.0 means a reward of 2 times the risk, whichever Stop loss mode is used. Opposite signal: no fixed take profit. The trade stays open until the opposite BUY/SELL signal fires (or the stop loss is hit), and no TP line is drawn. Ignored when Enable SL/TP is OFF.")
stSlMult = input.float(1.5, "Stop loss (x ATR)", minval=0.1, step=0.1, group=grpST, tooltip="Used only when Stop loss mode is ATR. Stop loss distance from entry as a multiple of ATR. Long: entry minus this distance. Short: entry plus this distance.")
stTpMult = input.float(3.0, "Take profit (x ATR)", minval=0.1, step=0.1, group=grpST, tooltip="Used only when Enable SL/TP is ON and Take profit mode is ATR target. Take profit distance from entry as a multiple of ATR. Long: entry plus this distance. Short: entry minus this distance.")
stTpRMult = input.float(0.5, "Take profit (x SL)", minval=0.1, step=0.1, group=grpST, tooltip="Used only when Enable SL/TP is ON and Take profit mode is SL multiple. Take profit distance from entry as a multiple of the stop loss distance. Long: entry plus this distance. Short: entry minus this distance.")
grpRisk = "Stop Loss / Take Profit"
useRisk = input.bool(true, "Enable SL/TP", group=grpRisk, tooltip="ON: the stop loss is placed using the Stop loss mode, Entry/SL/TP lines are drawn for the current open trade, and trades close when the SL or TP is hit. The info box statistics then include those exits. OFF: pure stop-and-reverse. No lines are drawn, trades only close on the opposite signal, and every other setting in this group is ignored.")
exitMode = input.string("Wick", "Exit trigger", options=["Wick", "Close"], group=grpRisk, tooltip="Wick: the SL or TP is hit as soon as the bar's high or low touches the level, and the trade exits at that exact price. Close: the SL or TP is hit only when a bar closes at or beyond the level, and the trade exits at that bar's close, so the result can be larger or smaller than the exact level. Ignored when Enable SL/TP is OFF.")
atrLen = input.int(14, "ATR length", minval=1, group=grpRisk, tooltip="Number of bars used for the ATR value, shared by every mode. ATR is read on the signal bar and locked in for that trade. It is also used by the Breakout base height and breakout strength checks, the MA Cross minimum cross strength filter, and the stop buffer and minimum stop distance settings.")
grpLB = "Lookback P/L"
lookback = input.int(20, "Lookback (last N closed trades)", minval=1, group=grpLB, tooltip="Number of most recent closed trades included in the info box statistics (the average time between signals and the average time per signal use the same count). Older trades drop out as new ones close. Each signal closes the open trade and opens a new one (the opposite direction when Alternate signals is ON), using the signal bar's close as the price. With SL/TP enabled, trades can also close at their SL or TP price.")
showTable = input.bool(true, "Show info box", group=grpLB, tooltip="Turns the lookback P/L info box on or off.")
tablePos = input.string("Top Right", "Info box position", options=["Top Left", "Top Center", "Top Right", "Middle Left", "Middle Center", "Middle Right", "Bottom Left", "Bottom Center", "Bottom Right"], group=grpLB, tooltip="Chart location of the info box.")
tableSize = input.string("Small", "Info box size", options=["Tiny", "Small", "Normal", "Large", "Huge"], group=grpLB, tooltip="Text size used inside the info box.")
showClosed = input.int(0, "Show closed trades", minval=0, maxval=50, group=grpLB, tooltip="Number of most recent closed trade setups kept on the chart. Each closed setup stays frozen from its entry bar to its exit bar (Entry, SL and TP lines, labels and shading), then the oldest one is removed when the limit is exceeded. 0 = off: only the current trade is drawn. When above 0, closed setups are kept even if Show exit X is OFF (the X itself still follows Show exit X). Uses the same drawing toggles as the current trade. Ignored when Enable SL/TP is OFF.")
grpScan = "Multi-Timeframe Scanner"
showScan = input.bool(true, "Show scanner", group=grpScan, tooltip="Shows a table that scans the chart's symbol on the timeframes below, using the same signal, stop loss, take profit and lookback settings as this indicator. Each timeframe keeps its own trade history and statistics. The candle type follows the chart (Standard or Heikin Ashi). Other chart types (Renko, Kagi and so on) cannot be copied, so the scanner falls back to Standard candles. Turn it off to save data requests and calculation time. Alerts and the info box are not affected.")
scTfList = input.text_area("5, 15, 30, 60, 4h, D", "Scanner timeframes (comma separated)", group=grpScan, tooltip="Timeframes to scan, separated by commas or one per line. The Engine Scanner uses this same list. Use plain numbers for minutes (15, 60, 240), or short forms such as 15m, 4h, 1D, 1W. A capital M means month, so use a lowercase m for minutes. A timeframe that TradingView does not recognise stops the script with an error.")
scMax = input.int(8, "Max timeframes", minval=1, maxval=64, group=grpScan, tooltip="How many timeframes to scan, taken from the top of the list. The Engine Scanner uses this same setting. Each timeframe is one data request. TradingView allows 40 unique requests per script on most plans and 64 on Professional plans (Expert, Ultimate), and the script errors if the plan limit is exceeded.")
scPosIn = input.string("Top Center", "Scanner position", options=["Top Left", "Top Center", "Top Right", "Middle Left", "Middle Center", "Middle Right", "Bottom Left", "Bottom Center", "Bottom Right"], group=grpScan, tooltip="Chart location of the scanner table.")
scSizeIn = input.string("Small", "Scanner size", options=["Tiny", "Small", "Normal", "Large", "Huge"], group=grpScan, tooltip="Text size used inside the scanner table.")
scDetail = input.string("High", "Scanner detail", options=["Micro", "Low", "Medium", "High", "Maximum"], group=grpScan, tooltip="How many columns the scanner table shows. High: Timeframe, Signal, Status, Avg Between, Entry, SL, TP, Open P/L, Avg P/L, Net P/L and Win Rate. Medium: High without Entry, SL and TP. Low: Medium without Open P/L and Avg P/L (Timeframe, Signal, Status, Avg Between, Net P/L and Win Rate). Micro: Low without Avg Between and Net P/L (Timeframe, Signal, Status and Win Rate). Maximum: High plus Last Signal (time since the last signal, after Avg Between) and Max DD (maximum drawdown over the lookback trades, after Net P/L). The calculation is the same at every level.")
grpEng = "Engine Scanner"
showEng = input.bool(true, "Show engine scanner", group=grpEng, tooltip="Shows a second scanner table that compares all five engines (OC, Breakout, Donchian, MA Cross and Supertrend) side by side on each timeframe, whatever the Signal mode is. Each engine uses its own settings from its mode group and keeps its own trade history, with the shared Enable SL/TP, Exit trigger and ATR length. It uses the timeframe list and Max timeframes from the Multi-Timeframe Scanner group. Each timeframe uses one more data request on top of the Multi-Timeframe Scanner, so with both scanners on, the requests double against the plan limit of 40 (64 on Professional plans). It works even when Show scanner is OFF. The candle type follows the chart (Standard or Heikin Ashi), as in the Multi-Timeframe Scanner. Turn it off to save data requests and calculation time. Signals, alerts and the info box are not affected.")
engPosIn = input.string("Bottom Center", "Engine scanner position", options=["Top Left", "Top Center", "Top Right", "Middle Left", "Middle Center", "Middle Right", "Bottom Left", "Bottom Center", "Bottom Right"], group=grpEng, tooltip="Chart location of the engine scanner table. Keep it away from the info box and the Multi-Timeframe Scanner, because only one table can sit in each spot.")
engSizeIn = input.string("Small", "Engine scanner size", options=["Tiny", "Small", "Normal", "Large", "Huge"], group=grpEng, tooltip="Text size used inside the engine scanner table.")
engDetail = input.string("Low", "Engine scanner detail", options=["Micro", "Low", "Medium", "High", "Maximum"], group=grpEng, tooltip="How many columns each engine shows. Every level shows all five engines side by side, so the table is five times as wide as the number of columns picked. Micro: Win Rate. Low: Status and Win Rate. Medium: Signal, Status and Win Rate. High: Signal, Status, Net P/L and Win Rate. Maximum: Signal, Status, Open P/L, Net P/L, Max DD and Win Rate. Signal is the direction of the engine's latest trade, Status is OPEN, TP or SL, and the statistics use the Lookback setting. The calculation is the same at every level.")
grpDisp = "Display"
showLabels = input.bool(true, "Show BUY/SELL labels", group=grpDisp, tooltip="Shows or hides the BUY and SELL labels. Alerts and the info box are not affected.")
lblSize = input.string("Small", "BUY/SELL label size", options=["Tiny", "Small", "Normal", "Large", "Huge"], group=grpDisp, tooltip="Size of the BUY and SELL labels on the chart. Used only when Show BUY/SELL labels is ON. Alerts and the info box are not affected.")
buyCol = input.color(#4CAF50, "Buy color", group=grpDisp, tooltip="Color of the BUY label, of the base zone behind a BUY in Breakout mode, of the MA shading while the fast MA is above the slow MA in MA Cross mode, and of the Supertrend line while the trend is up in Supertrend mode.")
sellCol = input.color(#F23645, "Sell color", group=grpDisp, tooltip="Color of the SELL label, of the base zone behind a SELL in Breakout mode, of the MA shading while the fast MA is below the slow MA in MA Cross mode, and of the Supertrend line while the trend is down in Supertrend mode.")
showEntryMark = input.bool(true, "Show entry marker (dot)", group=grpDisp, tooltip="Draws a small dot at the entry price of each signal, on the signal candle. In OC mode it sits on the signal candle's close. In Breakout mode it sits on the close in Bar Close (Entry) mode and on the base edge in the Edge modes. In Donchian mode it sits on the close in Bar Close (Entry) mode and on the broken band in Bar Close (Edge) mode. In MA Cross mode it sits on the close in Bar Close (Entry) mode and on the slow MA price in Bar Close (Edge) mode. In Supertrend mode it sits on the close in Bar Close (Entry) mode and on the broken Supertrend line price in Bar Close (Edge) mode. Shown even when the trade lines are off, and when Enable SL/TP is OFF.")
entryMarkCol = input.color(#2962FF, "Entry marker color", group=grpDisp, tooltip="Color of the entry dot. Used only when Show entry marker is ON.")
showAvgDot = input.bool(true, "Show avg time marker (dot)", group=grpDisp, tooltip="Draws a dot on the Entry line at the bar where an average trade would be over: the entry bar plus the average trade length (Avg Time/Sig in market time, converted to bars). The dot is placed when the trade opens, does not move, and disappears when the trade closes. If price has not hit the SL or TP by the time it reaches the dot, the trade is running longer than usual. Needs at least one closed trade, and Show trade lines ON.")
avgDotCol = input.color(color.black, "Avg time marker color", group=grpDisp, tooltip="Color of the avg time dot. Used only when Show avg time marker is ON.")
avgDotSize = input.string("Large", "Avg time marker size", options=["Tiny", "Small", "Normal", "Large", "Huge"], group=grpDisp, tooltip="Size of the avg time dot. Used only when Show avg time marker is ON.")
showTradeLines = input.bool(true, "Show trade lines", group=grpDisp, tooltip="ON: draws the Entry, SL and TP lines for the current trade. OFF: no lines are drawn. The price labels, shading and exit X have their own toggles and are not affected. Ignored when Enable SL/TP is OFF.")
entryCol = input.color(#2962FF, "Entry line color", group=grpDisp)
slCol = input.color(#F23645, "SL line color", group=grpDisp)
tpCol = input.color(#4CAF50, "TP line color", group=grpDisp)
showTradeLbl = input.bool(true, "Show trade labels", group=grpDisp, tooltip="ON: shows the Entry, SL and TP price labels attached to the trade lines. OFF: only the lines (and shading, if enabled) are drawn. Ignored when Enable SL/TP is OFF.")
showX = input.bool(true, "Show exit X", group=grpDisp, tooltip="ON: when price hits the SL or TP, the lines and shading stay on the chart, stop at the exit bar, and an X marks the exit price. They are replaced when the next signal fires (or kept as history when Show closed trades is above 0). OFF: the lines and shading disappear as soon as the SL or TP is hit. No X is drawn for an opposite-signal exit, because the new BUY/SELL signal starts a new setup.")
xCol = input.color(#2962FF, "Exit X color", group=grpDisp, tooltip="Color of the X drawn where price hits the SL or TP line. Used only when Show exit X is ON.")
showZone = input.bool(true, "Show trade zone shading", group=grpDisp, tooltip="ON: shades the area between entry and SL, and between entry and TP, for the current trade. The shading follows the lines: it stays after an SL or TP hit when Show exit X is ON, and is replaced by the next signal. There is no TP shading in Opposite signal mode. Ignored when Enable SL/TP is OFF.")
slZoneCol = input.color(color.new(#F23645, 85), "SL zone color", group=grpDisp, tooltip="Shading between entry and stop loss. Used only when Show trade zone shading is ON.")
tpZoneCol = input.color(color.new(#4CAF50, 85), "TP zone color", group=grpDisp, tooltip="Shading between entry and take profit. Used only when Show trade zone shading is ON.")
lineW = input.int(1, "Line width", minval=1, maxval=4, group=grpDisp)
// ── Mode and risk flags ───────────────────────────────────
isOC = mode == "OC"
isBrk = mode == "Breakout"
isDon = mode == "Donchian"
isMA = mode == "MA Cross"
isST = mode == "Supertrend"
string slSel = isOC ? ocSlMode : isBrk ? brkSlMode : isDon ? donSlMode : isMA ? maSlMode : stSlMode
string tpSel = isOC ? ocTpMode : isBrk ? brkTpMode : isDon ? donTpMode : isMA ? maTpMode : stTpMode
float slBufS = isOC ? ocSlBuf : isBrk ? brkSlBuf : isDon ? donSlBuf : isMA ? maSlBuf : stSlBuf
float slMultS = isOC ? ocSlMult : isBrk ? brkSlMult : isDon ? donSlMult : isMA ? maSlMult : stSlMult
float tpMultS = isOC ? ocTpMult : isBrk ? brkTpMult : isDon ? donTpMult : isMA ? maTpMult : stTpMult
float tpRMultS = isOC ? ocTpRMult : isBrk ? brkTpRMult : isDon ? donTpRMult : isMA ? maTpRMult : stTpRMult
bool alternate = isOC ? ocAlt : isBrk ? brkAlt : isDon ? donAlt : isMA ? maAlt : false // Supertrend flips alternate by nature
bool noOverlap = isOC ? ocNoOvl : isBrk ? brkNoOvl : isDon ? donNoOvl : isMA ? maNoOvl : stNoOvl
slNone = slSel == "None"
slAtr = slSel == "ATR"
slWick = slSel == "Candle wick"
slBody = slSel == "Candle body"
slEdge = slSel == "Base edge"
slOpp = slSel == "Channel opposite"
slMid = slSel == "Channel middle"
slSwing = slSel == "Swing"
slStl = slSel == "Supertrend line"
tpAtr = tpSel == "ATR target"
tpBase = tpSel == "Base height"
tpOpp = tpSel == "Opposite signal"
tpRisk = tpSel == "SL multiple"
hasSl = not slNone
hasTp = not tpOpp and not (tpRisk and not hasSl)
riskOn = useRisk and (hasSl or hasTp)
bothExits = hasSl and hasTp
exitOnClose = exitMode == "Close"
wickMode = brkMode == "Bar Wick (Edge)"
edgeEntry = brkMode != "Bar Close (Entry)"
donEdge = donEntMode == "Bar Close (Edge)"
maEdge = maEntMode == "Bar Close (Edge)"
stEdge = stEntMode == "Bar Close (Edge)"
tPos = switch tablePos
"Top Left" => position.top_left
"Top Center" => position.top_center
"Middle Left" => position.middle_left
"Middle Center" => position.middle_center
"Middle Right" => position.middle_right
"Bottom Left" => position.bottom_left
"Bottom Center" => position.bottom_center
"Bottom Right" => position.bottom_right
=> position.top_right
avgDotSz = switch avgDotSize
"Tiny" => size.tiny
"Normal" => size.normal
"Large" => size.large
"Huge" => size.huge
=> size.small
tSize = switch tableSize
"Tiny" => size.tiny
"Normal" => size.normal
"Large" => size.large
"Huge" => size.huge
=> size.small
// ── Shared state ──────────────────────────────────────────
// With Alternate signals ON, signals alternate (no repeated buys or sells); OFF, every qualifying signal fires. With Non-repaint set to Entries + Exits or Entries Only they fire on confirmed bars only
bool confirmed = nrMode == "Off" or barstate.isconfirmed
// SL/TP exits are live in Off mode, and in Entries Only mode when the exit trigger is Wick (a live Close exit can come and go, so it waits for the bar close)
bool exitLive = nrMode == "Off" or (nrMode == "Entries Only" and not exitOnClose)
bool exitConfirmed = exitLive or barstate.isconfirmed
var int dir = 0
var bool inTrade = false
var int lastSigBar = na
var int lastExitBar = na // bar where the last trade hit its SL or TP
var float entryPx = na
var float slPx = na
var float tpPx = na
// ── Common series ─────────────────────────────────────────
atr = ta.atr(atrLen)
[stLine, stDir] = ta.supertrend(stMult, stLen) // stDir is -1 while the Supertrend is up and 1 while it is down
// ── OC signal ─────────────────────────────────────────────
bodyHi = math.max(open, close)
bodyLo = math.min(open, close)
body = math.abs(close - open)
avgBody = ta.sma(body, bodyLen)
ocAvgVol = ta.sma(volume, bodyLen)
ocVolOk = ocVol <= 0 or volume >= ocAvgVol * ocVol
ocBull = close > open and close > bodyHi[1] and body >= avgBody * bodyMult and ocVolOk
ocBear = close < open and close < bodyLo[1] and body >= avgBody * bodyMult and ocVolOk
// ── Donchian signal ───────────────────────────────────────
// Bands use the previous bars only, so the signal bar can break them
float upB = ta.highest(high, donLen)[1]
float loB = ta.lowest(low, donLen)[1]
float midB = math.avg(upB, loB)
donAvgVol = ta.sma(volume, donLen)
donVolOk = donVol <= 0 or volume >= donAvgVol * donVol
donBull = close > upB and donVolOk
donBear = close < loB and donVolOk
// ── MA Cross signal ───────────────────────────────────────
f_src(string t) =>
switch t
"Open" => open
"High" => high
"Low" => low
"HL2" => hl2
"HLC3" => hlc3
"OHLC4" => ohlc4
=> close
f_ma(float src, int len, string t) =>
switch t
"SMA" => ta.sma(src, len)
"WMA" => ta.wma(src, len)
"HMA" => ta.hma(src, len)
"RMA" => ta.rma(src, len)
=> ta.ema(src, len)
float maPx = f_src(maSrc)
float fastMA = f_ma(maPx, fastLen, maType)
float slowMA = f_ma(maPx, slowLen, maType)
float trendMA = f_ma(maPx, maTrendLen, maType)
maAvgVol = ta.sma(volume, slowLen)
maVolOk = maVol <= 0 or volume >= maAvgVol * maVol
float swLo = ta.lowest(low, swingLen)
float swHi = ta.highest(high, swingLen)
maSepOk = minSep <= 0 or (not na(atr) and math.abs(fastMA - slowMA) >= atr * minSep)
// Fast MA crossing above the slow MA (BUY) or below it (SELL), with the optional filters
maBull = ta.crossover(fastMA, slowMA) and maVolOk and maSepOk and (not maTrend or close > trendMA)
maBear = ta.crossunder(fastMA, slowMA) and maVolOk and maSepOk and (not maTrend or close < trendMA)
// ── Breakout signal ───────────────────────────────────────
// Variable base: scans back from the bar before the signal candle and keeps the longest run of at least minLen bars (up to capLen) whose height is within rangeCap. The range only grows as the run gets longer, so the scan stops at the first run that is too tall
f_varBase(int minLen, int capLen, float rangeCap) =>
float bHi = na
float bLo = na
int bN = 0
float rHi = high[1]
float rLo = low[1]
int lim = math.min(capLen, bar_index)
if lim >= minLen and not na(rangeCap)
for k = 1 to lim
rHi := math.max(rHi, high[k])
rLo := math.min(rLo, low[k])
if rHi - rLo > rangeCap
break
if k >= minLen
bHi := rHi
bLo := rLo
bN := k
[bHi, bLo, bN]
emaT = ta.ema(close, brkTrendLen)
brkAvgVol = ta.sma(volume, brkVolLen)
brkVolOk = brkVol <= 0 or (not na(brkAvgVol) and volume >= brkAvgVol * brkVol)
fixHi = ta.highest(high, baseLen)[1]
fixLo = ta.lowest(low, baseLen)[1]
// Variable base mode: the longest run of bars (Base length up to Max base length) that still fits Max base height. The fresh-base rules shorten the longest run allowed
isVarBase = isBrk and baseMode == "Variable"
int capLen = isVarBase ? math.max(varMax, varMin) : 0
if not na(lastSigBar)
capLen := math.min(capLen, bar_index - lastSigBar - 1)
if noBaseInTrade and riskOn
capLen := inTrade ? 0 : na(lastExitBar) ? capLen : math.min(capLen, bar_index - lastExitBar - 1)
[varHi, varLo, varN] = f_varBase(varMin, capLen, atr * baseMult)
consHi = isVarBase ? varHi : fixHi // the base is the range of the candles before the current one
consLo = isVarBase ? varLo : fixLo
int baseN = isVarBase ? varN : baseLen
isBase = isVarBase ? varN > 0 : (fixHi - fixLo) <= atr * baseMult
brkBuf = na(atr) ? 0.0 : minBreak * atr
// A new signal needs a fresh base: the base window must not contain the previous signal candle, nor (optionally) any candle from a trade that was open
freshBase = isVarBase or ((na(lastSigBar) or bar_index - lastSigBar > baseLen) and (not (noBaseInTrade and riskOn) or (not inTrade and (na(lastExitBar) or bar_index - lastExitBar > baseLen))))
upBreak = (wickMode ? high : close) > consHi + brkBuf
dnBreak = (wickMode ? low : close) < consLo - brkBuf
bothSides = upBreak and dnBreak
brkBull = isBase and freshBase and upBreak and (not bothSides or close > open) and (not brkTrend or close > emaT) and brkVolOk
brkBear = isBase and freshBase and dnBreak and (not bothSides or close < open) and (not brkTrend or close < emaT) and brkVolOk
// ── Supertrend signal ─────────────────────────────────────
// A flip of the Supertrend direction is the signal
stBull = stDir < 0 and stDir[1] > 0
stBear = stDir > 0 and stDir[1] < 0
float stEntry = math.max(low, math.min(high, nz(stLine[1], close)))
// ── Entry and stop for each direction ─────────────────────
// The stop is worked out for both directions on every bar. In Breakout mode a signal only fires when its stop is on the losing side of the entry
float bufD = na(atr) ? 0.0 : slBufS * atr
float minD = isMA and not na(atr) ? slMin * atr : 0.0 // MA Cross only: the minimum stop distance
float maEntry = math.max(low, math.min(high, nz(slowMA, close)))
float entBuy = isBrk ? (edgeEntry ? consHi + brkBuf : close) : isDon ? (donEdge ? nz(upB, close) : close) : isMA ? (maEdge ? maEntry : close) : isST ? (stEdge ? stEntry : close) : close
float entSell = isBrk ? (edgeEntry ? consLo - brkBuf : close) : isDon ? (donEdge ? nz(loB, close) : close) : isMA ? (maEdge ? maEntry : close) : isST ? (stEdge ? stEntry : close) : close
float lvlBuy = slWick ? low - bufD : slBody ? open - bufD : slSwing ? swLo - bufD : slEdge ? consLo - bufD : slOpp ? nz(loB, low) - bufD : slMid ? nz(midB, entBuy) - bufD : slStl ? stLine - bufD : na
float lvlSell = slWick ? high + bufD : slBody ? open + bufD : slSwing ? swHi + bufD : slEdge ? consHi + bufD : slOpp ? nz(upB, high) + bufD : slMid ? nz(midB, entSell) + bufD : slStl ? stLine + bufD : na
float slBuyPx = not hasSl ? na : slAtr ? entBuy - atr * slMultS : isMA ? math.min(lvlBuy, entBuy - minD) : lvlBuy
float slSellPx = not hasSl ? na : slAtr ? entSell + atr * slMultS : isMA ? math.max(lvlSell, entSell + minD) : lvlSell
bool needStop = useRisk and hasSl
bool stopOkBuy = not isBrk or not needStop or (not na(slBuyPx) and slBuyPx < entBuy)
bool stopOkSell = not isBrk or not needStop or (not na(slSellPx) and slSellPx > entSell)
// ── Final signals ─────────────────────────────────────────
bool rawBull = isOC ? ocBull : isBrk ? brkBull : isDon ? donBull : isMA ? maBull : stBull
bool rawBear = isOC ? ocBear : isBrk ? brkBear : isDon ? donBear : isMA ? maBear : stBear
// A trade with both a stop and a target only ends at one of them, so every signal is blocked while it is open. Otherwise an opposite signal is its other way out, so only same-direction signals are blocked
// Supertrend only: if the open trade hits its SL or TP on this very bar, the exit closes it, so a flip on the same bar is not blocked (SL first when both are touched)
bool stSlPre = isST and useRisk and inTrade and exitConfirmed and hasSl and (exitOnClose ? (dir == 1 ? close <= slPx : close >= slPx) : (dir == 1 ? low <= slPx : high >= slPx))
bool stTpPre = isST and useRisk and inTrade and exitConfirmed and hasTp and not stSlPre and (exitOnClose ? (dir == 1 ? close >= tpPx : close <= tpPx) : (dir == 1 ? high >= tpPx : low <= tpPx))
bool blk = noOverlap and riskOn and inTrade and not (stSlPre or stTpPre)
buy = confirmed and rawBull and not (blk and (bothExits or dir == 1)) and (not alternate or dir != 1) and stopOkBuy
sell = confirmed and rawBear and not (blk and (bothExits or dir == -1)) and (not alternate or dir != -1) and stopOkSell
// ── Trade state ───────────────────────────────────────────
var array<float> pnls = array.new_float(0)
var array<int> reasons = array.new_int(0) // 1 = TP, -1 = SL, 0 = reversal
var array<float> gaps = array.new_float(0) // milliseconds between consecutive signals
var array<float> gapsM = array.new_float(0) // the same gaps in market time (bars x chart timeframe)
var int lastSigTime = na
var int mktSigBar = na // bar of the last signal, for market time
var int entryBar = na // bar of the open trade's signal, for market time
var array<float> durs = array.new_float(0) // milliseconds from the signal bar to the exit bar, per closed trade
var array<float> dursM = array.new_float(0) // the same durations in market time (bars x chart timeframe)
var int entryTime = na // time of the open trade's signal bar
var float slAtrX = na // latest stop distance in ATR units (shown for the non-ATR stop modes)
var line entryLn = na
var line slLn = na
var line tpLn = na
var label entryLbl = na
var label slLbl = na
var label tpLbl = na
var label xLbl = na
var label avgLbl = na // avg time dot of the open trade
var box slBox = na
var box tpBox = na
type TradeViz
line entryLn
line slLn
line tpLn
label entryLbl
label slLbl
label tpLbl
label xLbl
box slBox
box tpBox
var array<TradeViz> closedViz = array.new<TradeViz>()
deleteViz(TradeViz v) =>
line.delete(v.entryLn)
line.delete(v.slLn)
line.delete(v.tpLn)
label.delete(v.entryLbl)
label.delete(v.slLbl)
label.delete(v.tpLbl)
label.delete(v.xLbl)
box.delete(v.slBox)
box.delete(v.tpBox)
// Freezes a closed trade's drawings at its exit bar and stores them as history (oldest removed beyond Show closed trades)
archiveTrade(line eLn, line sLn, line tLn, label eLb, label sLb, label tLb, label xLb, box sBx, box tBx, int endBar) =>
if not (na(eLn) and na(sLn) and na(tLn) and na(eLb) and na(sLb) and na(tLb) and na(sBx) and na(tBx))
if not na(eLn)
line.set_extend(eLn, extend.none)
line.set_x2(eLn, endBar)
if not na(sLn)
line.set_extend(sLn, extend.none)
line.set_x2(sLn, endBar)
if not na(tLn)
line.set_extend(tLn, extend.none)
line.set_x2(tLn, endBar)
if not na(sBx)
box.set_extend(sBx, extend.none)
box.set_right(sBx, endBar)
if not na(tBx)
box.set_extend(tBx, extend.none)
box.set_right(tBx, endBar)
array.push(closedViz, TradeViz.new(eLn, sLn, tLn, eLb, sLb, tLb, xLb, sBx, tBx))
while array.size(closedViz) > showClosed
deleteViz(array.shift(closedViz))
recordTrade(float pnl, int reason) =>
array.push(pnls, pnl)
array.push(reasons, reason)
if not na(entryTime)
array.push(durs, 1.0 * (time - entryTime))
array.push(dursM, 1.0 * (bar_index - entryBar) * timeframe.in_seconds() * 1000)
while array.size(durs) > lookback
array.shift(durs)
while array.size(dursM) > lookback
array.shift(dursM)
while array.size(pnls) > lookback
array.shift(pnls)
array.shift(reasons)
clearLines() =>
line.delete(entryLn)
line.delete(slLn)
line.delete(tpLn)
label.delete(entryLbl)
label.delete(slLbl)
label.delete(tpLbl)
label.delete(xLbl)
label.delete(avgLbl)
box.delete(slBox)
box.delete(tpBox)
// ── 1) SL / TP exit check on existing trade (before any new signal) ──
// If SL and TP are both touched on the same bar, SL is assumed first.
bool slHit = false
bool tpHit = false
if useRisk and inTrade and exitConfirmed
slHit := hasSl and (exitOnClose ? (dir == 1 ? close <= slPx : close >= slPx) : (dir == 1 ? low <= slPx : high >= slPx))
tpHit := hasTp and not slHit and (exitOnClose ? (dir == 1 ? close >= tpPx : close <= tpPx) : (dir == 1 ? high >= tpPx : low <= tpPx))
if slHit or tpHit
float exitPx = exitOnClose ? close : (slHit ? slPx : tpPx)
float exitPnl = dir == 1 ? (exitPx - entryPx) / entryPx * 100 : (entryPx - exitPx) / entryPx * 100
recordTrade(exitPnl, slHit ? -1 : 1)
label.delete(avgLbl)
avgLbl := na
inTrade := false
lastExitBar := bar_index
if showX or showClosed > 0
// Keep the lines: stop them at the exit bar and mark the exit with an X
if not na(entryLn)
line.set_extend(entryLn, extend.none)
line.set_x2(entryLn, bar_index)
if not na(slLn)
line.set_extend(slLn, extend.none)
line.set_x2(slLn, bar_index)
if not na(tpLn)
line.set_extend(tpLn, extend.none)
line.set_x2(tpLn, bar_index)
if not na(slBox)
box.set_extend(slBox, extend.none)
box.set_right(slBox, bar_index)
if not na(tpBox)
box.set_extend(tpBox, extend.none)
box.set_right(tpBox, bar_index)
if showX
xLbl := label.new(bar_index, exitPx, "X", style=label.style_label_center, color=color.new(color.black, 100), textcolor=xCol, size=size.large)
if showClosed > 0
archiveTrade(entryLn, slLn, tpLn, entryLbl, slLbl, tpLbl, xLbl, slBox, tpBox, bar_index)
entryLn := na
slLn := na
tpLn := na
entryLbl := na
slLbl := na
tpLbl := na
xLbl := na
slBox := na
tpBox := na
else
clearLines()
// ── 2) New signal: close open trade (reversal) and open the new one ──
if buy or sell
if not na(lastSigTime)
array.push(gaps, 1.0 * (time - lastSigTime))
array.push(gapsM, 1.0 * (bar_index - mktSigBar) * timeframe.in_seconds() * 1000)
while array.size(gaps) > lookback
array.shift(gaps)
while array.size(gapsM) > lookback
array.shift(gapsM)
lastSigTime := time
mktSigBar := bar_index
if inTrade
float revPnl = dir == 1 ? (close - entryPx) / entryPx * 100 : (entryPx - close) / entryPx * 100
recordTrade(revPnl, 0)
label.delete(avgLbl)
avgLbl := na
if showClosed > 0
archiveTrade(entryLn, slLn, tpLn, entryLbl, slLbl, tpLbl, xLbl, slBox, tpBox, bar_index)
entryLn := na
slLn := na
tpLn := na
entryLbl := na
slLbl := na
tpLbl := na
xLbl := na
slBox := na
tpBox := na
clearLines()
dir := buy ? 1 : -1
lastSigBar := bar_index
if isBrk and brkShowBase
box.new(bar_index - baseN, consHi, bar_index, consLo, border_color=dir == 1 ? buyCol : sellCol, bgcolor=color.new(dir == 1 ? buyCol : sellCol, 85))
entryPx := dir == 1 ? entBuy : entSell
inTrade := true
entryTime := time
entryBar := bar_index
slPx := not hasSl ? na : dir == 1 ? slBuyPx : slSellPx
float riskDist = math.abs(entryPx - slPx)
slAtrX := hasSl and not slAtr and atr > 0 ? riskDist / atr : na
float tpDist = tpAtr ? atr * tpMultS : tpBase ? (consHi - consLo) * brkTpBMult : riskDist * tpRMultS
tpPx := not hasTp ? na : dir == 1 ? entryPx + tpDist : entryPx - tpDist
if useRisk and (not na(atr) or not riskOn)
if showTradeLines
entryLn := line.new(bar_index, entryPx, bar_index + 1, entryPx, extend=extend.right, color=entryCol, width=lineW)
if hasSl
slLn := line.new(bar_index, slPx, bar_index + 1, slPx, extend=extend.right, color=slCol, width=lineW, style=line.style_dashed)
if hasTp
tpLn := line.new(bar_index, tpPx, bar_index + 1, tpPx, extend=extend.right, color=tpCol, width=lineW, style=line.style_dashed)
if showAvgDot and showTradeLines and array.size(dursM) > 0
int avgBars = math.min(499, math.max(1, math.round(array.avg(dursM) / (timeframe.in_seconds() * 1000.0))))
avgLbl := label.new(bar_index + avgBars, entryPx, "●", xloc=xloc.bar_index, style=label.style_label_center, color=color.new(color.black, 100), textcolor=avgDotCol, size=avgDotSz)
if showTradeLbl
entryLbl := label.new(bar_index, entryPx, "Entry " + str.tostring(entryPx, format.mintick), style=label.style_label_left, color=color.new(color.black, 100), textcolor=entryCol, size=size.small)
if hasSl
slLbl := label.new(bar_index, slPx, "SL " + str.tostring(slPx, format.mintick), style=label.style_label_left, color=color.new(color.black, 100), textcolor=slCol, size=size.small)
if hasTp
tpLbl := label.new(bar_index, tpPx, "TP " + str.tostring(tpPx, format.mintick), style=label.style_label_left, color=color.new(color.black, 100), textcolor=tpCol, size=size.small)
if showZone
if hasSl
slBox := box.new(bar_index, math.max(entryPx, slPx), bar_index + 1, math.min(entryPx, slPx), border_color=na, bgcolor=slZoneCol, extend=extend.right)
if hasTp
tpBox := box.new(bar_index, math.max(entryPx, tpPx), bar_index + 1, math.min(entryPx, tpPx), border_color=na, bgcolor=tpZoneCol, extend=extend.right)
// ── Plots ─────────────────────────────────────────────────
plot(isBrk and brkShowTrend ? emaT : na, "Trend EMA", color=brkEmaCol, linewidth=brkEmaW)
pUp = plot(isDon and donShowChan ? upB : na, "Donchian upper band", color=donChanCol, linewidth=1)
pLo = plot(isDon and donShowChan ? loB : na, "Donchian lower band", color=donChanCol, linewidth=1)
plot(isDon and donShowChan and donShowMid ? midB : na, "Donchian middle line", color=color.new(donChanCol, 40), linewidth=1, style=plot.style_linebr)
fill(pUp, pLo, color=isDon and donShowChan and donShade ? donShadeCol : na, title="Donchian channel")
pFast = plot(isMA and maShowMAs ? fastMA : na, "Fast MA", color=maFastCol, linewidth=2)
pSlow = plot(isMA and maShowMAs ? slowMA : na, "Slow MA", color=maSlowCol, linewidth=2)
fill(pFast, pSlow, color=isMA and maShowMAs and maShowFill ? color.new(fastMA >= slowMA ? buyCol : sellCol, 85) : na, title="MA shading")
plot(isMA and maShowMAs and maTrend ? trendMA : na, "Trend MA", color=maTrendCol, linewidth=2)
plot(isST and stShowLine and stDir < 0 ? stLine : na, "Supertrend up", color=buyCol, linewidth=stLineW, style=plot.style_linebr)
plot(isST and stShowLine and stDir > 0 ? stLine : na, "Supertrend down", color=sellCol, linewidth=stLineW, style=plot.style_linebr)
plotshape(showEntryMark and (buy or sell) ? entryPx : na, "Entry marker", shape.circle, location.absolute, entryMarkCol, size=size.tiny)
plotshape(showLabels and lblSize == "Tiny" and buy, "Buy (Tiny)", shape.labelup, location.belowbar, buyCol, text="BUY", textcolor=color.white, size=size.tiny)
plotshape(showLabels and lblSize == "Tiny" and sell, "Sell (Tiny)", shape.labeldown, location.abovebar, sellCol, text="SELL", textcolor=color.white, size=size.tiny)
plotshape(showLabels and lblSize == "Small" and buy, "Buy (Small)", shape.labelup, location.belowbar, buyCol, text="BUY", textcolor=color.white, size=size.small)
plotshape(showLabels and lblSize == "Small" and sell, "Sell (Small)", shape.labeldown, location.abovebar, sellCol, text="SELL", textcolor=color.white, size=size.small)
plotshape(showLabels and lblSize == "Normal" and buy, "Buy (Normal)", shape.labelup, location.belowbar, buyCol, text="BUY", textcolor=color.white, size=size.normal)
plotshape(showLabels and lblSize == "Normal" and sell, "Sell (Normal)", shape.labeldown, location.abovebar, sellCol, text="SELL", textcolor=color.white, size=size.normal)
plotshape(showLabels and lblSize == "Large" and buy, "Buy (Large)", shape.labelup, location.belowbar, buyCol, text="BUY", textcolor=color.white, size=size.large)
plotshape(showLabels and lblSize == "Large" and sell, "Sell (Large)", shape.labeldown, location.abovebar, sellCol, text="SELL", textcolor=color.white, size=size.large)
plotshape(showLabels and lblSize == "Huge" and buy, "Buy (Huge)", shape.labelup, location.belowbar, buyCol, text="BUY", textcolor=color.white, size=size.huge)
plotshape(showLabels and lblSize == "Huge" and sell, "Sell (Huge)", shape.labeldown, location.abovebar, sellCol, text="SELL", textcolor=color.white, size=size.huge)
// ── Info box ──────────────────────────────────────────────
fmt(float x) =>
na(x) ? "n/a" : (x >= 0 ? "+" : "") + str.tostring(x, "0.00") + "%"
posCol(float x) =>
na(x) ? color.white : x >= 0 ? color.new(#4CAF50, 0) : color.new(#F23645, 0)
// Formats milliseconds in the largest unit that keeps the number at 1 or more
fmtDur(float ms) =>
float unitMs = na(ms) ? 1.0 : ms < 60000.0 ? 1000.0 : ms < 3600000.0 ? 60000.0 : ms < 86400000.0 ? 3600000.0 : ms < 604800000.0 ? 86400000.0 : ms < 2629800000.0 ? 604800000.0 : ms < 31557600000.0 ? 2629800000.0 : 31557600000.0
string unitTxt = na(ms) ? "" : ms < 60000.0 ? "sec" : ms < 3600000.0 ? "min" : ms < 86400000.0 ? "hr" : ms < 604800000.0 ? "days" : ms < 2629800000.0 ? "wks" : ms < 31557600000.0 ? "mo" : "yrs"
na(ms) ? "n/a" : str.tostring(ms / unitMs, "0.0") + " " + unitTxt
// Compact duration for the paired time rows: largest unit that keeps the number at 1 or more, one decimal under 10
fmtC(float ms) =>
float unitMs = ms < 60000.0 ? 1000.0 : ms < 3600000.0 ? 60000.0 : ms < 86400000.0 ? 3600000.0 : ms < 604800000.0 ? 86400000.0 : ms < 2629800000.0 ? 604800000.0 : ms < 31557600000.0 ? 2629800000.0 : 31557600000.0
string unitTxt = ms < 60000.0 ? "s" : ms < 3600000.0 ? "m" : ms < 86400000.0 ? "h" : ms < 604800000.0 ? "d" : ms < 2629800000.0 ? "w" : ms < 31557600000.0 ? "mo" : "y"
float v = ms / unitMs
str.tostring(v, v >= 10 ? "0" : "0.0") + unitTxt
// Calendar time and market time side by side as "cal / mkt", always both
fmtDual(float calMs, float mktMs) =>
na(calMs) ? "n/a" : fmtC(calMs) + " / " + (na(mktMs) ? "n/a" : fmtC(mktMs))
tfTxt = timeframe.isseconds ? str.tostring(timeframe.multiplier) + "s" : timeframe.isminutes ? (timeframe.multiplier % 60 == 0 ? str.tostring(math.round(timeframe.multiplier / 60)) + "h" : str.tostring(timeframe.multiplier) + "m") : timeframe.isdaily ? (timeframe.multiplier == 1 ? "D" : str.tostring(timeframe.multiplier) + "D") : timeframe.isweekly ? (timeframe.multiplier == 1 ? "W" : str.tostring(timeframe.multiplier) + "W") : (timeframe.multiplier == 1 ? "M" : str.tostring(timeframe.multiplier) + "M")
sessTxt = str.upper(str.substring(syminfo.session, 0, 1)) + str.substring(syminfo.session, 1)
chartType = chart.is_heikinashi ? "Heikin Ashi" : chart.is_renko ? "Renko" : chart.is_kagi ? "Kagi" : chart.is_linebreak ? "Line Break" : chart.is_pnf ? "Point & Figure" : chart.is_range ? "Range" : "Standard"
// Settings rows that are OFF are left out to save room: Min Volume, Min Breakout, Trend Filter and Min Cross Strength
bool rowVol = (isOC and ocVol > 0) or (isBrk and brkVol > 0) or (isDon and donVol > 0) or (isMA and maVol > 0)
bool rowMinBrk = isBrk and minBreak > 0
bool rowTrend = (isBrk and brkTrend) or (isMA and maTrend)
bool rowSep = isMA and minSep > 0
int nModeRows = (isBrk ? 6 : isST ? 3 : 4) + (rowVol ? 1 : 0) + (rowMinBrk ? 1 : 0) + (rowTrend ? 1 : 0) + (rowSep ? 1 : 0)
int nCommonRows = 3
int hdrRow = 4 + nModeRows + nCommonRows
var table infoBox = not showTable ? na : table.new(tPos, 2, hdrRow + 12, bgcolor=color.new(#131722, 10), frame_color=color.new(color.gray, 40), frame_width=1, border_color=color.new(color.gray, 60), border_width=1)
if barstate.isfirst and showTable
table.merge_cells(infoBox, 0, 0, 1, 0)
table.merge_cells(infoBox, 0, hdrRow, 1, hdrRow)
// Writes one label/value row and returns the next row number
f_row(int row, string lbl, string val, color vc) =>
table.cell(infoBox, 0, row, lbl, text_color=color.white, text_halign=text.align_left, text_size=tSize)
table.cell(infoBox, 1, row, val, text_color=vc, text_halign=text.align_right, text_size=tSize)
row + 1
if showTable and barstate.islast
int n = array.size(pnls)
int winCnt = 0
int lossCnt = 0
int tpCnt = 0
int slCnt = 0
int revCnt = 0
float winSum = 0.0
float lossSum = 0.0
float eq = 1.0
float peak = 1.0
float maxDD = 0.0
if n > 0
for i = 0 to n - 1
float p = array.get(pnls, i)
int r = array.get(reasons, i)
if r == 1
tpCnt += 1
else if r == -1
slCnt += 1
else
revCnt += 1
if p > 0
winCnt += 1
winSum += p
else if p < 0
lossCnt += 1
lossSum += p
eq := eq * (1 + p / 100)
peak := math.max(peak, eq)
maxDD := math.min(maxDD, (eq / peak - 1) * 100)
float netPnl = n > 0 ? (eq - 1) * 100 : na
float winRate = n > 0 ? winCnt / n * 100 : na
float avgWin = winCnt > 0 ? winSum / winCnt : na
float avgLoss = lossCnt > 0 ? lossSum / lossCnt : na
float openPnl = not inTrade ? na : dir == 1 ? (close - entryPx) / entryPx * 100 : (entryPx - close) / entryPx * 100
color onCol = color.new(#4CAF50, 0)
color offCol = color.new(#F23645, 0)
table.cell(infoBox, 0, 0, "XL - " + str.upper(mode) + " BUY/SELL SIGNALS", text_color=color.white, bgcolor=color.new(#3B5B92, 0), text_halign=text.align_center, text_size=tSize)
int rw = 1
rw := f_row(rw, "Chart Type", chartType, chart.is_standard ? color.white : offCol)
rw := f_row(rw, "Timeframe / Session", tfTxt + " / " + sessTxt, color.white)
rw := f_row(rw, "Non-Repaint", nrMode, nrMode == "Entries + Exits" ? onCol : nrMode == "Entries Only" ? color.orange : offCol)
if isOC
rw := f_row(rw, "Avg Body Length", str.tostring(bodyLen), color.white)
rw := f_row(rw, "Min Body", str.tostring(bodyMult, "0.0") + "x", color.white)
else if isBrk
rw := f_row(rw, "Base Length", (isVarBase ? str.tostring(varMin) + "-" + str.tostring(math.max(varMax, varMin)) + " bars" : str.tostring(baseLen) + " bars"), color.white)
rw := f_row(rw, "Breakout Entry Mode", brkMode, color.white)
rw := f_row(rw, "Max Base Height", str.tostring(baseMult, "0.0") + "x ATR", color.white)
if rowMinBrk
rw := f_row(rw, "Min Breakout", str.tostring(minBreak, "0.0") + "x ATR", color.white)
else if isDon
rw := f_row(rw, "Channel Length", str.tostring(donLen), color.white)
rw := f_row(rw, "Entry Mode", donEntMode, color.white)
else if isMA
rw := f_row(rw, "Fast / Slow MA", maType + " " + str.tostring(fastLen) + " / " + str.tostring(slowLen), color.white)
rw := f_row(rw, "Entry Mode", maEntMode, color.white)
if rowSep
rw := f_row(rw, "Min Cross Strength", str.tostring(minSep, "0.00") + "x ATR", color.white)
else
rw := f_row(rw, "Supertrend Len / Factor", str.tostring(stLen) + " / " + str.tostring(stMult, "0.0"), color.white)
rw := f_row(rw, "Entry Mode", stEntMode, color.white)
if rowVol
float volX = isOC ? ocVol : isBrk ? brkVol : isDon ? donVol : maVol
rw := f_row(rw, "Min Volume", str.tostring(volX, "0.0") + "x", color.white)
if rowTrend
rw := f_row(rw, "Trend Filter", isBrk ? "EMA " + str.tostring(brkTrendLen) : maType + " " + str.tostring(maTrendLen), color.white)
if not isST
rw := f_row(rw, "Alternate Signals", alternate ? "ON" : "OFF", alternate ? onCol : offCol)
rw := f_row(rw, "Ignore Signals in Trade", noOverlap ? "ON" : "OFF", noOverlap ? onCol : offCol)
if isBrk
rw := f_row(rw, "Ignore Base in Trade", noBaseInTrade ? "ON" : "OFF", noBaseInTrade ? onCol : offCol)
rw := f_row(rw, "Exit Trigger", riskOn ? exitMode : "-", color.white)
string slAtrTxt = na(slAtrX) ? "n/a" : str.tostring(slAtrX, "0.0") + "x ATR"
string slTxt = slAtr ? str.tostring(slMultS, "0.0") + "x ATR" : slStl ? "ST: " + slAtrTxt : slSwing ? "SW: " + slAtrTxt : slWick ? "CW: " + slAtrTxt : slBody ? "CB: " + slAtrTxt : slEdge ? "BE: " + slAtrTxt : slOpp ? "CO: " + slAtrTxt : slMid ? "CM: " + slAtrTxt : "None"
string tpTxt = tpAtr ? str.tostring(tpMultS, "0.0") + "x ATR" : tpBase ? str.tostring(brkTpBMult, "0.0") + "x Base" : tpRisk and hasSl ? str.tostring(tpRMultS, "0.0") + "x SL" : "Opp. Signal"
rw := f_row(rw, "Stop Loss", useRisk ? slTxt : "OFF", useRisk ? color.white : offCol)
rw := f_row(rw, "Take Profit", useRisk ? tpTxt : "OFF", useRisk ? color.white : offCol)
table.cell(infoBox, 0, hdrRow, "LOOKBACK P/L", text_color=color.white, bgcolor=color.new(#3B5B92, 0), text_halign=text.align_center, text_size=tSize)
rw := hdrRow + 1
rw := f_row(rw, "Trades Counted", str.tostring(n) + " / " + str.tostring(lookback), color.white)
rw := f_row(rw, "Exits TP / SL / Signal", (useRisk and hasTp ? str.tostring(tpCnt) : "-") + " / " + (useRisk and hasSl ? str.tostring(slCnt) : "-") + " / " + str.tostring(revCnt), color.white)
rw := f_row(rw, "Net P/L", fmt(netPnl), posCol(netPnl))
rw := f_row(rw, "Win Rate", na(winRate) ? "n/a" : str.tostring(winRate, "0") + "% (" + str.tostring(winCnt) + "W/" + str.tostring(lossCnt) + "L)", color.white)
rw := f_row(rw, "Avg Win / Loss", fmt(avgWin) + " / " + fmt(avgLoss), color.white)
rw := f_row(rw, "Max Drawdown", n > 0 ? fmt(maxDD) : "n/a", maxDD < 0 ? offCol : color.white)
rw := f_row(rw, "Open Trade P/L", fmt(openPnl), posCol(openPnl))
// Time between signals and time since the last signal, both in the same auto-scaled unit
float avgMs = array.size(gaps) > 0 ? array.avg(gaps) : na
float avgMsM = array.size(gapsM) > 0 ? array.avg(gapsM) : na
float avgDurMs = array.size(durs) > 0 ? array.avg(durs) : na
float avgDurMsM = array.size(dursM) > 0 ? array.avg(dursM) : na
float inMs = inTrade and not na(entryTime) ? 1.0 * (time - entryTime) : na
float inMsM = inTrade and not na(entryTime) ? 1.0 * (bar_index - entryBar) * timeframe.in_seconds() * 1000 : na
float sinceMs = na(lastSigTime) ? na : 1.0 * (time - lastSigTime)
float sinceMsM = na(lastSigTime) ? na : 1.0 * (bar_index - mktSigBar) * timeframe.in_seconds() * 1000
rw := f_row(rw, "Avg Time/Sig (cal/mkt)", fmtDual(avgDurMs, avgDurMsM), color.white)
rw := f_row(rw, "Time in Sig (cal/mkt)", fmtDual(inMs, inMsM), color.white)
rw := f_row(rw, "Time btw Sig (cal/mkt)", fmtDual(avgMs, avgMsM), color.white)
rw := f_row(rw, "Time from Sig (cal/mkt)", fmtDual(sinceMs, sinceMsM), color.white)
// ── Multi-timeframe scanner ───────────────────────────────
// Scans the chart's symbol on the timeframes in the Scanner group, using the signal mode and trade rules selected above.
// Each timeframe keeps its own trade history. Results are returned as of that timeframe's last CLOSED bar (non-repaint),
// so a signal appears on the first tick of the bar after the signal bar closes.
f_scan() =>
float a = ta.atr(atrLen)
// OC signal
float bd = math.abs(close - open)
float avgB = ta.sma(bd, bodyLen)
float bHi = math.max(open, close)
float bLo = math.min(open, close)
float avgVO = ta.sma(volume, bodyLen)
bool vOkO = ocVol <= 0 or volume >= avgVO * ocVol
bool ocBu = close > open and close > bHi[1] and bd >= avgB * bodyMult and vOkO
bool ocBe = close < open and close < bLo[1] and bd >= avgB * bodyMult and vOkO
// Donchian signal
float uB = ta.highest(high, donLen)[1]
float lB = ta.lowest(low, donLen)[1]
float mB = math.avg(uB, lB)
float avgVD = ta.sma(volume, donLen)
bool vOkD = donVol <= 0 or volume >= avgVD * donVol
bool donBu = close > uB and vOkD
bool donBe = close < lB and vOkD
// MA Cross signal
float mPx = f_src(maSrc)
float fM = f_ma(mPx, fastLen, maType)
float sM = f_ma(mPx, slowLen, maType)
float tM = f_ma(mPx, maTrendLen, maType)
float swL = ta.lowest(low, swingLen)
float swH = ta.highest(high, swingLen)
float avgVM = ta.sma(volume, slowLen)
bool vOkM = maVol <= 0 or volume >= avgVM * maVol
bool sOk = minSep <= 0 or (not na(a) and math.abs(fM - sM) >= a * minSep)
bool maBu = ta.crossover(fM, sM) and vOkM and sOk and (not maTrend or close > tM)
bool maBe = ta.crossunder(fM, sM) and vOkM and sOk and (not maTrend or close < tM)
// Supertrend signal
[stL, stD] = ta.supertrend(stMult, stLen)
bool stBu = stD < 0 and stD[1] > 0
bool stBe = stD > 0 and stD[1] < 0
float stEn = math.max(low, math.min(high, nz(stL[1], close)))
// Breakout base
float fHi = ta.highest(high, baseLen)[1]
float fLo = ta.lowest(low, baseLen)[1]
float bBuf = na(a) ? 0.0 : minBreak * a
float eT = ta.ema(close, brkTrendLen)
float avgVB = ta.sma(volume, brkVolLen)
bool vOkB = brkVol <= 0 or (not na(avgVB) and volume >= avgVB * brkVol)
var int d = 0
var bool inT = false
var float ePx = na
var float sPx = na
var float tPx = na
var int lastSig = na // bar of the last signal (Breakout fresh-base rule)
var int lastExit = na // bar where the last trade hit its SL or TP
var int sigT = na
var int lastRes = 0
var float lastPnl = na
var array<float> sGaps = array.new_float(0)
var float avgG = na
var array<float> sPnls = array.new_float(0)
var float netV = na
var int winV = 0
var int lossV = 0
var int nV = 0
var float avgPV = na
var float ddV = na
// Breakout signal
// Variable base mode: the longest run of bars that still fits Max base height, shortened by the fresh-base rules
int capL = isVarBase ? math.max(varMax, varMin) : 0
if not na(lastSig)
capL := math.min(capL, bar_index - lastSig - 1)
if noBaseInTrade and riskOn
capL := inT ? 0 : na(lastExit) ? capL : math.min(capL, bar_index - lastExit - 1)
[vHi, vLo, vN] = f_varBase(varMin, capL, a * baseMult)
float cHi = isVarBase ? vHi : fHi
float cLo = isVarBase ? vLo : fLo
bool baseOk = isVarBase ? vN > 0 : (fHi - fLo) <= a * baseMult
bool fresh = isVarBase or ((na(lastSig) or bar_index - lastSig > baseLen) and (not (noBaseInTrade and riskOn) or (not inT and (na(lastExit) or bar_index - lastExit > baseLen))))
bool upB2 = (wickMode ? high : close) > cHi + bBuf
bool dnB2 = (wickMode ? low : close) < cLo - bBuf
bool both = upB2 and dnB2
bool brkBu = baseOk and fresh and upB2 and (not both or close > open) and (not brkTrend or close > eT) and vOkB
bool brkBe = baseOk and fresh and dnB2 and (not both or close < open) and (not brkTrend or close < eT) and vOkB
// Entry and stop for each direction, exactly as the main logic does
float bufS = na(a) ? 0.0 : slBufS * a
float minS = isMA and not na(a) ? slMin * a : 0.0
float mEnt = math.max(low, math.min(high, nz(sM, close)))
float eBuy = isBrk ? (edgeEntry ? cHi + bBuf : close) : isDon ? (donEdge ? nz(uB, close) : close) : isMA ? (maEdge ? mEnt : close) : isST ? (stEdge ? stEn : close) : close
float eSell = isBrk ? (edgeEntry ? cLo - bBuf : close) : isDon ? (donEdge ? nz(lB, close) : close) : isMA ? (maEdge ? mEnt : close) : isST ? (stEdge ? stEn : close) : close
float lvB = slWick ? low - bufS : slBody ? open - bufS : slSwing ? swL - bufS : slEdge ? cLo - bufS : slOpp ? nz(lB, low) - bufS : slMid ? nz(mB, eBuy) - bufS : slStl ? stL - bufS : na
float lvS = slWick ? high + bufS : slBody ? open + bufS : slSwing ? swH + bufS : slEdge ? cHi + bufS : slOpp ? nz(uB, high) + bufS : slMid ? nz(mB, eSell) + bufS : slStl ? stL + bufS : na
float slB = not hasSl ? na : slAtr ? eBuy - a * slMultS : isMA ? math.min(lvB, eBuy - minS) : lvB
float slS = not hasSl ? na : slAtr ? eSell + a * slMultS : isMA ? math.max(lvS, eSell + minS) : lvS
bool needSt = useRisk and hasSl
bool okB = not isBrk or not needSt or (not na(slB) and slB < eBuy)
bool okS = not isBrk or not needSt or (not na(slS) and slS > eSell)
bool rawBu = isOC ? ocBu : isBrk ? brkBu : isDon ? donBu : isMA ? maBu : stBu
bool rawBe = isOC ? ocBe : isBrk ? brkBe : isDon ? donBe : isMA ? maBe : stBe
bool stSlP = isST and useRisk and inT and hasSl and (exitOnClose ? (d == 1 ? close <= sPx : close >= sPx) : (d == 1 ? low <= sPx : high >= sPx))
bool stTpP = isST and useRisk and inT and hasTp and not stSlP and (exitOnClose ? (d == 1 ? close >= tPx : close <= tPx) : (d == 1 ? high >= tPx : low <= tPx))
bool blkS = noOverlap and riskOn and inT and not (stSlP or stTpP)
bool buyS = rawBu and not (blkS and (bothExits or d == 1)) and (not alternate or d != 1) and okB
bool sellS = rawBe and not (blkS and (bothExits or d == -1)) and (not alternate or d != -1) and okS
bool rec = false // true on a bar where a trade closes
// SL / TP exit check (SL first when both are touched on the same bar)
if useRisk and inT
bool slH = hasSl and (exitOnClose ? (d == 1 ? close <= sPx : close >= sPx) : (d == 1 ? low <= sPx : high >= sPx))
bool tpH = hasTp and not slH and (exitOnClose ? (d == 1 ? close >= tPx : close <= tPx) : (d == 1 ? high >= tPx : low <= tPx))
if slH or tpH
float exitPx = exitOnClose ? close : (slH ? sPx : tPx)
lastPnl := d == 1 ? (exitPx - ePx) / ePx * 100 : (ePx - exitPx) / ePx * 100
lastRes := slH ? -1 : 1
inT := false
lastExit := bar_index
array.push(sPnls, lastPnl)
rec := true
// New signal: close an open trade (reversal) and open the new one
if buyS or sellS
if not na(sigT)
array.push(sGaps, time - sigT)
while array.size(sGaps) > lookback
array.shift(sGaps)
avgG := array.avg(sGaps)
sigT := time
if inT
lastPnl := d == 1 ? (close - ePx) / ePx * 100 : (ePx - close) / ePx * 100
lastRes := 0
array.push(sPnls, lastPnl)
rec := true
d := buyS ? 1 : -1
lastSig := bar_index
ePx := d == 1 ? eBuy : eSell
inT := true
sPx := not hasSl ? na : d == 1 ? slB : slS
float riskD = math.abs(ePx - sPx)
float tpD = tpAtr ? a * tpMultS : tpBase ? (cHi - cLo) * brkTpBMult : riskD * tpRMultS
tPx := not hasTp ? na : d == 1 ? ePx + tpD : ePx - tpD
// Lookback statistics over the last N closed trades (compounded, same as the info box)
if rec
while array.size(sPnls) > lookback
array.shift(sPnls)
float eqv = 1.0
float sumP = 0.0
float pk = 1.0
float dd2 = 0.0
int w = 0
int l = 0
for k = 0 to array.size(sPnls) - 1
float p = array.get(sPnls, k)
eqv := eqv * (1 + p / 100)
pk := math.max(pk, eqv)
dd2 := math.min(dd2, (eqv / pk - 1) * 100)
sumP += p
if p > 0
w += 1
else if p < 0
l += 1
ddV := dd2
netV := (eqv - 1) * 100
winV := w
lossV := l
nV := array.size(sPnls)
avgPV := sumP / array.size(sPnls)
// 0 = no trade yet, 1 = open, 2 = closed at TP, 3 = closed at SL
int stat = inT[1] ? 1 : (lastRes[1] == 1 ? 2 : lastRes[1] == -1 ? 3 : 0)
// 1 = the signal fired on the bar that just closed
int newF = (not na(sigT[1]) and sigT[1] == time[1]) ? 1 : 0
// Open trade P/L at the current price of that timeframe (blank when no trade is open)
float pnlOut = inT[1] ? (d[1] == 1 ? (close - ePx[1]) / ePx[1] * 100 : (ePx[1] - close) / ePx[1] * 100) : na
[d[1], stat, ePx[1], sPx[1], tPx[1], newF, close, avgG[1], netV[1], winV[1], lossV[1], nV[1], avgPV[1], pnlOut, sigT[1], ddV[1]]
// ── Engine scanner ────────────────────────────────────────
// Runs one engine (0 OC, 1 Breakout, 2 Donchian, 3 MA Cross, 4 Supertrend) with its own settings and its own trade history, exactly as the
// main logic and the Multi-Timeframe Scanner do for the selected mode. Each call site keeps its own state, so all five engines
// can run side by side inside one data request per timeframe. conf and exConf say when signals and exits count: the scanner passes
// true (closed bars only), the alerts pass the Non-repaint rules. The last four values are this bar's BUY, SELL, TP hit and SL hit.
f_eng(int m, bool conf, bool exConf) =>
bool eOC = m == 0
bool eBrk = m == 1
bool eDon = m == 2
bool eMA = m == 3
bool eST = m == 4
string sSel = eOC ? ocSlMode : eBrk ? brkSlMode : eDon ? donSlMode : eMA ? maSlMode : stSlMode
string tSel = eOC ? ocTpMode : eBrk ? brkTpMode : eDon ? donTpMode : eMA ? maTpMode : stTpMode
float sBuf = eOC ? ocSlBuf : eBrk ? brkSlBuf : eDon ? donSlBuf : eMA ? maSlBuf : stSlBuf
float sMul = eOC ? ocSlMult : eBrk ? brkSlMult : eDon ? donSlMult : eMA ? maSlMult : stSlMult
float tMul = eOC ? ocTpMult : eBrk ? brkTpMult : eDon ? donTpMult : eMA ? maTpMult : stTpMult
float tRMul = eOC ? ocTpRMult : eBrk ? brkTpRMult : eDon ? donTpRMult : eMA ? maTpRMult : stTpRMult
bool altS = eOC ? ocAlt : eBrk ? brkAlt : eDon ? donAlt : eMA ? maAlt : false
bool noOv = eOC ? ocNoOvl : eBrk ? brkNoOvl : eDon ? donNoOvl : eMA ? maNoOvl : stNoOvl
bool sAtr = sSel == "ATR"
bool sWk = sSel == "Candle wick"
bool sBd = sSel == "Candle body"
bool sEd = sSel == "Base edge"
bool sOp = sSel == "Channel opposite"
bool sMd = sSel == "Channel middle"
bool sSw = sSel == "Swing"
bool sSt = sSel == "Supertrend line"
bool tAt = tSel == "ATR target"
bool tBs = tSel == "Base height"
bool tOp = tSel == "Opposite signal"
bool tRk = tSel == "SL multiple"
bool hSl = sSel != "None"
bool hTp = not tOp and not (tRk and not hSl)
bool rOn = useRisk and (hSl or hTp)
bool bEx = hSl and hTp
bool varB = eBrk and baseMode == "Variable"
float a = ta.atr(atrLen)
// OC signal
float bd = math.abs(close - open)
float avgB = ta.sma(bd, bodyLen)
float bHi = math.max(open, close)
float bLo = math.min(open, close)
float avgVO = ta.sma(volume, bodyLen)
bool vOkO = ocVol <= 0 or volume >= avgVO * ocVol
bool ocBu = close > open and close > bHi[1] and bd >= avgB * bodyMult and vOkO
bool ocBe = close < open and close < bLo[1] and bd >= avgB * bodyMult and vOkO
// Donchian signal
float uB = ta.highest(high, donLen)[1]
float lB = ta.lowest(low, donLen)[1]
float mB = math.avg(uB, lB)
float avgVD = ta.sma(volume, donLen)
bool vOkD = donVol <= 0 or volume >= avgVD * donVol
bool donBu = close > uB and vOkD
bool donBe = close < lB and vOkD
// MA Cross signal
float mPx = f_src(maSrc)
float fM = f_ma(mPx, fastLen, maType)
float sM = f_ma(mPx, slowLen, maType)
float tM = f_ma(mPx, maTrendLen, maType)
float swL = ta.lowest(low, swingLen)
float swH = ta.highest(high, swingLen)
float avgVM = ta.sma(volume, slowLen)
bool vOkM = maVol <= 0 or volume >= avgVM * maVol
bool sOk = minSep <= 0 or (not na(a) and math.abs(fM - sM) >= a * minSep)
bool maBu = ta.crossover(fM, sM) and vOkM and sOk and (not maTrend or close > tM)
bool maBe = ta.crossunder(fM, sM) and vOkM and sOk and (not maTrend or close < tM)
// Supertrend signal
[stL, stD] = ta.supertrend(stMult, stLen)
bool stBu = stD < 0 and stD[1] > 0
bool stBe = stD > 0 and stD[1] < 0
float stEn = math.max(low, math.min(high, nz(stL[1], close)))
// Breakout base
float fHi = ta.highest(high, baseLen)[1]
float fLo = ta.lowest(low, baseLen)[1]
float bBuf = na(a) ? 0.0 : minBreak * a
float eT = ta.ema(close, brkTrendLen)
float avgVB = ta.sma(volume, brkVolLen)
bool vOkB = brkVol <= 0 or (not na(avgVB) and volume >= avgVB * brkVol)
var int d = 0
var bool inT = false
var float ePx = na
var float sPx = na
var float tPx = na
var int lastSig = na
var int lastExit = na
var int sigT = na
var int lastRes = 0
var float lastPnl = na
var array<float> sGaps = array.new_float(0)
var float avgG = na
var array<float> sPnls = array.new_float(0)
var float netV = na
var int winV = 0
var int lossV = 0
var int nV = 0
var float ddV = na
int capL = varB ? math.max(varMax, varMin) : 0
if not na(lastSig)
capL := math.min(capL, bar_index - lastSig - 1)
if noBaseInTrade and rOn
capL := inT ? 0 : na(lastExit) ? capL : math.min(capL, bar_index - lastExit - 1)
[vHi, vLo, vN] = f_varBase(varMin, capL, a * baseMult)
float cHi = varB ? vHi : fHi
float cLo = varB ? vLo : fLo
bool baseOk = varB ? vN > 0 : (fHi - fLo) <= a * baseMult
bool fresh = varB or ((na(lastSig) or bar_index - lastSig > baseLen) and (not (noBaseInTrade and rOn) or (not inT and (na(lastExit) or bar_index - lastExit > baseLen))))
bool upB2 = (wickMode ? high : close) > cHi + bBuf
bool dnB2 = (wickMode ? low : close) < cLo - bBuf
bool both = upB2 and dnB2
bool brkBu = baseOk and fresh and upB2 and (not both or close > open) and (not brkTrend or close > eT) and vOkB
bool brkBe = baseOk and fresh and dnB2 and (not both or close < open) and (not brkTrend or close < eT) and vOkB
// Entry and stop for each direction, exactly as the main logic does
float bufS = na(a) ? 0.0 : sBuf * a
float minS = eMA and not na(a) ? slMin * a : 0.0
float mEnt = math.max(low, math.min(high, nz(sM, close)))
float eBuy = eBrk ? (edgeEntry ? cHi + bBuf : close) : eDon ? (donEdge ? nz(uB, close) : close) : eMA ? (maEdge ? mEnt : close) : eST ? (stEdge ? stEn : close) : close
float eSell = eBrk ? (edgeEntry ? cLo - bBuf : close) : eDon ? (donEdge ? nz(lB, close) : close) : eMA ? (maEdge ? mEnt : close) : eST ? (stEdge ? stEn : close) : close
float lvB = sWk ? low - bufS : sBd ? open - bufS : sSw ? swL - bufS : sEd ? cLo - bufS : sOp ? nz(lB, low) - bufS : sMd ? nz(mB, eBuy) - bufS : sSt ? stL - bufS : na
float lvS = sWk ? high + bufS : sBd ? open + bufS : sSw ? swH + bufS : sEd ? cHi + bufS : sOp ? nz(uB, high) + bufS : sMd ? nz(mB, eSell) + bufS : sSt ? stL + bufS : na
float slB = not hSl ? na : sAtr ? eBuy - a * sMul : eMA ? math.min(lvB, eBuy - minS) : lvB
float slS = not hSl ? na : sAtr ? eSell + a * sMul : eMA ? math.max(lvS, eSell + minS) : lvS
bool needSt = useRisk and hSl
bool okB = not eBrk or not needSt or (not na(slB) and slB < eBuy)
bool okS = not eBrk or not needSt or (not na(slS) and slS > eSell)
bool rawBu = eOC ? ocBu : eBrk ? brkBu : eDon ? donBu : eMA ? maBu : stBu
bool rawBe = eOC ? ocBe : eBrk ? brkBe : eDon ? donBe : eMA ? maBe : stBe
bool stSlP = eST and useRisk and inT and exConf and hSl and (exitOnClose ? (d == 1 ? close <= sPx : close >= sPx) : (d == 1 ? low <= sPx : high >= sPx))
bool stTpP = eST and useRisk and inT and exConf and hTp and not stSlP and (exitOnClose ? (d == 1 ? close >= tPx : close <= tPx) : (d == 1 ? high >= tPx : low <= tPx))
bool blkS = noOv and rOn and inT and not (stSlP or stTpP)
bool buyS = conf and rawBu and not (blkS and (bEx or d == 1)) and (not altS or d != 1) and okB
bool sellS = conf and rawBe and not (blkS and (bEx or d == -1)) and (not altS or d != -1) and okS
bool rec = false
bool tpEv = false // TP hit on this bar
bool slEv = false // SL hit on this bar
// SL / TP exit check (SL first when both are touched on the same bar)
if useRisk and inT and exConf
bool slH = hSl and (exitOnClose ? (d == 1 ? close <= sPx : close >= sPx) : (d == 1 ? low <= sPx : high >= sPx))
bool tpH = hTp and not slH and (exitOnClose ? (d == 1 ? close >= tPx : close <= tPx) : (d == 1 ? high >= tPx : low <= tPx))
if slH or tpH
float exitPx = exitOnClose ? close : (slH ? sPx : tPx)
lastPnl := d == 1 ? (exitPx - ePx) / ePx * 100 : (ePx - exitPx) / ePx * 100
lastRes := slH ? -1 : 1
inT := false
lastExit := bar_index
array.push(sPnls, lastPnl)
rec := true
slEv := slH
tpEv := not slH
// New signal: close an open trade (reversal) and open the new one
if buyS or sellS
if not na(sigT)
array.push(sGaps, time - sigT)
while array.size(sGaps) > lookback
array.shift(sGaps)
avgG := array.avg(sGaps)
sigT := time
if inT
lastPnl := d == 1 ? (close - ePx) / ePx * 100 : (ePx - close) / ePx * 100
lastRes := 0
array.push(sPnls, lastPnl)
rec := true
d := buyS ? 1 : -1
lastSig := bar_index
ePx := d == 1 ? eBuy : eSell
inT := true
sPx := not hSl ? na : d == 1 ? slB : slS
float riskD = math.abs(ePx - sPx)
float tpD = tAt ? a * tMul : tBs ? (cHi - cLo) * brkTpBMult : riskD * tRMul
tPx := not hTp ? na : d == 1 ? ePx + tpD : ePx - tpD
// Lookback statistics over the last N closed trades (compounded, same as the info box)
if rec
while array.size(sPnls) > lookback
array.shift(sPnls)
float eqv = 1.0
float pk = 1.0
float dd2 = 0.0
int w = 0
int l = 0
for k = 0 to array.size(sPnls) - 1
float p = array.get(sPnls, k)
eqv := eqv * (1 + p / 100)
pk := math.max(pk, eqv)
dd2 := math.min(dd2, (eqv / pk - 1) * 100)
if p > 0
w += 1
else if p < 0
l += 1
ddV := dd2
netV := (eqv - 1) * 100
winV := w
lossV := l
nV := array.size(sPnls)
// 0 = no trade yet, 1 = open, 2 = closed at TP, 3 = closed at SL
int stat = inT[1] ? 1 : (lastRes[1] == 1 ? 2 : lastRes[1] == -1 ? 3 : 0)
float pnlOut = inT[1] ? (d[1] == 1 ? (close - ePx[1]) / ePx[1] * 100 : (ePx[1] - close) / ePx[1] * 100) : na
[d[1], stat, netV[1], winV[1], lossV[1], nV[1], ddV[1], pnlOut, sigT[1], avgG[1], buyS, sellS, tpEv, slEv]
// All five engines for one timeframe in a single data request (the last value is the timeframe's close)
f_all() =>
[d0, s0, n0, w0, l0, c0, g0, p0, t0, v0, b0, x0, y0, z0] = f_eng(0, true, true)
[d1, s1, n1, w1, l1, c1, g1, p1, t1, v1, b1, x1, y1, z1] = f_eng(1, true, true)
[d2, s2, n2, w2, l2, c2, g2, p2, t2, v2, b2, x2, y2, z2] = f_eng(2, true, true)
[d3, s3, n3, w3, l3, c3, g3, p3, t3, v3, b3, x3, y3, z3] = f_eng(3, true, true)
[d4, s4, n4, w4, l4, c4, g4, p4, t4, v4, b4, x4, y4, z4] = f_eng(4, true, true)
[d0, s0, n0, w0, l0, c0, g0, p0, t0, v0, d1, s1, n1, w1, l1, c1, g1, p1, t1, v1, d2, s2, n2, w2, l2, c2, g2, p2, t2, v2, d3, s3, n3, w3, l3, c3, g3, p3, t3, v3, d4, s4, n4, w4, l4, c4, g4, p4, t4, v4, close]
// Converts a typed timeframe to the format Pine expects: 15m -> 15, 4h -> 240, 1D -> D, 1W -> W (capital M = month)
f_tf(string raw) =>
string t = str.trim(raw)
int n = str.length(t)
string lc = str.substring(t, n - 1)
float num = str.tonumber(str.substring(t, 0, n - 1))
string res = t
if lc == "h" or lc == "H"
res := na(num) ? t : str.tostring(num * 60, "0")
else if lc == "m"
res := na(num) ? t : str.tostring(num, "0")
else if lc == "d" or lc == "D"
res := na(num) or num == 1 ? "D" : str.tostring(num, "0") + "D"
else if lc == "w" or lc == "W"
res := na(num) or num == 1 ? "W" : str.tostring(num, "0") + "W"
else if lc == "M"
res := na(num) or num == 1 ? "M" : str.tostring(num, "0") + "M"
res
// Splits the typed list on commas or new lines, trims each entry and skips empty ones
f_parseTf(string raw) =>
string cleaned = str.replace_all(str.replace_all(raw, "\n", ","), "\r", "")
array<string> parts = str.split(cleaned, ",")
array<string> out = array.new_string(0)
for p in parts
string t = str.trim(p)
if t != ""
array.push(out, f_tf(t))
if array.size(out) == 0
array.push(out, timeframe.period)
out
// Display label for a Pine timeframe: 15 -> 15m, 240 -> 4h, D -> D
f_label(string tf) =>
string r = tf
string lc = str.substring(tf, str.length(tf) - 1)
if lc != "D" and lc != "W" and lc != "M" and lc != "S"
float mins = str.tonumber(tf)
if not na(mins)
r := (mins >= 60 and mins % 60 == 0) ? str.tostring(mins / 60, "0") + "h" : str.tostring(mins, "0") + "m"
r
// Price format by magnitude: JPY-style pairs get 3 decimals, 4/5-digit pairs get 5
f_px(float x, float ref) =>
na(x) ? "-" : str.tostring(x, ref >= 1000 ? "0.00" : ref >= 20 ? "0.000" : "0.00000")
scPos = switch scPosIn
"Top Left" => position.top_left
"Top Center" => position.top_center
"Middle Left" => position.middle_left
"Middle Center" => position.middle_center
"Middle Right" => position.middle_right
"Bottom Left" => position.bottom_left
"Bottom Center" => position.bottom_center
"Bottom Right" => position.bottom_right
=> position.top_right
scSize = switch scSizeIn
"Tiny" => size.tiny
"Normal" => size.normal
"Large" => size.large
"Huge" => size.huge
=> size.small
f_scCell(table t, int c, int r, string txt, color tc, color bg) =>
table.cell(t, c, r, txt, text_color=tc, bgcolor=bg, text_halign=(c == 0 ? text.align_left : text.align_right), text_size=scSize)
var array<string> scTfs = f_parseTf(scTfList)
int nTf = math.min(scMax, array.size(scTfs))
string scanTk = chart.is_heikinashi ? ticker.heikinashi(syminfo.tickerid) : syminfo.tickerid
var array<int> aDir = array.new_int(64, 0)
var array<int> aStat = array.new_int(64, 0)
var array<float> aEnt = array.new_float(64, na)
var array<float> aSl = array.new_float(64, na)
var array<float> aTp = array.new_float(64, na)
var array<int> aNew = array.new_int(64, 0)
var array<float> aPx = array.new_float(64, na)
var array<float> aAvg = array.new_float(64, na)
var array<float> aNet = array.new_float(64, na)
var array<int> aWin = array.new_int(64, 0)
var array<int> aLoss = array.new_int(64, 0)
var array<int> aN = array.new_int(64, 0)
var array<float> aAvgP = array.new_float(64, na)
var array<float> aOp = array.new_float(64, na)
var array<int> aSg = array.new_int(64, na) // time of the last signal, per timeframe
var array<float> aDD = array.new_float(64, na)
var array<int> aAl = array.new_int(64, na) // signal time already alerted, per timeframe
string scMsg = ""
bool scBuy = false // a scanned timeframe just gave a BUY
bool scSell = false // a scanned timeframe just gave a SELL
// Requests only run while the scanner is shown, so turning it off frees the data requests
if showScan
for i = 0 to nTf - 1
string tf = array.get(scTfs, i)
[rD, rSt, rEn, rSl, rTp, rNew, rPx, rAv, rNet, rWin, rLoss, rN, rAvP, rOp, rSig, rDD] = request.security(scanTk, tf, f_scan(), ignore_invalid_symbol = true)
array.set(aDir, i, nz(rD))
array.set(aStat, i, nz(rSt))
array.set(aEnt, i, rEn)
array.set(aSl, i, rSl)
array.set(aTp, i, rTp)
array.set(aNew, i, nz(rNew))
array.set(aPx, i, rPx)
array.set(aAvg, i, rAv)
array.set(aNet, i, rNet)
array.set(aWin, i, nz(rWin))
array.set(aLoss, i, nz(rLoss))
array.set(aN, i, nz(rN))
array.set(aAvgP, i, rAvP)
array.set(aOp, i, rOp)
array.set(aSg, i, rSig)
array.set(aDD, i, rDD)
// A new signal on any scanned timeframe: history is marked as seen silently, live signals are collected for one alert
if not na(rSig) and rSig != array.get(aAl, i)
if barstate.isrealtime
scBuy := scBuy or nz(rD) == 1
scSell := scSell or nz(rD) == -1
scMsg += (scMsg == "" ? "" : " | ") + f_label(tf) + " " + (nz(rD) == 1 ? "BUY" : "SELL")
array.set(aAl, i, rSig)
if scMsg != ""
alert("XL " + mode + " Scanner " + syminfo.ticker + ": " + scMsg, alert.freq_once_per_bar)
bool scChartOk = chart.is_standard or chart.is_heikinashi
string scanType = chart.is_heikinashi ? "Heikin Ashi" : "Standard"
var table scanTbl = na
// Scanner Detail picks which columns show: 0 Timeframe, 1 Signal, 2 Status, 3 Avg Between, 4 Last Signal, 5 Entry, 6 SL, 7 TP, 8 Open P/L, 9 Avg P/L, 10 Net P/L, 11 Max DD, 12 Win Rate
array<int> scCols = scDetail == "Micro" ? array.from(0, 1, 2, 12) : scDetail == "Low" ? array.from(0, 1, 2, 3, 10, 12) : scDetail == "Medium" ? array.from(0, 1, 2, 3, 8, 9, 10, 12) : scDetail == "High" ? array.from(0, 1, 2, 3, 5, 6, 7, 8, 9, 10, 12) : array.from(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12)
int nCols = array.size(scCols)
if showScan and barstate.islast
table.delete(scanTbl)
scanTbl := table.new(scPos, nCols, nTf + 2, bgcolor=color.new(#131722, 10), frame_color=color.new(color.gray, 40), frame_width=1, border_color=color.new(color.gray, 60), border_width=1)
table.merge_cells(scanTbl, 0, 0, nCols - 1, 0)
string ttl = "XL - " + str.upper(mode) + " BUY/SELL SCANNER (" + syminfo.ticker + " / " + scanType + ")" + (scChartOk ? "" : " - chart is " + chartType + ", scanner uses Standard")
table.cell(scanTbl, 0, 0, ttl, text_color=color.white, bgcolor=scChartOk ? color.new(#3B5B92, 0) : color.new(#F23645, 0), text_halign=text.align_center, text_size=scSize)
array<string> hdr = array.from("Timeframe", "Signal", "Status", "Avg Between", "Last Signal", "Entry", "SL", "TP", "Open P/L", "Avg P/L", "Net P/L", "Max DD", "Win Rate / " + str.tostring(lookback))
for j = 0 to nCols - 1
table.cell(scanTbl, j, 1, array.get(hdr, array.get(scCols, j)), text_color=color.new(color.white, 0), bgcolor=color.new(#3B5B92, 40), text_halign=(j == 0 ? text.align_left : text.align_right), text_size=scSize)
for i = 0 to nTf - 1
int rw = i + 2
string lbl = f_label(array.get(scTfs, i))
float px = array.get(aPx, i)
bool ok = not na(px)
int dd = array.get(aDir, i)
int stt = array.get(aStat, i)
float en = array.get(aEnt, i)
float slv = array.get(aSl, i)
float tpv = array.get(aTp, i)
// NEW = the signal fired on the bar that just closed on that timeframe
bool isNew = ok and array.get(aNew, i) == 1
color bg = isNew ? color.new(dd == 1 ? buyCol : sellCol, 70) : na
string dirTxt = not ok ? "n/a" : dd == 1 ? "BUY" : dd == -1 ? "SELL" : "-"
color dirCol = dd == 1 ? buyCol : dd == -1 ? sellCol : color.gray
string stTxt = not ok ? "-" : stt == 1 ? "OPEN" : stt == 2 ? "TP" : stt == 3 ? "SL" : "-"
color stCol = stt == 1 ? color.white : stt == 2 ? buyCol : stt == 3 ? sellCol : color.gray
bool hasTrade = ok and dd != 0
float av = array.get(aAvg, i)
float lsg = array.get(aSg, i)
float mdd = array.get(aDD, i)
float ap = array.get(aAvgP, i)
float nt = array.get(aNet, i)
int wn = array.get(aWin, i)
int ls = array.get(aLoss, i)
int cnt = array.get(aN, i)
bool hasStats = ok and cnt > 0
float op = array.get(aOp, i)
bool isOpen = ok and stt == 1
// Text and color for all 13 columns, then only the columns picked by Scanner Detail are drawn
array<string> tx = array.from(lbl, dirTxt, stTxt, not ok or na(av) ? "-" : fmtDur(av), not ok or na(lsg) ? "-" : fmtDur(time - lsg), hasTrade ? f_px(en, px) : "-", hasTrade ? f_px(slv, px) : "-", hasTrade ? f_px(tpv, px) : "-", isOpen ? fmt(op) : "-", hasStats ? fmt(ap) : "-", hasStats ? fmt(nt) : "-", hasStats ? fmt(mdd) : "-", hasStats ? str.tostring(wn / cnt * 100, "0") + "% (" + str.tostring(wn) + "W/" + str.tostring(ls) + "L)" : "-")
array<color> tc = array.from(color.white, dirCol, stCol, color.white, color.white, color.white, color.white, color.white, isOpen ? posCol(op) : color.gray, hasStats ? posCol(ap) : color.gray, hasStats ? posCol(nt) : color.gray, hasStats and mdd < 0 ? color.new(#F23645, 0) : color.white, hasStats and cnt < lookback ? color.new(#F23645, 0) : color.white)
for j = 0 to nCols - 1
int c = array.get(scCols, j)
f_scCell(scanTbl, j, rw, array.get(tx, c), array.get(tc, c), bg)
// ── Engine scanner: all five engines side by side ─────────
engPos = switch engPosIn
"Top Left" => position.top_left
"Top Center" => position.top_center
"Middle Left" => position.middle_left
"Middle Center" => position.middle_center
"Middle Right" => position.middle_right
"Bottom Left" => position.bottom_left
"Bottom Center" => position.bottom_center
"Bottom Right" => position.bottom_right
=> position.top_right
engSize = switch engSizeIn
"Tiny" => size.tiny
"Normal" => size.normal
"Large" => size.large
"Huge" => size.huge
=> size.small
// The engine scanner uses the Multi-Timeframe Scanner's timeframe list and Max timeframes
var array<int> xDir = array.new_int(320, 0)
var array<int> xStat = array.new_int(320, 0)
var array<float> xNet = array.new_float(320, na)
var array<int> xWin = array.new_int(320, 0)
var array<int> xLoss = array.new_int(320, 0)
var array<int> xN = array.new_int(320, 0)
var array<float> xDD = array.new_float(320, na)
var array<float> xOp = array.new_float(320, na)
var array<int> xSg = array.new_int(320, na)
var array<float> xAvg = array.new_float(320, na)
var array<float> xPx = array.new_float(64, na)
var array<int> xAl = array.new_int(320, na) // signal time already alerted, per timeframe and engine
array<bool> engScBuy = array.new_bool(5, false) // an engine just gave a BUY on a scanned timeframe
array<bool> engScSell = array.new_bool(5, false) // an engine just gave a SELL on a scanned timeframe
// Requests only run while the engine scanner is shown, so turning it off frees the data requests
if showEng
for i = 0 to nTf - 1
string etf = array.get(scTfs, i)
[e0Dir, e0Stat, e0Net, e0Win, e0Loss, e0N, e0DD, e0Op, e0Sg, e0Avg, e1Dir, e1Stat, e1Net, e1Win, e1Loss, e1N, e1DD, e1Op, e1Sg, e1Avg, e2Dir, e2Stat, e2Net, e2Win, e2Loss, e2N, e2DD, e2Op, e2Sg, e2Avg, e3Dir, e3Stat, e3Net, e3Win, e3Loss, e3N, e3DD, e3Op, e3Sg, e3Avg, e4Dir, e4Stat, e4Net, e4Win, e4Loss, e4N, e4DD, e4Op, e4Sg, e4Avg, ePx] = request.security(scanTk, etf, f_all(), ignore_invalid_symbol = true)
array.set(xPx, i, ePx)
array.set(xDir, i * 5 + 0, nz(e0Dir))
array.set(xStat, i * 5 + 0, nz(e0Stat))
array.set(xNet, i * 5 + 0, e0Net)
array.set(xWin, i * 5 + 0, nz(e0Win))
array.set(xLoss, i * 5 + 0, nz(e0Loss))
array.set(xN, i * 5 + 0, nz(e0N))
array.set(xDD, i * 5 + 0, e0DD)
array.set(xOp, i * 5 + 0, e0Op)
array.set(xSg, i * 5 + 0, e0Sg)
array.set(xAvg, i * 5 + 0, e0Avg)
array.set(xDir, i * 5 + 1, nz(e1Dir))
array.set(xStat, i * 5 + 1, nz(e1Stat))
array.set(xNet, i * 5 + 1, e1Net)
array.set(xWin, i * 5 + 1, nz(e1Win))
array.set(xLoss, i * 5 + 1, nz(e1Loss))
array.set(xN, i * 5 + 1, nz(e1N))
array.set(xDD, i * 5 + 1, e1DD)
array.set(xOp, i * 5 + 1, e1Op)
array.set(xSg, i * 5 + 1, e1Sg)
array.set(xAvg, i * 5 + 1, e1Avg)
array.set(xDir, i * 5 + 2, nz(e2Dir))
array.set(xStat, i * 5 + 2, nz(e2Stat))
array.set(xNet, i * 5 + 2, e2Net)
array.set(xWin, i * 5 + 2, nz(e2Win))
array.set(xLoss, i * 5 + 2, nz(e2Loss))
array.set(xN, i * 5 + 2, nz(e2N))
array.set(xDD, i * 5 + 2, e2DD)
array.set(xOp, i * 5 + 2, e2Op)
array.set(xSg, i * 5 + 2, e2Sg)
array.set(xAvg, i * 5 + 2, e2Avg)
array.set(xDir, i * 5 + 3, nz(e3Dir))
array.set(xStat, i * 5 + 3, nz(e3Stat))
array.set(xNet, i * 5 + 3, e3Net)
array.set(xWin, i * 5 + 3, nz(e3Win))
array.set(xLoss, i * 5 + 3, nz(e3Loss))
array.set(xN, i * 5 + 3, nz(e3N))
array.set(xDD, i * 5 + 3, e3DD)
array.set(xOp, i * 5 + 3, e3Op)
array.set(xSg, i * 5 + 3, e3Sg)
array.set(xAvg, i * 5 + 3, e3Avg)
array.set(xDir, i * 5 + 4, nz(e4Dir))
array.set(xStat, i * 5 + 4, nz(e4Stat))
array.set(xNet, i * 5 + 4, e4Net)
array.set(xWin, i * 5 + 4, nz(e4Win))
array.set(xLoss, i * 5 + 4, nz(e4Loss))
array.set(xN, i * 5 + 4, nz(e4N))
array.set(xDD, i * 5 + 4, e4DD)
array.set(xOp, i * 5 + 4, e4Op)
array.set(xSg, i * 5 + 4, e4Sg)
array.set(xAvg, i * 5 + 4, e4Avg)
// A new signal on a scanned timeframe, per engine: history is marked as seen silently, live signals raise the alert
for k = 0 to 4
int ax = i * 5 + k
int sg = array.get(xSg, ax)
if not na(sg) and sg != array.get(xAl, ax)
if barstate.isrealtime
if array.get(xDir, ax) == 1
array.set(engScBuy, k, true)
else
array.set(engScSell, k, true)
array.set(xAl, ax, sg)
// Engine scanner detail picks which columns each engine shows: 0 Signal, 1 Status, 2 Avg Between, 3 Open P/L, 4 Net P/L, 5 Max DD, 6 Win Rate
array<int> engCols = engDetail == "Micro" ? array.from(6) : engDetail == "Low" ? array.from(1, 6) : engDetail == "Medium" ? array.from(0, 1, 6) : engDetail == "High" ? array.from(0, 1, 4, 6) : array.from(0, 1, 3, 4, 5, 6)
int nEc = array.size(engCols)
var table engTbl = na
if showEng and barstate.islast
table.delete(engTbl)
int nc = 1 + 5 * nEc
engTbl := table.new(engPos, nc, nTf + 3, bgcolor=color.new(#131722, 10), frame_color=color.new(color.gray, 40), frame_width=1, border_color=color.new(color.gray, 60), border_width=1)
table.merge_cells(engTbl, 0, 0, nc - 1, 0)
string engTtl = "XL - Engine Scanner (" + syminfo.ticker + " / " + scanType + ")" + (scChartOk ? "" : " - chart is " + chartType + ", scanner uses Standard")
table.cell(engTbl, 0, 0, engTtl, text_color=color.white, bgcolor=scChartOk ? color.new(#3B5B92, 0) : color.new(#F23645, 0), text_halign=text.align_center, text_size=engSize)
array<string> engNames = array.from("OC", "Breakout", "Donchian", "MA Cross", "Supertrend")
array<string> engHdr = array.from("Signal", "Status", "Avg Between", "Open P/L", "Net P/L", "Max DD", "Win Rate / " + str.tostring(lookback))
table.cell(engTbl, 0, 1, "", text_color=color.white, bgcolor=color.new(#3B5B92, 40), text_size=engSize)
table.cell(engTbl, 0, 2, "Timeframe", text_color=color.white, bgcolor=color.new(#3B5B92, 40), text_halign=text.align_left, text_size=engSize)
for k = 0 to 4
int c0 = 1 + k * nEc
color hb = k % 2 == 0 ? color.new(#3B5B92, 0) : color.new(#2A4170, 0)
if nEc > 1
table.merge_cells(engTbl, c0, 1, c0 + nEc - 1, 1)
table.cell(engTbl, c0, 1, array.get(engNames, k), text_color=color.white, bgcolor=hb, text_halign=text.align_center, text_size=engSize)
for j = 0 to nEc - 1
table.cell(engTbl, c0 + j, 2, array.get(engHdr, array.get(engCols, j)), text_color=color.white, bgcolor=color.new(hb, 40), text_halign=text.align_center, text_size=engSize)
for i = 0 to nTf - 1
int rw = i + 3
float px = array.get(xPx, i)
bool ok = not na(px)
table.cell(engTbl, 0, rw, f_label(array.get(scTfs, i)), text_color=color.white, text_halign=text.align_left, text_size=engSize)
for k = 0 to 4
int ix = i * 5 + k
int dd = array.get(xDir, ix)
int stt = array.get(xStat, ix)
float av = array.get(xAvg, ix)
float op = array.get(xOp, ix)
float nt = array.get(xNet, ix)
float mdd = array.get(xDD, ix)
int wn = array.get(xWin, ix)
int ls = array.get(xLoss, ix)
int cnt = array.get(xN, ix)
bool hasStats = ok and cnt > 0
bool isOpen = ok and stt == 1
string dirTxt = not ok ? "n/a" : dd == 1 ? "BUY" : dd == -1 ? "SELL" : "-"
color dirCol = dd == 1 ? buyCol : dd == -1 ? sellCol : color.gray
string stTxt = not ok ? "-" : stt == 1 ? "OPEN" : stt == 2 ? "TP" : stt == 3 ? "SL" : "-"
color stCol = stt == 1 ? color.white : stt == 2 ? buyCol : stt == 3 ? sellCol : color.gray
array<string> tx = array.from(dirTxt, stTxt, not ok or na(av) ? "-" : fmtDur(av), isOpen ? fmt(op) : "-", hasStats ? fmt(nt) : "-", hasStats ? fmt(mdd) : "-", hasStats ? str.tostring(wn / cnt * 100, "0") + "% (" + str.tostring(wn) + "W/" + str.tostring(ls) + "L)" : "-")
array<color> tc = array.from(dirCol, stCol, color.white, isOpen ? posCol(op) : color.gray, hasStats ? posCol(nt) : color.gray, hasStats and mdd < 0 ? color.new(#F23645, 0) : color.white, hasStats and cnt < lookback ? color.new(#F23645, 0) : color.white)
for j = 0 to nEc - 1
int c = array.get(engCols, j)
table.cell(engTbl, 1 + k * nEc + j, rw, array.get(tx, c), text_color=array.get(tc, c), text_halign=text.align_center, text_size=engSize)
// ── Alerts: every engine, whatever the Signal mode is ─────
// Each engine runs in the background on the chart's timeframe with its own settings and the Non-repaint rules, so one copy of the
// indicator can alert on all five engines. An alert keeps the settings it had when it was created.
[fa1, fa2, fa3, fa4, fa5, fa6, fa7, fa8, fa9, fa10, evOcBuy, evOcSell, evOcTp, evOcSl] = f_eng(0, confirmed, exitConfirmed)
[fb1, fb2, fb3, fb4, fb5, fb6, fb7, fb8, fb9, fb10, evBrkBuy, evBrkSell, evBrkTp, evBrkSl] = f_eng(1, confirmed, exitConfirmed)
[fc1, fc2, fc3, fc4, fc5, fc6, fc7, fc8, fc9, fc10, evDonBuy, evDonSell, evDonTp, evDonSl] = f_eng(2, confirmed, exitConfirmed)
[fd1, fd2, fd3, fd4, fd5, fd6, fd7, fd8, fd9, fd10, evMaBuy, evMaSell, evMaTp, evMaSl] = f_eng(3, confirmed, exitConfirmed)
[fe1, fe2, fe3, fe4, fe5, fe6, fe7, fe8, fe9, fe10, evStBuy, evStSell, evStTp, evStSl] = f_eng(4, confirmed, exitConfirmed)
// All engines together: one entry for a buy, one for a sell
bool anyBuy = evOcBuy or evBrkBuy or evDonBuy or evMaBuy or evStBuy
bool anySell = evOcSell or evBrkSell or evDonSell or evMaSell or evStSell
alertcondition(anyBuy, "XL Buy Signal (All Engines)", "XL BUY | {{ticker}} {{interval}}")
alertcondition(anySell, "XL Sell Signal (All Engines)", "XL SELL | {{ticker}} {{interval}}")
alertcondition(array.includes(engScBuy, true), "XL Scanner Buy Signal (All Engines, Any Timeframe)", "XL scanner BUY on a scanned timeframe | {{ticker}}")
alertcondition(array.includes(engScSell, true), "XL Scanner Sell Signal (All Engines, Any Timeframe)", "XL scanner SELL on a scanned timeframe | {{ticker}}")
alertcondition(evOcBuy or evOcSell, "OC Buy/Sell Signal", "XL OC signal | {{ticker}} {{interval}}")
alertcondition(evOcTp or evOcSl, "OC Take Profit or Stop Loss Hit", "XL OC exit (TP or SL) | {{ticker}} {{interval}}")
alertcondition(array.get(engScBuy, 0) or array.get(engScSell, 0), "OC Scanner Buy/Sell Signal (Any Timeframe)", "XL OC scanner signal on a scanned timeframe | {{ticker}}")
alertcondition(evBrkBuy or evBrkSell, "Breakout Buy/Sell Signal", "XL Breakout signal | {{ticker}} {{interval}}")
alertcondition(evBrkTp or evBrkSl, "Breakout Take Profit or Stop Loss Hit", "XL Breakout exit (TP or SL) | {{ticker}} {{interval}}")
alertcondition(array.get(engScBuy, 1) or array.get(engScSell, 1), "Breakout Scanner Buy/Sell Signal (Any Timeframe)", "XL Breakout scanner signal on a scanned timeframe | {{ticker}}")
alertcondition(evDonBuy or evDonSell, "Donchian Buy/Sell Signal", "XL Donchian signal | {{ticker}} {{interval}}")
alertcondition(evDonTp or evDonSl, "Donchian Take Profit or Stop Loss Hit", "XL Donchian exit (TP or SL) | {{ticker}} {{interval}}")
alertcondition(array.get(engScBuy, 2) or array.get(engScSell, 2), "Donchian Scanner Buy/Sell Signal (Any Timeframe)", "XL Donchian scanner signal on a scanned timeframe | {{ticker}}")
alertcondition(evMaBuy or evMaSell, "MA Cross Buy/Sell Signal", "XL MA Cross signal | {{ticker}} {{interval}}")
alertcondition(evMaTp or evMaSl, "MA Cross Take Profit or Stop Loss Hit", "XL MA Cross exit (TP or SL) | {{ticker}} {{interval}}")
alertcondition(array.get(engScBuy, 3) or array.get(engScSell, 3), "MA Cross Scanner Buy/Sell Signal (Any Timeframe)", "XL MA Cross scanner signal on a scanned timeframe | {{ticker}}")
alertcondition(evStBuy or evStSell, "Supertrend Buy/Sell Signal", "XL Supertrend signal | {{ticker}} {{interval}}")
alertcondition(evStTp or evStSl, "Supertrend Take Profit or Stop Loss Hit", "XL Supertrend exit (TP or SL) | {{ticker}} {{interval}}")
alertcondition(array.get(engScBuy, 4) or array.get(engScSell, 4), "Supertrend Scanner Buy/Sell Signal (Any Timeframe)", "XL Supertrend scanner signal on a scanned timeframe | {{ticker}}")