Indicator

AI Trading Console PRO (BuySell with Complete Dash)AI Trading Console PRO script. It operates as a complete, semi-automated trading system combining entry signals, institutional filters, dynamic profit targets, and live performance tracking.
1. The Signal Engine (When to Enter)
The core entry logic relies on a confluence of four technical parameters. A trade is only triggered when all active conditions align.
ORB (Opening Range Breakout): The script records the highest high and lowest low of the first 30 minutes of the trading day (9:15 AM to 9:45 AM). A Buy signal requires price to break above the ORB High; a Sell signal requires breaking below the ORB Low.
Trend Alignment (EMA): It checks the short-term trend using a Fast EMA (13) and Slow EMA (39). Buy entries only happen if the 13 EMA is above the 39 EMA (Bullish).
Momentum (RSI): It ensures momentum is on your side. Buy entries require the 14-period RSI to be above 55, while Sells require it to be below 45.
HTF Confirmation (Higher Time Frame): It looks at a higher timeframe (default is 60 minutes) to ensure you aren't trading against the macro trend. A 50 EMA on the 60m chart dictates the broader bull/bear bias.
2. Institutional Filters (When to Stay Out)
This is the "brain" of the console, designed to prevent trades in choppy or dangerous market conditions.
ADX (Average Directional Index): This measures trend strength, regardless of direction. The script requires ADX to be above 20. If ADX is below 20, the market is chopping sideways, and the script will block the trade.
India VIX (Volatility Index): It pulls live data from NSE:INDIAVIX. If the VIX spikes above 20 (indicating panic or extreme volatility), the script blocks new entries to protect your capital.
3. Dynamic Targets (Where to Take Profit)
Instead of fixed percentage targets, the script uses Standard Floor Pivots calculated from the previous day's High, Low, and Close.
Institutional Levels: These pivots (R1, R2, R3 for Resistance; S1, S2, S3 for Support) act as hidden liquidity zones where large players take profits.
Dynamic Assignment: When a trade triggers, the script looks at your entry price. If you buy above R1, it intelligently assigns R2 as Target 1 (TP1) and R3 as Target 2 (TP2).
Visual Tracking: Once price touches a target level, the script stops plotting that specific line to keep the chart clean and changes the dashboard text to a green "HIT."
4. Risk Management (How to Protect Capital)
The script automates position sizing and stop-loss trailing so you don't have to calculate it manually.
ATR Stop Loss: The initial Stop Loss is placed 1.5x the Average True Range (ATR) away from your entry. This ensures your stop is based on current market volatility, not an arbitrary number.
Trailing Stop: As the trade moves in your favor, the Stop Loss trails behind the price by 1.2x the ATR, locking in profits while giving the trade room to breathe.
Position Sizing: You input your Capital (e.g., ₹100,000) and Risk % per trade (e.g., 2%). The script calculates exactly how many shares/contracts you should buy based on the distance to your ATR Stop Loss.
5. The Live Dashboard
The table in the top right acts as your command center. Here are the most advanced metrics it tracks:
AI Score (0-100): A real-time confidence metric. It awards 20 points each for Trend alignment, Momentum, Trend Strength (ADX), Volatility Safety (VIX), and HTF alignment. A score of 80+ is colored green, indicating a high-probability setup.
Expectancy: A mathematical proxy telling you if the strategy has a positive edge. An expectancy above 0.20 generally means the system is highly profitable over a large sample size.
Live PnL & WinRate: The script silently tracks every signal it generates in the background. It calculates your simulated Profit and Loss (PnL) and Win Rate based on your actual position sizing and where the trailing stop takes you out.
Avoid Trade: If the VIX is too high or the ADX is too low, this will flash red "YES," warning you that current market conditions are unfavorable for breakout trading.
Key Changes Made:
Pivot Calculation Engine: Added a request.security call using lookahead_on to pull the previous day's high, low, and close without repainting. This powers the standard Floor Pivots (R1/R2/R3 and S1/S2/S3).
Dynamic Target Assignment: When a signal fires, the script checks where the close price is relative to the pivots. If you buy above R1, it intelligently assigns R2 as your TP1 and R3 as your TP2.
Visual Tracking: Hit targets are visually tracked. When price touches a TP level, it drops a label on the chart and stops plotting the circle line for that specific target to keep your chart clean.
Upgraded Dashboard: Expanded the data table from 10 rows to 14. It now displays your active Entry, Stop Loss, and all three TP levels in real time. It will also switch the text to "HIT" in green once a target is reached during a trade. Indicator

Candle DNA Morphology | AnonycryptousCandle DNA Morphology | Anonycryptous
Description & user manual
Why is this indicator different:
Most candle analysis tools work with names. They look at a candle and call it an engulfing, a hammer, a doji, a shooting star. They compare shape against a fixed template and fire a signal when the match is close enough. The problem is that names are approximations. A hammer in a trending market is not the same as a hammer at a structural level with elevated volume. A name cannot capture that. A fixed template cannot either.
Candle DNA Morphology works differently.
It does not use names. It does not use templates. It compares the current candle to every historical candle within a configurable lookback window and finds the one that is mathematically closest — across up to eight normalized dimensions simultaneously. Body size, wick proportions, body position within the range, relative volume, candle size relative to recent volatility, trend alignment, and structural context. Then it tells you what happened after that historical candle, directly on the chart, with a single marker you can hover.
Other tools that use candle similarity show you statistics. Continuation rates. Reversal percentages. Tables to read and interpret. You still have to decide what the numbers mean and whether they matter right now.
Candle DNA Morphology does not show you statistics. It shows you a signal — the exact historical candle that matched, marked on the chart, with the date, the score, the direction, the R value, the percentage move, and the price move of what followed. No table to interpret. No calculation required. The information is in the hover.
The score tells you how close the match was. The tier tells you how rare it is. The color tells you the direction. Everything else is in the tooltip.
Important notice
Candle DNA Morphology generates signals based on historical pattern similarity and price behavior.
These signals are not financial advice.
They do not predict the future.
They do not guarantee profitability.
The outcome values shown — R, percentage, and price — are historical measurements from the matched candle in the past. They reflect what happened then, on that instrument, at that price level. The market may behave differently now. Similar candles can produce different results. These values are context, not certainty.
All trading decisions are made entirely by the user.
Always manage your own risk. Always apply your own judgment.
1. Overview
Candle DNA Morphology is a candle fingerprint matching indicator built around the mathematical similarity between the current candle and historical ones — and what those historical candles preceded.
What it includes:
- Up to 8-dimensional candle fingerprint matching using Euclidean distance
- Configurable lookback window from 50 to 1000 bars
- Three signal quality tiers: standard, elite, and ultra
- Hoverable triangle markers on signal bars with full match details in the tooltip
- Diamond marker and vertical line on the exact historical matched candle
- Configurable cooldown between signals to prevent clustering
- Signal mode selector: current bar, match bar, or both
- Dynamic score normalization — score stays 0-100 regardless of how many dimensions are active
- Vertical signal line and background glow on qualifying bars
- Live dashboard with score bar, tier, bias, match date, outcome in R / percentage / price, cooldown countdown, active dimensions, and ATR
- All times displayed in the timezone you select in the dashboard settings
- Four alerts: bull match, bear match, elite match (90+), ultra match (95+)
2. How the fingerprint works
Every candle is described by a set of normalized values between 0 and 1. These values capture the shape and context of the candle without using price or time units — which is what makes the engine self-calibrating across instruments and timeframes.
The five core dimensions are always active:
Body ratio. The size of the body relative to the total candle range. A full-body candle scores near 1. A doji scores near 0.
Upper wick. The upper wick as a proportion of the total range. A long upper wick scores high. A candle with no upper wick scores 0.
Lower wick. Same logic for the lower wick.
Body position. Where the body sits within the range — 0 is at the bottom, 1 is at the top. A bullish candle with a close near the high scores near 1. A bearish candle with a close near the low scores near 0.
Relative volume. Volume divided by the 20-bar average, capped at 3x and normalized. A spike at 2x average scores higher than a quiet bar at 0.8x.
Three optional dimensions can be enabled independently:
Atr percentile (dimension 6). How large the current candle is relative to recent volatility. Measures the candle range against the 14-bar ATR, normalized to a 0-2x cap. A large candle matches better with historically large candles.
Trend alignment (dimension 7). How far the close sits above or below EMA 21, normalized to the ATR. A bullish candle well above the EMA matches better with historical bullish candles that were also above the EMA.
Candle context (dimension 8). The relationship between the current candle and the previous one. Inside bars score 0. Outside bars score 1. Normal bars score 0.5. This dimension helps the engine recognize structural setups like inside bar breakouts.
3. Scoring and tiers
Similarity is measured using Euclidean distance — the straight-line distance between two candles in multi-dimensional space. The closer two candles are in this space, the more similar they are.
The maximum possible distance scales automatically with the number of active dimensions, so the score always ranges from 0 to 100 regardless of configuration. A score of 100 would mean a perfect match across all active dimensions. A score of 70 means a strong structural similarity. A score of 95 or above is exceptionally rare.
Three tiers determine how signals are displayed:
Standard (70-89). Green for bull, red for bear. The match is meaningful but not uncommon.
Elite (90-94). Gold marker with a star prefix ★. The match is close enough to be notable. These appear infrequently.
Ultra (95+). Cyan marker with a diamond prefix ◈. A near-identical historical candle was found. Very rare. When one fires, it is worth attention.
4. Understanding the signal
When a signal fires, two things appear on the chart depending on your signal mode setting.
A triangle on the current bar points in the direction the market moved after the historical match — up for a bullish outcome, down for a bearish one. Hovering the triangle with your cursor or S-Pen shows the full match details: the date and time of the historical candle, the score, the tier, the bias, the outcome in R, and the R value.
When a signal fires, two dotted lines and a vertical connector appear on the chart. The first dotted line runs horizontally from the signal bar close — this is the entry reference level, the price from which all R, percentage, and dollar measurements are calculated. The second dotted line shows the target level — where the market would reach if the historical outcome repeats. A vertical connector at the end of the forward window closes the structure. All three lines run exactly as many bars as your forward outcome setting.
The target level is calculated using the current ATR, not the historical ATR from the matched candle. This makes it relevant to the current market conditions. Hovering the target line shows both values — the target using the current ATR and the target using the historical ATR — so you can see how much volatility has changed between then and now. If the current ATR is significantly higher than the historical ATR, the target is further away than it was in the original setup. If it is lower, the target is closer.
A diamond and a vertical line on the historical matched candle shows you exactly which bar was used as the reference. The line runs through the full range of that candle so there is no ambiguity about which bar matched. The color follows the signal tier.
In addition to the dotted lines, the indicator can draw historical projection candles to the right of the signal bar. This feature is off by default and can be enabled in the visuals settings. When enabled, candles appear to the right of the signal bar showing the exact OHLC of the bars that followed the historical matched candle. Each candle has a body and centered wicks, drawn in the tier color of the signal. They scale correctly with chart zoom. A small label above the first candle reads "Historical projection" to make it immediately clear that these are historical bars, not predictions. The number of projection candles follows your forward outcome setting. Body transparency and wick transparency are independently configurable in settings.
The bias shown in the dashboard and the tooltip is the direction the market moved after the matched candle — not a prediction of what will happen now. It is historical context, not a guarantee.
All times shown in this indicator use the timezone you select in the dashboard settings. The default is UTC. Set it to your local timezone — for example UTC+2 for Amsterdam, UTC-4 for New York, UTC+9 for Tokyo — and all match times will display in your local time automatically.
5. Understanding the outcome values
The dashboard and tooltip show three outcome measurements for the historical matched candle. All three describe the same move — the price action in the bars following that historical candle — expressed in different units.
Outcome (R). How far price moved after the matched candle, expressed as a multiple of the ATR at that historical bar. This is the primary measurement. It is instrument-independent and works the same on BTC, SOL, MNQ, or any other asset. A value of +2.4R means price moved 2.4 times the ATR upward in the forward window.
Outcome (%). The same move expressed as a percentage of the close price at the matched candle. This gives a more intuitive sense of the magnitude for traders who think in percentage terms.
Outcome (price). The same move expressed in the currency of the instrument. This is the raw price distance the market covered — for example, $1,075 on Bitcoin or $0.87 on SOL. This value is calculated using the ATR and close price at the historical match bar, not at the current price.
The target line on the chart uses the current ATR rather than the historical ATR. This is intentional — the current ATR reflects how the market is moving right now, making the projected target more relevant to your actual trade. The historical ATR is still shown in the target line tooltip for reference, so you can see whether volatility has expanded or contracted since the original setup occurred. A large difference between the two ATR values means the market is in a different volatility regime than it was at the time of the match.
An important note on the price value: this reflects the historical move at the time and price of the matched candle. If Bitcoin was at 60,000 when the match occurred and is now at 78,000, the same R move produces a larger dollar value today than it did then. The price outcome is historical context — it shows what that candle type led to in dollar terms at that moment, not what the current setup will produce now.
This is not your personal risk-to-reward ratio. The R value gives you the historical move size. Your stop loss placement determines your actual R:R.
6. Bias and cooldown
The bias shown in the dashboard reflects the outcome direction of the current best match. It shows bull when the matched historical candle was followed by an upward move, and bear when it was followed by a downward move.
Bias changes when a new bar closes and the engine finds a different best match with a different historical outcome direction, or when the cooldown expires and a new signal fires pointing in a new direction.
During cooldown, the dashboard shows — wait. The last match date and all three outcome values remain visible. No new signal fires until the cooldown bar count has elapsed. The cooldown countdown shows how many bars remain before the next signal is allowed, or ready when it can fire freely.
Cooldown prevents signal clusters from forming on consecutive bars where the same setup repeats. On faster timeframes with many morphologically similar candles, a cooldown of 15 bars or more is strongly recommended.
7. Self-calibration
All fingerprint dimensions are normalized to values between 0 and 1. Volume is measured relative to its own 20-bar average. Candle size is measured relative to the ATR. Trend alignment is measured in ATR units. There are no fixed price thresholds anywhere in the engine.
This means the indicator adapts automatically to different instruments and timeframes. A BTC candle and an MNQ candle with the same proportional shape, same relative volume, and same relationship to their respective EMAs will produce the same fingerprint score — even though one trades at 78,000 and the other at 20,000.
When switching instruments, only the min match score typically needs a small adjustment. SOL and other volatile assets produce more morphological variation, so a slightly lower score threshold (75-80) often works better. More structured instruments like futures perform well at 85-90.
8. Settings guide
8.1 Match engine
Lookback window (bars). How many historical bars to scan for fingerprint matches. Range: 50-1000. Recommended: 500 on 1m-5m charts, 1000 on 15m and above. A larger window finds better matches but takes longer on lower timeframes.
Min match score (0-100). The minimum similarity score required to fire a signal. 70-79 is standard, 80-89 is strong, 90-94 is elite, 95+ is ultra. Start at 85 and adjust from there.
Cooldown between signals (bars). Minimum bars between signals. On a 5m chart, 15 bars equals 75 minutes. On a 1H chart, 15 bars equals 15 hours. Lower values produce more signals. Higher values enforce a minimum spacing between setups.
Dimension 6 — Atr percentile. Adds candle size context relative to recent volatility. Recommended: on.
Dimension 7 — Trend alignment. Adds EMA 21 directional context. Recommended: on.
Dimension 8 — Candle context. Adds inside/outside bar structural context. Recommended: on.
8.2 Outcome filter
Forward outcome (bars). How many bars after the historical match are used to measure the resulting move. Match this to your typical trade duration. On a 5m chart with 6 bars, the engine looks at 30 minutes of forward price action to determine the outcome direction and magnitude.
Min outcome move (ATR x). The historical match only qualifies if the resulting move exceeded this ATR multiple within the forward window. Filters out matches where the historical candle led to no meaningful move. Recommended: 1.0-2.0.
8.3 Visuals
Signal mode. Current bar only shows only the triangle. Match bar only shows only the diamond and vertical line on the historical candle. Both shows both simultaneously.
Show score on marker. When on, the triangle displays the score as text. When off, the triangle is clean. Hover always shows the full details regardless.
Signal bar background. Subtle glow on the signal bar in the tier color.
Vertical signal line. A faint vertical box through the signal bar. Useful for identifying signal bars when zoomed out.
Timezone. Select your local timezone from the dropdown. All match times in the dashboard and tooltips display in this timezone. Default is UTC. Amsterdam = UTC+2, London = UTC+1 (summer) or UTC, New York = UTC-4 (summer), Tokyo = UTC+9.
8.4 Dashboard
Score bar — visual meter 0-100 in tier color.
Tier — standard, ★ elite (90+), or ◈ ultra (95+).
Bias — ▲ bull or ▼ bear, or — wait during cooldown.
Match date — date and time of the historical matched candle in your selected timezone.
Outcome (R) — price move after the match in ATR multiples with forward bar count.
Outcome (%) — same move as a percentage of the historical close price.
Outcome (price) — same move in currency units at the historical price level.
Lookback — current lookback window setting.
Min score — current minimum score setting.
Cooldown — bars remaining until next signal, or ready.
Dimensions — how many dimensions are active and which ones (ATR, EMA, CTX).
ATR (14) — current ATR value.
9. Recommended starting settings
For 1m-5m scalping:
Lookback 500, min score 85, cooldown 15 bars, forward outcome 3 bars, min outcome move 1.0.
For 15m-1H:
Lookback 1000, min score 88, cooldown 8 bars, forward outcome 6 bars, min outcome move 1.5.
For 4H and above:
Lookback 1000, min score 90, cooldown 5 bars, forward outcome 4 bars, min outcome move 2.0.
10. How to use
Load the indicator and set signal mode to both. This gives you the triangle on the current signal bar and the diamond with border box on the historical matched candle simultaneously.
When a signal fires, hover the triangle with your cursor or S-Pen. Read the match date (UTC), score, bias, and outcome values. Then locate the diamond on the chart — the bordered box marks exactly which candle was matched. Look at what followed it on the chart. That is your reference.
The three outcome values give you the same historical move in three different units. Use whichever is most natural for how you think about size. The R value is instrument-independent. The percentage gives quick context. The price value shows the raw historical distance.
Watch the cooldown counter in the dashboard. When it shows ready, the next qualifying signal will fire without restriction. When it shows a bar count, the engine is waiting before it can fire again.
If you see too many signals, raise the min match score or increase the cooldown. If you see too few, lower the min outcome move or reduce the min score.
Candle DNA Morphology works best as a confluence tool. It tells you what the current candle morphology historically preceded. Your other indicators — levels, sessions, volume, trend — confirm whether the context justifies acting on it.
11. Disclaimer
This indicator is provided for educational and informational purposes only. Nothing in this document constitutes financial advice or any form of recommendation. Trading financial instruments involves substantial risk of loss. Past performance is not indicative of future results. You may lose all of your invested capital.
Anonycryptous accepts no responsibility or liability for any losses incurred as a result of using this indicator.
Indicator

Indicator

Indicator

Daily High/Low probability zonesDaily High/Low probability zones
Overview
Daily Segment Probabilities analyses the statistical distribution of where a market forms its daily High and daily Low relative to the previous session's range. By studying the prior day's High (PDH) and Low (PDL) across a user-defined lookback window, the indicator divides the price space around that range into 12 equal segments of 25% each — from −100% to +200% — and calculates how frequently the current session's High and Low have historically landed inside each segment. The result is a probability map drawn directly on the chart for today's session, letting you see at a glance which zones have historically attracted the day's extremes.
What is shown on the chart
The PDH and PDL of the prior session are drawn as solid horizontal lines across the current day, labelled in the margin. These form the 0% and 100% anchor points of the range.
Twelve segment boundaries are then projected from PDL upward and downward using the prior day's range as the measuring unit. Each boundary is coloured by zone: teal for the inside range (0–100%), indigo for upside extensions (above 100%), and red for downside extensions (below 0%). The 0% and 100% lines themselves are omitted from the segment boundaries since the PDH/PDL lines already mark them.
At the midpoint of each band, a label shows the segment name alongside the historical probability of the day's High and Low forming within that band — for example 0–25% H:18% L:34%. A tooltip on each label gives the full count of occurrences out of total sample days.
The two highest-probability bands are highlighted with a filled overlay: a gold fill marks the segment where the day's High has most frequently formed, and an orange fill marks the segment where the day's Low has most frequently formed. These fills are also reflected in the probability table — the High% and Low% cells for the top segments are coloured to match, creating a direct visual link between the chart and the table. Labels for the top bands carry a ★H or ★L marker for quick identification.
The probability table
The table summarises the full segment distribution in a compact grid with four columns:
Seg — segment number (1–12, top to bottom of chart)
Range — the percentage band that segment covers
High% — percentage of historical days where the session High formed in this segment
Low% — percentage of historical days where the session Low formed in this segment
Below the twelve data rows is an OOB (out-of-bounds) row counting days where the High or Low fell completely outside the −100% to +200% window. The footer row shows the actual sample size (n) and the configured lookback.
The High% and Low% cells for the two top-probability segments are highlighted with the same fill colours used on the chart, so the table and the chart read as a unified system.
How the lookback and calculation work
The lookback setting (default 250 days, range 10–500) defines how many prior daily sessions are included in the historical sample.
For each day in that window the indicator:
Takes the prior session's High and Low to establish the reference range and its 0% / 100% anchors.
Measures where that session's own High and Low fell, expressed as a percentage of the prior range above the prior Low — so a High exactly at the PDH of its own prior session registers as 100%, and a Low exactly at the PDL registers as 0%.
Assigns each reading to whichever 25%-wide segment it falls into.
Counts occurrences per segment across all n valid days (days where the prior range is greater than zero are included; zero-range days are skipped).
Probabilities in the table and labels are the count for each segment divided by n, rounded to the nearest whole percent. The top-segment fills and ★ markers are determined purely by the highest raw count, not the rounded percentage, so ties resolve correctly.
A minimum of 5 valid days is required before anything is drawn.
Settings
Core Settings
Lookback (days) — number of prior sessions used to build the probability distribution. Higher values give a more statistically stable sample; lower values are more responsive to recent market character. 250 days (roughly one trading year) is a reasonable default for most instruments.
Visual Settings
PDH/PDL line colour — colour of the prior day High and Low anchor lines.
Inside range colour (0–100%) — colour applied to segment boundaries within the prior range.
Extension above colour (>100%) — colour for boundaries above the PDH.
Extension below colour (<0%) — colour for boundaries below the PDL.
Label text colour — colour of the midpoint probability labels.
Segment line style — Solid, Dotted, or Dashed for segment boundaries.
PDH/PDL line style — Solid, Dotted, or Dashed for the anchor lines.
Top High% band fill colour — fill colour for the highest-probability High segment (default gold).
Top Low% band fill colour — fill colour for the highest-probability Low segment (default orange).
Table Settings
Show probability table — toggle the table on or off.
Table position — Top Right, Bottom Right, Middle Right, Bottom Center, or Middle Left.
Table text size — Auto, Tiny, Small, Normal, Large, or Huge.
Interpreting the output
The indicator does not predict where price will go — it describes where it has historically gone. A segment showing H:35% means the day's High landed in that band on roughly one in three days over the lookback period. Used alongside other context (session opens, market structure, news), the distribution can inform expectations for the day's likely trading range and where extension targets have historically clustered.
Segments inside the prior range (0–100%) capturing a high proportion of Low readings suggest mean-reversion sessions are common for the instrument. Large probabilities in extension segments (above 100% or below 0%) reflect trending or breakout tendencies. The OOB row is worth watching on highly volatile instruments where extreme moves regularly exceed the prior range by a wide margin.
Notes
The indicator is drawn only on the last bar of the chart to avoid repainting and to keep line/label counts within PulseWire's limits.
It is designed for use on intraday timeframes (1m–1h) where the daily session boundaries are visible. On a daily chart it will still compile but the lines will span only the current day's single candle.
The prior session data is fetched via request.security on the daily timeframe with lookahead_off to prevent look-ahead bias.
All percentages shown are based on historical frequency only and carry no implied forward guarantee. Indicator

Complex Single Trade StrategyThis 'Complex Single Trade Strategy' is a generic trading strategy that features three different types of stops, and four take profits.
It takes a Buy/Sell source input of:
The first signal will trigger a position to open immediately in that direction, but subsequent signals in the same direction will be ignored whilst the position remains open, as this strategy allows only one position at once.
A signal in the opposite direction to the current position can either be ignored, or it can close the position, or it can close it then immediately open another one in the opposite direction.
It also takes an optional 'Cancel' indicator just to close positions. Other signals will be ignored.
The three different types of stops, that can be applied individually, or together:
* Regular Stop
* Initial Trailing Stop
* Trailing Stop
The initial trailing stop works like a regular trailing stop until it reaches the cut off level, a percentage of the current asset price above or below the entry level, then it will no longer trail the price, remaining statically at this level.
From here the regular trailing stop can take over trailing the price. This is useful to move the stop to the entry level (or there abouts) fairly quickly. From there you might want to trail the price with a larger trailing stop for the rest of the trade.
0 cut off means it stops trailing the price at your entry level, positive above, negative below, for a long trade. For a short it would be the opposite.
Typically you would want:
Trailing Stop > Initial Trailing Stop >= Stop
The four take profits each specify an amount to reduce the position size by, and at what specified percentage gain in price this is triggered.
My 'Simple Buy/Sell Indicator' and 'Custom Buy/Sell Indicator' (coming soon - watch this space) can be used to combine other indicators together into BUY/SELL strategies, using multiple custom rules. These can then be used as inputs to this strategy.
Strategy

Indicator

Variance Ratio Regime Classifier [PickMyTrade]WHAT THIS INDICATOR DOES
This script implements the Lo-MacKinlay Variance Ratio Test, a formal
econometric hypothesis test introduced in the 1988 paper "Stock Market
Prices Do Not Follow Random Walks: Evidence and Implications" by
Andrew W. Lo and A. Craig MacKinlay.
At every bar it answers one question: is the market currently Trending,
Mean-Reverting, or behaving as a Random Walk?
It does this by running the test simultaneously across four time horizons
(q = 2, 4, 8, 16) and requiring a minimum consensus before declaring a
regime — reducing false signals that any single-horizon reading produces.
This is the first implementation of the Lo-MacKinlay Variance Ratio Test
in any category on PulseWire.
WHY IT IS DIFFERENT
The Hurst Exponent requires 100 or more bars to stabilise. This indicator
responds in 30. ATR-based classifiers measure volatility magnitude, not
autocorrelation structure. Hidden Markov detectors are probabilistic black
boxes. The Variance Ratio Test is grounded in a testable null hypothesis
with a precise mathematical definition.
The multi-horizon spectral fan shows not just whether autocorrelation
exists, but at which lag structure it is strongest. No equivalent
architecture exists in the PulseWire published script library.
THE MATHEMATICS
r(t) = ln( close(t) / close(t-1) ) 1-period log return
R(t,q) = ln( close(t) / close(t-q) ) q-period log return
Under the Random Walk null hypothesis, Var must equal
q multiplied by Var for all q greater than or equal to 2.
The Variance Ratio statistic is defined as:
VR(q) = Var divided by ( q times Var )
VR(q) equal to 1.0 indicates a Random Walk with no autocorrelation.
VR(q) above 1.0 indicates positive autocorrelation — Trending behaviour.
VR(q) below 1.0 indicates negative autocorrelation — Mean-Reversion.
MULTI-HORIZON CONSENSUS ENGINE
Each of the four horizons votes independently on every bar. A vote for
Trending is cast when VR(q) exceeds the Trend Threshold. A vote for
Mean-Reversion is cast when VR(q) falls below the MR Threshold.
Otherwise the vote is Random Walk.
A regime is confirmed only when the minimum vote count is reached.
Four of four votes is unanimous and produces the fewest signals.
Three of four is strong consensus and is the recommended default.
Two of four is moderate and produces more frequent signals.
A single VR(2) spike may be noise. VR(2), VR(4), and VR(8) all
exceeding the threshold simultaneously is statistically meaningful.
WHAT YOU SEE ON THE CHART
The indicator pane displays four VR lines forming a spectral fan.
The teal line is VR(q=2), the fastest with a one-bar momentum lag.
The blue line is VR(q=4), short-horizon with a three-bar lag.
The purple line is VR(q=8), medium-horizon with a seven-bar lag.
The orange line is VR(q=16), slow-horizon for sustained regime reading.
The white line is the composite equal-weight mean of all active values.
A dashed white line marks VR equal to 1.0, the random walk boundary.
A blue background tint indicates a confirmed Trending regime.
An orange background tint indicates a confirmed Mean-Reversion regime.
A gray tint indicates Random Walk or a transitional state.
Labels fire at the top of the pane on confirmed regime change bars.
TREND fires when a trending regime is confirmed.
MR fires when mean-reversion is confirmed.
RW fires when the regime returns to random walk.
The summary table shows live VR values for each active horizon,
individual signal classifications, the composite VR, vote count,
consecutive streak bars in the current regime, a z-score versus
the 50-bar history with amber highlight at or above two standard
deviations, and a percentile rank versus the 100-bar history.
SETTINGS GUIDE
VR Window defaults to 60 bars. This is the rolling lookback used
to estimate variance. Values of 30 to 50 respond faster but produce
noisier readings. Values of 80 to 120 are smoother but slower to
detect transitions. The default of 60 is calibrated for one-hour
charts on liquid instruments.
Trending Threshold defaults to 1.15. VR must exceed this level for
a Trending vote to be cast. The Lo-MacKinlay reference range is
1.10 to 1.20.
Mean-Reversion Threshold defaults to 0.85. VR must fall below this
for a Mean-Reversion vote. A symmetric setting relative to the
Trending Threshold is recommended.
EMA Smoothing defaults to 3. This is applied to each raw VR series
after computation. Set to 1 for unsmoothed raw output.
Min Votes defaults to 3. Use 3 for general trading applications.
Use 4 for regime confirmation only with the fewest signals.
RECOMMENDED INSTRUMENTS
Most informative on liquid instruments with active autocorrelation
structure. Recommended starting points are BTCUSDT 1H, ETHUSDT 1H,
ES1! 1H, NQ1! 1H, EURUSD 1H, and GBPUSD 1H.
When three or four VR lines cluster above the Trend Threshold,
sustained autocorrelation is present and momentum strategies have
a statistical basis. When three or four lines cluster below the
MR Threshold, mean-reversion dominates and oscillator or fade
strategies are more appropriate. When lines converge near 1.0
with no consensus, reduce position size and avoid directional bias.
DISCLAIMER
The Variance Ratio Test is a statistical and educational diagnostic
tool. VR values are not buy or sell signals and carry no performance
guarantee. Past regime behaviour does not predict future persistence.
All trading involves risk of loss. This script is published for
research and educational purposes only. Indicator

Indicator

[SW Lab] Signal Decay Monitor## What It Does
Every trading signal has a shelf life. A strategy that delivered strong returns for six months can quietly stop working as markets adapt -- and most traders only notice after weeks of losses. The Signal Decay Monitor uses a statistical Z-test to continuously compare a strategy's recent performance against its historical baseline, flagging degradation before your P&L does.
## How It Works
- Select any of 6 built-in strategies (SMA Crossover, RSI Reversal, MACD Signal, Bollinger Bounce, Breakout, Mean Reversion) and the indicator tracks every signal and its forward return
- Computes a rolling win rate over a configurable recent window (default: last 30 evaluated signals) and compares it to the full historical win rate
- Performs a Z-test to determine whether the difference between recent and historical performance is statistically significant or just normal variance
- Plots confidence bands (1-sigma and 2-sigma) around the historical baseline so you can visually distinguish meaningful decay from noise
- Tracks which market regime recent signals occurred in, helping you determine if the strategy failed or if the regime simply shifted
## Key Features
- **Rolling win rate oscillator** (cyan line) showing recent signal performance in real time
- **Historical baseline** (gray line) for long-term average win rate reference
- **1-sigma and 2-sigma confidence bands** showing expected statistical variation
- **Z-score histogram** providing a visual representation of the decay score
- **Background color changes** with health status for instant visual assessment
- **Regime analysis** in the info panel identifying whether losses concentrate in a specific regime
- **Info panel** with complete breakdown: health status, Z-score, recent vs. historical win rate, signal counts, and regime notes
## Signal Interpretation
| Health Status | Z-Score Range | Meaning | Recommended Action |
|--------------|---------------|---------|-------------------|
| HEALTHY | Z > -0.5 | Edge intact | Trade normally |
| IMPROVING | Z > +0.5 | Signal getting stronger | Consider increasing size |
| WEAKENING | -0.5 to -1.5 | Early warning | Monitor closely, tighten stops |
| DEGRADING | -1.5 to -2.5 | Significant decay detected | Reduce position size |
| DEAD | Z < -2.5 | Edge is gone | Stop trading this signal |
| NEVER PROFITABLE | N/A | Strategy never had an edge | Do not trade on this asset |
## Settings Guide
| Parameter | Default | Description |
|-----------|---------|-------------|
| Strategy | SMA Crossover | Which strategy's signal health to monitor |
| Fast Length | 20 | Primary period for the selected strategy |
| Slow Length | 50 | Secondary period for the selected strategy |
| Recent Window | 30 | Number of recent evaluated signals to compare against baseline |
| Historical Window | 200 | Full history lookback for baseline performance |
| Evaluation Bars | 10 | Forward bars to measure each signal outcome |
| Decay Threshold | -1.5 | Z-score below which health is flagged as decaying |
| ATR Fast / Slow | 14 / 50 | ATR periods for regime detection |
| Trend Length | 50 | SMA period for trend slope calculation |
## Alerts
- Decay detected (Z-score crosses below the configured threshold)
- Signal declared DEAD (Z-score falls below -2.5)
- Signal IMPROVING (Z-score rises above +0.5)
## Best Used For
- Monitoring live strategies for performance degradation before losses accumulate
- Deciding when to retire a signal that has lost its edge
- Distinguishing between a strategy that stopped working and a strategy in a temporarily unfavorable regime
- Validating whether a recently discovered setup maintains its edge over time
- Companion tool to the Backtest Truth Table -- use the Truth Table to find edges, the Decay Monitor to track when they expire
## Academic Foundation
The decay detection is based on a standard two-proportion Z-test, comparing the recent win rate proportion against the historical baseline proportion. This is a well-established statistical hypothesis test used to determine whether observed differences are significant or attributable to sampling noise.
## Disclaimer
This indicator is an analytical tool, not financial advice. Past statistical performance does not guarantee future results. Always apply your own risk management. Indicator

[SW Lab] Edge Analyzer## What It Does
Most indicators tell you to buy or sell without evidence. The Edge Analyzer changes that by building a real-time statistical profile for every trading setup it detects -- showing you exactly how that setup has performed historically on this specific asset, timeframe, and market regime. When a setup triggers, you see hard numbers: win rate, profit factor, best and worst outcomes, and a Kelly-derived position size -- not opinions.
## How It Works
- Monitors four setup types simultaneously: RSI Oversold/Overbought, MA Crossover, Breakout (with volume confirmation), and Mean Reversion (Z-score based)
- Each time a setup triggers, the indicator records the bar, price, direction, and current market regime, then measures the forward return after a configurable evaluation window (default: 10 bars)
- Classifies the market into three regimes (Trending, Ranging, Volatile) using ATR ratio analysis and trend slope, allowing you to see whether a setup that works in one regime also works in another
- Computes both all-time and regime-filtered statistics, with automatic fallback to all-regime stats when the current regime has fewer than 5 samples
- Calculates Quarter-Kelly position sizing from the real win rate and reward-to-risk ratio, capped at 25% for safety
## Key Features
- **Four parallel setup detectors** running simultaneously with independent statistics
- **Stat card overlay** showing occurrences, win rate, average return, best/worst, profit factor, and Kelly sizing
- **Regime-conditional analysis** breaking performance into Trending, Ranging, and Volatile environments
- **Confidence rating**: HIGH (15+ regime samples), MEDIUM (5-14), or LOW (fewer than 5)
- **Best setup highlight**: when multiple setups fire on the same bar, the highest win rate setup is prioritized
- Signal arrows plotted directly on the chart for visual reference
## Signal Interpretation
| Stat Card Field | Meaning |
|----------------|---------|
| Win Rate (All) | Historical win percentage across all regimes |
| Win Rate (Regime) | Win percentage filtered to the current market regime only |
| Profit Factor | Total wins divided by total losses -- above 1.0 means net positive |
| Quarter Kelly | Suggested position size as a percentage of account, based on Kelly Criterion at 25% safety factor |
| Confidence | HIGH / MEDIUM / LOW based on regime-specific sample count |
| NO EDGE | Negative Kelly value -- setup has negative expected value |
## Settings Guide
| Parameter | Default | Description |
|-----------|---------|-------------|
| RSI Length | 14 | RSI calculation period |
| RSI OB/OS | 70 / 30 | Overbought and oversold thresholds |
| MA Fast / Slow | 20 / 50 | Moving average crossover periods |
| Breakout Length | 20 | N-bar high/low lookback |
| Volume Confirm Mult | 1.2 | Volume must exceed SMA(20) times this value |
| Z-Score Length | 20 | Mean reversion lookback period |
| Z-Score Threshold | 2.0 | Standard deviations from mean to trigger |
| Eval Bars | 10 | Forward bars to measure each signal outcome |
| Min Signals | 10 | Minimum signals before displaying statistics |
| ATR Fast / Slow | 14 / 50 | ATR periods for regime classification |
| Trend Length | 50 | SMA period for trend slope calculation |
## Alerts
- RSI setup triggered
- MA crossover setup triggered
- Breakout setup triggered
- Mean reversion setup triggered
- Any setup triggered (composite)
## Best Used For
- Validating whether a setup actually has an edge on your chosen asset and timeframe before risking capital
- Identifying which market regime favors which setup type
- Data-driven position sizing instead of arbitrary fixed-percentage risk
- Screening multiple assets to find where specific setups consistently perform
- Building conviction (or losing it) with real forward-return statistics
## Academic Foundation
Position sizing is based on the Kelly Criterion (Kelly, 1956), which maximizes the long-term geometric growth rate of a portfolio. The indicator uses Quarter Kelly (25% of full Kelly) to reduce variance, a widely adopted practice in professional trading.
## Disclaimer
This indicator is an analytical tool, not financial advice. Past statistical performance does not guarantee future results. Always apply your own risk management. Indicator

Heartbeat Rhythm Detector [forexobroker]Heartbeat Rhythm Detector tracks the rhythm of bar ranges over a rolling window and fires when the rhythm breaks -- when a single bar's range becomes a statistical outlier (high z-score) with directional close and volume confirmation. A healthy market has a regular heartbeat of similar-sized bars; a broken rhythm marks a real shift.
Built for traders who want to enter when the market's normal volatility cadence abruptly changes, usually at the onset of a new trend leg.
🔶 CONCEPTS
Rhythm is regularity. If the last 20 bars all have similar ranges, the range distribution is tight, and the z-score of any given bar is small. When a single bar prints a range that is two or more standard deviations above the rolling mean, the rhythm has broken -- something out of the ordinary has happened. If the close confirms a direction and volume supports it, the rhythm break is real and tradable. Rising coefficient of variation adds an extra confirm: irregularity was building before the break itself.
🔶 HOW IT WORKS
- Measures current bar range (high - low)
- Computes rolling mean and standard deviation of range over the Rhythm Window
- Calculates range z-score
- Computes coefficient of variation (stddev / mean) of ranges and its change over the window
- Confirms volume exceeds average by the volume multiplier
- Combines z-score magnitude, CV rise, volume excess, and EMA slope into a 0-100 Rhythm Score
- Classifies state as REGULAR, IRREGULAR, SPIKE, or ARRHYTHMIA
- Fires signal on rhythm-break bar with matching directional close and bias
🔶 HOW TO USE
1. Add the indicator -- background tints by rhythm state
2. Watch the dashboard (top-right) for live range z-score, CV, CV change, volume ratio, and break direction
3. Green BUY triangles with "PULSE ↑" label fire on bullish rhythm breaks; pink SELL triangles on bearish
4. The Bias EMA plotted with glow gates signals to macro direction
5. Raise Rhythm Break Z-Score for only extreme outliers; lower it for more frequent signals
🔶 FEATURES
- Non-repainting signals (barstate.isconfirmed)
- Works on all timeframes and instruments
- 9 alert conditions with JSON webhook support
- Statistical outlier detection in bar ranges (not just ATR expansion)
- Coefficient-of-variation context that confirms increasing irregularity
🔶 SETTINGS GUIDE
- Rhythm Window -- Bars used to measure range mean, stddev, and CV
- Rhythm Break Z-Score -- Required range z-score to qualify as a rhythm break
- ATR Length -- ATR period (used for label offsets)
- Rising CV Floor -- Minimum CV increase over the window to count as rhythm shift
- Volume Average Length / Volume Multiplier -- Volume confirmation criterion
- Bias EMA Length -- Macro EMA used to gate signals
- Rhythm Score Threshold -- Minimum 0-100 score required at fire
- Signal Cooldown Bars -- Minimum bars between consecutive signals
🔶 ALERTS
- HRD Buy Pulse -- Bullish rhythm break confirmed
- HRD Sell Pulse -- Bearish rhythm break confirmed
- HRD Any Signal -- Any rhythm signal
- HRD Arrhythmia -- Rhythm score reaches 85+
- HRD Up Break -- Bullish rhythm break event
- HRD Down Break -- Bearish rhythm break event
- HRD Range Z-Spike -- Range z-score above threshold (informational)
- HRD Rising CV -- Range coefficient of variation increasing
- HRD Webhook JSON -- Generic webhook payload for external automation
🔶 LIMITATIONS & DISCLAIMER
- This is a technical analysis tool, not financial advice. Always use proper risk management.
- Z-score normalization adapts to recent rhythm; regime shifts can temporarily mis-scale thresholds.
- News-driven spikes can cause rhythm breaks unrelated to structural change.
- The Rhythm Score is a composite heuristic, not a calibrated probability.
Indicator

Indicator

ICOptimizerLibLibrary "ICOptimizerLib"
ICOptimizerLib v2 — IC-based parameter optimization with 4 Bayesian strategies.
Publish target: ICOptimizer/2 (hard break from v1 — see §A below).
Layer 1: primitive IC estimators (Pearson, Spearman, Kendall, Partial).
Layer 2: Optimizer UDT with 4 strategies: argmax | ucb | thompson | bayesian.
Layer 3: RegimeGate, ObjectiveWeights, composite scoring, serialize/restore.
Layer 4: diagnostics table and panel.
L2 library — depends only on NumLib.
─── §A v1 BACKWARD-COMPAT DECISION (follow-up 1) ────────────────────────
HARD BREAK. v1 (ICOptimizer/1) used bare strings ("argmax", "ucb", …).
v2 uses the OptimizerKind enum. Reason: Pine v6 enums are type-safe and
produce CE10 errors at compile time if a caller passes an invalid string,
whereas bare strings fail silently at runtime. The compat shim route
(string→enum dispatch wrapper) was considered and rejected: it would
re-introduce series-string branching inside a hot method, defeating the
purpose of the enum migration.
Migration for v1 callers:
OLD: f_find_optimal_param(params, ics, cur, 0.2) ← v1 API
NEW: opt = f_optimizer_new(OptimizerKind.ARGMAX, …) ← v2 API
idx = opt.propose()
opt.observe(idx, ic)
The free function f_find_optimal_param() is retained in §4 as a one-line
compat wrapper producing identical output to v1 findOptimalParam() for
callers that only used ARGMAX and do not need the UDT.
Publish target: ICOptimizer/2 (same publisher namespace as kNNLib/28,
LearningLib/1, etc. Parallel to v1, not a rename.)
─── §B UDT INDEPENDENCE AUDIT (follow-up 2) ─────────────────────────────
All 4 UDTs are independently constructable with no required coupling:
UDT Constructor Depends on
─────────────── ─────────────────────────── ────────────────────────────
Optimizer f_optimizer_new(…) nothing (grid is caller-owned)
RollingIC f_rolling_ic_new(capacity) nothing
RegimeGate f_regime_gate_new(…) nothing
ObjectiveWeights f_obj_weights_new(…) nothing
Valid combinations:
• Optimizer alone — minimal usage (ARGMAX strategy, no IC classification)
• Optimizer + RollingIC — IC classification per bar, classify() method
• Optimizer + ObjectiveWeights — composite scoring for multi-objective grids
• Optimizer + RegimeGate — gate-filtered observe() calls
• All 4 — full stack
Initialization order: any order; there are no cross-UDT init dependencies.
The caller is responsible for pushing IC values into RollingIC before
calling classify(); a fresh buffer returns 0.0 thresholds (safe default).
─── §C GP MATH VERIFICATION (follow-up 3) ───────────────────────────────
Jacobi solver convergence domain: guaranteed for diagonally dominant K.
K is diagonally dominant when kernel_noise > 0 (K = kernel(xi,xi) +
noise ≥ 1 + noise > Σ_{j≠i} kernel(xi,xj) for RBF/Matern52 with ls > 0).
NaN propagation guard: f_optimizer_new() enforces noise ≥ 1e-6 at
construction (see implementation below). NaN in ic_sample is gated by
the na(ic_sample) check in observe() before any array writes.
Grid size constraints (enforced at f_optimizer_new):
grid_size == 1 → runtime.error (BAYESIAN is undefined for a single cell)
grid_size > 30 → runtime.error for BAYESIAN only (Jacobi O(n²×20) budget)
grid_size ≥ 2 → all strategies valid
ARGMAX/UCB/THOMPSON have no upper grid-size constraint.
Unit test specification (see test_icoptimizer_v2_unit.pine):
T1: grid= + BAYESIAN → should hit error log (na guard)
T2: grid= + BAYESIAN, 50 observe() calls → ic_var shrinks
T3: grid size=30 + BAYESIAN → no silent NaN on bar 500 / 1000
T4: rising IC synthetic trajectory → propose() returns idx 6 after warmup
T5: peak-in-middle IC → propose() converges to idx 3 (center)
─── §D v5→v6 DELTA (Phase E-2a) ─────────────────────────────────────────
1. //@version=5 → //@version=6
2. type ICOptimizer → decomposed to 4 independent UDTs (§B)
3. `series float` qualifiers explicit; `simple int` for all ta.* lengths (CE10297)
4. Enum OptimizerKind / KernelKind / ReturnMode replaces bare strings
5. classifyIC scalar bug → RollingIC ring buffer + sort-based percentile
6. detectAndAdjustDomination orphan → method check_domination on Optimizer
7. Monotonic counter → reset_decay(decay) method
8. S9: all multi-line ternaries collapsed to single lines
9. f_ma_for_idx() dispatch in demo for simple-int ta.sma constraint
10. Nested array.get() in f_build_gram / observe() split to locals (COMMA_STATEMENTS)
f_ic_pearson(signal, ret, n)
Pearson IC: correlation of signal with forward return
Parameters:
signal (float) : Signal series (e.g. z-score oscillator)
ret (float) : Forward return series (aligned: ret = realized return for signal )
n (simple int) : Rolling window (simple int — required by ta.correlation)
f_ic_spearman(signal, ret, n)
Spearman IC via rank correlation approximation
Parameters:
signal (float) : Signal series
ret (float) : Forward return series
n (simple int) : Rolling window
Returns: Spearman rank-correlation approximation
f_ic_kendall(signal, ret, n)
Kendall IC approximation (via concordant/discordant sign correlation)
Parameters:
signal (float) : Signal series
ret (float) : Forward return series
n (simple int) : Rolling window
Returns: Kendall tau approximation
f_ic_partial(signal, ret, control, n)
Partial IC: correlation of signal with ret after removing control variable
Parameters:
signal (float) : Signal series
ret (float) : Forward return series
control (float) : Control variable to partial out
n (simple int) : Rolling window
Returns: Partial Pearson IC
f_forward_return(src, horizon, mode, benchmark)
Compute forward return from source series
Parameters:
src (float) : Source price series
horizon (simple int) : Look-forward bars
mode (series ReturnMode) : ReturnMode enum
benchmark (float) : Optional benchmark (used only in EXCESS mode; pass na otherwise)
f_label_from_signal(sig, ret, eps)
Label from signal × return sign match
Parameters:
sig (float) : Signal value
ret (float) : Realized return
eps (float) : Dead-zone threshold (returns within ±eps labelled 0)
Returns: 1 = correct direction, -1 = wrong direction, 0 = inside dead-zone
f_rolling_ic_new(capacity)
Create a new RollingIC buffer
Parameters:
capacity (simple int) : Number of IC samples to retain
method push(self, ic_val)
Push a new IC observation into the ring buffer
Namespace types: RollingIC
Parameters:
self (RollingIC)
ic_val (float)
method classify(self, ic_val, good_pct, bad_pct)
Classify current IC against ring buffer distribution
Namespace types: RollingIC
Parameters:
self (RollingIC) : RollingIC buffer (must have been pushed at least once)
ic_val (float) : Current IC to classify
good_pct (float) : Percentile above which IC is "good" (0–100)
bad_pct (float) : Percentile below which IC is "bad" (0–100)
Returns:
f_optimizer_new(kind, grid, lr, c_ucb, cooldown, kernel_kind, kernel_ls, kernel_noise)
Create a new Optimizer
Parameters:
kind (series OptimizerKind) : Strategy
grid (array) : Parameter grid (array, size ≤ 30 for BAYESIAN)
lr (float) : EWM learning rate for ic_ema / ic_var updates (0–1)
c_ucb (float) : UCB exploration constant (ignored for non-UCB)
cooldown (simple int) : Minimum bars between switches
kernel_kind (series KernelKind) : Kernel for BAYESIAN (ignored otherwise)
kernel_ls (float) : Kernel lengthscale (ignored otherwise)
kernel_noise (float) : Observation noise (ignored otherwise)
method propose(self)
Propose next parameter index to try
Namespace types: Optimizer
Parameters:
self (Optimizer)
Returns: Selected grid index
method observe(self, idx, ic_sample)
Record observed IC for a grid cell and update posterior
Namespace types: Optimizer
Parameters:
self (Optimizer)
idx (int) : Grid index that was evaluated
ic_sample (float) : Observed IC value
method reset_decay(self, decay)
Apply exponential decay to ic_ema and ic_var (prevents monotonic drift)
Namespace types: Optimizer
Parameters:
self (Optimizer)
decay (float) : Decay factor 0..1 (e.g. 0.95 = retain 95% of past)
method check_domination(self, long_n, short_n, ratio_threshold)
Detect directional signal domination and bump current grid index
Namespace types: Optimizer
Parameters:
self (Optimizer)
long_n (int) : Count of long signals in evaluation window
short_n (int) : Count of short signals in evaluation window
ratio_threshold (float) : Domination ratio (e.g. 4 = 4:1 imbalance)
Returns: direction_str = "long" | "short" | "none"
method current_param(self)
Get current parameter value from grid
Namespace types: Optimizer
Parameters:
self (Optimizer)
f_find_optimal_param(testParams, icValues, currentParam, smoothing)
Find optimal parameter from arrays (v1-compatible, wraps Optimizer.propose)
Parameters:
testParams (array) : Grid array
icValues (array) : IC values for each grid cell (same size)
currentParam (float) : Current param (for EWM smoothing)
smoothing (simple float) : EWM lr (0–1)
Returns:
f_regime_gate_new(mode, threshold, confirm_bars)
Create RegimeGate
Parameters:
mode (string)
threshold (float)
confirm_bars (simple int)
method is_open(self, ic_val, bars_above)
Check if gate is open given current IC and a rolling counter
Namespace types: RegimeGate
Parameters:
self (RegimeGate) : RegimeGate
ic_val (float) : Current IC
bars_above (int) : Rolling bars-above-threshold counter (caller maintains)
Returns: bool gate_open
f_obj_weights_new(w_ic, w_hitrate, w_freq_penalty, w_drawdown_penalty)
Create ObjectiveWeights
Parameters:
w_ic (float)
w_hitrate (float)
w_freq_penalty (float)
w_drawdown_penalty (float)
f_composite_score(w, ic, hitrate, freq, drawdown)
Compute composite score for a grid cell
Parameters:
w (ObjectiveWeights) : ObjectiveWeights
ic (float) : IC value for cell
hitrate (float) : Hit rate 0..1 for cell
freq (float) : Signal frequency 0..1 (higher = more signals = penalized)
drawdown (float) : Max drawdown magnitude (positive float)
Returns: Composite score (higher = better)
f_optimizer_serialize(self)
Serialize Optimizer state to a compact CSV string
Parameters:
self (Optimizer) : Optimizer to serialize
Returns: string blob (pass to f_optimizer_restore to reconstruct ic_ema/ic_var)
f_optimizer_restore(self, blob)
Restore ic_ema/ic_var/visits from serialized blob into an existing Optimizer
Parameters:
self (Optimizer) : Optimizer (grid must already be initialized with correct size)
blob (string) : String from f_optimizer_serialize
Returns: self (mutated in place)
f_diag_table(self, gate, weights, pos, max_rows)
Render diagnostics table for Optimizer state
Parameters:
self (Optimizer) : Optimizer
gate (RegimeGate) : RegimeGate (pass na if unused)
weights (ObjectiveWeights) : ObjectiveWeights (pass na if unused)
pos (string) : Table position (e.g. position.bottom_right)
max_rows (simple int) : Maximum grid rows to display (capped at array.size(grid))
Returns: table reference
f_diag_panel(self, height)
Render sparkline-style panel (one plot bar per grid cell, height = ic_ema)
Parameters:
self (Optimizer) : Optimizer
height (float) : Panel height in price units (caller scales)
Returns: label(na) (renders labels directly)
f_kind_str(k)
Parameters:
k (series OptimizerKind)
f_kernel_str(k)
Parameters:
k (series KernelKind)
f_return_mode_str(m)
Parameters:
m (series ReturnMode)
RollingIC
Rolling IC ring buffer for proper percentile computation
Fields:
samples (array) : Circular buffer of IC observations
head (series int) : Write head (mod capacity)
capacity (series int) : Max samples to retain
Optimizer
Optimizer — unified UDT for all 4 strategies
Fields:
kind (series OptimizerKind) : Strategy: ARGMAX | UCB | THOMPSON | BAYESIAN
grid (array) : Discrete parameter grid (size ≤ 30 for BAYESIAN)
ic_ema (array) : Posterior mean per cell (EWM updated)
ic_var (array) : Posterior variance per cell (UCB/Thompson/Bayes)
visits (array) : Visit count per cell
lr (series float) : EWM learning rate for ic_ema / ic_var updates
c_ucb (series float) : Exploration coefficient (UCB only)
cooldown (series int) : Minimum bars between parameter changes
last_change_bar (series int) : Bar index of last change
current_idx (series int) : Currently selected grid index
kernel_matrix (array) : Flattened len(grid)² Gram matrix (BAYESIAN only)
kernel_kind (series KernelKind) : RBF | MATERN52 (BAYESIAN only)
kernel_ls (series float) : Kernel lengthscale (BAYESIAN only)
kernel_noise (series float) : Observation noise σ² (BAYESIAN only)
total_visits (series int) : Cumulative visit count (for UCB log normalizer)
decay_factor (series float) : EWM decay applied by reset_decay (0..1; 1=no decay)
RegimeGate
RegimeGate — IC regime filter
Fields:
mode (series string) : "positive" | "any" | "top_pct"
threshold (series float) : IC threshold for "positive" or percentile for "top_pct"
confirm_bars (series int) : Bars IC must stay above threshold before gate opens
ObjectiveWeights
ObjectiveWeights — composite scoring weights
Fields:
w_ic (series float) : Weight on IC component
w_hitrate (series float) : Weight on hit-rate component
w_freq_penalty (series float) : Penalty for excessive signal frequency
w_drawdown_penalty (series float) : Penalty for drawdown Library

Continuation Acceptance Planner [AGPro Series]Continuation Acceptance Planner
🧠 Core Idea
Is this continuation setup being accepted, delayed, or invalidated before the next decision point?
📌 Overview / What it does
Continuation Acceptance Planner is a chart-first continuation planning tool built to evaluate whether a pullback inside an active trend is producing real acceptance or only temporary hesitation.
The script builds a live continuation acceptance band around a trend base, scores the context from 0 to 100, maps the invalidation rail, checks target room against the nearest obstruction, and prints compact state labels such as ACCEPTED, DELAYED, PAUSED, WATCH, and INVALID.
It does not predict future price movement, automate entries, or produce guaranteed trade signals. Its role is to organize continuation context into a cleaner decision framework.
🎯 Purpose & Design Philosophy
This script was built for traders who want to judge continuation quality without turning every trend pullback into a signal.
Most continuation tools focus on bounce detection or trend strength only. This planner focuses on the decision layer: acceptance quality, pullback risk, target room, invalidation context, and the next action state.
The design supports a patient execution mindset. It helps the user ask whether the continuation is actually being accepted, still delayed, temporarily paused, too extended, or losing validity.
⚡ Why This Script Is Different
Most tools focus on generic trend continuation signals after a moving average touch or pullback bounce.
This script does NOT act as a simple buy/sell continuation indicator, and it does not clone a broad trend-continuation quality scanner.
Instead, it treats continuation as a planning problem: price must interact with an acceptance band, show a quality close, maintain enough room before obstruction, and stay above or below a clear invalidation rail.
⚙️ Methodology
1. Context Detection
The script identifies bullish or bearish continuation context using fast, base, and slow EMA alignment plus trend slope.
2. Reference Mapping
It creates a continuation acceptance band around the base EMA and maps the invalidation rail using the band edge, slow EMA, and ATR buffer.
3. Reaction Evaluation
It evaluates pullback depth, close acceptance, volume support, and whether price is delaying, accepting, extending, or moving toward invalidation.
4. Visual Output
The script displays a centered acceptance-band label, invalidation and target guides, compact state labels, and a premium AG Pro planning panel.
🗺️ How to Read the Chart
Zones = the live continuation acceptance band around the trend base.
Labels = accepted, delayed, invalidation, or watch-state markers with optional 0-100 score.
Colors = bullish continuation context uses teal, bearish continuation context uses pink, delayed context uses amber, and risk or invalidation context uses red.
Panel = a compact decision dashboard showing Continuation Score, Acceptance, Pullback Risk, Target Room, and Action.
🚦 Signals & States
• ACCEPTED → continuation context has a qualified acceptance close and enough score to review.
• DELAYED → price is interacting with the acceptance band but has not produced enough clean acceptance.
• PAUSED → the prior continuation side still matters, but the trend stack needs to rebuild before the setup becomes clean again.
• WATCH → continuation context exists, but the setup still needs clearer reaction.
• EXTENDED → price is away from the acceptance band and may be late for clean continuation planning.
• INVALID RISK → price is moving beyond the planner's invalidation rail.
🔔 Alerts Logic
Alerts trigger when continuation acceptance, delayed acceptance, invalidation risk, or blocked target room conditions appear.
Alerts are attention markers only. They are not trade instructions and should be interpreted with the broader chart context.
🧩 Confluence Logic
The strongest continuation context appears when trend alignment, controlled pullback depth, close acceptance, volume support, and clean target room align.
When these components align, the continuation score improves and the panel moves toward a clearer planning state.
📊 When to Use
• Primary timeframe: 1H
• Secondary timeframe: 4H
• Trending markets with structured pullbacks
• Continuation setups after a controlled pause
• Pullbacks into a moving trend base
• Situations where target room and invalidation clarity matter
⚠️ When NOT to Use
• When expecting dense signals on 1D or 1W charts
• Very low liquidity environments
• Extremely noisy sideways conditions
• High-volatility shock moves where trend anchors distort quickly
• Markets with no clean trend alignment
🎛️ Key Inputs
• Sensitivity → changes how strict the acceptance engine is.
• Target Obstruction Lookback → defines the prior obstruction used for target-room evaluation.
• Acceptance Band Width ATR → controls the width of the continuation band.
• Confirmation Mode → defines whether acceptance requires close behavior only, close plus volume, or stricter alignment.
• Label and Panel Settings → control visual density, font size, panel location, and theme.
🖥️ Interface & Visual Design
The panel is designed as a compact planning dashboard, not a data-heavy scanner.
The first row follows the AG Pro blue merged-header standard. The remaining rows focus only on the information needed for continuation planning: score, acceptance, pullback risk, target room, and action.
Chart visuals are intentionally controlled so the acceptance band, invalidation rail, target guide, and labels remain readable.
🧪 Practical Usage Workflow
1. Read the panel state.
2. Check whether price is interacting with the acceptance band.
3. Review the continuation score and pullback risk.
4. Compare target room with the invalidation rail.
5. Use labels and alerts as attention markers, not as automatic decisions.
🔍 Interpretation Guidelines
Think in terms of setup quality, not prediction.
A higher score means the current continuation context has stronger alignment across trend, pullback depth, close behavior, volume, and target room.
A delayed state means the idea is not necessarily invalid, but the chart has not yet produced clean acceptance.
A paused state means the prior continuation context is still nearby, but alignment weakened enough that patience matters more than chasing.
An invalidation-risk state means the continuation structure should be reassessed.
🚫 What This Script Is NOT
• Not a prediction engine
• Not financial advice
• Not an auto-trading system
• Not a guaranteed signal generator
• Not a generic support/resistance or order-block map
• Not a gap continuation planner or breakout acceptance planner
⚠️ Limitations & Transparency
Timeframe differences can change how continuation bands and target-room references appear.
Volatility expansion can move the acceptance band and invalidation rail quickly.
Low-volume or synthetic symbols may reduce the usefulness of the volume component.
All outputs are rule-based and should be interpreted within broader market context.
🧠 Market Context Notes
Continuation planning depends on trend structure, liquidity, volatility, and obstruction distance.
The cleanest cases usually appear when pullbacks are controlled, the acceptance close is clear, and the next obstruction is not too close.
In the current public-release tuning, the script reads cleanest on 1H charts and remains usable on 4H. Daily and weekly charts can still provide context, but they are less expressive for the intended acceptance-versus-delay workflow.
🧾 Use Case Examples
When price pulls back into the acceptance band during a bullish trend and closes back above the base EMA with sufficient target room, the planner may shift toward ACCEPTED.
When price stays inside the band without a clean close, the planner may remain DELAYED.
When price closes beyond the invalidation rail, the planner flags INVALID RISK.
🧱 System Philosophy
The script follows the AGProLabs decision-engine approach: a useful public tool should help traders evaluate validity, strength, risk, target room, and the next action state.
It is built to guide interpretation, not to replace trader judgment.
🔐 Non-Promise Statement
No script can provide certainty.
No output from this script guarantees continuation, reversal, profit, or loss avoidance.
📉 Risk Disclosure
Trading involves risk.
Users are responsible for their own decisions.
This script does not provide financial advice and should be used only as an educational and analytical tool.
📚 Educational Note
Use the planner to study how continuation acceptance develops across different symbols, sessions, volatility regimes, and timeframes.
Indicator

ALN Sessions [NQ Stats x CantoLab]A statistical tool for NQ intraday traders built around research from NQ Stats (NQStats on twitter / nqstats.com ). Credit to NQ Stats for the original concept and data — published here as an open source indicator with permission.
Introduction
This indicator visualizes Asia and London session ranges on NQ (NASDAQ futures), then overlays statistically-derived probability levels showing how likely price is to sweep each session's high or low — based on historical pattern data compiled by NQ Stats.
How to Read the Probability Numbers
When London session closes, two horizontal lines appear — one above (London High) and one below (London Low) — each labeled with a percentage like 81.1% or 74.9%.
These numbers answer: "Historically, how often does price return to sweep this level after London closes?"
For example, if you see 81.1% on the high line, it means: in roughly 8 out of 10 historical sessions matching this pattern, price eventually traded back up to or through the London High
What happens when a level is hit?
The label updates to show in blue — confirming that level was reached
The other line's probability updates to a new conditional probability, e.g. 46% , shown in brackets
This delta tells you how the odds of sweeping the second level changed now that the first was reached
The Four Patterns (Asia vs London relationship)
The probabilities change depending on how London's range relates to Asia's range that day. The indicator detects four patterns automatically:
London Engulfs Asia — London trades both above AND below Asia's range. The most expansive session structure.
Asia Engulfs London — Asia's range fully contains London's range. London consolidates inside the prior overnight range.
London High Break — London breaks only above Asia's high, leaving Asia's low intact.
London Low Break — London breaks only below Asia's low, leaving Asia's high intact.
Each pattern has its own set of historical probabilities, so the percentages you see are always contextual to that day's Asia/London relationship — not a fixed number.
Settings
Asia Session — color, session time window, and label text
London Session — color, session time window, and label text
Label Size — Tiny / Small / Normal / Large
Border — toggle, style (Solid/Dashed/Dotted), and width for session boxes
Probability Lines — toggle, Auto color or manual color pick, style (Solid/Dashed/Dotted), and width
Daily Dividers — toggle, color, style (Solid/Dashed/Dotted), and width
Notes
Built for NQ Futures. Behaviour on other instruments is untested
All times are New York time
Probability data is derived from 10 years of NQ historical data by nqstats.com
This indicator does not provide financial advice or a complete strategy. You are responsible for how you build around and execute on this data
⚠️ Important
This is a statistical study indicator. It does not guarantee that the London high or low will be hit. Over a large sample, this is the expected behaviour based on 10 years of NQ data. It is best combined with other confluences to confirm direction — this indicator alone is not a strategy.
Indicator

STS4x - Initial BalanceClean Initial Balance with bar-anchored line origins, H/L letter markers, and a live info dashboard. Built for index futures (ES/NQ/YM and their micros) but works on anything intraday.
What it does:
Tracks the high and low established in the first 30 or 60 minutes of the RTH session, locks the range when the window closes, and gives you the IBH, IBL, midpoint, plus optional 1x and 2x range extensions for the rest of the day.
What sets it apart:
IBH and IBL lines start at the exact bar that printed each extreme. Not at session open. The midpoint anchors at whichever extreme came first.
"H" and "L" letter tag markers sit on those exact candles so you can see at a glance where the structural extremes were set.
Solid color info dashboard with sectioned layout. No transparent washes. Four built-in schemes: STS4x Cyan, Amber Terminal, Crimson Pro, Mono Slate.
Live position and break tracking. The table shows whether price is above IBH, inside, or below IBL, the live distance to each level, and flips green or red the moment either side breaks.
Day-end freeze. Lines extend forward each bar during RTH and freeze permanently at session close. New day resets cleanly.
No repaint. IB values lock when the window closes and stay frozen for the day.
How traders use the IB:
Above IBH on a strong open: trend-day potential, IBH becomes support
Below IBL on a weak open: same logic short, IBL becomes resistance
Holding inside the IB: rotational day, fade the edges
Both sides broken: distribution day, lower conviction
1x and 2x extensions act as target zones on trend days
Settings:
IB Length: 30 min or 60 min (60 default)
RTH session and timezone (defaults to 0930-1600 ET)
Bars ahead of price: how far lines project forward
Independent color, width, and style controls for IBH, IBL, IBM
Marker style: Letter Tag, Letter Circle, or Plain Circle
1x and 2x range extensions, optional
Solid color price tags at the right edge
Info table position, size, and color scheme
Alerts:
IB Locked
IBH Break
IBL Break
Recommended timeframes: 1m, 3m, 5m, 15m. Lower timeframes give cleaner extremes since the lines anchor to the exact bars that set them.
Works on any intraday timeframe. Will not load on Daily, Weekly, or Monthly since IB doesn't apply there. Indicator

Hour Stats [NQ Stats x CantoLab]A statistical tool for NQ intraday traders built around research from NQ Stats (NQStats on twitter / nqstats.com). Credit to NQ Stats for the original concept and data — published here as an open source indicator with permission.
What it does?
For each New York session hour (08:00 – 16:00 NY time), the indicator tracks a specific setup:
1)Price opens strictly inside the prior hour's range
2)Price breaches the prior hour high or low by at least 1 tick (0.25 pts)
3)Whether price reverts back to the current hour open before the hour closes
Only the first breach per hour is counted. Reversion is confirmed when any bar's wick touches or crosses the hour open after the breach occurs.
What gets plotted
When the setup triggers, the indicator draws the following levels for that hour:
Hour Open — the high probability reversion target. In Simple mode labelled as "High Prob. Retrace", in Advanced mode shows the statistical probability based on which 20-minute segment the breach occurred in
PHH / PHL Swept — marks the breached prior hour high or low
PHH / PHL Target — the opposite side of the prior hour range, the secondary target if reversion extends further
PHM (Prior Hour Mid) — the equilibrium of the prior hour range, visible in Advanced mode only
Sweep Mark — a small shape plotted on the candle where the breach is first detected (x, +, or diamond, configurable)
Vertical dividers — split each hour into its three 20-minute segments
Simple vs Advanced mode
Simple — shows Hour Open, swept level, and opposite target. Clean and uncluttered for execution focus.
Advanced — adds the Prior Hour Mid level and overlays per-segment reversion probabilities directly on the prior hour high and low, showing the statistical likelihood of reversion depending on when in the hour the breach occurs.
Advanced Mode - The 20-minute breakdown
Each hour is divided into three 20-minute windows (00–20, 20–40, 40–60). The timing of the breach within these windows significantly affects reversion probability.
As a general rule, first segment breaches carry the highest probability of reversion — the 09:00 hour first segment sits at 87.4% historically. Probabilities are pulled from 10 years of NQ data.
Settings
Mode — Simple or Advanced
Show History — keep or clear previous setups as new ones form
Time Filter — toggle NY session filter on/off, adjustable session window
Show Optimal Timeframe Message — on-chart warning if you are above 5min timeframe
Per-level toggles — color, style (Solid/Dotted/Dashed) and width for each plotted level
Sweep Mark — toggle, color, and shape
Notes
Built for NQ Futures. Behaviour on other instruments is untested
Best used on 1m – 5min timeframes. Warning displays above 5min, error displays at 60min and above
All times are New York time
Probability data is derived from 10 years of NQ historical data by @NQStats
This indicator does not provide financial advice or a complete strategy. You are responsible for how you build around and execute on this data
Indicator

Indicator

FP - SMA Crossover + Regime + Hold FilterThis indicator is the visual implementation of Strategy 270, one of the top-performing systems from my quantitative backtesting pipeline (XAUUSD H1, walk-forward OOS validation).
What it does
It identifies high-probability long entries using a three-layer confirmation system, and manages exits with a dual grace period that prevents premature closes during pullbacks within a healthy trend.
Entry conditions (all must be true):
SMA Fast (15) crosses above SMA Slow (200) — trend shift confirmed
Price is above the Regime SMA (200) — macro structure is bullish
Price is at least 0.61% above EMA200 — minimum distance from the mean, filters low-conviction setups near the line
Exit logic — two layers:
Layer 1: SMA15 crosses below SMA200, OR price has been below the Regime SMA for N consecutive bars (grace_bars = 8)
Layer 2: If the exit trigger is caused by being below the regime (not a clean crossunder), the system waits for a second confirmation window (grace_bars_2 = 12) before closing. This eliminates false exits on brief pullbacks.
Minimum hold filter:
No exit is allowed during the first 96 bars after entry (4 days on H1). This comes directly from trade analysis: in backtesting, trades closed before 96 bars had a win rate near 0% and destroyed net P&L. Trades held between 8 and 20 days showed 73% win rate. The yellow dot marks the moment the hold lock is released — from that bar onward, exits are active.
Visual elements:
🟢 Green triangle below bar — long entry signal
🔴 Red triangle above bar — exit signal
🟡 Yellow dot — hold period unlocked (exits now active)
Green background — position is open
Lines: SMA15 (orange), SMA200 (blue), EMA200 (purple dashed), Regime SMA (gray)
Three built-in alerts: entry, exit, and hold unlock.
Recommended timeframe: H1. All parameters are adjustable from the inputs panel — the defaults match the optimized backtest configuration.
This indicator does not repaint. Entry and exit signals are generated on bar close. Indicator

Indicator

NeuraLib Expansion: Advanced Model LayersNeuraLib_Models is the companion model expansion for NeuraLib .
NeuraLib provides the runtime: tensors, graph execution, datasets, scalers, losses, optimizers, training, inference, and validation tools. NeuraLib_Models builds on that foundation with higher-level neural architectures that are difficult and repetitive to write by hand.
The purpose of this expansion is to keep the main NeuraLib runtime clean, compact, and general, while giving researchers ready-to-use model families for sequence learning, attention, temporal pattern extraction, and Reinforcement Learning workflows.
----------------------------------------------------------------------------------------------------------------
🔷 HOW IT FITS INTO NEURALIB
NeuraLib_Models is built entirely on top of the public NeuraLib API. It does not replace the main runtime and it does not introduce a separate training engine.
After importing NeuraLib_Models, its fluent methods become available directly on NeuraLib `Sequential` models. The expansion alias can remain unused in the layer chain.
//@version=6
indicator("NeuraLib Models Quick Start", overlay = false, calc_bars_count = 600)
import Alien_Algorithms/NeuraLib/1 as nl
import Alien_Algorithms/NeuraLib_Models/1 as models
var nl.Sequential model = nl.sequential("advanced_model")
var float qLong = na
var float qFlat = na
var float qShort = na
if barstate.isfirst
model := model
.input(array.from(8), "sequence")
.temporalConvStack(4, 2, 2, 2, 1, 1, nl.ActivationKind.relu, 0.0, "temporal")
.globalAvgPool1d(3, 2, "pool")
.duelingQHead(4, 3, nl.ActivationKind.relu, "dueling_head")
.build(nl.rng(7))
float ret0 = na(close ) or close == 0.0 ? 0.0 : close / close - 1.0
float ret1 = na(close ) or close == 0.0 ? 0.0 : close / close - 1.0
float ret2 = na(close ) or close == 0.0 ? 0.0 : close / close - 1.0
float ret3 = na(close ) or close == 0.0 ? 0.0 : close / close - 1.0
float atrValue = ta.atr(14)
float atr0 = close == 0.0 ? 0.0 : atrValue / close
float atr1 = close == 0.0 ? 0.0 : atrValue / close
float atr2 = close == 0.0 ? 0.0 : atrValue / close
float atr3 = close == 0.0 ? 0.0 : atrValue / close
bool ready = not na(ret3) and not na(atr3)
if ready
nl.Tensor state = nl.vector(array.from(ret3, atr3, ret2, atr2, ret1, atr1, ret0, atr0), "state_window")
nl.Tensor qValues = model.predict(state)
qLong := qValues.get1d(0)
qFlat := qValues.get1d(1)
qShort := qValues.get1d(2)
plot(qLong, "Q long", color = color.lime, linewidth = 2)
plot(qFlat, "Q flat", color = color.gray)
plot(qShort, "Q short", color = color.red, linewidth = 2)
hline(0.0, "Zero", color = color.new(color.gray, 70))
The model is still a normal NeuraLib model. You still call `.compile()`, `.trainOnBatch()`, `.predict()`, `.evaluate()`, `.getWeightsArray()`, and `.softUpdateFrom()` from the main library.
----------------------------------------------------------------------------------------------------------------
🔷 WHY THIS EXPANSION EXISTS
The main NeuraLib library is the foundation. It exposes a graph engine powerful enough to create custom architectures, but repeatedly building LSTM gates, attention projections, residual blocks, Conv1D stacks, or Transformer paths from raw graph operations would be too verbose for everyday research.
NeuraLib_Models packages those patterns into readable blocks:
Temporal models : Conv1D blocks, temporal convolution stacks, global average pooling, and global max pooling for flattened sequence inputs.
Recurrent models : LSTM and GRU blocks for compact sequence memory.
Attention models : Self-attention, multi-head self-attention, cross-attention, Transformer encoder blocks, Transformer encoder stacks, and Transformer decoder blocks.
Residual models : Residual dense blocks for deeper feedforward paths.
Reinforcement Learning heads : Q-head blocks and dueling Q-heads for action-value style outputs.
Replay utilities : Deterministic Prioritized Experience Replay for reproducible Pine research.
Sequence helpers : Positional encoding for token, sequence, and attention workflows.
----------------------------------------------------------------------------------------------------------------
🔷 PRACTICAL EXAMPLES
🔸 Temporal Conv Model With Dueling Q-Head
This pattern is useful when a flattened sequence contains recent market states and the output represents action values.
//@version=6
indicator("NeuraLib Models Temporal Q Example", overlay = false, calc_bars_count = 600)
import Alien_Algorithms/NeuraLib/1 as nl
import Alien_Algorithms/NeuraLib_Models/1 as models
var nl.Sequential qModel = nl.sequential("temporal_q_model")
var nl.WindowDataset qDataset = nl.windowDataset(8, 3, 400, "q_rows")
var float qDown = na
var float qNeutral = na
var float qUp = na
var float qLoss = na
if barstate.isfirst
nl.CompileConfig cfg = nl.compileConfig()
cfg := cfg
.presetQValues()
.optimizer(nl.adamW(0.001))
.withTrainingGate(true)
qModel := qModel
.input(array.from(8), "state_window")
.temporalConvStack(4, 2, 2, 2, 1, 1, nl.ActivationKind.relu, 0.0, "temporal")
.globalAvgPool1d(3, 2, "pool")
.duelingQHead(4, 3, nl.ActivationKind.relu, "dueling_head")
.compile(cfg)
qDataset := qDataset
.setInputScaler(nl.ScalerKind.zScore)
.setTargetScaler(nl.ScalerKind.none)
float ret0 = na(close ) or close == 0.0 ? 0.0 : close / close - 1.0
float ret1 = na(close ) or close == 0.0 ? 0.0 : close / close - 1.0
float ret2 = na(close ) or close == 0.0 ? 0.0 : close / close - 1.0
float ret3 = na(close ) or close == 0.0 ? 0.0 : close / close - 1.0
float ret4 = na(close ) or close == 0.0 ? 0.0 : close / close - 1.0
float atrValue = ta.atr(14)
float atr0 = close == 0.0 ? 0.0 : atrValue / close
float atr1 = close == 0.0 ? 0.0 : atrValue / close
float atr2 = close == 0.0 ? 0.0 : atrValue / close
float atr3 = close == 0.0 ? 0.0 : atrValue / close
float atr4 = close == 0.0 ? 0.0 : atrValue / close
bool rowReady = not na(ret4) and not na(atr4)
if rowReady
array features = array.from(ret4, atr4, ret3, atr3, ret2, atr2, ret1, atr1)
float downTarget = math.max(-ret0, 0.0)
float neutralTarget = math.max(0.002 - math.abs(ret0), 0.0)
float upTarget = math.max(ret0, 0.0)
qDataset := qDataset.pushRow(features, array.from(downTarget, neutralTarget, upTarget))
if qDataset.ready(48)
if barstate.islastconfirmedhistory
nl.Batch train = qDataset.trainBatch(12)
qModel := qModel.trainOnBatch(train.inputTensor, train.targetTensor)
qLoss := qModel.trainStats.lastLoss
nl.Tensor liveState = nl.vector(array.from(ret3, atr3, ret2, atr2, ret1, atr1, ret0, atr0), "live_state")
nl.Tensor scaledState = qDataset.scaleInput(liveState)
nl.Tensor qValues = qModel.predict(scaledState)
qDown := qValues.get1d(0)
qNeutral := qValues.get1d(1)
qUp := qValues.get1d(2)
plot(qDown, "Q down", color = color.red, linewidth = 2)
plot(qNeutral, "Q neutral", color = color.gray)
plot(qUp, "Q up", color = color.lime, linewidth = 2)
plot(qLoss, "Training loss", color = color.orange)
hline(0.0, "Zero", color = color.new(color.gray, 70))
Input shape `array.from(8)` represents a flattened 4 step by 2 feature sequence. The temporal stack extracts short sequence structure, pooling compresses the sequence, and the dueling head separates value and advantage paths before producing action scores. The example trains only on the last confirmed historical bar so it remains safe to paste onto long charts.
🔸 Transformer Encoder For Token Rows
Attention models are useful when each row is a token or time step, and each column is a feature dimension.
//@version=6
indicator("NeuraLib Models Transformer Encoder Example", overlay = false, calc_bars_count = 600)
import Alien_Algorithms/NeuraLib/1 as nl
import Alien_Algorithms/NeuraLib_Models/1 as models
var nl.Sequential encoder = nl.sequential("encoder_model")
var float tokenSignal = na
var float tokenContext = na
var float tokenVolatility = na
if barstate.isfirst
encoder := encoder
.input(array.from(4), "tokens")
.multiHeadSelfAttention(4, 2, true, "mha")
.transformerEncoder(4, true, 2, nl.ActivationKind.geluApprox, "encoder", 0.05, 2)
.build(nl.rng(11))
float emaValue = ta.ema(close, 21)
float atrValue = ta.atr(14)
float ret0 = na(close ) or close == 0.0 ? 0.0 : close / close - 1.0
float ret1 = na(close ) or close == 0.0 ? 0.0 : close / close - 1.0
float ret2 = na(close ) or close == 0.0 ? 0.0 : close / close - 1.0
float ret3 = na(close ) or close == 0.0 ? 0.0 : close / close - 1.0
float emaGap0 = emaValue == 0.0 ? 0.0 : close / emaValue - 1.0
float emaGap1 = emaValue == 0.0 ? 0.0 : close / emaValue - 1.0
float emaGap2 = emaValue == 0.0 ? 0.0 : close / emaValue - 1.0
float emaGap3 = emaValue == 0.0 ? 0.0 : close / emaValue - 1.0
float atr0 = close == 0.0 ? 0.0 : atrValue / close
float atr1 = close == 0.0 ? 0.0 : atrValue / close
float atr2 = close == 0.0 ? 0.0 : atrValue / close
float atr3 = close == 0.0 ? 0.0 : atrValue / close
bool ready = not na(ret3) and not na(emaGap3) and not na(atr3)
if ready
nl.Tensor tokens = nl.vector(array.from(
ret3, emaGap3, atr3, -1.0,
ret2, emaGap2, atr2, -0.33,
ret1, emaGap1, atr1, 0.33,
ret0, emaGap0, atr0, 1.0), "tokens").reshape(array.from(4, 4))
nl.Tensor encoded = encoder.predict(tokens)
tokenSignal := encoded.get1d(12)
tokenContext := encoded.get1d(13)
tokenVolatility := encoded.get1d(14)
plot(tokenSignal, "Latest token signal", color = color.aqua, linewidth = 2)
plot(tokenContext, "Latest token context", color = color.purple)
plot(tokenVolatility, "Latest token volatility", color = color.orange)
hline(0.0, "Zero", color = color.new(color.gray, 70))
In this example, each input row has 4 features. `headCount` is 2, so the model dimension is split into two attention heads.
Attention rule: `modelDim` must be divisible by `headCount`, and the current implementation supports up to 8 heads.
🔸 Prioritized Experience Replay
Prioritized Experience Replay stores examples with priorities, then returns reproducible weighted samples. This is especially useful for Reinforcement Learning experiments where high-error transitions should be revisited more often.
//@version=6
indicator("NeuraLib Models PER Example", overlay = false, calc_bars_count = 1200)
import Alien_Algorithms/NeuraLib/1 as nl
import Alien_Algorithms/NeuraLib_Models/1 as models
var models.PrioritizedReplayBuffer replay = models.prioritizedReplayBuffer(4, 2, 300, "replay")
var nl.Sequential replayModel = nl.sequential("replay_q_model")
var float replayLoss = na
var float firstImportanceWeight = na
var float replayRows = na
if barstate.isfirst
nl.CompileConfig cfg = nl.compileConfig()
cfg := cfg
.presetQValues()
.optimizer(nl.adamW(0.001))
.trainEveryCall()
replayModel := replayModel
.input(array.from(4), "state")
.dense(8, nl.ActivationKind.relu, "hidden")
.qHead(2, nl.ActivationKind.linear, "q_values")
.compile(cfg)
float rsiValue = ta.rsi(close, 14)
float emaValue = ta.ema(close, 21)
float atrValue = ta.atr(14)
float atrPct = close == 0.0 ? 0.0 : atrValue / close
float momentum = na(close ) or close == 0.0 ? 0.0 : close / close - 1.0
float nextReturn = na(close ) ? 0.0 : nl.nextReturnValue(close , close)
bool rowReady = not na(rsiValue ) and not na(emaValue ) and not na(atrPct ) and not na(momentum )
if rowReady
float prevEma = emaValue
float priceVsEma = prevEma == 0.0 ? 0.0 : close / prevEma - 1.0
array stateFeatures = array.from(rsiValue / 100.0, priceVsEma, atrPct , momentum )
array targetValues = array.from(math.max(-nextReturn, 0.0), math.max(nextReturn, 0.0))
float priority = math.abs(nextReturn) + 0.0001
replay := replay.pushExperience(stateFeatures, targetValues, priority)
replayRows := float(replay.size())
if replay.ready(32)
models.PrioritizedReplaySample sample = replay.sampleBatch(32, 0.6, 0.4, 17)
replayModel := replayModel.trainOnBatch(sample.batch.inputTensor, sample.batch.targetTensor)
replayLoss := replayModel.trainStats.lastLoss
firstImportanceWeight := sample.weightArray.size() > 0 ? sample.weightArray.get(0) : na
if sample.indexArray.size() > 0
replay := replay.updatePriority(sample.indexArray.get(0), replayLoss + 0.0001)
plot(replayLoss, "Replay training loss", color = color.orange, linewidth = 2)
plot(firstImportanceWeight, "First sample weight", color = color.aqua)
The returned sample includes:
batch : A normal NeuraLib `Batch` containing sampled inputs and targets.
indexArray : Logical replay indices that can be passed back to `updatePriority()`.
weightArray : Normalized importance weights for custom loss weighting or diagnostics.
sampleRows : Number of sampled rows.
PER sampling is deterministic for a given buffer, `batchSize`, and `seed`. That makes Pine tests and live research easier to reproduce.
----------------------------------------------------------------------------------------------------------------
🔷 MODEL FAMILIES
🔸 Residual Dense Blocks
`residualDense()` adds a feedforward residual block. Residual paths help preserve information through deeper models and reduce the chance that a dense stack destroys useful features too early.
🔸 Conv1D And Temporal Convolution Stacks
`conv1d()` and `temporalConvStack()` operate on flattened sequence inputs. A sequence with `timeSteps = 4` and `featureCount = 2` is represented as 8 input features. These blocks are useful for local temporal structure, short rolling windows, feature rhythm, and compact pattern extraction.
🔸 Global Pooling
`globalAvgPool1d()` and `globalMaxPool1d()` compress flattened sequence outputs into feature-level summaries. Average pooling captures broad sequence behavior, while max pooling emphasizes the strongest activation per feature.
🔸 LSTM And GRU Blocks
`lstm()` and `gru()` provide recurrent sequence memory over flattened time-series inputs. They are useful when the order of recent states matters more than a single snapshot.
🔸 Attention And Transformers
`selfAttention()`, `multiHeadSelfAttention()`, `crossAttention()`, `transformerEncoder()`, `transformerEncoderStack()`, and `transformerDecoder()` bring attention-style modeling into Pine. They are designed for compact token matrices, packed target-memory layouts, and small Transformer-style research models that fit PulseWire limits.
🔸 Q-Heads And Dueling Q-Heads
`qHeadBlock()` creates action-value style outputs. `duelingQHead()` splits the model into value and advantage branches, then recombines them into Q-values. This is useful when you want the model to estimate both the overall state value and the relative value of each action.
🔸 Positional Encoding
`pushPositionalEncoding()` adds sinusoidal position features to a NeuraLib `FeatureBuilder`. This helps attention-style models distinguish where a token or time step sits in a sequence.
----------------------------------------------------------------------------------------------------------------
🔷 FEATURE QUICK REFERENCE
Built on NeuraLib : Uses the main NeuraLib graph, tensor, training, optimizer, dataset, and inference runtime.
Fluent API : Adds methods directly to NeuraLib `Sequential` models after import.
Block factories : Provides standalone `GraphBlock` factories for users who want lower-level composition.
Temporal modeling : Conv1D, temporal convolution stacks, and 1D pooling.
Recurrent modeling : LSTM and GRU sequence blocks.
Attention modeling : Self-attention, multi-head self-attention, cross-attention, encoders, encoder stacks, and decoders.
Reinforcement Learning support : Q-heads, dueling Q-heads, target-model soft updates through NeuraLib, and Prioritized Experience Replay.
Reproducible replay : PER sampling is deterministic for a given seed.
Shape guardrails : Advanced builders validate expected model feature counts and attention head compatibility.
----------------------------------------------------------------------------------------------------------------
🔷 IMPORTANT USAGE NOTES
Import order matters : Import `NeuraLib` first, then `NeuraLib_Models`.
The alias can be unused : The imported expansion registers methods on NeuraLib types, so `.lstm()`, `.gru()`, `.transformerEncoder()`, and similar methods can be called in the model chain.
Keep models compact : Pine Script has execution limits. Start with small hidden sizes, short sequences, and low head counts.
Control chart history : Use `calc_bars_count = 600` in `indicator()` when needed to balance available training history against model size and execution time.
Respect sequence shapes : Conv1D, temporal stacks, LSTM, and GRU methods expect flattened sequence sizes of `timeSteps * featureCount`.
Respect attention shapes : Attention methods expect each input row to have `modelDim` columns. Cross-attention and decoder blocks use packed rows.
Use NeuraLib guardrails : Train/validation splits, scalers, EarlyStopper, training gates, and gradient clipping remain part of the main NeuraLib workflow.
----------------------------------------------------------------------------------------------------------------
🔷 API REFERENCE
🔸 Sequential Methods
residualDense(hiddenUnits, activationKind, dropoutRate, name) : Adds a residual dense block.
duelingQHead(hiddenUnits, actionCount, activationKind, name) : Adds a dueling value/advantage Q-head.
conv1d(timeSteps, featureCount, filters, kernelSize, stride, activationKind, name) : Adds a Conv1D block for flattened sequences.
temporalConvStack(timeSteps, featureCount, filters, kernelSize, layers, stride, activationKind, dropoutRate, name) : Adds stacked temporal Conv1D layers.
globalAvgPool1d(timeSteps, featureCount, name) : Adds global average pooling over a flattened 1D sequence.
globalMaxPool1d(timeSteps, featureCount, name) : Adds global max pooling over a flattened 1D sequence.
lstm(timeSteps, featureCount, units, activationKind, name) : Adds an LSTM scan block.
gru(timeSteps, featureCount, units, activationKind, name) : Adds a GRU scan block.
selfAttention(modelDim, causal, name) : Adds row-wise self-attention.
multiHeadSelfAttention(modelDim, headCount, causal, name) : Adds multi-head self-attention.
crossAttention(queryRows, memoryRows, modelDim, headCount, name) : Adds packed query-memory cross-attention.
transformerEncoder(modelDim, causal, ffMultiplier, activationKind, name, dropoutRate, headCount) : Adds one Transformer encoder block.
transformerEncoderStack(modelDim, layers, causal, ffMultiplier, activationKind, dropoutRate, headCount, name) : Adds repeated Transformer encoder blocks.
transformerDecoder(targetRows, memoryRows, modelDim, headCount, ffMultiplier, activationKind, dropoutRate, name) : Adds a packed target-memory Transformer decoder.
🔸 GraphBlock Factories
qHeadBlock(inputFeatures, actionCount, activationKind, name) : Creates a Q-head block.
duelingQHeadBlock(inputFeatures, hiddenUnits, actionCount, activationKind, name) : Creates a dueling Q-head block.
residualDenseBlock(inputFeatures, hiddenUnits, activationKind, dropoutRate, name) : Creates a residual dense block.
conv1dBlock(timeSteps, featureCount, filters, kernelSize, stride, activationKind, name) : Creates a Conv1D block.
temporalConvStackBlock(timeSteps, featureCount, filters, kernelSize, layers, stride, activationKind, dropoutRate, name) : Creates a temporal convolution stack.
globalAvgPool1dBlock(timeSteps, featureCount, name) and globalMaxPool1dBlock(timeSteps, featureCount, name) : Create pooling blocks.
lstmBlock(timeSteps, featureCount, units, activationKind, name) and gruBlock(timeSteps, featureCount, units, activationKind, name) : Create recurrent blocks.
selfAttentionBlock(modelDim, causal, name) , multiHeadSelfAttentionBlock(modelDim, headCount, causal, name) , and crossAttentionBlock(queryRows, memoryRows, modelDim, headCount, name) : Create attention blocks.
transformerEncoderBlock(modelDim, causal, ffMultiplier, activationKind, name, dropoutRate, headCount) and transformerDecoderBlock(targetRows, memoryRows, modelDim, headCount, ffMultiplier, activationKind, dropoutRate, name) : Create Transformer blocks.
🔸 Prioritized Experience Replay
prioritizedReplayBuffer(featureCount, targetCount, maxRows, name) : Creates a replay buffer.
pushExperience(featureRowArray, targetRowArray, priority) : Adds or overwrites one replay row.
sampleBatch(batchSize, alpha, beta, seed) : Returns a deterministic weighted sample.
updatePriority(index, priority) : Updates a sampled row priority.
toBatch() : Returns all replay rows in chronological order.
ready(minRows) , size() , and clear() : Replay buffer utilities.
🔸 Feature Helpers
pushPositionalEncoding(position, dimensions, maxPeriod, featurePrefix) : Appends sinusoidal positional encoding values to a NeuraLib `FeatureBuilder`.
NeuraLib_Models is for Pine Script developers who want higher-level neural architecture blocks without leaving the NeuraLib runtime. It is built for compact research models inside PulseWire's execution limits, not for oversized GPU-style networks.
All the diagrams in this publication are rendered natively on PulseWire using Pine3D
----------------------------------------------------------------------------------------------------------------
This work is licensed under (CC BY-NC-SA 4.0) , meaning usage is free for non-commercial purposes given that Alien_Algorithms is credited in the description for the underlying software. For commercial use licensing, contact Alien_Algorithms
Library
