Z-Score Buy/Sell Signals

tgregg75 · study · 1255 行 · 点赞 69 · TradingView 原页

本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。

Pine Script

//@version=6
indicator("Z-Score Buy/Sell Signals", shorttitle="Z-Score Signals", 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.")
grpSig   = "📡 Signals"
zEngIn   = input.string("Body", "Z-score engine", options=["Body", "Return", "Price vs Mean"], group=grpSig, tooltip="What the z-score measures. Body: the size of the signal candle's body (open to close). A candle with an unusually large body fires, and its color sets the direction: green is a BUY, red is a SELL. Return: the bar's close-to-close percent change. An unusually large rise is a BUY and an unusually large fall is a SELL. Price vs Mean: the close itself against the recent average price. A close unusually far above the average is a BUY, unusually far below is a SELL, like a close outside a Bollinger band. All three follow the move and measure the signal bar against the bars BEFORE it.")
zLen     = input.int(50, "Z-score length", minval=5, group=grpSig, tooltip="Number of bars used to build the bell curve of candle bodies: the average body (the middle of the curve) and the standard deviation (its spread). Both are read on the bars BEFORE the signal candle, so the signal candle is measured against the normal behavior that came before it. Also the averaging length for the volume filter.")
zMult    = input.float(2.0, "Min z-score (std devs)", minval=0.0, step=0.1, group=grpSig, tooltip="How far out on the bell curve the signal bar must be, in standard deviations from the average of the chosen engine (body, return or price). Body: the body must be at least the average body + this number x standard deviation. Return and Price vs Mean: the z-score must be at least this high for a BUY or at most minus this for a SELL. 2.0 is the classic outlier mark (about the top 2.5% of a perfect bell curve). Candle bodies are not a perfect bell curve, they lean toward many small bodies and a long tail of large ones, so in practice more candles pass than 2.5%. Raise it for fewer, stronger signals. Lower it for more signals.")
ocRule   = input.bool(true, "Require close beyond prior body", group=grpSig, tooltip="ON: a signal also needs the OC close rule. A BUY must be a green candle closing above the previous candle's body (the higher of its open and close). A SELL must be a red candle closing below the previous candle's body. OFF: the z-score alone decides, and for the Return and Price vs Mean engines the candle color and the previous body are ignored. For the Body engine the candle color still sets the direction.")
sigDirIn = input.string("Alternate Signals", "Signal Direction", options=["Alternate Signals", "Any Signal", "Buy Only Sig", "Sell Only Sig"], group=grpSig, tooltip="Alternate Signals: signals alternate BUY, SELL, BUY and so on, and a signal in the same direction as the open trade is skipped. Any Signal: every qualifying candle fires, in both directions. Buy Only Sig: only BUY signals fire and SELL signals never appear. Sell Only Sig: only SELL signals fire and BUY signals never appear. 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. With Any Signal, Buy Only Sig or Sell Only Sig, 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, unless Ignore signals while a trade is open blocks it.")
bool alternate = sigDirIn == "Alternate Signals"
noOverlap = input.bool(true, "Ignore signals while a trade is open", group=grpSig, 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.")
 
grpFilt = "🔎 Signal Filters"
volMult  = input.float(0.0, "Min volume vs average (x)", minval=0.0, step=0.5, group=grpFilt, tooltip="Minimum volume of the signal candle as a multiple of its average volume (same length as the Z-score 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.")
 
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.")
slMode   = input.string("Candle wick", "Stop loss mode", options=["ATR", "Candle wick", "Candle body", "None"], group=grpRisk, 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.")
slBuf    = input.float(0.0, "Stop buffer (x ATR)", minval=0.0, step=0.05, group=grpRisk, 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 below. Ignored by the ATR and None stop loss modes, and when Enable SL/TP is OFF.")
tpMode   = input.string("SL multiple", "Take profit mode", options=["ATR target", "SL multiple", "Opposite signal"], group=grpRisk, 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.")
atrLen   = input.int(14, "ATR length", minval=1, group=grpRisk, tooltip="Number of bars used for the ATR value. ATR is read on the signal bar and locked in for that trade. Ignored when Enable SL/TP is OFF.")
slMult   = input.float(1.5, "Stop loss (x ATR)", minval=0.1, step=0.1, group=grpRisk, 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.")
tpMult   = input.float(3.0, "Take profit (x ATR)", minval=0.1, step=0.1, group=grpRisk, 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.")
tpRMult  = input.float(1.0, "Take profit (x SL)", minval=0.1, step=0.1, group=grpRisk, 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.")
 
grpSize   = "💰 Position Sizing"
useSize   = input.bool(false, "Show position size", group=grpSize, tooltip="ON: works out how large each trade should be so that hitting the stop loss costs about the Risk per trade amount. The size is shown on the Entry and SL/TP labels, in the info box and in an extra alert message. OFF: nothing is calculated or shown. Needs a stop loss (Stop loss mode other than None) and Enable SL/TP ON, because the size comes from the distance between entry and stop. Works for forex, stocks, ETFs and crypto. Futures are not supported and show n/a.")
showSizeBox = input.bool(false, "Show size in info box", group=grpSize, tooltip="ON: adds a Position Size section to the info box with the risk per trade, the size, the risk and reward in money, and the cost of the open trade. Used only when Show position size is ON and the info box is shown. The labels and alerts are not affected.")
riskAmt   = input.float(100.0, "Risk per trade", minval=0.01, step=10.0, group=grpSize, tooltip="The amount you are willing to lose if the stop loss is hit, in the Account currency. Example: 100 means a stopped-out trade loses about 100. Size = this amount divided by the distance from entry to stop, converted to the Account currency. It is a fixed number you type in. Used when Risk method is Fixed amount. The Net $ column of the symbols scanner always uses this amount, even when Risk method is Kelly.")
acctCcy   = input.string("USD", "Account currency", options=["USD", "EUR", "GBP", "JPY", "AUD", "CAD", "CHF", "NZD", "SEK", "NOK", "DKK", "SGD", "HKD", "MXN", "ZAR"], group=grpSize, tooltip="Currency of your account. Used to convert the stop distance when the symbol is quoted in another currency (for example USDJPY is quoted in JPY). If the conversion rate is not available the size shows n/a.")
 
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 with Alternate Signals), using the signal bar's close as the price. With SL/TP enabled, trades can also close at their SL or TP price.")
 
grpInfo   = "📊 Info Box"
showTable = input.bool(true, "Show info box", group=grpInfo, tooltip="Turns the lookback P/L info box on or off.")
tablePos  = input.string("Bottom Left", "Info box position", options=["Top Left", "Top Center", "Top Right", "Middle Left", "Middle Center", "Middle Right", "Bottom Left", "Bottom Center", "Bottom Right"], group=grpInfo, tooltip="Chart location of the info box.")
tableSize = input.string("Tiny", "Info box size", options=["Tiny", "Small", "Normal", "Large", "Huge"], group=grpInfo, tooltip="Text size used inside the info box.")
 
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("15, 30, 60, 4h", "Scanner timeframes (comma separated)", group=grpScan, tooltip="Timeframes to scan, separated by commas or one per line. 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. 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("Tiny", "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: Timeframe, Status, Net P/L and Win Rate. Micro: Timeframe, 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.")
 
grpSym    = "🌐 Symbols Scanner"
showSym   = input.bool(true, "Show symbol scanner", group=grpSym, tooltip="Shows a table with one row per symbol and one column per timeframe. Each cell is the Z-Score win rate of that symbol on that timeframe over the Lookback trades, using the same signal, stop loss, take profit and lookback settings as this indicator, and the cell turns green (long) or red (short) while a trade is open on that timeframe. The columns use the timeframe list and Max timeframes from the Multi-Timeframe Scanner group, and it works even when Show scanner is OFF. Each symbol and timeframe pair is one data request, so the table stops at the request limit below. The candle type follows the chart (Standard or Heikin Ashi). Turn it off to save data requests and calculation time. Alerts and the info box are not affected.")
symExIn   = input.string("", "Default exchange", group=grpSym, tooltip="Optional. Type an exchange once, for example TASTYFX, and every symbol in the list that has no exchange of its own uses it, so USDJPY becomes TASTYFX:USDJPY. A symbol typed with its own exchange, for example NASDAQ:MSFT, keeps it. Leave blank and TradingView picks the feed, which can differ from your chart. Match it to your chart so the symbol scanner reads the same candles as the main scanner.")
symListIn = input.text_area("", "Symbols (comma separated, ALL CAPS)", group=grpSym, tooltip="Symbols to scan, separated by commas or one per line. Use ALL CAPS (recommended). Just type the symbol, for example SPY, MSFT or EURUSD, and TradingView picks the exchange automatically. If you need a specific feed, add the exchange in front, for example AMEX:SPY or BINANCE:BTCUSDT. A symbol that TradingView does not recognise shows n/a. The symbol name in the table is the part after the colon, if any.")
symMax    = input.int(10, "Max symbols", minval=1, maxval=40, group=grpSym, tooltip="How many symbols to scan, taken from the top of the list. The table also stops when the request limit below is reached, and the title says how many symbols are shown.")
symReqLimit = input.int(40, "Request limit", minval=1, maxval=64, group=grpSym, tooltip="Unique data requests this script may use. TradingView allows 40 per script on most plans and 64 on the Ultimate plan. The symbol scanner uses symbols x timeframes of them, and the script already uses one for position sizing (when the position size currency differs) and one per timeframe of the Multi-Timeframe Scanner while it is shown. The script errors if the plan limit is exceeded, so keep this at your plan's limit or lower.")
symPosIn  = input.string("Bottom Center", "Symbol scanner position", options=["Top Left", "Top Center", "Top Right", "Middle Left", "Middle Center", "Middle Right", "Bottom Left", "Bottom Center", "Bottom Right"], group=grpSym, tooltip="Chart location of the symbol scanner table. Only one table can sit in each spot, so keep it away from the info box and the Multi-Timeframe Scanner.")
symSizeIn = input.string("Tiny", "Symbol scanner size", options=["Tiny", "Small", "Normal", "Large", "Huge"], group=grpSym, tooltip="Text size used inside the symbol scanner table.")
symMetricIn = input.string("W/R %", "Symbols scanner shows", options=["W/R %", "Net %", "Net $", "W/R % & Net %", "W/R % & Net $", "Net % & Net $"], group=grpSym, tooltip="What each cell of the symbols scanner shows over the last Lookback closed trades. W/R %: the win rate. Net %: the net result in percent, compounded, the same figure as Net P/L in the info box. Net $: the net result in the account currency, worked out as the sum of each trade's result in R multiples (result divided by its stop distance) times the Risk per trade amount in the Position Sizing group, so every trade risks the same amount. Net $ needs a stop loss; with Stop loss mode None it shows n/a. The combined choices show two figures in one cell, in the order of the name: W/R % & Net %, W/R % & Net $ and Net % & Net $. Dim text means fewer closed trades than the Lookback. Green / red cell still means a trade is open.")
symLayoutIn = input.string("1 line", "Combined cell layout", options=["1 line", "2 lines"], group=grpSym, tooltip="How the two figures of a combined choice are laid out. 1 line: each figure in its own cell, side by side, so every timeframe gets two columns and the rows keep their height. 2 lines: each figure in its own cell, stacked, so every symbol gets two rows and the columns stay narrow. The first figure in the name comes first. Used only when Symbols scanner shows is one of the combined choices.")
symWMult = input.float(1.2, "Net cell width multiplier", minval=0.8, maxval=3.0, step=0.1, group=grpSym, tooltip="Width of the Net % and Net $ cells, and of every cell in a combined choice, as a multiple of the win rate cell width for the chosen Symbol scanner size. Lower makes the table narrower. If the numbers wrap or get cut off, raise it. Used only when Symbols scanner shows is not W/R %.")
 
grpDisp = "🎨 Display"
showClosed = input.int(10, "Show closed trades", minval=0, maxval=50, group=grpDisp, 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.")
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.")
lblWrMode = input.string("Off", "Win rate in BUY/SELL labels", options=["Off", "Signal WR", "Direction WR"], group=grpDisp, tooltip="Adds the win rate to the BUY and SELL labels at the moment the signal fires, for example BUY 65% Sig. A tag after the number tells which win rate it is: Sig for Signal WR and Dir for Direction WR. Off: plain BUY and SELL labels. Signal WR: the win rate of the last closed trades (up to the Lookback count), both directions together, including the trade that signal closes. Direction WR: the win rate of the last Lookback closed trades in the same direction as the signal, so a BUY label shows how recent BUY trades did and a SELL label how recent SELL trades did. When fewer closed trades than the Lookback exist, the label shows the win and loss count instead, for example BUY 3W/1L Dir, because a percentage from a few trades is misleading. With no closed trades yet it shows only BUY or SELL. These labels are drawn as label objects that appear when the bar closes, and TradingView keeps the newest 500 labels. Used only when Show BUY/SELL labels is ON. Alerts and the info box are not affected.")
bool showLblWr = lblWrMode != "Off"
buyCol   = input.color(#4CAF50, "Buy color", group=grpDisp, tooltip="Color of the BUY label. A BUY fires when a bullish candle closes above the previous candle's body high and passes the body size filter.")
sellCol  = input.color(#F23645, "Sell color", group=grpDisp, tooltip="Color of the SELL label. A SELL fires when a bearish candle closes below the previous candle's body low and passes the body size filter.")
showEntryMark = input.bool(true, "Show entry marker (dot)", group=grpDisp, tooltip="Draws a small dot at the entry price on the signal candle, which is that candle's close. 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.")
showSlMark = input.bool(true, "Show SL marker (dot)", group=grpDisp, tooltip="Draws a small dot at the stop loss price on the signal candle, where the trade opens. Drawn with the trade lines: it needs Show trade lines and Enable SL/TP ON, and it stays or goes with the lines of closed trades. Needs a stop loss.")
slMarkCol = input.color(#F23645, "SL marker color", group=grpDisp, tooltip="Color of the SL dot. Used only when Show SL marker is ON.")
showTpMark = input.bool(true, "Show TP marker (dot)", group=grpDisp, tooltip="Draws a small dot at the take profit price on the signal candle, where the trade opens. Drawn with the trade lines: it needs Show trade lines and Enable SL/TP ON, and it stays or goes with the lines of closed trades. Needs a take profit (not Opposite signal).")
tpMarkCol = input.color(#4CAF50, "TP marker color", group=grpDisp, tooltip="Color of the TP dot. Used only when Show TP marker is ON.")
markSize = input.string("Large", "SL/TP marker size", options=["Tiny", "Small", "Normal", "Large", "Huge"], group=grpDisp, tooltip="Size of the SL and TP dots. Used only when a 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 (Av 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.")
showAvgLine = input.bool(true, "Show avg time line (vertical)", group=grpDisp, tooltip="Draws a vertical line at the same bar as the avg time marker, from the stop loss to the take profit (the entry price stands in for a missing stop or target). It stays visible even when a solid label background covers the dot. Needs Show trade lines ON and at least one closed trade, like the dot. It belongs to the open trade and is removed when the trade closes.")
avgLineCol = input.color(color.black, "Avg time line color", group=grpDisp, tooltip="Color of the avg time line. Used only when Show avg time line is ON.")
avgLineW = input.int(1, "Avg time line width", minval=1, maxval=4, group=grpDisp, tooltip="Thickness of the avg time line. Used only when Show avg time line is ON.")
avgLineStyleIn = input.string("Dotted", "Avg time line style", options=["Dotted", "Dashed", "Solid"], group=grpDisp, tooltip="Dotted, dashed or solid. Used only when Show avg time line 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)
showLblBg = input.bool(false, "Solid label background", group=grpDisp, tooltip="ON: the Entry, SL and TP labels get a solid background so the trade lines do not run through the text. OFF: transparent labels. Used only when Show trade labels is not Off.")
lblBgCol = input.color(color.new(color.yellow, 30), "Label background color", group=grpDisp, tooltip="Background color of the Entry, SL and TP labels. Used only when Solid label background is ON.")
tradeLblMode = input.string("Current Any", "Show trade labels", options=["All", "Current Any", "Current Open", "Off"], group=grpDisp, tooltip="Controls the Entry, SL and TP price labels attached to the trade lines. All: labels on every trade shown, including the closed trades kept as history. Current Any: labels only on the latest trade, open or closed, until the next signal replaces it. Current Open: labels only while the trade is open, and they disappear when it hits its SL or TP. Off: only the lines (and shading, if enabled) are drawn. Lines, shading and the exit X are not affected. Ignored when Enable SL/TP is OFF.")
tradeLblSide = input.string("Left", "Trade label side", options=["Right", "Left"], group=grpDisp, tooltip="Which side of the entry bar the Entry, SL and TP labels are drawn on. Right: the labels start at the entry bar and run to the right, over the trade. Left (default): the labels end at the entry bar and run to the left, over the candles before the trade. Used only when Show trade labels is not Off.")
bool showTradeLbl = tradeLblMode != "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.")
lblBg    = showLblBg ? lblBgCol : color.new(color.black, 100)
tradeLblStyle = tradeLblSide == "Left" ? label.style_label_right : label.style_label_left   // the label box runs to the left of the point for style_label_right
lineW    = input.int(1, "Line width", minval=1, maxval=4, group=grpDisp)
 
grpAlert = "🔔 Alerts"
useAlertFilter = input.bool(true, "Use alert filter", group=grpAlert, tooltip="ON: only BUY and SELL alerts with a good enough record go out, using the minimum win rate below and a full Lookback of closed trades. OFF: every BUY and SELL alerts right away, with no win rate or trade count requirement, and the minimum below is ignored. TP hit and SL hit alerts are never filtered.")
alertMinWr = input.int(60, "Min win rate for alerts (%)", minval=0, maxval=100, group=grpAlert, tooltip="Only BUY and SELL alerts with a good enough record go out: the Z-Score BUY and SELL alerts, the scanner alerts and the position size alert. A new signal alerts only when the win rate over the last Lookback closed trades, counting the trade the signal itself closes, is at or above this number AND there are at least as many closed trades as the Lookback. For the scanner alerts the win rate is the one shown for that timeframe in the scanner table. Set 0 to alert on every full-sample signal. Used only when Use alert filter is ON. TP hit and SL hit alerts are not filtered. An alert keeps the settings it had when it was created, so create it again after changing this number.")
engAlertTest = input.bool(false, "Test alert (fires on every bar)", group=grpAlert, tooltip="For testing only. ON: sends a test message at every live bar, so you can confirm an alert reaches you. Use the alert named Z-Score Test Alert, or an 'Any alert() function call' alert for the text message. Turn it OFF afterwards. An alert keeps the settings it had when it was created, so create a test alert with this ON and the real alerts with it OFF.")
 
// Kelly inputs sit after every other input so the saved values of the earlier inputs keep their place (they show in the Position Sizing group)
riskMethodIn = input.string("Fixed amount", "Risk method", options=["Fixed amount", "Kelly"], group=grpSize, tooltip="Fixed amount: every trade risks the Risk per trade amount. Kelly: the risk per trade is worked out from the record of the last closed trades with the Kelly Criterion: Kelly fraction = win rate - loss rate / payoff, where the payoff is the average win divided by the average loss (both measured in R, the multiples of the stop distance). The risk is then Account size x Kelly fraction x Kelly multiplier, and never more than the Max risk cap. With Kelly, a trade is sized only when there are enough closed trades and the record shows an edge. Otherwise the size shows n/a. Used only when Show position size is ON.")
acctSize  = input.float(1000.0, "Account size", minval=1.0, step=1000.0, group=grpSize, tooltip="Your account value in the Account currency. Used only when Risk method is Kelly, because the Kelly fraction is a percent of the account.")
kellyMult = input.float(0.25, "Kelly multiplier", minval=0.05, maxval=1.0, step=0.05, group=grpSize, tooltip="The share of the full Kelly fraction that is risked. 1.0 is full Kelly, 0.5 is half Kelly, 0.25 is quarter Kelly. Full Kelly gives large drawdowns and depends heavily on an accurate win rate and payoff, so most traders use a fraction of it. Used only when Risk method is Kelly.")
kellyLb   = input.int(20, "Kelly lookback (closed trades)", minval=10, maxval=500, group=grpSize, tooltip="How many of the most recent closed trades the Kelly fraction is worked out from. This is separate from the Lookback (last N closed trades) input, which drives the win rate shown on the labels, the info box and the alert filter. A longer record gives a steadier Kelly fraction. Used only when Risk method is Kelly.")
kellyMin  = input.int(10, "Min trades for Kelly", minval=5, maxval=500, group=grpSize, tooltip="The least number of closed trades needed before Kelly sizes a trade. Below it the size shows n/a. If the chart has fewer closed trades than this, Kelly never sizes. Used only when Risk method is Kelly.")
kellyCap  = input.float(1.0, "Max risk cap (% of account)", minval=0.1, step=0.1, group=grpSize, tooltip="The most any trade may risk, as a percent of the Account size, however large the Kelly fraction is. Used only when Risk method is Kelly.")
bool kellyOn = riskMethodIn == "Kelly"
 
tpAtr    = tpMode == "ATR target"
tpRisk   = tpMode == "SL multiple"
hasSl    = slMode != "None"
hasTp    = tpMode != "Opposite signal" and not (tpMode == "SL multiple" and slMode == "None")
riskOn   = useRisk and (hasSl or hasTp)
slAtr    = slMode == "ATR"
slWick   = slMode == "Candle wick"
exitOnClose = exitMode == "Close"
 
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
 
avgLineStyle = switch avgLineStyleIn
    "Dashed" => line.style_dashed
    "Solid"  => line.style_solid
    => line.style_dotted
 
avgDotSz = switch avgDotSize
    "Tiny"   => size.tiny
    "Normal" => size.normal
    "Large"  => size.large
    "Huge"   => size.huge
    => size.small
 
dotSz = switch markSize
    "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
 
// ── Open/Close-only logic ─────────────────────────────────
bodyHi  = math.max(open, close)
bodyLo  = math.min(open, close)
body    = math.abs(close - open)
bodyMean = nz(ta.sma(body, zLen)[1])   // the middle of the bell curve of bodies, from the bars before the signal candle
bodySd   = nz(ta.stdev(body, zLen)[1]) // the spread of the bell curve of bodies, from the bars before the signal candle
bodyZ    = bodySd > 0 ? (body - bodyMean) / bodySd : na   // z-score of the signal candle's body
retPct   = (close / close[1] - 1) * 100
retMean  = nz(ta.sma(retPct, zLen)[1])
retSd    = nz(ta.stdev(retPct, zLen)[1])
retZ     = retSd > 0 ? (retPct - retMean) / retSd : na   // z-score of the bar's percent change
pxMean   = nz(ta.sma(close, zLen)[1])
pxSd     = nz(ta.stdev(close, zLen)[1])
pxZ      = pxSd > 0 ? (close - pxMean) / pxSd : na   // z-score of the close against the recent average price
engBull  = zEngIn == "Body" ? (close > open and bodyZ >= zMult) : zEngIn == "Return" ? retZ >= zMult : pxZ >= zMult
engBear  = zEngIn == "Body" ? (close < open and bodyZ >= zMult) : zEngIn == "Return" ? retZ <= -zMult : pxZ <= -zMult
avgVol  = ta.sma(volume, zLen)
volOk   = volMult <= 0 or volume >= avgVol * volMult
atr     = ta.atr(atrLen)
 
// The z-score test of the chosen engine, plus (when on) the OC close rule: a green candle closing above the prior body for a BUY, a red candle closing below it for a SELL
bullBreak = engBull and (not ocRule or (close > open and close > bodyHi[1])) and volOk
bearBreak = engBear and (not ocRule or (close < open and close < bodyLo[1])) and volOk
 
// With Signal Direction on Alternate Signals, signals alternate (no repeated buys or sells); on Any Signal, every qualifying candle 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
// 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
blocked = noOverlap and riskOn and inTrade
bothExits = hasSl and hasTp
buy  = confirmed and bullBreak and not (blocked and (bothExits or dir == 1)) and (not alternate or dir != 1) and sigDirIn != "Sell Only Sig"
sell = confirmed and bearBreak and not (blocked and (bothExits or dir == -1)) and (not alternate or dir != -1) and sigDirIn != "Buy Only Sig"
 
// ── Position sizing ───────────────────────────────────────
// The stop distance is in the symbol's quote currency, so it is converted to the account currency (1.0 when they match or sizing is off)
float fxRate = useSize and syminfo.currency != acctCcy ? request.currency_rate(syminfo.currency, acctCcy, true) : 1.0
 
// R multiple of each closed trade (result divided by the stop distance, both in percent of entry), for the Kelly Criterion
var array<float> kR = array.new_float(0)
 
// Kelly Criterion over the last Kelly lookback closed trades: [trades, win rate, payoff (avg win R / avg loss R), Kelly fraction]
f_kelly() =>
    int n = 0
    int w = 0
    int l = 0
    float ws = 0.0
    float ls = 0.0
    if array.size(kR) > 0
        for i = 0 to array.size(kR) - 1
            float r = array.get(kR, i)
            if not na(r)
                n += 1
                if r > 0
                    w += 1
                    ws += r
                else if r < 0
                    l += 1
                    ls += -r
    float wr = n > 0 ? w / n : na
    float b = w > 0 and l > 0 ? (ws / w) / (ls / l) : na
    float fs = na(wr) ? na : (w == 0 and l > 0) ? -1.0 : na(b) ? na : wr - (1.0 - wr) / b
    [n, wr, b, fs]
 
// Risk per trade in the account currency: the fixed amount, or the Kelly amount (na while there are too few trades or no edge)
f_riskNow() =>
    float res = riskAmt
    if kellyOn
        [kN, kWr, kB, kF] = f_kelly()
        res := kN >= kellyMin and not na(kF) and kF > 0 ? acctSize * math.min(kF * kellyMult, kellyCap / 100.0) : na
    res
 
// Units that risk the chosen amount at the stop: risk amount / (stop distance x conversion). Rounded down: 4 decimals for crypto, whole units otherwise. Futures are not supported
f_units(float dist) =>
    float rk = f_riskNow()
    float raw = useSize and syminfo.type != "futures" and dist > 0 and fxRate > 0 and not na(rk) ? rk / (dist * fxRate) : na
    syminfo.type == "crypto" ? math.floor(raw * 10000.0) / 10000.0 : math.floor(raw)
 
// Size as text: forex in units and standard lots, crypto with decimals, stocks and funds in shares
f_sizeTxt(float u) =>
    na(u) ? "n/a" : syminfo.type == "forex" ? str.tostring(u, "0") + " u (" + str.tostring(u / 100000.0, "0.00") + " lot)" : syminfo.type == "crypto" ? str.tostring(u, "0.0000") : (syminfo.type == "stock" or syminfo.type == "fund" or syminfo.type == "dr") ? str.tostring(u, "0") + " sh" : str.tostring(u, "0") + " u"
 
// ── Trade state ───────────────────────────────────────────
var float entryPx = na
var float entryRiskPct = na   // stop distance of the open trade in percent of entry, for R multiples
var float posUnits = na      // size of the open trade
var float posRiskCash = na   // account-currency loss if the stop is hit
var float posCost = na       // account-currency value of the position at entry (cost basis, or notional for forex)
var float posRewCash = na    // account-currency gain if the target is hit
var float slPx = na
var float tpPx = na
var array<float> pnls = array.new_float(0)
var array<float> pnlsB = array.new_float(0)   // closed BUY trades, for Direction WR
var array<float> pnlsS = array.new_float(0)   // closed SELL trades, for Direction WR
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 (calendar time)
var array<float> gapsM = array.new_float(0)   // the same gaps in market time (bars x chart timeframe)
var int lastSigTime = na
var int lastSigBar = 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 (calendar time)
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 int closedEntryTime = na   // entry time of the most recent closed trade, for Time from Sig
var int closedEntryBar = na   // entry bar of the most recent closed trade, for Time from Sig
var float slAtrX = na   // latest stop distance in ATR units (shown for the candle 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
var line avgLn = na   // vertical line at the avg time bar, open trade only
var label slDot = na   // SL dot, drawn with the trade lines
var label tpDot = na   // TP dot, drawn with the trade lines
var box slBox = na
var box tpBox = na
 
type TradeViz
    line entryLn
    line slLn
    line tpLn
    label entryLbl
    label slLbl
    label tpLbl
    label xLbl
    label avgLbl
    label slDot
    label tpDot
    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)
    label.delete(v.avgLbl)
    label.delete(v.slDot)
    label.delete(v.tpDot)
    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, label aLb, label sDt, label tDt, 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(aLb) 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, aLb, sDt, tDt, sBx, tBx))
        while array.size(closedViz) > showClosed
            deleteViz(array.shift(closedViz))
 
recordTrade(float pnl, int reason) =>
    array.push(kR, na(entryRiskPct) or entryRiskPct <= 0 ? na : pnl / entryRiskPct)
    while array.size(kR) > kellyLb
        array.shift(kR)
    array.push(pnls, pnl)
    array<float> pnlsDir = dir == 1 ? pnlsB : pnlsS   // dir is still the direction of the trade being closed
    array.push(pnlsDir, pnl)
    while array.size(pnlsDir) > lookback
        array.shift(pnlsDir)
    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)
    line.delete(avgLn)
    label.delete(slDot)
    label.delete(tpDot)
    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)
        closedEntryTime := entryTime
        closedEntryBar := entryBar
        inTrade := false
        // The avg time dot only belongs to an open trade
        label.delete(avgLbl)
        avgLbl := na
        line.delete(avgLn)
        avgLn := na
        if tradeLblMode == "Current Open"
            label.delete(entryLbl)
            label.delete(slLbl)
            label.delete(tpLbl)
            entryLbl := na
            slLbl := na
            tpLbl := na
        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, avgLbl, slDot, tpDot, slBox, tpBox, bar_index)
                entryLn := na
                slLn := na
                tpLn := na
                entryLbl := na
                slLbl := na
                tpLbl := na
                xLbl := na
                avgLbl := na
                slDot := na
                tpDot := na
                slBox := na
                tpBox := na
        else
            clearLines()
 
// ── 2) New signal: close open trade (reversal) and open the opposite one ──
string sigWrTxt = ""   // the win rate text for this bar's BUY / SELL label
if buy or sell
    if not na(lastSigTime)
        array.push(gaps, 1.0 * (time - lastSigTime))
        array.push(gapsM, 1.0 * (bar_index - lastSigBar) * timeframe.in_seconds() * 1000)
        while array.size(gaps) > lookback
            array.shift(gaps)
        while array.size(gapsM) > lookback
            array.shift(gapsM)
    lastSigTime := time
    lastSigBar := bar_index
    if inTrade
        float revPnl = dir == 1 ? (close - entryPx) / entryPx * 100 : (entryPx - close) / entryPx * 100
        recordTrade(revPnl, 0)
        closedEntryTime := entryTime
        closedEntryBar := entryBar
        label.delete(avgLbl)
        avgLbl := na
        line.delete(avgLn)
        avgLn := na
        if showClosed > 0
            archiveTrade(entryLn, slLn, tpLn, entryLbl, slLbl, tpLbl, xLbl, avgLbl, slDot, tpDot, slBox, tpBox, bar_index)
            entryLn := na
            slLn := na
            tpLn := na
            entryLbl := na
            slLbl := na
            tpLbl := na
            xLbl := na
            avgLbl := na
            slDot := na
            tpDot := na
            slBox := na
            tpBox := na
    // Current Any / Current Open: the trades kept as history lose their labels when the next signal arrives
    if tradeLblMode == "Current Any" or tradeLblMode == "Current Open"
        for v in closedViz
            label.delete(v.entryLbl)
            label.delete(v.slLbl)
            label.delete(v.tpLbl)
            v.entryLbl := na
            v.slLbl := na
            v.tpLbl := na
    clearLines()
    // Win rate at the moment of entry: the closed trades so far (up to the Lookback), including the one this signal just closed. A thin sample shows the win / loss count
    array<float> wrArr = lblWrMode == "Direction WR" ? (buy ? pnlsB : pnlsS) : pnls
    int wrN = array.size(wrArr)
    int wrW = 0
    int wrL = 0
    if wrN > 0
        for i = 0 to wrN - 1
            float wp = array.get(wrArr, i)
            if wp > 0
                wrW += 1
            else if wp < 0
                wrL += 1
    string wrTag = lblWrMode == "Direction WR" ? " Dir" : " Sig"   // tells which win rate the label shows
    sigWrTxt := wrN == 0 ? "" : (wrN < lookback ? str.tostring(wrW) + "W/" + str.tostring(wrL) + "L" : str.tostring(wrW / wrN * 100, "0") + "%") + wrTag
    dir := buy ? 1 : -1
    entryPx := close
    inTrade := true
    entryTime := time
    entryBar := bar_index
    float bufD = na(atr) ? 0.0 : slBuf * atr
    slPx := not hasSl ? na : slAtr ? (dir == 1 ? close - atr * slMult : close + atr * slMult) : slWick ? (dir == 1 ? low - bufD : high + bufD) : (dir == 1 ? open - bufD : open + bufD)
    float riskDist = math.abs(close - slPx)
    slAtrX := hasSl and not slAtr and atr > 0 ? riskDist / atr : na
    float tpDist = tpAtr ? atr * tpMult : riskDist * tpRMult
    tpPx := not hasTp ? na : dir == 1 ? close + tpDist : close - tpDist
    entryRiskPct := hasSl and close > 0 ? riskDist / close * 100 : na
    posUnits := f_units(riskDist)
    posRiskCash := na(posUnits) ? na : posUnits * riskDist * fxRate
    posCost := na(posUnits) ? na : posUnits * close * fxRate
    posRewCash := na(posUnits) or not hasTp ? na : posUnits * tpDist * fxRate
    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 showSlMark and hasSl
                slDot := label.new(bar_index, slPx, "●", xloc=xloc.bar_index, style=label.style_label_center, color=color.new(color.black, 100), textcolor=slMarkCol, size=dotSz)
            if showTpMark and hasTp
                tpDot := label.new(bar_index, tpPx, "●", xloc=xloc.bar_index, style=label.style_label_center, color=color.new(color.black, 100), textcolor=tpMarkCol, size=dotSz)
        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 showAvgLine and showTradeLines and array.size(dursM) > 0
            int avgBarsL = math.min(499, math.max(1, math.round(array.avg(dursM) / (timeframe.in_seconds() * 1000.0))))
            float avgLnA = hasSl ? slPx : entryPx
            float avgLnB = hasTp ? tpPx : entryPx
            if not hasSl and not hasTp
                avgLnA := entryPx - (na(atr) ? 0.0 : atr)
                avgLnB := entryPx + (na(atr) ? 0.0 : atr)
            avgLn := line.new(bar_index + avgBarsL, avgLnA, bar_index + avgBarsL, avgLnB, xloc=xloc.bar_index, color=avgLineCol, width=avgLineW, style=avgLineStyle)
        if showTradeLbl
            entryLbl := label.new(bar_index, entryPx, "Entry " + str.tostring(entryPx, format.mintick) + (useSize ? " | " + f_sizeTxt(posUnits) + (na(posCost) ? "" : " | " + str.tostring(posCost, "0") + " " + acctCcy) : ""), style=tradeLblStyle, color=lblBg, textcolor=entryCol, size=size.small)
            if hasSl
                slLbl := label.new(bar_index, slPx,    "SL " + str.tostring(slPx, format.mintick) + (useSize and not na(posRiskCash) ? " | -" + str.tostring(posRiskCash, "0.00") + " " + acctCcy : ""),       style=tradeLblStyle, color=lblBg, textcolor=slCol,    size=size.small)
            if hasTp
                tpLbl := label.new(bar_index, tpPx, "TP " + str.tostring(tpPx, format.mintick) + (useSize and not na(posRewCash) ? " | +" + str.tostring(posRewCash, "0.00") + " " + acctCcy : ""), style=tradeLblStyle, color=lblBg, 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)
 
// Alert win rate filter: the closed trades so far (up to the Lookback), including the one this signal just closed
bool alWrOk = false
if buy or sell
    int alN = array.size(pnls)
    int alW = 0
    if alN > 0
        for i = 0 to alN - 1
            if array.get(pnls, i) > 0
                alW += 1
    alWrOk := not useAlertFilter or (alN >= lookback and alN > 0 and math.round(alW / alN * 100) >= alertMinWr)
 
// ── Plots ─────────────────────────────────────────────────
plotshape(showEntryMark and (buy or sell) ? entryPx : na, "Entry marker", shape.circle, location.absolute, entryMarkCol, size=size.tiny)
// With Show win rate in BUY/SELL labels ON, the labels are drawn as label objects so the text can carry the win rate. They are created on closed bars only, so a live signal never leaves a stray label
float lblGapWr = na(atr) ? 0.0 : atr * 0.25
lblSzWr = switch lblSize
    "Tiny"   => size.tiny
    "Normal" => size.normal
    "Large"  => size.large
    "Huge"   => size.huge
    => size.small
if showLabels and showLblWr and barstate.isconfirmed and (buy or sell)
    label.new(bar_index, buy ? low - lblGapWr : high + lblGapWr, (buy ? "BUY" : "SELL") + (sigWrTxt == "" ? "" : " " + sigWrTxt), xloc=xloc.bar_index, style=buy ? label.style_label_up : label.style_label_down, color=buy ? buyCol : sellCol, textcolor=color.white, size=lblSzWr)
plotshape(showLabels and not showLblWr and lblSize == "Tiny" and buy,  "Buy (Tiny)",  shape.labelup,   location.belowbar, buyCol,  text="BUY",  textcolor=color.white, size=size.tiny)
plotshape(showLabels and not showLblWr and lblSize == "Tiny" and sell, "Sell (Tiny)", shape.labeldown, location.abovebar, sellCol, text="SELL", textcolor=color.white, size=size.tiny)
plotshape(showLabels and not showLblWr and lblSize == "Small" and buy,  "Buy (Small)",  shape.labelup,   location.belowbar, buyCol,  text="BUY",  textcolor=color.white, size=size.small)
plotshape(showLabels and not showLblWr and lblSize == "Small" and sell, "Sell (Small)", shape.labeldown, location.abovebar, sellCol, text="SELL", textcolor=color.white, size=size.small)
plotshape(showLabels and not showLblWr and lblSize == "Normal" and buy,  "Buy (Normal)",  shape.labelup,   location.belowbar, buyCol,  text="BUY",  textcolor=color.white, size=size.normal)
plotshape(showLabels and not showLblWr and lblSize == "Normal" and sell, "Sell (Normal)", shape.labeldown, location.abovebar, sellCol, text="SELL", textcolor=color.white, size=size.normal)
plotshape(showLabels and not showLblWr and lblSize == "Large" and buy,  "Buy (Large)",  shape.labelup,   location.belowbar, buyCol,  text="BUY",  textcolor=color.white, size=size.large)
plotshape(showLabels and not showLblWr and lblSize == "Large" and sell, "Sell (Large)", shape.labeldown, location.abovebar, sellCol, text="SELL", textcolor=color.white, size=size.large)
plotshape(showLabels and not showLblWr and lblSize == "Huge" and buy,  "Buy (Huge)",  shape.labelup,   location.belowbar, buyCol,  text="BUY",  textcolor=color.white, size=size.huge)
plotshape(showLabels and not showLblWr 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"
 
var table infoBox = not showTable ? na : table.new(tPos, 2, useSize and showSizeBox ? (kellyOn ? 32 : 29) : 24, 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, 12, 1, 12)
    if useSize and showSizeBox
        table.merge_cells(infoBox, 0, 24, 1, 24)
 
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
 
    table.cell(infoBox, 0, 0, "Z-SCORE BUY/SELL SIGNALS", text_color=color.white, bgcolor=color.new(#3B5B92, 0), text_halign=text.align_center, text_size=tSize)
 
    table.cell(infoBox, 0, 1, "Chart Type", text_color=color.white, text_halign=text.align_left, text_size=tSize)
    table.cell(infoBox, 1, 1, chartType, text_color=chart.is_standard ? color.white : color.new(#F23645, 0), text_halign=text.align_right, text_size=tSize)
 
    table.cell(infoBox, 0, 2, "Timeframe / Session", text_color=color.white, text_halign=text.align_left, text_size=tSize)
    table.cell(infoBox, 1, 2, tfTxt + " / " + sessTxt, text_color=color.white, text_halign=text.align_right, text_size=tSize)
 
    table.cell(infoBox, 0, 3, "Non-Repaint", text_color=color.white, text_halign=text.align_left, text_size=tSize)
    table.cell(infoBox, 1, 3, nrMode, text_color=nrMode == "Entries + Exits" ? color.new(#4CAF50, 0) : nrMode == "Entries Only" ? color.orange : color.new(#F23645, 0), text_halign=text.align_right, text_size=tSize)
 
    table.cell(infoBox, 0, 7, "Signal Direction", text_color=color.white, text_halign=text.align_left, text_size=tSize)
    table.cell(infoBox, 1, 7, sigDirIn == "Alternate Signals" ? "Alternate" : sigDirIn == "Any Signal" ? "Any" : sigDirIn == "Buy Only Sig" ? "Buy only" : "Sell only", text_color=sigDirIn == "Any Signal" ? color.new(#F23645, 0) : color.new(#4CAF50, 0), text_halign=text.align_right, text_size=tSize)
 
    table.cell(infoBox, 0, 4, "Z-Score Engine / Length", text_color=color.white, text_halign=text.align_left, text_size=tSize)
    table.cell(infoBox, 1, 4, zEngIn + " / " + str.tostring(zLen), text_color=color.white, text_halign=text.align_right, text_size=tSize)
 
    table.cell(infoBox, 0, 5, "Min Z-Score", text_color=color.white, text_halign=text.align_left, text_size=tSize)
    table.cell(infoBox, 1, 5, str.tostring(zMult, "0.0") + " σ", text_color=color.white, text_halign=text.align_right, text_size=tSize)
 
    table.cell(infoBox, 0, 6, "Min Volume", text_color=color.white, text_halign=text.align_left, text_size=tSize)
    table.cell(infoBox, 1, 6, volMult > 0 ? str.tostring(volMult, "0.0") + "x" : "OFF", text_color=volMult > 0 ? color.white : color.new(#F23645, 0), text_halign=text.align_right, text_size=tSize)
 
    table.cell(infoBox, 0, 8, "Ignore Signals in Trade", text_color=color.white, text_halign=text.align_left, text_size=tSize)
    table.cell(infoBox, 1, 8, noOverlap ? "ON" : "OFF", text_color=noOverlap ? color.new(#4CAF50, 0) : color.new(#F23645, 0), text_halign=text.align_right, text_size=tSize)
 
    table.cell(infoBox, 0, 9, "Exit Trigger", text_color=color.white, text_halign=text.align_left, text_size=tSize)
    table.cell(infoBox, 1, 9, riskOn ? exitMode : "-", text_color=color.white, text_halign=text.align_right, text_size=tSize)
 
    string slAtrTxt = na(slAtrX) ? "n/a" : str.tostring(slAtrX, "0.0") + "x ATR"
    string slTxt = slAtr ? str.tostring(slMult, "0.0") + "x ATR" : slWick ? "CW: " + slAtrTxt : hasSl ? "CB: " + slAtrTxt : "None"
    string tpTxt = tpAtr ? str.tostring(tpMult, "0.0") + "x ATR" : tpRisk and hasSl ? str.tostring(tpRMult, "0.0") + "x SL" : "Opp. Signal"
    table.cell(infoBox, 0, 10, "Stop Loss", text_color=color.white, text_halign=text.align_left, text_size=tSize)
    table.cell(infoBox, 1, 10, useRisk ? slTxt : "OFF", text_color=useRisk ? color.white : color.new(#F23645, 0), text_halign=text.align_right, text_size=tSize)
 
    table.cell(infoBox, 0, 11, "Take Profit", text_color=color.white, text_halign=text.align_left, text_size=tSize)
    table.cell(infoBox, 1, 11, useRisk ? tpTxt : "OFF", text_color=useRisk ? color.white : color.new(#F23645, 0), text_halign=text.align_right, text_size=tSize)
 
    table.cell(infoBox, 0, 12, "LOOKBACK P/L", text_color=color.white, bgcolor=color.new(#3B5B92, 0), text_halign=text.align_center, text_size=tSize)
 
    table.cell(infoBox, 0, 13, "Trades Counted", text_color=color.white, text_halign=text.align_left, text_size=tSize)
    table.cell(infoBox, 1, 13, str.tostring(n) + " / " + str.tostring(lookback), text_color=color.white, text_halign=text.align_right, text_size=tSize)
 
    table.cell(infoBox, 0, 14, "Exits TP / SL / Signal", text_color=color.white, text_halign=text.align_left, text_size=tSize)
    table.cell(infoBox, 1, 14, (useRisk and hasTp ? str.tostring(tpCnt) : "-") + " / " + (useRisk and hasSl ? str.tostring(slCnt) : "-") + " / " + str.tostring(revCnt), text_color=color.white, text_halign=text.align_right, text_size=tSize)
 
    table.cell(infoBox, 0, 15, "Net P/L", text_color=color.white, text_halign=text.align_left, text_size=tSize)
    table.cell(infoBox, 1, 15, fmt(netPnl), text_color=posCol(netPnl), text_halign=text.align_right, text_size=tSize)
 
    table.cell(infoBox, 0, 16, "Win Rate", text_color=color.white, text_halign=text.align_left, text_size=tSize)
    table.cell(infoBox, 1, 16, na(winRate) ? "n/a" : str.tostring(winRate, "0") + "% (" + str.tostring(winCnt) + "W/" + str.tostring(lossCnt) + "L)", text_color=color.white, text_halign=text.align_right, text_size=tSize)
 
    table.cell(infoBox, 0, 17, "Avg Win / Loss", text_color=color.white, text_halign=text.align_left, text_size=tSize)
    table.cell(infoBox, 1, 17, fmt(avgWin) + " / " + fmt(avgLoss), text_color=color.white, text_halign=text.align_right, text_size=tSize)
 
    table.cell(infoBox, 0, 18, "Max Drawdown", text_color=color.white, text_halign=text.align_left, text_size=tSize)
    table.cell(infoBox, 1, 18, n > 0 ? fmt(maxDD) : "n/a", text_color=maxDD < 0 ? color.new(#F23645, 0) : color.white, text_halign=text.align_right, text_size=tSize)
 
    table.cell(infoBox, 0, 19, "Open Trade P/L", text_color=color.white, text_halign=text.align_left, text_size=tSize)
    table.cell(infoBox, 1, 19, fmt(openPnl), text_color=posCol(openPnl), text_halign=text.align_right, text_size=tSize)
 
    // 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
    // Time from Sig ignores the open trade: it runs from the entry of the most recent closed trade to the current bar
    float sinceMs = na(closedEntryTime) ? na : 1.0 * (time - closedEntryTime)
    float sinceMsM = na(closedEntryBar) ? na : 1.0 * (bar_index - closedEntryBar) * timeframe.in_seconds() * 1000
    table.cell(infoBox, 0, 20, "Time in Sig (cal/mkt)", text_color=color.white, text_halign=text.align_left, text_size=tSize)
    table.cell(infoBox, 1, 20, fmtDual(inMs, inMsM), text_color=color.white, text_halign=text.align_right, text_size=tSize)
 
    table.cell(infoBox, 0, 21, "Av Time/Sig (cal/mkt)", text_color=color.white, text_halign=text.align_left, text_size=tSize)
    table.cell(infoBox, 1, 21, fmtDual(avgDurMs, avgDurMsM), text_color=color.white, text_halign=text.align_right, text_size=tSize)
 
    table.cell(infoBox, 0, 22, "Time from Sig (cal/mkt)", text_color=color.white, text_halign=text.align_left, text_size=tSize)
    table.cell(infoBox, 1, 22, fmtDual(sinceMs, sinceMsM), text_color=color.white, text_halign=text.align_right, text_size=tSize)
 
    table.cell(infoBox, 0, 23, "Av Time btw Sig (cal/mkt)", text_color=color.white, text_halign=text.align_left, text_size=tSize)
    table.cell(infoBox, 1, 23, fmtDual(avgMs, avgMsM), text_color=color.white, text_halign=text.align_right, text_size=tSize)
 
    if useSize and showSizeBox
        string szRisk = inTrade and not na(posRiskCash) ? "-" + str.tostring(posRiskCash, "0.00") : "-"
        string szRew = inTrade and not na(posRewCash) ? "+" + str.tostring(posRewCash, "0.00") : "-"
        table.cell(infoBox, 0, 24, "POSITION SIZE", text_color=color.white, bgcolor=color.new(#3B5B92, 0), text_halign=text.align_center, text_size=tSize)
 
        float riskShown = f_riskNow()
        table.cell(infoBox, 0, 25, "Risk per trade", text_color=color.white, text_halign=text.align_left, text_size=tSize)
        table.cell(infoBox, 1, 25, na(riskShown) ? "n/a" : str.tostring(riskShown, "0.00") + " " + acctCcy, text_color=na(riskShown) ? color.orange : color.white, text_halign=text.align_right, text_size=tSize)
 
        int ko = 0
        if kellyOn
            ko := 3
            [kN, kWr, kB, kF] = f_kelly()
            float kUsed = na(kF) or kF <= 0 ? na : math.min(kF * kellyMult, kellyCap / 100.0)
            string kStat = kN < kellyMin ? "Need " + str.tostring(kellyMin) + " trades" : na(kF) ? "-" : kF <= 0 ? "No edge" : str.tostring(kF * 100, "0.0") + "% / " + str.tostring(kUsed * 100, "0.0") + "%" + (kF * kellyMult > kellyCap / 100.0 ? " (cap)" : "")
            table.cell(infoBox, 0, 26, "Risk Method", text_color=color.white, text_halign=text.align_left, text_size=tSize)
            table.cell(infoBox, 1, 26, "Kelly " + str.tostring(kellyMult, "0.00") + "x", text_color=color.white, text_halign=text.align_right, text_size=tSize)
            table.cell(infoBox, 0, 27, "Kelly Full / Used", text_color=color.white, text_halign=text.align_left, text_size=tSize)
            table.cell(infoBox, 1, 27, kStat, text_color=kN < kellyMin or na(kF) or kF <= 0 ? color.orange : color.white, text_halign=text.align_right, text_size=tSize)
            table.cell(infoBox, 0, 28, "Kelly Trades / WR / Payoff", text_color=color.white, text_halign=text.align_left, text_size=tSize)
            table.cell(infoBox, 1, 28, str.tostring(kN) + " / " + (na(kWr) ? "-" : str.tostring(kWr * 100, "0") + "%") + " / " + (na(kB) ? "-" : str.tostring(kB, "0.00")), text_color=color.white, text_halign=text.align_right, text_size=tSize)
 
        table.cell(infoBox, 0, 26 + ko, "Size (open trade)", text_color=color.white, text_halign=text.align_left, text_size=tSize)
        table.cell(infoBox, 1, 26 + ko, inTrade ? f_sizeTxt(posUnits) : "-", text_color=color.white, text_halign=text.align_right, text_size=tSize)
 
        table.cell(infoBox, 0, 27 + ko, "Risk / Reward (" + acctCcy + ")", text_color=color.white, text_halign=text.align_left, text_size=tSize)
        table.cell(infoBox, 1, 27 + ko, szRisk + " / " + szRew, text_color=color.white, text_halign=text.align_right, text_size=tSize)
 
        table.cell(infoBox, 0, 28 + ko, (syminfo.type == "forex" ? "Notional (" : "Cost (") + acctCcy + ")", text_color=color.white, text_halign=text.align_left, text_size=tSize)
        table.cell(infoBox, 1, 28 + ko, inTrade and not na(posCost) ? str.tostring(posCost, "0.00") : "-", text_color=color.white, text_halign=text.align_right, text_size=tSize)
 
 
// ── Multi-timeframe scanner ───────────────────────────────
// Scans the chart's symbol on the timeframes in the Scanner group, using the same Z-Score signal and trade rules as 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 bd   = math.abs(close - open)
    float avgB = nz(ta.sma(bd, zLen)[1])
    float sdB = nz(ta.stdev(bd, zLen)[1])
    float zB = sdB > 0 ? (bd - avgB) / sdB : na
    float rP = (close / close[1] - 1) * 100
    float rM = nz(ta.sma(rP, zLen)[1])
    float rS = nz(ta.stdev(rP, zLen)[1])
    float zR = rS > 0 ? (rP - rM) / rS : na
    float pM = nz(ta.sma(close, zLen)[1])
    float pS = nz(ta.stdev(close, zLen)[1])
    float zP = pS > 0 ? (close - pM) / pS : na
    float avgV = ta.sma(volume, zLen)
    bool vOk   = volMult <= 0 or volume >= avgV * volMult
    float a    = ta.atr(atrLen)
    float prevHi = math.max(open[1], close[1])
    float prevLo = math.min(open[1], close[1])
    bool eB = zEngIn == "Body" ? (close > open and zB >= zMult) : zEngIn == "Return" ? zR >= zMult : zP >= zMult
    bool eS = zEngIn == "Body" ? (close < open and zB >= zMult) : zEngIn == "Return" ? zR <= -zMult : zP <= -zMult
    bool bull = eB and (not ocRule or (close > open and close > prevHi)) and vOk
    bool bear = eS and (not ocRule or (close < open and close < prevLo)) and vOk
 
    var int d = 0
    var bool inT = false
    var float ePx = na
    var float sPx = na
    var float tPx = 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 array<float> sRs = array.new_float(0)   // the same closed trades as R multiples (result / stop distance), for Net $
    var float eRisk = na   // stop distance of the open trade in percent of the entry
    var float netV = na
    var float netRV = na   // sum of the R multiples of the last Lookback trades
    var int winV = 0
    var int lossV = 0
    var int nV = 0
    var float avgPV = na
    var float ddV = na
 
    // Signals use the trade state from the previous bar, exactly as the main logic does
    bool blk = noOverlap and riskOn and inT
    bool buyS  = bull and not (blk and (bothExits or d == 1))  and (not alternate or d != 1) and sigDirIn != "Sell Only Sig"
    bool sellS = bear and not (blk and (bothExits or d == -1)) and (not alternate or d != -1) and sigDirIn != "Buy Only Sig"
 
    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
            array.push(sPnls, lastPnl)
            array.push(sRs, na(eRisk) or eRisk == 0 ? na : lastPnl / eRisk)
            rec := true
 
    // New signal: close an open trade (reversal) and open the new one
    if buyS or sellS
        if inT
            lastPnl := d == 1 ? (close - ePx) / ePx * 100 : (ePx - close) / ePx * 100
            lastRes := 0
            array.push(sPnls, lastPnl)
            array.push(sRs, na(eRisk) or eRisk == 0 ? na : lastPnl / eRisk)
            rec := true
        d := buyS ? 1 : -1
        ePx := close
        inT := true
        if not na(sigT)
            array.push(sGaps, time - sigT)
            while array.size(sGaps) > lookback
                array.shift(sGaps)
            avgG := array.avg(sGaps)
        sigT := time
        float bufD = na(a) ? 0.0 : slBuf * a
        sPx := not hasSl ? na : slAtr ? (d == 1 ? close - a * slMult : close + a * slMult) : slWick ? (d == 1 ? low - bufD : high + bufD) : (d == 1 ? open - bufD : open + bufD)
        float riskD = math.abs(close - sPx)
        eRisk := hasSl ? riskD / close * 100 : na
        float tpD = tpAtr ? a * tpMult : riskD * tpRMult
        tPx := not hasTp ? na : d == 1 ? close + tpD : close - 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)
            array.shift(sRs)
        float eqv = 1.0
        float sumP = 0.0
        float sumR = 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
            sumR += nz(array.get(sRs, k))
            if p > 0
                w += 1
            else if p < 0
                l += 1
        ddV := dd2
        netV := (eqv - 1) * 100
        netRV := hasSl ? sumR : na
        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], netRV[1]]
 
// The symbol scanner only needs the direction, the trade status (1 = open), the win and trade counts and the close, so each request returns just those five values
f_scanSym() =>
    [yD, yS, yEn, ySl, yTp, yNw, yPx, yAv, yNet, yWin, yLoss, yN, yAvP, yOp, ySig, yDD, yNetR] = f_scan()
    [yD, yS, yWin, yN, yPx, yNet, yNetR]
 
// 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, rNetR] = 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)
            int cntA = nz(rN)
            bool passA = not useAlertFilter or (cntA >= lookback and cntA > 0 and math.round(nz(rWin) / cntA * 100) >= alertMinWr)
            if barstate.isrealtime and passA
                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("Z-Score 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, 2, 12) : scDetail == "Low" ? array.from(0, 2, 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 = "Z-SCORE SCANNER - " + zEngIn + " " + str.tostring(zMult, "0.0") + "σ (" + 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
        color bg = 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 ? (cnt < lookback ? str.tostring(wn) + "W/" + str.tostring(ls) + "L" : 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)
 
// ── Symbol scanner ────────────────────────────────────────
// One row per symbol, one column per timeframe, each cell the Z-Score win rate over the Lookback trades. Every symbol and timeframe pair
// is one data request with its own trade history, using the same Z-Score rules as the main logic and the scanner above.
f_parseSyms(string raw, string ex) =>
    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 != ""
            string u = str.upper(t)
            array.push(out, ex != "" and not str.contains(u, ":") ? ex + ":" + u : u)
    out
 
var array<string> symArr = f_parseSyms(symListIn, str.upper(str.trim(symExIn)))
int symUsed = (useSize and syminfo.currency != acctCcy ? 1 : 0) + (showScan ? nTf : 0)
int symAvail = math.max(0, symReqLimit - symUsed)
int nSymTf = math.min(nTf, math.max(1, symAvail))
int symWant = math.min(symMax, array.size(symArr))
int nSym = nSymTf > 0 ? math.min(symWant, math.floor(symAvail / nSymTf)) : 0
 
var array<int>   syDir = array.new_int(64, 0)
var array<int>   sySt  = array.new_int(64, 0)
var array<int>   syWin = array.new_int(64, 0)
var array<int>   syN   = array.new_int(64, 0)
var array<float> syPx  = array.new_float(64, na)
var array<float> syNet = array.new_float(64, na)   // net percent of the last Lookback trades
var array<float> syNetR = array.new_float(64, na)   // sum of the R multiples of the last Lookback trades
 
// Requests only run while the symbol scanner is shown
// A Pine loop counts downward when its end is below its start, so "for si = 0 to nSym - 1" would still run with nSym = 0 and read an empty array. The loops are skipped instead
if showSym and nSym > 0
    for si = 0 to nSym - 1
        string symTk = array.get(symArr, si)
        string symReqTk = chart.is_heikinashi ? ticker.heikinashi(symTk) : symTk
        for ti = 0 to nSymTf - 1
            [qD, qSt, qWin, qN, qPx, qNet, qNetR] = request.security(symReqTk, array.get(scTfs, ti), f_scanSym(), ignore_invalid_symbol = true)
            int qx = si * nSymTf + ti
            array.set(syDir, qx, nz(qD))
            array.set(sySt, qx, nz(qSt))
            array.set(syWin, qx, nz(qWin))
            array.set(syN, qx, nz(qN))
            array.set(syPx, qx, qPx)
            array.set(syNet, qx, qNet)
            array.set(syNetR, qx, qNetR)
 
symPos = switch symPosIn
    "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
 
symSize = switch symSizeIn
    "Tiny"   => size.tiny
    "Normal" => size.normal
    "Large"  => size.large
    "Huge"   => size.huge
    => size.small
 
// Every timeframe column gets the same width (percent of the pane width), scaled with the text size
float symColW0 = switch symSizeIn
    "Tiny"   => 3.5
    "Normal" => 5.5
    "Large"  => 7.0
    "Huge"   => 9.0
    => 4.5
// Net figures are wider than a win rate, so their columns are wider
bool symCombo = str.contains(symMetricIn, "&")
bool symSide = symCombo and symLayoutIn == "1 line"    // each figure in its own cell, side by side
bool symStack = symCombo and symLayoutIn == "2 lines"  // each figure in its own cell, stacked in two rows per symbol
int symPerTf = symSide ? 2 : 1       // columns per timeframe
int symRowsPer = symStack ? 2 : 1    // rows per symbol
// The figure in the first and the second cell: 0 win rate, 1 net percent, 2 net money
int symMetA = str.startswith(symMetricIn, "W/R") ? 0 : str.startswith(symMetricIn, "Net %") ? 1 : 2
int symMetB = symMetricIn == "W/R % & Net %" ? 1 : 2
// In a combined choice every cell gets the wider net width, so all the cells match
float symWA = symMetA == 0 and not symCombo ? symColW0 : symColW0 * symWMult
float symWB = symColW0 * symWMult
float symColW = symStack ? math.max(symWA, symWB) : symWA
 
var table symTbl = na
 
if showSym and barstate.islast
    table.delete(symTbl)
    int symCols = 1 + nSymTf * symPerTf
    // When the request limit cuts symbols or timeframes, an extra row under the title says why (the header and data rows move down one)
    bool symCut = symWant > 0 and (nSym < symWant or nSymTf < nTf)
    int wr = symCut ? 1 : 0
    symTbl := table.new(symPos, symCols, nSym * symRowsPer + 2 + wr, 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(symTbl, 0, 0, symCols - 1, 0)
    string symNote = symWant == 0 ? " - add symbols in the settings" : ""
    string symEx = str.upper(str.trim(symExIn))
    // With few timeframe columns the table is narrow, so the title breaks into two clean lines instead of wrapping in the middle of a phrase
    string symMetLbl = str.replace_all(str.replace_all(symMetricIn, "W/R %", "WR"), "Net $", "Net " + acctCcy)
    string symTtl = "Z-Score Symbols Scanner" + (nSymTf * symPerTf <= 3 ? "\n" : " - ") + zEngIn + " " + str.tostring(zMult, "0.0") + "σ - " + symMetLbl + "/" + str.tostring(lookback) + " - " + (symEx == "" ? "Auto" : symEx) + symNote
    string symTip = symMetLbl + " over the last " + str.tostring(lookback) + " closed trades. WR = win rate, Net % = compounded net result, Net " + acctCcy + " = sum of R multiples x " + str.tostring(riskAmt, "0.00") + " risk per trade. Green / red cell = trade open (long / short). Candles: " + scanType + (scChartOk ? "" : " (chart is " + chartType + ", scanner uses Standard)")
    table.cell(symTbl, 0, 0, symTtl, text_color=color.white, bgcolor=scChartOk ? color.new(#3B5B92, 0) : color.new(#F23645, 0), text_halign=text.align_center, text_size=symSize, tooltip=symTip)
    if symCut
        int fitTf = math.floor(symAvail / symWant)
        int fitSym = math.floor(symAvail / nTf)
        string fixTxt = fitTf >= 1 ? "Fix: " + str.tostring(math.min(fitTf, nTf)) + " timeframes max, or " + str.tostring(fitSym) + " symbols max" : "Fix: raise Request limit or turn off Show scanner"
        string cutTxt = "Showing " + str.tostring(nSym) + " of " + str.tostring(symWant) + " symbols - request limit\n" + fixTxt + (showScan ? "\nor turn off Show scanner" : "")
        string cutTip = (nSymTf < nTf ? "Showing " + str.tostring(nSymTf) + " of " + str.tostring(nTf) + " timeframes. " : "") + "Needs " + str.tostring(symWant * nTf) + " requests, limit " + str.tostring(symReqLimit) + (symUsed > 0 ? " (" + str.tostring(symUsed) + " used elsewhere in the script)" : "") + ". Fixes: remove timeframes (Max timeframes in the Multi-Timeframe Scanner group), shorten the symbol list, turn off Show scanner to free its requests, or raise Request limit to 64 if your plan is Ultimate."
        table.merge_cells(symTbl, 0, 1, symCols - 1, 1)
        table.cell(symTbl, 0, 1, cutTxt, text_color=color.white, bgcolor=color.new(#F23645, 30), text_halign=text.align_center, text_size=symSize, tooltip=cutTip)
    table.cell(symTbl, 0, 1 + wr, "Symbol", text_color=color.white, bgcolor=color.new(#3B5B92, 40), text_halign=text.align_left, text_size=symSize)
    for ti = 0 to nSymTf - 1
        int hc = 1 + ti * symPerTf
        if symSide
            table.merge_cells(symTbl, hc, 1 + wr, hc + 1, 1 + wr)
        table.cell(symTbl, hc, 1 + wr, f_label(array.get(scTfs, ti)), width=symSide ? 0.0 : symColW, text_color=color.white, bgcolor=color.new(#3B5B92, ti % 2 == 0 ? 40 : 65), text_halign=text.align_center, text_size=symSize)
    if nSym > 0
        for si = 0 to nSym - 1
            int rw = 2 + wr + si * symRowsPer
            array<string> symParts = str.split(array.get(symArr, si), ":")
            if symStack
                table.merge_cells(symTbl, 0, rw, 0, rw + 1)
            table.cell(symTbl, 0, rw, array.get(symParts, array.size(symParts) - 1), text_color=color.white, text_halign=text.align_left, text_size=symSize)
            for ti = 0 to nSymTf - 1
                int qx = si * nSymTf + ti
                bool qOk = not na(array.get(syPx, qx))
                int qDir = array.get(syDir, qx)
                bool qOpen = array.get(sySt, qx) == 1
                int qWn = array.get(syWin, qx)
                int qCnt = array.get(syN, qx)
                bool qHas = qOk and qCnt > 0
                float qNp = array.get(syNet, qx)
                float qNr = array.get(syNetR, qx)
                float qNd = na(qNr) ? na : qNr * riskAmt
                string qW = str.tostring(qWn / qCnt * 100, "0") + "%"
                // Negative net figures go in parentheses so a loss stands out, for example (0.4%) or (20)
                string qP = na(qNp) ? "n/a" : qNp >= 0 ? "+" + str.tostring(qNp, "0.0") + "%" : "(" + str.tostring(math.abs(qNp), "0.0") + "%)"
                string qD = na(qNd) ? "n/a" : qNd >= 0 ? "+" + str.tostring(qNd, "0") : "(" + str.tostring(math.abs(qNd), "0") + ")"
                string vA = symMetA == 0 ? qW : symMetA == 1 ? qP : qD
                string vB = symMetB == 1 ? qP : qD
                string tA = not qOk ? "n/a" : qHas ? vA : "-"
                string tB = not qOk ? "n/a" : qHas ? vB : "-"
                // Green / red background only while a trade is open on that timeframe (green = long, red = short). Dim text = fewer closed trades than the Lookback
                color qBg = qOk and qOpen and qDir != 0 ? color.new(qDir == 1 ? buyCol : sellCol, 70) : na
                color qTc = qHas ? (qCnt < lookback ? color.new(color.white, 45) : color.white) : color.gray
                int dc = 1 + ti * symPerTf
                table.cell(symTbl, dc, rw, tA, width=symSide ? symWA : symColW, text_color=qTc, bgcolor=qBg, text_halign=text.align_center, text_size=symSize)
                if symSide
                    table.cell(symTbl, dc + 1, rw, tB, width=symWB, text_color=qTc, bgcolor=qBg, text_halign=text.align_center, text_size=symSize)
                if symStack
                    table.cell(symTbl, dc, rw + 1, tB, width=symColW, text_color=qTc, bgcolor=qBg, text_halign=text.align_center, text_size=symSize)
 
// ── Alerts ────────────────────────────────────────────────
alertcondition(buy and alWrOk,    "Z-Score Buy Signal",  "BUY: Z-score signal")
alertcondition(sell and alWrOk,   "Z-Score Sell Signal", "SELL: Z-score signal")
alertcondition(tpHit,  "Z-Score Take Profit Hit", "TP hit on the open trade")
alertcondition(slHit,  "Z-Score Stop Loss Hit",   "SL hit on the open trade")
alertcondition(scBuy,  "Z-Score Scanner Buy (Any Timeframe)",  "BUY signal on a scanned timeframe")
alertcondition(scSell, "Z-Score Scanner Sell (Any Timeframe)", "SELL signal on a scanned timeframe")
 
// With Show position size ON, each BUY/SELL also sends one alert() message that carries the entry, stop, target and size (pick "Any alert() function call" when creating the alert)
if useSize and (buy or sell) and alWrOk
    alert("Z-Score " + (buy ? "BUY " : "SELL ") + syminfo.ticker + " | Entry " + str.tostring(entryPx, format.mintick) + (hasSl ? " | SL " + str.tostring(slPx, format.mintick) : "") + (hasTp ? " | TP " + str.tostring(tpPx, format.mintick) : "") + " | Size " + f_sizeTxt(posUnits) + (na(posCost) ? "" : " | " + (syminfo.type == "forex" ? "Notional " : "Cost ") + str.tostring(posCost, "0.00") + " " + acctCcy) + (na(posRiskCash) ? "" : " | Risk " + str.tostring(posRiskCash, "0.00") + " " + acctCcy), alert.freq_once_per_bar)
 
// Test alert: confirms an alert reaches you. Use Z-Score Test Alert, or "Any alert() function call" for the text message
alertcondition(engAlertTest and barstate.isrealtime, "Z-Score Test Alert", "Z-Score alert test: {{ticker}} {{interval}} {{timenow}}")
if engAlertTest and barstate.isrealtime
    alert("Z-Score alert test / " + syminfo.ticker + " / " + str.format_time(timenow, "yyyy-MM-dd HH:mm"), alert.freq_once_per_bar)

← 返回列表