Continuous Accumulation Strategy [DCA] v9🇬🇧 English: Continuous Accumulation Strategy   v9.4 
This script is a full-featured  strategy  designed to backtest the "Buy the Dip" or "Dollar Cost Averaging" (DCA) philosophy. Its core feature is the  Dynamic Peak Detection  logic, which solves the "lock-in" problem of previous versions. Instead of getting stuck on an old high, the strategy constantly adapts to the market by referencing the most recent peak.
 Key Features 
*    Dynamic Peak Detection:  You define the "Peak Lookback Period." For example, on a Daily chart, setting it to `5` references the peak of the last business week.
*    Stable Order Management:  The strategy consistently uses a  fixed cash amount  (e.g., $100) for each entry, which prevents any runtime errors related to negative equity.
*    Publishing-Ready:  To meet TradingView's requirement for a backtest report, this strategy executes a symbolic, one-time "dummy trade" (one buy and one sell) at the very beginning of the test period.  This first trade should be ignored when analyzing performance , as its only purpose is to enable publication.
 How It Works 
The main logic follows an adaptive cycle:  Find Dynamic Peak -> Wait for a Drop -> Buy on Crossover -> Repeat. 
1.   Finds the Dynamic Peak:  On every bar, it identifies the highest price within your defined lookback period.
2.   Calculates the Drop:  It constantly calculates the percentage drop from this moving peak.
3.   Executes an Entry:  The moment the price crosses below a target drop percentage, it executes a buy order.
4.   Continuously Adapts:  As the price moves, the dynamic peak is constantly updated, meaning the strategy never gets locked and is always ready for the next opportunity.
 How to Use This Strategy 
*    Focus on the Strategy Tester:  After adding it to the chart, analyze the  Equity Curve, Net Profit, and Max Drawdown  to see how this accumulation philosophy would have performed on your favorite asset.
*    Optimize Parameters:  Adjust the "Peak Lookback Period" and "Drop Percentages" to fit the volatility of the asset you are testing.
This is a tool for  testing and analyzing  a "buy and accumulate" philosophy. Its main logic does  not  generate sell signals.
Cari dalam skrip untuk "one一季度财报"
Trend FriendTrend Friend — What it is and how to use it
I built Trend Friend to stop redrawing the same trendlines all day. It automatically connects confirmed swing points (fractals) and keeps the most relevant lines in front of you. The goal: give you clean, actionable structure without the guesswork.
What it does (in plain English)
Finds swing highs/lows using a Fractal Period you choose.
Draws auto-trendlines between the two most recent confirmed highs and the two most recent confirmed lows.
Colours by intent:
Lines drawn from highs (potential resistance / bearish) = Red
Lines drawn from lows (potential support / bullish) = Green
Keeps the chart tidy: The newest lines are styled as “recent,” older lines are dimmed as “historical,” and it prunes anything beyond your chosen limit.
Optional crosses & alerts: You can highlight when price closes across the most recent line and set alerts for new lines formed and upper/lower line crosses.
Structure labels: It tags HH, LH, HL, LL at the swing points, so you can quickly read trend/rotation.
How it works (under the hood)
A “fractal” here is a confirmed pivot: the highest high (or lowest low) with n bars on each side. That means pivots only confirm after n bars, so signals are cleaner and less noisy.
When a new pivot prints, the script connects it to the prior pivot of the same type (high→high, low→low). That gives you one “bearish” line from highs and one “bullish” line from lows.
The newest line is marked as recent (brighter), and the previous recent line becomes historical (dimmed). You can keep as many pairs as you want, but I usually keep it tight.
Inputs you’ll actually use
Fractal Period (n): this is the big one. It controls how swingy/strict the pivots are.
Lower n → more swings, more lines (faster, noisier)
Higher n → fewer swings, cleaner lines (slower, swing-trade friendly)
Max pair of lines: how many pairs (up+down) to keep on the chart. 1–3 is a sweet spot.
Extend: extend lines Right (my default) or Both ways if you like the context.
Line widths & colours: recent vs. historical are separate so you can make the active lines pop.
Show crosses: toggle the X markers when price crosses a line. I turn this on when I’m actively hunting breakouts/retests.
Reading the chart
Red lines (from highs): I treat these as potential resistance. A clean break + hold above a red line often flips me from “fade” to “follow.”
Green lines (from lows): Potential support. Same idea in reverse: break + hold below and I stop buying dips until I see structure reclaim.
HH / LH / HL / LL dots: quick read on structure.
HH/HL bias = uptrend continuation potential
LH/LL bias = downtrend continuation potential
Mixed prints = rotation/chop—tighten risk or wait for clarity.
My H1 guidance (fine-tuning Fractal Period)
If you’re mainly on H1 (my use case), tune like this:
Fast / aggressive: n = 6–8 (lots of signals, good for momentum days; more chop risk)
Balanced (recommended): n = 9–12 (keeps lines meaningful but responsive)
Slow / swing focus: n = 13–21 (filters noise; better for trend days and higher-TF confluence)
Rule of thumb: if you’re getting too many touches and whipsaws, increase n. If you’re late to obvious breaks, decrease n.
How I trade it (example workflow)
Pick your n for the session (H1: start at 9–12).
Mark the recent red & green lines. That’s your immediate structure.
Look for interaction:
Rejections from a line = fade potential back into the range.
Break + close across a line = watch the retest for continuation.
Confirm with context: session bias, HTF structure, and your own tools (VWAP, RSI, volume, FVG/OB, etc.).
Plan the trade: enter on retest or reclaim, stop beyond the line/last swing, target the opposite side or next structure.
Alerts (set and forget)
“New trendline formed” — fires when a new high/low pivot confirms and a fresh line is drawn.
“Upper/lower trendline crossed” — fires when price crosses the most recent red/green line.
Use these to track structure shifts without staring at the screen.
Good to know (honest limitations)
Confirmation lag: pivots need n bars on both sides, so signals arrive after the swing confirms. That’s by design—less noise, fewer fake lines.
Lines update as structure evolves: when a new pivot forms, the previous “recent” line becomes “historical,” and older ones can be removed based on your max setting.
Not an auto trendline crystal ball: it won’t predict which line holds or breaks—it just keeps the most relevant structure clean and up to date.
Final notes
Works on any timeframe; I built it with H1 in mind and scale to H4/D1 by increasing n.
Pairs nicely with session tools and VWAP for intraday, or with supply/demand / FVGs for swing planning.
Risk first: lines are structure, not guarantees. Manage position size and stops as usual.
Not financial advice. Trade your plan. Stay nimble.
RSI ADX Bollinger Analysis High-level purpose and design philosophy
 This indicator — RSI-ADX-Bollinger Analysis  — is a compact, educational market-analysis toolkit that blends momentum (RSI), trend strength (ADX), volatility structure (Bollinger Bands) and simple volumetrics to provide traders a snapshot of market condition and trade idea quality. The design philosophy is explicit and layered: use each component to answer a different question about price action (momentum, conviction, volatility, participation), then combine answers to form a more robust, explainable signal. The mashup is intended for analysis and learning, not automatic execution: it surfaces the why behind signals so traders can test, learn and apply rules with risk management.
________________________________________
What each indicator contributes (component-by-component)
RSI (Relative Strength Index) — role and behavior: RSI measures short-term momentum by comparing recent gains to recent losses. A high RSI (near or above the overbought threshold) indicates strong recent buying pressure and potential exhaustion if price is extended. A low RSI (near or below the oversold threshold) indicates strong recent selling pressure and potential exhaustion or a value area for mean-reversion. In this dashboard RSI is used as the primary momentum trigger: it helps identify whether price is locally over-extended on the buy or sell side.
ADX (Average Directional Index) — role and behavior: ADX measures trend strength independently of direction. When ADX rises above a chosen threshold (e.g., 25), it signals that the market is trending with conviction; ADX below the threshold suggests range or weak trend. Because patterns and momentum signals perform differently in trending vs. ranging markets, ADX is used here as a filter: only when ADX indicates sufficient directional strength does the system treat RSI+BB breakouts as meaningful trade candidates.
Bollinger Bands — role and behavior: Bollinger Bands (20-period basis ± N standard deviations) show volatility envelope and relative price position vs. a volatility-adjusted mean. Price outside the upper band suggests pronounced extension relative to recent volatility; price outside the lower band suggests extended weakness. A band expansion (increasing width) signals volatility breakout potential; contraction signals range-bound conditions and potential squeeze. In this dashboard, Bollinger Bands provide the volatility/structural context: RSI extremes plus price beyond the band imply a stronger, volatility-backed move.
Volume split & basic MA trend — role and behavior: Buy-like and sell-like volume (simple heuristic using close>open or closeopen) or sell-like (close1.2 for validation and compare win rate and expectancy.
4.	TF alignment: Accept signals only when higher timeframe (e.g., 4h) trend agrees — compare results.
5.	Parameter sensitivity: Vary RSI threshold (70/30 vs 80/20), Bollinger stddev (2 vs 2.5), and ADX threshold (25 vs 30) and measure stability of results.
These exercises teach both statistical thinking and the specific failure modes of the mashup.
________________________________________
Limitations, failure modes and caveats (explicit & teachable)
• ADX and Bollinger measures lag during fast-moving news events — signals can be late or wrong during earnings, macro shocks, or illiquid sessions.
• Volume classification by open/close is a heuristic; it does not equal TAPEDATA, footprint or signed volume. Use it as supportive evidence, not definitive proof.
• RSI can remain overbought or oversold for extended stretches in persistent trends — relying solely on RSI extremes without ADX or BB context invites large drawdowns.
• Small-cap or low-liquidity instruments yield noisy band behavior and unreliable volume ratios.
Being explicit about these limitations is a strong point in a TradingView description — it demonstrates transparency and educational intent.
________________________________________
Originality & mashup justification (text you can paste)
This script intentionally combines classical momentum (RSI), volatility envelope (Bollinger Bands) and trend-strength (ADX) because each indicator answers a different and complementary question: RSI answers is price locally extreme?, Bollinger answers is price outside normal volatility?, and ADX answers is the market moving with conviction?. Volume participation then acts as a practical check for real market involvement. This combination is not a simple “indicator mashup”; it is a designed ensemble where each element reduces the others’ failure modes and together produce a teachable, testable signal framework. The script’s purpose is educational and analytical — to show traders how to interpret the interplay of momentum, volatility, and trend strength.
________________________________________
TradingView publication guidance & compliance checklist
To satisfy TradingView rules about mashups and descriptions, include the following items in your script description (without exposing source code):
1.	Purpose statement: One or two lines describing the script’s objective (educational multi-indicator market overview and idea filter).
2.	Component list: Name the major modules (RSI, Bollinger Bands, ADX, volume heuristic, SMA trend checks, signal tracking) and one-sentence reason for each.
3.	How they interact: A succinct non-code explanation: “RSI finds momentum extremes; Bollinger confirms volatility expansion; ADX confirms trend strength; all three must align for a BUY/SELL.”
4.	Inputs: List adjustable inputs (RSI length and thresholds, BB length & stddev, ADX threshold & smoothing, volume MA, table position/size).
5.	Usage instructions: Short workflow (check TF alignment → confirm participation → define stop & R:R → backtest).
6.	Limitations & assumptions: Explicitly state volume is approximated, ADX has lag, and avoid promising guaranteed profits.
7.	Non-promotional language: No external contact info, ads, claims of exclusivity or guaranteed outcomes.
8.	Trademark clause: If you used trademark symbols, remove or provide registration proof.
9.	Risk disclaimer: Add the copy-ready disclaimer below.
This matches TradingView’s request for meaningful descriptions that explain originality and inter-component reasoning.
________________________________________
Copy-ready short publication description (paste into TradingView)
Advanced RSI-ADX-Bollinger Market Overview — educational multi-indicator dashboard. This script combines RSI (momentum extremes), Bollinger Bands (volatility envelope and band expansion), ADX (trend strength), simple SMA trend bias and a basic buy/sell volume heuristic to surface high-quality idea candidates. Signals require alignment of momentum, volatility expansion and rising ADX; volume participation is displayed to support signal confidence. Inputs are configurable (RSI length/levels, BB length/stddev, ADX length/threshold, volume MA, display options). This tool is intended for analysis and learning — not for automated execution. Users should back test and apply robust risk management. Limitations: volume classification here is a heuristic (close>open), ADX and BB measures lag in fast news events, and results vary by instrument liquidity.
________________________________________
Copy-ready risk & misuse disclaimer (paste into description or help file)
This script is provided for educational and analytical purposes only and does not constitute financial or investment advice. It does not guarantee profits. Indicators are heuristics and may give false or late signals; always back test and paper-trade before using real capital. The author is not responsible for trading losses resulting from the use or misuse of this indicator. Use proper position sizing and risk controls.
________________________________________
Risk Disclaimer: This tool is provided for education and analysis only. It is not financial advice and does not guarantee returns. Users assume all risk for trades made based on this script. Back test thoroughly and use proper risk management.
EMA Cross Alert V666 [noFuck]EMA Cross Alert — What it does 
EMA Cross Alert watches three EMAs (Short, Mid, Long), detects their crossovers, and reports exactly one signal per bar by priority: EARLY > Short/Mid > Mid/Long > Short/Long. Optional EARLY mode pings when Short crosses Long while Mid is still between them—your polite early heads-up.
 Why you might like it 
 
  Three crossover types: s/m, m/l, s/l
  EARLY detection: earlier hints, not hype
  One signal per bar: less noise, more focus
  Clear visuals: tags, big cross at signal price, EARLY triangles
  Alert-ready: dynamic alert text on bar close + static alertconditions for UI
 
 Inputs (plain English) 
 
  Short/Mid/Long EMA length — how fast each EMA reacts
  Extra EMA length (visual only) — context EMA; does not affect signals
  Price source — e.g., Close
  Show cross tags / EARLY triangles / large cross — visual toggles
  Enable EARLY signals (Short/Long before Mid) — turn early pings on/off
  Count Mid EMA as "between" even when equal (inclusive) — ON: Mid counts even if exactly equal to Short or Long; OFF (default): Mid must be strictly between them
  Enable dynamic alerts (one per bar close) — master alert switch
  Alert on Short/Mid, Mid/Long, Short/Long, EARLY — per-signal alert toggles
 
 Quick tips 
 
  Start with defaults; if you want more EARLY on smooth/low-TF markets, turn “inclusive” ON
  Bigger lengths = calmer trend-following; smaller = faster but choppier
  Combine with volume/structure/risk rules—the indicator is the drummer, not the whole band
 
 Disclaimer 
Alerts, labels, and triangles are not trade ideas or financial advice. They are informational signals only. You are responsible for entries, exits, risk, and position sizing. Past performance is yesterday; the future is fashionably late.
 Credits 
Built with the enthusiastic help of Code Copilot (AI)—massively involved, shamelessly proud, and surprisingly good at breakfasting on exponential moving averages.
Pivot Points mura visionWhat it is 
A clean, single-set pivot overlay that lets you choose the pivot  type  (Traditional/Fibonacci), the  anchor timeframe  (Daily/Weekly/Monthly/Quarterly, or Auto), and fully customize  colors, line width/style , and  labels . The script never draws duplicate sets—exactly one pivot pack is displayed for the chosen (or auto-detected) anchor.
 How it works 
 
 Pivots are computed with ta.pivot_point_levels() for the selected  anchor timeframe .
 The script supports the standard 7 levels:  P, R1/S1, R2/S2, R3/S3 .
 Lines span exactly one anchor period forward from the current bar time.
 Label suffix shows the anchor source:  D  (Daily),  W  (Weekly),  M  (Monthly),  Q  (Quarterly).
 
 Auto-anchor logic 
 
 Intraday ≤ 15 min → Daily pivots (D) 
 Intraday 20–120 min → Weekly pivots (W) 
 Intraday > 120 min (3–4 h) → Monthly pivots (M) 
 Daily and above → Quarterly pivots (Q) 
 
This keeps the chart readable while matching the most common trader expectations across timeframes.
 Inputs 
 
 Pivot Type  — Traditional or Fibonacci.
 Pivots Timeframe  — Auto, Daily (1D), Weekly (1W), Monthly (1M), Quarterly (3M).
 Line Width / Line Style  — width 1–10; style Solid, Dashed, or Dotted.
 Show Labels / Show Prices  — toggle level tags and price values.
 Colors  — user-selectable colors for  P, R*, S* .
 
 How to use 
 
 Pick a symbol/timeframe.
 Leave  Pivots Timeframe = Auto  to let the script choose; or set a fixed anchor if you prefer.
 Toggle  labels  and  prices  to taste; adjust  line style/width  and  colors  for your theme.
 Read the market like a map:
   
 P  often acts as a mean/rotation point.
 R1/S1  are common first reaction zones;  R2/S2  and  R3/S3  mark stronger extensions.
 Confluence with S/R, trendlines, session highs/lows, or volume nodes improves context.
 
 Good practices 
 
 Use  Daily pivots  for intraday scalps (≤15m).
 Use  Weekly/Monthly  for swing bias on 1–4 h.
 Use  Quarterly  when analyzing on Daily and higher to frame larger cycles.
 Combine with trend filters (e.g., EMA/KAMA 233) or volatility tools for entries and risk.
 
 Notes & limitations 
 
 The script shows  one  pivot pack at a time by design (prevents clutter and duplicates).
 Historical values follow TradingView’s standard pivot definitions; results can vary across assets/exchanges.
 No alerts are included (levels are static within the anchor period).
Market Pulse Dip RadarThis indicator is designed to help traders spot meaningful dips in price and then evaluate whether those dips are worth trading or not. It doesn’t just mark a dip; it also helps with risk management, trade planning, and filtering out weak signals.
Here’s how it works:
First, it looks at the recent high price and checks how much the market has dropped from that high. If the drop is larger than the minimum percentage you set, it marks it as a potential dip.
Next, it checks the trend structure by using two moving averages (a fast one and a slow one). If the fast average is below the slow average, it means the market is in a weaker structure, and that dip is considered more valid.
On top of that, you can enable a multi-timeframe filter. For example, if you are trading on the 15-minute chart, you can ask the indicator to confirm that the 1-hour trend is also supportive before showing you a dip. This helps avoid trading against the bigger trend.
Risk management is built in. The indicator automatically suggests a stop-loss by combining volatility (ATR) and recent swing lows. It then draws three profit target levels (1x risk, 2x risk, and 3x risk). This makes it easier to plan where to exit if the trade works.
A key part of this tool is the confidence score. Each dip signal is rated from 0 to 100. The score depends on how deep the dip is, how far apart the moving averages are, how healthy volatility is, and whether the higher timeframe supports the trade. The score is then labeled as High, Medium, Low, or Wait. This helps traders focus only on the stronger setups.
On the chart, dip signals are marked with a diamond shape under the bars. The color of the diamond tells you if it’s high, medium, or low quality. When a signal appears, the indicator also plots horizontal lines for the entry, stop, and targets.
To make it easier to read, there is also a dashboard box that shows the current score, quality, dip percentage, and suggested stop-loss. This means you don’t have to calculate or check different things yourself – everything is visible in one place.
Finally, it comes with alerts. You can set alerts for when a dip signal happens, or when it’s medium or high confidence. This way, you don’t need to stare at charts all day; TradingView can notify you.
So in short, this tool:
•	Finds dips based on your rules.
•	Filters them using structure, volatility, and higher timeframe trend.
•	Suggests stop-loss and profit targets.
•	Rates each dip with a confidence score.
•	Shows all this info in a clean dashboard and alerts you when it happens.
👉 Do you want me to now explain how a trader would actually use it in practice (step by step, from signal to trade)?
Mikula's Master 360° Square of 12Mikula’s Master 360° Square of 12 
An educational W. D. Gann study indicator for price and time. Anchor a compact Square of 12 table to a start point you choose. Begin from a bar’s High or Low (or set a manual start price). From that anchor you can progress or regress the table to study how price steps through cycles in either direction.
 What you’re looking at :
Zodiac rail (far left): the twelve signs.
Degree rail: 24 rows in 15° steps from 15° up to 360°/0°.
Transit rail and Natal rail: track one planet per rail. Each planet is placed at its current row (℞ shown when retrograde). As longitude advances, the planet climbs bottom → top, then wraps to the bottom at the next sign; during retrograde it steps downward.
Hover a planet’s cell to see a tooltip with its exact longitude and sign (e.g., 152.4° ♌︎). The linked price cell in the grid moves with the planet’s row so you can follow a planet’s path through the zodiac as a path through price.
Price grid (right): the 12×24 Square of 12. Each column is a cycle; cells are stepped price levels from your start price using your increment.
Bottom rail: shows the current square number and labels the twelve columns in that square.
 How the square is read 
The square always begins at the bottom left. Read each column bottom → top. At the top, return to the bottom of the next column and read up again. One square contains twelve cycles. Because the anchor can be a High or a Low, you can progress the table upward from the anchor or regress it downward while keeping the same bottom-to-top reading order.
 Iterate Square (shifting) 
Iterate Square shifts the entire 12×24 grid to the next set of twelve cycles.
Square 1 shows cycles 1–12; Square 2 shows 13–24; Square 3 shows 25–36, etc.
 Visibility rules 
Pivot cells are table-bound. If you shift the square beyond those prices, their highlights won’t appear in the table.
A/B levels and Transit/Natal planetary lines are chart overlays and can remain visible on the table as you shift the square.
 Quick use 
Choose an anchor (date/time + High/Low) or  enable a manual start price .
Set the increment. If you anchored with a Low and want the table to step downward from there, use a negative value.
Optional: pick Transit and Natal planets (one per rail), toggle their plots, and hover their cells for longitude/sign.
Optional: turn on A/B levels to display repeating bands from the start price.
Optional: enable swing pivots to tint matching cells after the anchor.
Use Iterate Square to shift to later squares of twelve cycles.
 Examples 
These are exploratory examples to spark ideas:
Overview layout (zodiac & degree rails, Transit/Natal rails, price grid)
  
A-levels plotted, pivots tinted on the table, real-time price highlighted
  
Drawing angles from the anchor using price & time read from the table
  
Using a TradingView Gann box along the A-levels to study reactions
  
 Attribution & originality 
  
This script is an original implementation (no external code copied). Conceptual credit to Patrick Mikula, whose discussion of the Master 360° Square of 12 inspired this study’s presentation.
 Further reading (neutral pointers) 
Patrick Mikula, Gann’s Scientific Methods Unveiled, Vol. 2, “W. D. Gann’s Use of the Circle Chart.”
W. D. Gann’s Original Commodity Course (as provided by WDGAN.com).
No affiliation implied.
License CC BY-NC-SA 4.0 (non-commercial; please attribute @Javonnii and link the original).
Dependency AstroLib by @BarefootJoey
Disclaimer Educational use only; not financial advice.
DYNAMIC TRADING DASHBOARDStudy Material for the "Dynamic Trading Dashboard"
 This Dynamic Trading Dashboard is designed as an educational tool within the TradingView environment. It compiles commonly used market indicators and analytical methods into one visual interface so that traders and learners can see relationships between indicators and price action. Understanding these indicators, step by step, can help traders develop discipline, improve technical analysis skills, and build strategies. Below is a detailed explanation of each module.
________________________________________
 1. Price and Daily Reference Points
 The dashboard displays the current price, along with percentage change compared to the day’s opening price. It also highlights whether the price is moving upward or downward using directional symbols. Alongside, it tracks daily high, low, open, and daily range.
For traders, daily levels provide valuable reference points. The daily high and low are considered intraday support and resistance, while the median price of the day often acts as a pivot level for mean reversion traders. Monitoring these helps learners see how price oscillates within daily ranges.
________________________________________
 2. VWAP (Volume Weighted Average Price)
 VWAP is calculated as a cumulative average price weighted by volume. The dashboard compares the current price with VWAP, showing whether the market is trading above or below it.
For traders, VWAP is often a guide for institutional order flow. Price trading above VWAP suggests bullish sentiment, while trading below VWAP indicates bearish sentiment. Learners can use VWAP as a training tool to recognize trend-following vs. mean reversion setups.
________________________________________
 3. Volume Analysis
 The system distinguishes between buy volume (when the closing price is higher than the open) and sell volume (when the closing price is lower than the open). A progress bar highlights the ratio of buying vs. selling activity in percentage.
This is useful because volume confirms price action. For instance, if prices rise but sell volume dominates, it can signal weakness. New traders learning with this tool should focus on how volume often precedes price reversals and trends.
________________________________________
 4. RSI (Relative Strength Index)
 RSI is a momentum oscillator that measures price strength on a scale from 0 to 100. The dashboard classifies RSI readings into overbought (>70), oversold (<30), or neutral zones and adds visual progress bars.
RSI helps learners understand momentum shifts. During training, one should notice how trending markets can keep RSI extended for longer periods (not immediate reversal signals), while range-bound markets react more sharply to RSI extremes. It is an excellent tool for practicing trend vs. range identification.
________________________________________
 5. MACD (Moving Average Convergence Divergence)
 The MACD indicator involves a fast EMA, slow EMA, and signal line, with focus on crossovers. The dashboard shows whether a “bullish cross” (MACD above signal line) or “bearish cross” (MACD below signal line) has occurred.
MACD teaches traders to identify trend momentum shifts and divergence. During practice, traders can explore how MACD signals align with VWAP trends or RSI levels, which helps in building a structured multi-indicator analysis.
________________________________________
 6. Stochastic Oscillator
 This indicator compares the current close relative to a range of highs and lows over a period. Displayed values oscillate between 0 and 100, marking zones of overbought (>80) and oversold (<20).
Stochastics are useful for students of trading to recognize short-term momentum changes. Unlike RSI, it reacts faster to price volatility, so false signals are common. Part of the training exercise can be to observe how stochastic “flips” can align with volume surges or daily range endpoints.
________________________________________
 7. Trend & Momentum Classification
 The dashboard adds simple labels for trend (uptrend, downtrend, neutral) based on RSI thresholds. Additionally, it provides quick momentum classification (“bullish hold”, “bearish hold”, or neutral).
This is beneficial for beginners as it introduces structured thinking: differentiating long-term market bias (trend) from short-term directional momentum. By combining both, traders can practice filtering signals instead of trading randomly.
________________________________________
 8. Accumulation / Distribution Bias
 Based on RSI levels, the script generates simplified tags such as “Accumulate Long”, “Accumulate Short”, or “Wait”.
This is purely an interpretive guide, helping learners think in terms of accumulation phases (when markets are low) and distribution phases (when markets are high). It reinforces the concept that trading is not only directional but also involves timing.
________________________________________
 9. Overall Market Status and Score
 Finally, the dashboard compiles multiple indicators (VWAP position, RSI, MACD, Stochastics, and price vs. median levels) into a Market Score expressed as a percentage. It also labels the market as Overbought, Oversold, or Normal.
This scoring system isn’t a recommendation but a learning framework. Students can analyze how combining different indicators improves decision-making. The key training focus here is confluence: not depending on one indicator but observing when several conditions align.
Extended Study Material with Formulas
________________________________________
 1. Daily Reference Levels (High, Low, Open, Median, Range)
 •	Day High (H): Maximum price of the session.
DayHigh=max(Hightoday)DayHigh=max(Hightoday)
•	Day Low (L): Minimum price of the session.
DayLow=min(Lowtoday)DayLow=min(Lowtoday)
•	Day Open (O): Opening price of the session.
DayOpen=OpentodayDayOpen=Opentoday
•	Day Range:
Range=DayHigh−DayLowRange=DayHigh−DayLow
•	Median: Mid-point between high and low.
Median=DayHigh+DayLow2Median=2DayHigh+DayLow
These act as intraday guideposts for seeing how far the price has stretched from its key reference levels.
________________________________________
 2. VWAP (Volume Weighted Average Price)
 VWAP considers both price and volume for a weighted average:
VWAPt=∑i=1t(Pricei×Volumei)∑i=1tVolumeiVWAPt=∑i=1tVolumei∑i=1t(Pricei×Volumei)
Here, Price_i can be the average price (High + Low + Close) ÷ 3, also known as hlc3.
•	Interpretation: Price above VWAP = bullish bias; Price below = bearish bias.
________________________________________
 3. Volume Buy/Sell Analysis
 The dashboard splits total volume into buy volume and sell volume based on candle type.
•	Buy Volume:
BuyVol=Volumeif Close > Open, else 0BuyVol=Volumeif Close > Open, else 0
•	Sell Volume:
SellVol=Volumeif Close < Open, else 0SellVol=Volumeif Close < Open, else 0
•	Buy Ratio (%):
VolumeRatio=BuyVolBuyVol+SellVol×100VolumeRatio=BuyVol+SellVolBuyVol×100
This helps traders gauge who is in control during a session—buyers or sellers.
________________________________________
 4. RSI (Relative Strength Index)
 RSI measures strength of momentum by comparing gains vs. losses.
Step 1: Compute average gains (AG) and losses (AL).
AG=Average of Upward Closes over N periodsAG=Average of Upward Closes over N periodsAL=Average of Downward Closes over N periodsAL=Average of Downward Closes over N periods
Step 2: Calculate relative strength (RS).
RS=AGALRS=ALAG
Step 3: RSI formula.
RSI=100−1001+RSRSI=100−1+RS100
•	Used to detect overbought (>70), oversold (<30), or neutral momentum zones.
________________________________________
 5. MACD (Moving Average Convergence Divergence)
 •	Fast EMA:
EMAfast=EMA(Close,length=fast)EMAfast=EMA(Close,length=fast)
•	Slow EMA:
EMAslow=EMA(Close,length=slow)EMAslow=EMA(Close,length=slow)
•	MACD Line:
MACD=EMAfast−EMAslowMACD=EMAfast−EMAslow
•	Signal Line:
Signal=EMA(MACD,length=signal)Signal=EMA(MACD,length=signal)
•	Histogram:
Histogram=MACD−SignalHistogram=MACD−Signal
Crossovers between MACD and Signal are used in studying bullish/bearish phases.
________________________________________
 6. Stochastic Oscillator
 Stochastic compares the current close against a range of highs and lows.
%K=Close−LowestLowHighestHigh−LowestLow×100%K=HighestHigh−LowestLowClose−LowestLow×100
Where LowestLow and HighestHigh are the lowest and highest values over N periods.
The %D line is a smooth version of %K (using a moving average).
%D=SMA(%K,smooth)%D=SMA(%K,smooth)
•	Values above 80 = overbought; below 20 = oversold.
________________________________________
 7. Trend and Momentum Classification
 This dashboard generates simplified trend/momentum logic using RSI.
•	Trend:
•	RSI < 40 → Downtrend
•	RSI > 60 → Uptrend
•	In Between → Neutral
•	Momentum Bias:
•	RSI > 70 → Bullish Hold
•	RSI < 30 → Bearish Hold
•	Otherwise Neutral
This is not predictive, only a classification framework for educational use.
________________________________________
 8. Accumulation/Distribution Bias
 Based on extreme RSI values:
•	RSI < 25 → Accumulate Long Bias
•	RSI > 80 → Accumulate Short Bias
•	Else → Wait/No Action
This helps learners understand the idea of accumulation at lows (strength building) and distribution at highs (profit booking).
________________________________________
 9. Overall Market Status and Score
 The tool adds up 5 bullish conditions:
1.	Price above VWAP
2.	RSI > 50
3.	MACD > Signal
4.	Stochastic > 50
5.	Price above Daily Median
BullishScore=ConditionsMet5×100BullishScore=5ConditionsMet×100
Then it categorizes the market:
•	RSI > 70 or Stoch > 80 → Overbought
•	RSI < 30 or Stoch < 20 → Oversold
•	Else → Normal
This encourages learners to think in terms of probabilistic conditions instead of single-indicator signals.
________________________________________
 ⚠️ Warning:
 •	Trading financial markets involves substantial risk.
•	You can lose more money than you invest.
•	Past performance of indicators does not guarantee future results.
•	This script must not be copied, resold, or republished without authorization from aiTrendview.
By using this material or the code, you agree to take full responsibility for your trading decisions and acknowledge that this is not financial advice.
________________________________________
 ⚠️ Disclaimer and Warning (From aiTrendview)
 This Dynamic Trading Dashboard is created strictly for educational and research purposes on the TradingView platform. It does not provide financial advice, buy/sell recommendations, or guaranteed returns. Any use of this tool in live trading is completely at the user’s own risk. Markets are inherently risky; losses can exceed initial investment.
The intellectual property of this script and its methodology belongs to aiTrendview. Unauthorized reproduction, modification, or redistribution of this code is strictly prohibited. By using this study material or the script, you acknowledge personal responsibility for any trading outcomes. Always consult professional financial advisors before making investment decisions.
Volume-Weighted Money Flow [sgbpulse]Overview 
The  VWMF  indicator is an advanced technical analysis tool that combines and summarizes five leading momentum and volume indicators  (OBV, PVT, A/D, CMF, MFI)  into one clear oscillator.  The indicator helps to provide a clear picture of  market sentiment  by measuring the pressure from buyers and sellers. Unlike single indicators, VWMF provides a comprehensive view of market money flow by weighting existing indicators and presenting them in a uniform and understandable format.
 Indicator Components 
VWMF combines the following indicators, each normalized to a range of 0 to 100 before being weighted:
 
 On-Balance Volume (OBV):  A cumulative indicator that measures positive and negative volume flow.
 Price-Volume Trend (PVT):  Similar to OBV, but incorporates relative price change for a more precise measure.
 Accumulation/Distribution Line (A/D):  Used to identify whether an asset is being bought (accumulated) or sold (distributed).
 Chaikin Money Flow (CMF):  Measures the money flow over a period based on the close price's position relative to the candle's range.
 Money Flow Index (MFI):  A momentum oscillator that combines price and volume to measure buying and selling pressure.
 
 Understanding the Normalized Oscillators 
The indicator combines the five different momentum indicators by normalizing each one to a uniform range of  0 to 100 .
 Why is Normalization Important? 
Indicators like OBV, PVT, and the A/D Line are  cumulative indicators  whose values can become very large. To assess their trend, we use a Moving Average as a  dynamic reference line . The Moving Average allows us to understand whether the indicator is currently trending up or down relative to its average behavior over time.
 How Does Normalization Work? 
Our normalization fully preserves the original trend of each indicator.
 
 For Cumulative Indicators (OBV, PVT, A/D):  We calculate the difference between the current indicator value and its Moving Average. This difference is then passed to the normalization process.
- If the indicator is above its Moving Average, the difference will be positive, and the normalized value will be above 50.
- If the indicator is below its Moving Average, the difference will be negative, and the normalized value will be below 50.
 Handling Extreme Values:  To overcome the issue of extreme values in indicators like  OBV, PVT, and the A/D Line , the function calculates the highest absolute value over the selected period. This value is used to prevent sharp spikes or drops in a single indicator from compromising the accuracy of the normalization over time. It's a sophisticated method that ensures the oscillators remain relevant and accurate.
 For Bounded Indicators (CMF, MFI):  These indicators already operate within a known range (for example, CMF is between -1 and 1, and MFI is between 0 and 100), so they are normalized directly without an additional reference line.
 
 Reference Line Settings: 
 
 Moving Average Type:  Allows the user to choose between a Simple Moving Average (SMA) and an Exponential Moving Average (EMA).
 Volume Flow MA Length:  Allows the user to set the lookback period for the Moving Average, which affects the indicator's sensitivity.
 
The 50 line serves as the new "center line." This ensures that, even after normalization, the determination of whether a specific indicator supports a bullish or bearish trend remains clear.
 Settings and Visual Tools 
The indicator offers several customization options to provide a rich analysis experience:
 
 VWMF Oscillator (Blue Line):  Represents the weighted average of all five indicators. Values above 50 indicate bullish momentum, and values below 50 indicate bearish momentum.
 Strength Metrics (Bullish/Bearish Strength %):  Two metrics that appear on the status line, showing the percentage of indicators supporting the current trend. They range from 0% to 100%, providing a quick view of the strength of the consensus.
 Dynamic Background Colors:  The background color of the chart automatically changes to bullish (a blue shade by default) or bearish (a default brown-gray shade) based on the trend. The transparency of the color shows the consensus strength—the more opaque the background, the more indicators support the trend.
 Advanced Settings: 
-  Background Color Logic:  Allows the user to choose the trigger for the background color:  Weighted Value  (based on the combined oscillator) or  Strength  (based on the majority of individual indicators).
- Weights:  Provides full control over the weight of each of the five indicators in the final oscillator.
 
 Using the Data Window 
TradingView provides a useful  Data Window  that allows you to see the exact numerical values of each normalized oscillator separately, in addition to the trend strength data.
You can use this window to:
 
 Get more detailed information on each indicator:  Viewing the precise numerical data of each of the five indicators can help in making trading decisions.
 Calibrate weights:  If you want to manually adjust the indicator weights (in the settings menu), you can do so while tracking the impact of each indicator on the weighted oscillator in the Data Window.
 
The indicator's  default  setting is an equal weight of  20%  for each of the five indicators.
 Alert Conditions 
The indicator comes with a variety of built-in alerts that can be configured through the TradingView alerts menu:
 
 VWMF Cross Above 50:  An alert when the VWMF oscillator crosses above the 50 line, indicating a potential bullish momentum shift.
 VWMF Cross Below 50:  An alert when the VWMF oscillator crosses below the 50 line, indicating a potential bearish momentum shift.
 Bullish Strength: High But Not Absolute Consensus:  An alert when the bullish trend strength reaches 60% or more but is less than 100%, indicating a high but not absolute consensus.
 Bullish Strength at 100%:  An alert when all five indicators (MFI, OBV, PVT, A/D, CMF) show bullish strength, indicating a full and absolute consensus.
 Bearish Strength: High But Not Absolute Consensus:  An alert when the bearish trend strength reaches 60% or more but is less than 100%, indicating a high but not absolute consensus.
 Bearish Strength at 100%:  An alert when all five indicators (MFI, OBV, PVT, A/D, CMF) show bearish strength, indicating a full and absolute consensus.
 
 Summary 
The VWMF indicator is a powerful, all-in-one tool for analyzing market momentum, money flow, and sentiment. By combining and normalizing five different indicators into a single oscillator, it offers a holistic and accurate view of the market's underlying trend. Its dynamic visual features and customizable settings, including the ability to adjust indicator weights, provide a flexible experience for both novice and experienced traders. The built-in alerts for momentum shifts and trend consensus make it an effective tool for spotting trading opportunities with confidence. In essence, VWMF distills complex market data into clear, actionable signals.
 Important Note: Trading Risk 
This indicator is intended for educational and informational purposes only and does not constitute investment advice or a recommendation for trading in any form whatsoever.
Trading in financial markets involves significant risk of capital loss. It is important to remember that past performance is not indicative of future results. All trading decisions are your sole responsibility. Never trade with money you cannot afford to lose.
RTH Levels: VWAP + PDH/PDL + ONH/ONL + IBAlgo Index — Levels Pro (ONH/ONL • PDH/PDL  • VWAP±Bands • IB • Gaps)
Purpose. A session-aware, non-repainting levels tool for intraday decision-making. Designed for futures and indices, with clean visuals, alerts, and a one-click Minimal Mode for screenshot-ready charts.
What it plots
	•	PDH/PDL (RTH-only) – Prior Regular Trading Hours high/low, computed intraday and frozen at the RTH close (no 24h mix-ups, no repainting).
	•	ONH/ONL – Prior Overnight high/low, held throughout RTH.
	•	RTH VWAP with ±σ bands – Volume-weighted variance, reset each RTH.
	•	Initial Balance (IB) – First N minutes of RTH, plus 1.5× / 2.0× extensions after IB completes.
	•	Today’s RTH Open & Prior RTH Close – With gap detection and “gap filled” alert.
	•	Killzone shading – NY Open (09:30–10:30 ET) and Lunch (11:15–13:30 ET).
	•	Values panel (top-right) – Each level with live distance in points & ticks.
	•	Right-edge level tags – With anti-overlap (stagger + vertical jitter).
	•	Price-scale tags – Native trackprice markers that always “stick” to the axis.
⸻
New in v6.4
	•	Minimal Mode: one click for a clean look (thinner lines, VWAP bands/IB extensions hidden, on-chart right-edge labels off; price-scale tags remain).
	•	Theme presets: Dark Hi-Contrast / Light Minimal / Futures Classic / Muted Dark.
	•	Anti-overlap controls: horizontal staggering, vertical jitter, and baseline offset to keep tags readable even when levels cluster.
⸻
Quick start (2 minutes)
	1.	Add to chart → keep defaults.
	2.	Sessions (ET):
	•	RTH Session default: 09:30–16:00 (US equities cash hours).
	•	Overnight Session default: 18:00–09:29.
Adjust for your market if you use different “day” hours (e.g., many use 08:20–13:30 ET for COMEX Gold).
	3.	Theme & Minimal Mode: pick a Theme Preset; enable Minimal Mode for screenshots.
	4.	Visibility: toggle PD/ON/VWAP/IB/References/Panel to taste.
	5.	Right-edge labels: turn Show Right-Edge Labels on. If they crowd, tune:
	•	Anti-overlap: min separation (ticks)
	•	Horizontal offset per tag (bars)
	•	Vertical jitter per step (ticks)
	•	Right-edge baseline offset (bars)
	6.	Alerts: open Add alert → Condition:   and pick the events you want.
⸻
How levels are computed (no repainting)
	•	PDH/PDL: Intraday H/L are accumulated only while in RTH and saved at RTH close for “yesterday’s” values.
	•	ONH/ONL: Accumulated across the defined Overnight window and then held during RTH.
	•	RTH VWAP & ±σ: Volume-weighted mean and standard deviation, reset at the RTH open.
	•	IB: First N minutes of RTH (default 60). Extensions (1.5×/2.0×) appear after IB completes.
	•	Gaps: Today’s RTH open vs prior RTH close; “Gap Filled” triggers when price trades back to prior close.
⸻
Practical playbooks (how to trade around the levels)
1) PDH/PDL interactions
	•	Rejection: Price taps PDH/PDL then closes back inside → mean-reversion toward VWAP/IB.
	•	Acceptance: Close/hold beyond PDH/PDL with momentum → continuation to next HTF/IB target.
	•	Alert: PD Touch/Break.
2) ONH/ONL “taken”
	•	Often one ON extreme is taken during RTH. ONH Taken / ONL Taken → check if it’s a clean break or sweep & reclaim.
	•	Sweep + reclaim near VWAP can fuel rotations through the ON range.
3) VWAP ±σ framework
	•	Balanced: First tag of ±1σ often reverts toward VWAP.
	•	Trend: Persistent trade beyond ±1σ + IB break → target ±2σ/±3σ.
	•	Alerts: VWAP Cross and VWAP Reject (cross then immediate fail back).
4) IB breaks
	•	After IB completes, a clean IB break commonly targets 1.5× and sometimes 2.0×.
	•	Quick return inside IB = possible fade back to the opposite IB edge/VWAP.
	•	Alerts: IB Break Up / Down.
5) Gaps
	•	Gap-and-go: Opening drive away from prior close + VWAP support → trend until IB completion.
	•	Gap-fill: Weak open and VWAP overhead/underfoot → trade toward prior close; manage on Gap Filled alert.
Pro tip: Stack confluences (e.g., ONL sweep + VWAP reclaim + IB hold) and respect your execution rules (e.g., require a 5-minute close in direction, or your order-flow confirmation).
⸻
Inputs you’ll actually touch
	•	Sessions (ET): Session Timezone, RTH Session, Overnight Session.
	•	Visibility: toggles for PD/ON/VWAP/IB/Ref/Panel.
	•	VWAP bands: set σ multipliers (±1/±2/±3).
	•	IB: duration (minutes) and extension multipliers (1.5× / 2.0×).
	•	Style & Theme: Theme Preset, Main Line Width, Trackprice, Minimal Mode, and anti-overlap controls.
⸻
Alerts included
	•	PD Touch/Break — High ≥ PDH or Low ≤ PDL
	•	ONH Taken / ONL Taken — First in-RTH take of ONH/ONL
	•	VWAP Cross — Close crosses VWAP
	•	VWAP Reject — Cross then immediate fail back
	•	IB Break Up / Down — Break of IB High/Low after IB completes
	•	Gap Filled — Price trades back to prior RTH close
Setup: Add alert → Condition: Algo Index — Levels Pro → choose event → message → Notify on app/email.
⸻
Panel guide
The top-right panel shows each level plus live distance from last price:
LevelValue   (Δpoints | Δticks)
Coloring: green if level is below current price, red if above.
⸻
Styling & screenshot tips
	•	Use Theme Preset that matches your chart.
	•	For dark charts, “Dark Hi-Contrast” with Main Line Width = 3 works well.
	•	Enable Trackprice for crisp axis tags that always stick to the right edge.
	•	Turn on Minimal Mode for cleaner screenshots (no VWAP bands or IB extensions, on-chart tags off; price-scale tags remain).
	•	If tags crowd, increase min separation (ticks) to 30–60 and horizontal offset to 3–5; add vertical jitter (4–12 ticks) and/or push tags farther right with baseline offset (bars).
⸻
Behavior & limitations
	•	Levels are computed incrementally; tables refresh on the last bar for efficiency.
	•	Right-edge labels are placed at bar_index + offset and do not track extra right-margin scrolling (TradingView limitation). The price-scale tags (from trackprice) do track the axis.
	•	“RTH” is what you define in inputs. If your market uses different day hours, change the session strings so PDH/PDL reflect your definition of “yesterday’s session.”
⸻
FAQ
Q: My PDH/PDL don’t match the daily chart.
A: By design this uses RTH-only highs/lows, not 24h daily bars. Adjust sessions if you want a different definition.
Q: Right-edge tags overlap or don’t sit at the far right.
A: Increase min separation / horizontal offset / vertical jitter and/or push tags farther with baseline offset. If you want markers that always hug the axis, rely on Trackprice.
Q: Can I change killzones?
A: Yes—edit the session strings in settings or request a version with user inputs for custom windows.
⸻
Disclaimer
Educational use only. This is not financial advice. Always apply your own risk management and confirmation rules.
⸻
Enjoy it? Please ⭐ the script and share screenshots using Minimal Mode + a Theme Preset that fits your style.
Malama's KAYCAP Pre-Market Box# Pre-Market Single Candle Range Box
## What Makes This Script Original
While many scripts plot entire pre-market session ranges, this indicator focuses specifically on **a single user-defined candle** within the pre-market period rather than the entire session. This targeted approach allows traders to isolate the most relevant price action from a specific time (default: 4:00 AM EST) that often establishes key levels for the trading day.
## Core Methodology & Technical Implementation
**Single Candle Isolation:**
- Captures OHLC data from one specific minute within pre-market hours (user configurable)
- Differentiates between the candle's body (open/close range) and wicks (high/low extremes)
- Creates four distinct reference levels instead of traditional session high/low boxes
**Dual Box Structure:**
- **Inner Box (Body):** Plots the range between open and close prices of the target candle
- **Outer Boundaries:** Separately plots the high and low of that same candle
- **Visual Differentiation:** Uses different colors and line weights to distinguish body vs. wick levels
**Time-Specific Logic:**
The script uses precise time matching (`hour == boxHour and minute == boxMinute`) to capture data from exactly one candle, rather than aggregating an entire session. This creates four specific price levels:
- Box Top: Higher of open/close (body boundary)
- Box Bottom: Lower of open/close (body boundary)  
- Box High: Candle high (wick extreme)
- Box Low: Candle low (wick extreme)
## Why This Approach Differs from Standard Session Boxes
**vs. Full Session Ranges:** Focuses on a single critical minute rather than entire pre-market period
**vs. Traditional S/R:** Creates both body and wick levels from one specific candle
**vs. Opening Range:** Uses pre-market data rather than regular session opening minutes
## Practical Application
The 4:00 AM EST default targets a time when institutional pre-market activity often establishes initial sentiment and key levels. By isolating this specific candle's range:
- **Body levels** often act as initial support/resistance during regular hours
- **Wick extremes** provide broader range boundaries for breakout analysis
- **Precise timing** allows focus on the most statistically relevant pre-market moment
## Technical Considerations
- Requires intraday timeframes (1-minute recommended) to capture specific candle data
- Time settings should match your broker's timezone for accurate candle selection
- Works best on liquid instruments where pre-market activity is meaningful
- The selected candle must exist in your data feed for the levels to plot
## Customization Options
All timing parameters are adjustable:
- Target candle hour and minute
- Pre-market session definition (for context)
- Visual styling for all four level types
This focused approach provides more granular analysis than broad session ranges while maintaining simplicity in execution.
Machine Learning BBPct [BackQuant]Machine Learning BBPct  
 What this is (in one line) 
A Bollinger Band %B oscillator enhanced with a  simplified K-Nearest Neighbors (KNN)  pattern matcher. The model compares today’s context (volatility, momentum, volume, and position inside the bands) to similar situations in recent history and blends that historical consensus back into the raw %B to reduce noise and improve context awareness. It is informational and diagnostic—designed to describe market state, not to sell a trading system.
 Background: %B in plain terms 
Bollinger %B measures where price sits inside its dynamic envelope:  0  at the lower band,  1  at the upper band, ~ 0.5  near the basis (the moving average). Readings toward 1 indicate pressure near the envelope’s upper edge (often strength or stretch), while readings toward 0 indicate pressure near the lower edge (often weakness or stretch). Because bands adapt to volatility, %B is naturally comparable across regimes.
 Why add (simplified) KNN? 
Classic %B is reactive and can be whippy in fast regimes. The simplified KNN layer builds a “nearest-neighbor memory” of recent market states and asks:  “When the market looked like this before, where did %B tend to be next bar?”  It then blends that estimate with the current %B. Key ideas:
•  Feature vector . Each bar is summarized by up to five normalized features:
  – %B itself (normalized)
  – Band width (volatility proxy)
  – Price momentum (ROC)
  – Volume momentum (ROC of volume)
  – Price position within the bands
•  Distance metric . Euclidean distance ranks the most similar recent bars.
•  Prediction . Average the neighbors’  prior  %B (lagged to avoid lookahead), inverse-weighted by distance.
•  Blend . Linearly combine raw %B and KNN-predicted %B with a configurable weight; optional filtering then adapts to confidence.
This remains “simplified” KNN: no training/validation split, no KD-trees, no scaling beyond windowed min-max, and no probabilistic calibration. 
 How the script is organized (by input groups) 
 1) BBPct Settings 
•  Price Source  – Which price to evaluate (%B is computed from this).
•  Calculation Period  – Lookback for SMA basis and standard deviation.
•  Multiplier  – Standard deviation width (e.g., 2.0).
•  Apply Smoothing / Type / Length  – Optional smoothing of the %B stream before ML (EMA, RMA, DEMA, TEMA, LINREG, HMA, etc.). Turning this off gives you the raw %B.
 2) Thresholds 
•  Overbought/Oversold  – Default 0.8 / 0.2 (inside  ).
•  Extreme OB/OS  – Stricter zones (e.g., 0.95 / 0.05) to flag stretch conditions.
 3) KNN Machine Learning 
•  Enable KNN  – Switch between pure %B and hybrid.
•  K (neighbors)  – How many historical analogs to blend (default 8).
•  Historical Period  – Size of the search window for neighbors.
•  ML Weight  – Blend between raw %B and KNN estimate.
•  Number of Features  – Use 2–5 features; higher counts add context but raise the risk of overfitting in short windows.
 4) Filtering 
•  Method  – None, Adaptive, Kalman-style (first-order), 
or Hull smoothing.
•  Strength  – How aggressively to smooth. “Adaptive” uses model confidence to modulate its alpha: higher confidence → stronger reliance on the ML estimate.
 5) Performance Tracking 
•  Win-rate Period  – Simple running score of past signal outcomes based on target/stop/time-out logic (informational, not a robust backtest).
•  Early Entry Lookback  – Horizon for forecasting a potential threshold cross.
•  Profit Target / Stop Loss  – Used only by the internal win-rate heuristic.
 6) Self-Optimization 
•  Enable Self-Optimization  – Lightweight, rolling comparison of a few canned settings (K = 8/14/21 via simple rules on %B extremes).
•  Optimization Window & Stability Threshold  – Governs how quickly preferred K changes and how sensitive the overfitting alarm is.
•  Adaptive Thresholds  – Adjust the OB/OS lines with volatility regime (ATR ratio), widening in calm markets and tightening in turbulent ones (bounded 0.7–0.9 and 0.1–0.3).
 7) UI Settings 
•  Show Table / Zones / ML Prediction / Early Signals  – Toggle informational overlays.
•  Signal Line Width, Candle Painting, Colors  – Visual preferences.
 Step-by-step logic 
 A) Compute %B 
Basis = SMA(source, len); dev = stdev(source, len) × multiplier; Upper/Lower = Basis ± dev.
%B = (price − Lower) / (Upper − Lower). Optional smoothing yields  standardBB .
 B) Build the feature vector 
All features are min-max normalized over the KNN window so distances are in comparable units. Features include normalized %B, normalized band width, normalized price ROC, normalized volume ROC, and normalized position within bands. You can limit to the first N features (2–5).
 C) Find nearest neighbors 
For each bar inside the lookback window, compute the Euclidean distance between current features and that bar’s features. Sort by distance, keep the top  K .
 D) Predict and blend 
Use inverse-distance weights (with a strong cap for near-zero distances) to average neighbors’  prior %B  (lagged by one bar). This becomes the KNN estimate. Blend it with raw %B via the ML weight. A variance of neighbor %B around the prediction becomes an  uncertainty proxy ; combined with a  stability score  (how long parameters remain unchanged), it forms  mlConfidence  ∈  . The Adaptive filter optionally transforms that confidence into a smoothing coefficient.
 E) Adaptive thresholds 
Volatility regime (ATR(14) divided by its 50-bar SMA) nudges OB/OS thresholds wider or narrower within fixed bounds. The aim: comparable extremeness across regimes.
 F) Early entry heuristic 
A tiny two-step slope/acceleration probe extrapolates finalBB forward a few bars. If it is on track to cross OB/OS soon (and slope/acceleration agree), it flags an  EARLY_BUY/SELL  candidate with an internal confidence score. This is explicitly a heuristic—use as an attention cue, not a signal by itself.
 G) Informational win-rate 
The script keeps a rolling array of trade outcomes derived from signal transitions + rudimentary exits (target/stop/time). The percentage shown is a  rough diagnostic , not a validated backtest.
 Outputs and visual language 
•  ML Bollinger %B (finalBB)  – The main line after KNN blending and optional filtering.
•  Gradient fill  – Greenish tones above 0.5, reddish below, with intensity following distance from the midline.
•  Adaptive zones  – Overbought/oversold and extreme bands; shaded backgrounds appear at extremes.
•  ML Prediction (dots)  – The KNN estimate plotted as faint circles; becomes bright white when confidence > 0.7.
•  Early arrows  – Optional small triangles for approaching OB/OS.
•  Candle painting  – Light green above the midline, light red below (optional).
•  Info panel  – Current value, signal classification, ML confidence, optimized K, stability, volatility regime, adaptive thresholds, overfitting flag, early-entry status, and total signals processed.
 Signal classification (informational) 
The indicator does  not  fire trade commands; it labels state:
•  STRONG_BUY / STRONG_SELL  – finalBB beyond extreme OS/OB thresholds.
•  BUY / SELL  – finalBB beyond adaptive OS/OB.
•  EARLY_BUY / EARLY_SELL  – forecast suggests a near-term cross with decent internal confidence.
•  NEUTRAL  – between adaptive bands.
 Alerts (what you can automate) 
• Entering adaptive OB/OS and extreme OB/OS.
• Midline cross (0.5).
• Overfitting detected (frequent parameter flipping).
• Early signals when early confidence > 0.7.
These are purely descriptive triggers around the indicator’s state.
 Practical interpretation 
•  Mean-reversion context  – In range markets, adaptive OS/OB with ML smoothing can reduce whipsaws relative to raw %B.
•  Trend context  – In persistent trends, the KNN blend can keep finalBB nearer the mid/upper region during healthy pullbacks if history supports similar contexts.
•  Regime awareness  – Watch the volatility regime and adaptive thresholds. If thresholds compress (high vol), “OB/OS” comes sooner; if thresholds widen (calm), it takes more stretch to flag.
•  Confidence as a weight  – High mlConfidence implies neighbors agree; you may rely more on the ML curve. Low confidence argues for de-emphasizing ML and leaning on raw %B or other tools.
•  Stability score  – Rising stability indicates consistent parameter selection and fewer flips; dropping stability hints at a shifting backdrop.
 Methodological notes 
•  Normalization  uses rolling min-max over the KNN window. This is simple and scale-agnostic but sensitive to outliers; the distance metric will reflect that.
•  Distance  is unweighted Euclidean. If you raise featureCount, you increase dimensionality; consider keeping K larger and lookback ample to avoid sparse-neighbor artifacts.
•  Lag handling  intentionally uses neighbors’ previous %B for prediction to avoid lookahead bias.
•  Self-optimization  is deliberately modest: it only compares a few canned K/threshold choices using simple “did an extreme anticipate movement?” scoring, then enforces a stability regime and an overfitting guard. It is not a grid search or GA.
•  Kalman option  is a first-order recursive filter (fixed gain), not a full state-space estimator.
•  Hull option  derives a dynamic length from 1/strength; it is a convenience smoothing alternative.
 Limitations and cautions 
•  Non-stationarity  – Nearest neighbors from the recent window may not represent the future under structural breaks (policy shifts, liquidity shocks).
•  Curse of dimensionality  – Adding features without sufficient lookback can make genuine neighbors rare.
•  Overfitting risk  – The script includes a crude overfitting detector (frequent parameter flips) and will fall back to defaults when triggered, but this is only a guardrail.
•  Win-rate display  – The internal score is illustrative; it does not constitute a tradable backtest.
•  Latency vs. smoothness  – Smoothing and ML blending reduce noise but add lag; tune to your timeframe and objectives.
 Tuning guide 
•  Short-term scalping  – Lower len (10–14), slightly lower multiplier (1.8–2.0), small K (5–8), featureCount 3–4, Adaptive filter ON, moderate strength.
•  Swing trading  – len (20–30), multiplier ~2.0, K (8–14), featureCount 4–5, Adaptive thresholds ON, filter modest.
•  Strong trends  – Consider higher adaptive_upper/lower bounds (or let volatility regime do it), keep ML weight moderate so raw %B still reflects surges.
•  Chop  – Higher ML weight and stronger Adaptive filtering; accept lag in exchange for fewer false extremes.
 How to use it responsibly 
Treat this as a state descriptor and context filter. Pair it with your execution signals (structure breaks, volume footprints, higher-timeframe bias) and risk management. If mlConfidence is low or stability is falling, lean less on the ML line and more on raw %B or external confirmation.
 Summary 
Machine Learning BBPct augments a familiar oscillator with a transparent, simplified KNN memory of recent conditions. By blending neighbors’ behavior into %B and adapting thresholds to volatility regime—while exposing confidence, stability, and a plain early-entry heuristic—it provides an informational, probability-minded view of stretch and reversion that you can interpret alongside your own process.
Capiba Custom RSI with Divergences v2
🇬🇧 English
Summary
This indicator is an enhanced and customizable version of the classic RSI, designed to provide clearer and more powerful trading signals. It combines an alternative, more price-sensitive RSI calculation with an automatic divergence detection, which is one of the most effective tools for predicting trend reversals and finding high-probability entry and exit points.
Built upon the compilation of knowledge and open-source codes from the community, this script has been refined to be an all-in-one tool for traders who base their strategies on momentum and trend exhaustion.
Key Features and How to Use
Ultimate RSI and Signal Line (Momentum)
What it is: The main indicator (white line) is an RSI variation that reacts more dynamically to changes in price volatility. It is accompanied by a signal line (orange, by default), which is a moving average of the RSI itself, serving to smooth the indicator and generate crossover signals.
How to use for Entries/Exits:
Buy Signal (Short-Term): Crossover of the RSI line (white) above the signal line (orange).
Sell Signal (Short-Term): Crossover of the RSI line (white) below the signal line (orange). These are momentum signals, ideal for confirming a trend or for scalping.
Automatic Divergence Detection (Reversal Signals) This is the most powerful feature of the indicator. A divergence occurs when the price moves in one direction and the momentum indicator moves in the opposite direction, signaling a likely exhaustion of the current trend.
Bullish Divergence (Green Line):
What it is: The price makes a lower low, but the RSI makes a higher low.
Meaning: Selling pressure is decreasing. It is a strong signal of a potential market bottom and an excellent entry opportunity for a long position.
Bearish Divergence (Red Line):
What it is: The price makes a higher high, but the RSI makes a lower high.
Meaning: Buying pressure is losing strength. It is a strong signal of a potential market top and an excellent exit opportunity for a long position or an entry for a short position.
Customizable Overbought & Oversold Levels
The horizontal lines (default 80 and 20) and the colored areas show when the asset is overextended to the upside (overbought) or downside (oversold), helping to contextualize the divergence and crossover signals.
Recommended Strategy
For maximum effectiveness, combine the signals:
High-Probability Entry (Buy): Look for a Bullish Divergence (green line) forming in the oversold zone. Confirm the entry when the RSI line crosses above its signal line.
High-Probability Exit (Sell): Look for a Bearish Divergence (red line) forming in the overbought zone. Confirm the exit or new short entry when the RSI line crosses below its signal line.
Acknowledgements
This indicator was developed by compiling and customizing excellent open-source ideas and codes shared by the TradingView community. Special thanks to everyone who contributes to the advancement of technical analysis.
Chart-Only Scanner — Pro Table v2.5.1Chart-Only Scanner — Pro Table v2.5
User Manual (Pine Script v6)
What this tool does (in one line)
A compact, on-chart table that scores the current chart symbol (or an optional override) using momentum, volume, trend, volatility, and pattern checks—so you can quickly decide UP, DOWN, or WAIT.
Quick Start (90 seconds)
Add the indicator to any chart and timeframe (1m…1M).
Leave “Override chart symbol” = OFF to auto-use the chart’s symbol.
Choose your layout:
Row (wide horizontal strip), or Grid (title + labeled cells).
Pick a size preset (Micro, Small, Medium, Large, Mobile).
Optional: turn on “Use Higher TF (EMA 20/50)” and set HTF Multiplier (e.g., 4 ⇒ if chart is 15m, HTF is 60m).
Watch the table:
DIR (↑/↓/→), ROC%, MOM, VOL, EMA stack, HTF, REV, SCORE, ACT.
Add an alert if you want: the script fires when |SCORE| ≥ Action threshold.
What to expect
A small table appears on the chart corner you choose, updating each bar (or only at bar close if you keep default smart-update).
The ACT cell shows 🔥 (strong), 👀 (medium), or ⏳ (weak).
Panels & Settings (every option explained)
Core
Momentum Period: Lookback for rate-of-change (ROC%). Shorter = more reactive; longer = smoother.
ROC% Threshold: Minimum absolute ROC% to call direction UP (↑) or DOWN (↓); otherwise →.
Require Volume Confirmation: If ON and VOL ≤ 1.0, the SCORE is forced to 0 (prevents low-volume false positives).
Override chart symbol + Custom symbol: By default, the indicator uses the chart’s symbol. Turn this ON to lock to a specific ticker (e.g., a perpetual).
Higher TF
Use Higher TF (EMA 20/50): Compares EMA20 vs EMA50 on a higher timeframe.
HTF Multiplier: Higher TF = (chart TF × multiplier).
Example: on 3H chart with multiplier 2 ⇒ HTF = 6H.
Volatility & Oscillators
ATR Length: Used to show ATR% (ATR relative to price).
RSI Length: Standard RSI; colors: green ≤30 (oversold), red ≥70 (overbought).
Stoch %K Length: With %D = SMA(%K, 3).
MACD Fast/Slow/Signal: Standard MACD values; we display Line, Signal, Histogram (L/S/H).
ADX Length (Wilder): Wilder’s smoothing (internal derivation); also shows +DI / −DI if you enable the ADX column.
EMAs / Trend
EMA Fast/Mid/Slow: We compute EMA(20/50/200) by default (editable).
EMA Stack: Bull if Fast > Mid > Slow; Bear if Fast < Mid < Slow; Flat otherwise.
Benchmark (optional, OFF by default)
Show Relative Strength vs Benchmark: Displays RS% = ROC(symbol) − ROC(benchmark) over the Momentum Period.
Benchmark Symbol: Ticker used for comparison (e.g., BTCUSDT as a market proxy).
Columns (show/hide)
Toggle which fields appear in the table. Hiding unused fields keeps the layout clean (especially on mobile).
Display
Layout Mode:
Row = a single two-row strip; each column is a metric.
Grid = a title row plus labeled pairs (label/value) arranged in rows.
Size Preset: Micro, Small, Medium, Large, Mobile change text size and the grid density.
Table Corner: Where the panel sits (e.g., Top Right).
Opaque Table Background: ON = dark card; OFF = transparent(ish).
Update Every Bar: ON = update intra-bar; OFF = smart update (last bar / real-time / confirmed history).
Action threshold (|score|): The cutoff for 🔥 and alert firing (default 70).
How to read each field
CHART: The active symbol name (or your custom override).
DIR: ↑ (ROC% > threshold), ↓ (ROC% < −threshold), → otherwise.
ROC%: Rate of change over Momentum Period.
Formula: (Close − Close ) / Close  × 100.
MOM: A scaled momentum score: min(100, |ROC%| × 10).
VOL: Volume ratio vs 20-bar SMA: Volume / SMA(Volume,20).
1.5 highlights as yellow (significant participation).
ATR%: (ATR / Close) × 100 (volatility relative to price).
RSI: Colored for extremes: ≤30 green, ≥70 red.
Stoch K/D: %K and %D numbers.
MACD L/S/H: Line, Signal, Histogram. Histogram color reflects sign (green > 0, red < 0).
ADX, +DI, −DI: Trend strength and directional components (Wilder). ADX ≥ 25 is highlighted.
EMA 20/50/200: Current EMA values (editable lengths).
STACK: Bull/Bear/Flat as defined above.
VWAP%: (Close − VWAP) / Close × 100 (premium/discount to VWAP).
HTF: ▲ if HTF EMA20 > EMA50; ▼ if <; · if flat/off.
RS%: Symbol’s ROC% − Benchmark ROC% (positive = outperforming).
REV (reversal):
🟢 Eng/Pin = bullish engulfing or bullish pin detected,
🔴 Eng/Pin = bearish engulfing or bearish pin,
· = none.
SCORE (absolute shown as a number; sign shown via DIR and ACT):
Components:
base = MOM × 0.4
volBonus = VOL > 1.5 ? 20 : VOL × 13.33
htfBonus = use_mtf ? (HTF == DIR ? 30 : HTF == 0 ? 15 : 0) : 0
trendBonus = (STACK == DIR) ? 10 : 0
macdBonus = 0 (placeholder for future versions)
scoreRaw = base + volBonus + htfBonus + trendBonus + macdBonus
SCORE = DIR ≥ 0 ? scoreRaw : −scoreRaw
If Require Volume Confirmation and VOL ≤ 1.0 ⇒ SCORE = 0.
ACT:
🔥 if |SCORE| ≥ threshold
👀 if 50 < |SCORE| < threshold
⏳ otherwise
Practical examples
Strong long (trend + participation)
DIR = ↑, ROC% = +3.2, MOM ≈ 32, VOL = 1.9, STACK = Bull, HTF = ▲, REV = 🟢
SCORE: base(12.8) + volBonus(20) + htfBonus(30) + trend(10) ≈ 73 → ACT = 🔥
Action idea: look for longs on pullbacks; confirm risk with ATR%.
Weak long (no volume)
DIR = ↑, ROC% = +1.0, but VOL = 0.8 and Require Volume Confirmation = ON
SCORE forced to 0 → ACT = ⏳
Action: wait for volume > 1.0 or turn off confirmation knowingly.
Bearish reversal warning
DIR = →, REV = 🔴 (bearish engulfing), RSI = 68, HTF = ▼
SCORE may be mid-range; ACT = 👀
Action: watch for breakdown and rising VOL.
Alerts (how to use)
The script calls alert() whenever |SCORE| ≥ Action threshold.
To receive pop-ups, sounds, or emails: click “⏰ Alerts” in TradingView, choose this indicator, and pick “Any alert() function call.”
The alert message includes: symbol, |SCORE|, DIR.
Layout, Size, and Corner tips
Row is best when you want a compact status ribbon across the top.
Grid is clearer on big screens or when you enable many columns.
Size:
Mobile = one pair per row (tall, readable)
Micro/Small = dense; good for many fields
Large = presentation/screenshots
Corner: If the table overlaps price, change the corner or set Opaque Background = OFF.
Repaint & timeframe behavior
Default smart update prefers stability (last bar / live / confirmed history).
For a stricter, “close-only” behavior (less repaint): turn Update Every Bar = OFF and avoid Heikin Ashi when you want raw market OHLC (HA modifies price inputs).
HTF logic is derived from a clean, integer multiple of your chart timeframe (via multiplier). It works with 3H/4H and any TF.
Performance notes
The script analyzes one symbol (chart or override) with multiple metrics using efficient tuple requests.
If you later want a multi-symbol grid, do it with pages (10–15 per page + rotate) to stay within platform limits (recommended future add-on).
Troubleshooting
No table visible
Ensure the indicator is added and not hidden.
Try toggling Opaque Background or switch Corner (it might be behind other drawings).
Keep Columns count reasonable for the chosen Size.
If you turned ON Override, verify the Custom symbol exists on your data provider.
Numbers look different on HA candles
Heikin Ashi modifies OHLC; switch to regular candles if you need raw price metrics.
3H/4H issues
Use integer HTF Multiplier (e.g., 2, 4). The tool builds the correct string internally; no manual timeframe strings needed.
Power user tips
Volume gating: keeping Require Volume Confirmation = ON filters most fake moves; if you’re a scalper, reduce strictness or turn it off.
Action threshold: 60–80 is typical. Higher = fewer but stronger signals.
Benchmark RS%: great for spotting leaders/laggards; positive RS% = outperformance vs benchmark.
Change policy & safety
This version doesn’t alter your historical logic you tested (no radical changes).
Any future “radical” change (score weights, HTF logic, UI hiding data) will ship with a toggle and an Impact Statement so you can keep old behavior if you prefer.
Glossary (quick)
ROC%: Percent change over N bars.
MOM: Scaled momentum (0–100).
VOL ratio: Volume vs 20-bar average.
ATR%: ATR as % of price.
ADX/DI: Trend strength / direction components (Wilder).
EMA stack: Relationship between EMAs (bullish/bearish/flat).
VWAP%: Premium/discount to VWAP.
RS%: Relative strength vs benchmark.
Markov Chain [3D] | FractalystWhat exactly is a Markov Chain? 
This indicator uses a Markov Chain model to analyze, quantify, and visualize the transitions between market regimes (Bull, Bear, Neutral) on your chart. It dynamically detects these regimes in real-time, calculates transition probabilities, and displays them as animated 3D spheres and arrows, giving traders intuitive insight into current and future market conditions.
 How does a Markov Chain work, and how should I read this spheres-and-arrows diagram? 
Think of three weather modes:  Sunny, Rainy, Cloudy.  
Each sphere is one mode. The loop on a sphere means “stay the same next step” (e.g., Sunny again tomorrow).
The arrows leaving a sphere show where things usually go next if they change (e.g., Sunny moving to Cloudy).
Some paths matter more than others. A more prominent loop means the current mode tends to persist. A more prominent outgoing arrow means a change to that destination is the usual next step.
Direction isn’t symmetric: moving Sunny→Cloudy can behave differently than Cloudy→Sunny.
Now relabel the spheres to markets:  Bull, Bear, Neutral. 
Spheres: market regimes (uptrend, downtrend, range).
Self‑loop: tendency for the current regime to continue on the next bar.
Arrows: the most common next regime if a switch happens.
How to read: Start at the sphere that matches current bar state. If the loop stands out, expect continuation. If one outgoing path stands out, that switch is the typical next step. Opposite directions can differ (Bear→Neutral doesn’t have to match Neutral→Bear).
 What states and transitions are shown? 
The three market states visualized are:
Bullish (Bull): Upward or strong-market regime.
Bearish (Bear): Downward or weak-market regime.
Neutral: Sideways or range-bound regime.
Bidirectional animated arrows and probability labels show how likely the market is to move from one regime to another (e.g., Bull → Bear or Neutral → Bull).
 How does the regime detection system work? 
You can use either built-in price returns (based on adaptive Z-score normalization) or supply three custom indicators (such as volume, oscillators, etc.).
Values are statistically normalized (Z-scored) over a configurable lookback period.
The normalized outputs are classified into Bull, Bear, or Neutral zones.
If using three indicators, their regime signals are averaged and smoothed for robustness.
 How are transition probabilities calculated? 
On every confirmed bar, the algorithm tracks the sequence of detected market states, then builds a rolling window of transitions.
The code maintains a transition count matrix for all regime pairs (e.g., Bull → Bear).
Transition probabilities are extracted for each possible state change using Laplace smoothing for numerical stability, and frequently updated in real-time.
 What is unique about the visualization? 
3D animated spheres represent each regime and change visually when active.
Animated, bidirectional arrows reveal transition probabilities and allow you to see both dominant and less likely regime flows.
Particles (moving dots) animate along the arrows, enhancing the perception of regime flow direction and speed.
All elements dynamically update with each new price bar, providing a live market map in an intuitive, engaging format.
 Can I use custom indicators for regime classification? 
Yes! Enable the "Custom Indicators" switch and select any three chart series as inputs. These will be normalized and combined (each with equal weight), broadening the regime classification beyond just price-based movement.
 What does the “Lookback Period” control? 
Lookback Period (default: 100) sets how much historical data builds the probability matrix. Shorter periods adapt faster to regime changes but may be noisier. Longer periods are more stable but slower to adapt.
 How is this different from a Hidden Markov Model (HMM)? 
It sets the window for both regime detection and probability calculations. Lower values make the system more reactive, but potentially noisier. Higher values smooth estimates and make the system more robust.
 How is this Markov Chain different from a Hidden Markov Model (HMM)? 
Markov Chain (as here): All market regimes (Bull, Bear, Neutral) are directly observable on the chart. The transition matrix is built from actual detected regimes, keeping the model simple and interpretable.
Hidden Markov Model: The actual regimes are unobservable ("hidden") and must be inferred from market output or indicator "emissions" using statistical learning algorithms. HMMs are more complex, can capture more subtle structure, but are harder to visualize and require additional machine learning steps for training.
A standard Markov Chain models transitions between observable states using a simple transition matrix, while a Hidden Markov Model assumes the true states are hidden (latent) and must be inferred from observable “emissions” like price or volume data. In practical terms, a Markov Chain is transparent and easier to implement and interpret; an HMM is more expressive but requires statistical inference to estimate hidden states from data.
Markov Chain: states are observable; you directly count or estimate transition probabilities between visible states. This makes it simpler, faster, and easier to validate and tune.
HMM: states are hidden; you only observe emissions generated by those latent states. Learning involves machine learning/statistical algorithms (commonly Baum–Welch/EM for training and Viterbi for decoding) to infer both the transition dynamics and the most likely hidden state sequence from data.
  How does the indicator avoid “repainting” or look-ahead bias? 
All regime changes and matrix updates happen only on confirmed (closed) bars, so no future data is leaked, ensuring reliable real-time operation.
 Are there practical tuning tips? 
Tune the Lookback Period for your asset/timeframe: shorter for fast markets, longer for stability.
Use custom indicators if your asset has unique regime drivers.
Watch for rapid changes in transition probabilities as early warning of a possible regime shift.
 Who is this indicator for? 
Quants and quantitative researchers exploring probabilistic market modeling, especially those interested in regime-switching dynamics and Markov models.
Programmers and system developers who need a probabilistic regime filter for systematic and algorithmic backtesting:
The Markov Chain   indicator is ideally suited for programmatic integration via its bias output (1 = Bull, 0 = Neutral, -1 = Bear).
Although the visualization is engaging, the core output is designed for automated, rules-based workflows—not for discretionary/manual trading decisions.
Developers can connect the indicator’s output directly to their Pine Script logic (using input.source()), allowing rapid and robust backtesting of regime-based strategies.
It acts as a plug-and-play regime filter: simply plug the bias output into your entry/exit logic, and you have a scientifically robust, probabilistically-derived signal for filtering, timing, position sizing, or risk regimes.
The MC's output is intentionally "trinary" (1/0/-1), focusing on clear regime states for unambiguous decision-making in code. If you require nuanced, multi-probability or soft-label state vectors, consider expanding the indicator or stacking it with a probability-weighted logic layer in your scripting.
Because it avoids subjectivity, this approach is optimal for systematic quants, algo developers building backtested, repeatable strategies based on probabilistic regime analysis.
 What's the mathematical foundation behind this? 
The mathematical foundation behind this Markov Chain indicator—and probabilistic regime detection in finance—draws from two principal models: the (standard) Markov Chain and the Hidden Markov Model (HMM).
 How to use this indicator programmatically? 
The Markov Chain   indicator automatically exports a  bias value (+1 for Bullish, -1 for Bearish, 0 for Neutral)  as a plot visible in the Data Window. This allows you to integrate its regime signal into your own scripts and strategies for backtesting, automation, or live trading.
 Step-by-Step Integration with Pine Script (input.source) 
 Add the Markov Chain indicator to your chart. 
This must be done first, since your custom script will "pull" the bias signal from the indicator's plot.
 In your strategy, create an input using input.source() 
Example:
 //@version=5
strategy("MC Bias Strategy Example")
mcBias = input.source(close, "MC Bias Source")
 
After saving, go to your script’s settings. For the “MC Bias Source” input, select the plot/output of the Markov Chain indicator (typically its bias plot).
 Use the bias in your trading logic 
Example (long only on Bull, flat otherwise):
 if mcBias == 1
    strategy.entry("Long", strategy.long)
else
    strategy.close("Long")
 
For more advanced workflows, combine mcBias with additional filters or trailing stops.
 How does this work behind-the-scenes? 
 TradingView’s input.source()  lets you use any plot from another indicator as a real-time, “live” data feed in your own script (source).
The selected bias signal is available to your Pine code as a variable, enabling logical decisions based on regime (trend-following, mean-reversion, etc.).
This enables powerful  strategy modularity : decouple regime detection from entry/exit logic, allowing fast experimentation without rewriting core signal code.
 Integrating 45+ Indicators with Your Markov Chain — How & Why 
The  Enhanced Custom Indicators Export  script exports a massive suite of over 45 technical indicators—ranging from classic momentum (RSI, MACD, Stochastic, etc.) to trend, volume, volatility, and oscillator tools—all pre-calculated, centered/scaled, and available as plots.
 // Enhanced Custom Indicators Export - 45 Technical Indicators
// Comprehensive technical analysis suite for advanced market regime detection
//@version=6
indicator('Enhanced Custom Indicators Export | Fractalyst', shorttitle='Enhanced CI Export', overlay=false, scale=scale.right, max_labels_count=500, max_lines_count=500)
// |----- Input Parameters -----| //
momentum_group = "Momentum Indicators"
trend_group = "Trend Indicators"
volume_group = "Volume Indicators"
volatility_group = "Volatility Indicators"
oscillator_group = "Oscillator Indicators"
display_group = "Display Settings"
// Common lengths
length_14 = input.int(14, "Standard Length (14)", minval=1, maxval=100, group=momentum_group)
length_20 = input.int(20, "Medium Length (20)", minval=1, maxval=200, group=trend_group)
length_50 = input.int(50, "Long Length (50)", minval=1, maxval=200, group=trend_group)
// Display options
show_table = input.bool(true, "Show Values Table", group=display_group)
table_size = input.string("Small", "Table Size", options= , group=display_group)
// |----- MOMENTUM INDICATORS (15 indicators) -----| //
// 1. RSI (Relative Strength Index)
rsi_14 = ta.rsi(close, length_14)
rsi_centered = rsi_14 - 50
// 2. Stochastic Oscillator
stoch_k = ta.stoch(close, high, low, length_14)
stoch_d = ta.sma(stoch_k, 3)
stoch_centered = stoch_k - 50
// 3. Williams %R
williams_r = ta.stoch(close, high, low, length_14) - 100
// 4. MACD (Moving Average Convergence Divergence)
  = ta.macd(close, 12, 26, 9)
// 5. Momentum (Rate of Change)
momentum = ta.mom(close, length_14)
momentum_pct = (momentum / close ) * 100
// 6. Rate of Change (ROC)
roc = ta.roc(close, length_14)
// 7. Commodity Channel Index (CCI)
cci = ta.cci(close, length_20)
// 8. Money Flow Index (MFI)
mfi = ta.mfi(close, length_14)
mfi_centered = mfi - 50
// 9. Awesome Oscillator (AO)
ao = ta.sma(hl2, 5) - ta.sma(hl2, 34)
// 10. Accelerator Oscillator (AC)
ac = ao - ta.sma(ao, 5)
// 11. Chande Momentum Oscillator (CMO)
cmo = ta.cmo(close, length_14)
// 12. Detrended Price Oscillator (DPO)
dpo = close - ta.sma(close, length_20) 
// 13. Price Oscillator (PPO)
ppo = ta.sma(close, 12) - ta.sma(close, 26)
ppo_pct = (ppo / ta.sma(close, 26)) * 100
// 14. TRIX
trix_ema1 = ta.ema(close, length_14)
trix_ema2 = ta.ema(trix_ema1, length_14)
trix_ema3 = ta.ema(trix_ema2, length_14)
trix = ta.roc(trix_ema3, 1) * 10000
// 15. Klinger Oscillator
klinger = ta.ema(volume * (high + low + close) / 3, 34) - ta.ema(volume * (high + low + close) / 3, 55)
// 16. Fisher Transform
fisher_hl2 = 0.5 * (hl2 - ta.lowest(hl2, 10)) / (ta.highest(hl2, 10) - ta.lowest(hl2, 10)) - 0.25
fisher = 0.5 * math.log((1 + fisher_hl2) / (1 - fisher_hl2))
// 17. Stochastic RSI
stoch_rsi = ta.stoch(rsi_14, rsi_14, rsi_14, length_14)
stoch_rsi_centered = stoch_rsi - 50
// 18. Relative Vigor Index (RVI)
rvi_num = ta.swma(close - open)
rvi_den = ta.swma(high - low)
rvi = rvi_den != 0 ? rvi_num / rvi_den : 0
// 19. Balance of Power (BOP)
bop = (close - open) / (high - low)
// |----- TREND INDICATORS (10 indicators) -----| //
// 20. Simple Moving Average Momentum
sma_20 = ta.sma(close, length_20)
sma_momentum = ((close - sma_20) / sma_20) * 100
// 21. Exponential Moving Average Momentum
ema_20 = ta.ema(close, length_20)
ema_momentum = ((close - ema_20) / ema_20) * 100
// 22. Parabolic SAR
sar = ta.sar(0.02, 0.02, 0.2)
sar_trend = close > sar ? 1 : -1
// 23. Linear Regression Slope
lr_slope = ta.linreg(close, length_20, 0) - ta.linreg(close, length_20, 1)
// 24. Moving Average Convergence (MAC)
mac = ta.sma(close, 10) - ta.sma(close, 30)
// 25. Trend Intensity Index (TII)
tii_sum = 0.0
for i = 1 to length_20
    tii_sum += close > close  ? 1 : 0
tii = (tii_sum / length_20) * 100
// 26. Ichimoku Cloud Components
ichimoku_tenkan = (ta.highest(high, 9) + ta.lowest(low, 9)) / 2
ichimoku_kijun = (ta.highest(high, 26) + ta.lowest(low, 26)) / 2
ichimoku_signal = ichimoku_tenkan > ichimoku_kijun ? 1 : -1
// 27. MESA Adaptive Moving Average (MAMA)
mama_alpha = 2.0 / (length_20 + 1)
mama = ta.ema(close, length_20)
mama_momentum = ((close - mama) / mama) * 100
// 28. Zero Lag Exponential Moving Average (ZLEMA)
zlema_lag = math.round((length_20 - 1) / 2)
zlema_data = close + (close - close )
zlema = ta.ema(zlema_data, length_20)
zlema_momentum = ((close - zlema) / zlema) * 100
// |----- VOLUME INDICATORS (6 indicators) -----| //
// 29. On-Balance Volume (OBV)
obv = ta.obv
// 30. Volume Rate of Change (VROC)
vroc = ta.roc(volume, length_14)
// 31. Price Volume Trend (PVT)
pvt = ta.pvt
// 32. Negative Volume Index (NVI)
nvi = 0.0
nvi := volume < volume  ? nvi  + ((close - close ) / close ) * nvi  : nvi 
// 33. Positive Volume Index (PVI)
pvi = 0.0
pvi := volume > volume  ? pvi  + ((close - close ) / close ) * pvi  : pvi 
// 34. Volume Oscillator
vol_osc = ta.sma(volume, 5) - ta.sma(volume, 10)
// 35. Ease of Movement (EOM)
eom_distance = high - low
eom_box_height = volume / 1000000
eom = eom_box_height != 0 ? eom_distance / eom_box_height : 0
eom_sma = ta.sma(eom, length_14)
// 36. Force Index
force_index = volume * (close - close )
force_index_sma = ta.sma(force_index, length_14)
// |----- VOLATILITY INDICATORS (10 indicators) -----| //
// 37. Average True Range (ATR)
atr = ta.atr(length_14)
atr_pct = (atr / close) * 100
// 38. Bollinger Bands Position
bb_basis = ta.sma(close, length_20)
bb_dev = 2.0 * ta.stdev(close, length_20)
bb_upper = bb_basis + bb_dev
bb_lower = bb_basis - bb_dev
bb_position = bb_dev != 0 ? (close - bb_basis) / bb_dev : 0
bb_width = bb_dev != 0 ? (bb_upper - bb_lower) / bb_basis * 100 : 0
// 39. Keltner Channels Position
kc_basis = ta.ema(close, length_20)
kc_range = ta.ema(ta.tr, length_20)
kc_upper = kc_basis + (2.0 * kc_range)
kc_lower = kc_basis - (2.0 * kc_range)
kc_position = kc_range != 0 ? (close - kc_basis) / kc_range : 0
// 40. Donchian Channels Position
dc_upper = ta.highest(high, length_20)
dc_lower = ta.lowest(low, length_20)
dc_basis = (dc_upper + dc_lower) / 2
dc_position = (dc_upper - dc_lower) != 0 ? (close - dc_basis) / (dc_upper - dc_lower) : 0
// 41. Standard Deviation
std_dev = ta.stdev(close, length_20)
std_dev_pct = (std_dev / close) * 100
// 42. Relative Volatility Index (RVI)
rvi_up = ta.stdev(close > close  ? close : 0, length_14)
rvi_down = ta.stdev(close < close  ? close : 0, length_14)
rvi_total = rvi_up + rvi_down
rvi_volatility = rvi_total != 0 ? (rvi_up / rvi_total) * 100 : 50
// 43. Historical Volatility
hv_returns = math.log(close / close )
hv = ta.stdev(hv_returns, length_20) * math.sqrt(252) * 100
// 44. Garman-Klass Volatility
gk_vol = math.log(high/low) * math.log(high/low) - (2*math.log(2)-1) * math.log(close/open) * math.log(close/open)
gk_volatility = math.sqrt(ta.sma(gk_vol, length_20)) * 100
// 45. Parkinson Volatility
park_vol = math.log(high/low) * math.log(high/low)
parkinson = math.sqrt(ta.sma(park_vol, length_20) / (4 * math.log(2))) * 100
// 46. Rogers-Satchell Volatility
rs_vol = math.log(high/close) * math.log(high/open) + math.log(low/close) * math.log(low/open)
rogers_satchell = math.sqrt(ta.sma(rs_vol, length_20)) * 100
// |----- OSCILLATOR INDICATORS (5 indicators) -----| //
// 47. Elder Ray Index
elder_bull = high - ta.ema(close, 13)
elder_bear = low - ta.ema(close, 13)
elder_power = elder_bull + elder_bear
// 48. Schaff Trend Cycle (STC)
stc_macd = ta.ema(close, 23) - ta.ema(close, 50)
stc_k = ta.stoch(stc_macd, stc_macd, stc_macd, 10)
stc_d = ta.ema(stc_k, 3)
stc = ta.stoch(stc_d, stc_d, stc_d, 10)
// 49. Coppock Curve
coppock_roc1 = ta.roc(close, 14)
coppock_roc2 = ta.roc(close, 11)
coppock = ta.wma(coppock_roc1 + coppock_roc2, 10)
// 50. Know Sure Thing (KST)
kst_roc1 = ta.roc(close, 10)
kst_roc2 = ta.roc(close, 15)
kst_roc3 = ta.roc(close, 20)
kst_roc4 = ta.roc(close, 30)
kst = ta.sma(kst_roc1, 10) + 2*ta.sma(kst_roc2, 10) + 3*ta.sma(kst_roc3, 10) + 4*ta.sma(kst_roc4, 15)
// 51. Percentage Price Oscillator (PPO)
ppo_line = ((ta.ema(close, 12) - ta.ema(close, 26)) / ta.ema(close, 26)) * 100
ppo_signal = ta.ema(ppo_line, 9)
ppo_histogram = ppo_line - ppo_signal
// |----- PLOT MAIN INDICATORS -----| //
// Plot key momentum indicators
plot(rsi_centered, title="01_RSI_Centered", color=color.purple, linewidth=1)
plot(stoch_centered, title="02_Stoch_Centered", color=color.blue, linewidth=1)
plot(williams_r, title="03_Williams_R", color=color.red, linewidth=1)
plot(macd_histogram, title="04_MACD_Histogram", color=color.orange, linewidth=1)
plot(cci, title="05_CCI", color=color.green, linewidth=1)
// Plot trend indicators
plot(sma_momentum, title="06_SMA_Momentum", color=color.navy, linewidth=1)
plot(ema_momentum, title="07_EMA_Momentum", color=color.maroon, linewidth=1)
plot(sar_trend, title="08_SAR_Trend", color=color.teal, linewidth=1)
plot(lr_slope, title="09_LR_Slope", color=color.lime, linewidth=1)
plot(mac, title="10_MAC", color=color.fuchsia, linewidth=1)
// Plot volatility indicators
plot(atr_pct, title="11_ATR_Pct", color=color.yellow, linewidth=1)
plot(bb_position, title="12_BB_Position", color=color.aqua, linewidth=1)
plot(kc_position, title="13_KC_Position", color=color.olive, linewidth=1)
plot(std_dev_pct, title="14_StdDev_Pct", color=color.silver, linewidth=1)
plot(bb_width, title="15_BB_Width", color=color.gray, linewidth=1)
// Plot volume indicators
plot(vroc, title="16_VROC", color=color.blue, linewidth=1)
plot(eom_sma, title="17_EOM", color=color.red, linewidth=1)
plot(vol_osc, title="18_Vol_Osc", color=color.green, linewidth=1)
plot(force_index_sma, title="19_Force_Index", color=color.orange, linewidth=1)
plot(obv, title="20_OBV", color=color.purple, linewidth=1)
// Plot additional oscillators
plot(ao, title="21_Awesome_Osc", color=color.navy, linewidth=1)
plot(cmo, title="22_CMO", color=color.maroon, linewidth=1)
plot(dpo, title="23_DPO", color=color.teal, linewidth=1)
plot(trix, title="24_TRIX", color=color.lime, linewidth=1)
plot(fisher, title="25_Fisher", color=color.fuchsia, linewidth=1)
// Plot more momentum indicators
plot(mfi_centered, title="26_MFI_Centered", color=color.yellow, linewidth=1)
plot(ac, title="27_AC", color=color.aqua, linewidth=1)
plot(ppo_pct, title="28_PPO_Pct", color=color.olive, linewidth=1)
plot(stoch_rsi_centered, title="29_StochRSI_Centered", color=color.silver, linewidth=1)
plot(klinger, title="30_Klinger", color=color.gray, linewidth=1)
// Plot trend continuation
plot(tii, title="31_TII", color=color.blue, linewidth=1)
plot(ichimoku_signal, title="32_Ichimoku_Signal", color=color.red, linewidth=1)
plot(mama_momentum, title="33_MAMA_Momentum", color=color.green, linewidth=1)
plot(zlema_momentum, title="34_ZLEMA_Momentum", color=color.orange, linewidth=1)
plot(bop, title="35_BOP", color=color.purple, linewidth=1)
// Plot volume continuation
plot(nvi, title="36_NVI", color=color.navy, linewidth=1)
plot(pvi, title="37_PVI", color=color.maroon, linewidth=1)
plot(momentum_pct, title="38_Momentum_Pct", color=color.teal, linewidth=1)
plot(roc, title="39_ROC", color=color.lime, linewidth=1)
plot(rvi, title="40_RVI", color=color.fuchsia, linewidth=1)
// Plot volatility continuation
plot(dc_position, title="41_DC_Position", color=color.yellow, linewidth=1)
plot(rvi_volatility, title="42_RVI_Volatility", color=color.aqua, linewidth=1)
plot(hv, title="43_Historical_Vol", color=color.olive, linewidth=1)
plot(gk_volatility, title="44_GK_Volatility", color=color.silver, linewidth=1)
plot(parkinson, title="45_Parkinson_Vol", color=color.gray, linewidth=1)
// Plot final oscillators
plot(rogers_satchell, title="46_RS_Volatility", color=color.blue, linewidth=1)
plot(elder_power, title="47_Elder_Power", color=color.red, linewidth=1)
plot(stc, title="48_STC", color=color.green, linewidth=1)
plot(coppock, title="49_Coppock", color=color.orange, linewidth=1)
plot(kst, title="50_KST", color=color.purple, linewidth=1)
// Plot final indicators
plot(ppo_histogram, title="51_PPO_Histogram", color=color.navy, linewidth=1)
plot(pvt, title="52_PVT", color=color.maroon, linewidth=1)
// |----- Reference Lines -----| //
hline(0, "Zero Line", color=color.gray, linestyle=hline.style_dashed, linewidth=1)
hline(50, "Midline", color=color.gray, linestyle=hline.style_dotted, linewidth=1)
hline(-50, "Lower Midline", color=color.gray, linestyle=hline.style_dotted, linewidth=1)
hline(25, "Upper Threshold", color=color.gray, linestyle=hline.style_dotted, linewidth=1)
hline(-25, "Lower Threshold", color=color.gray, linestyle=hline.style_dotted, linewidth=1)
// |----- Enhanced Information Table -----| //
if show_table and barstate.islast
    table_position = position.top_right
    table_text_size = table_size == "Tiny" ? size.tiny : table_size == "Small" ? size.small : size.normal
    
    var table info_table = table.new(table_position, 3, 18, bgcolor=color.new(color.white, 85), border_width=1, border_color=color.gray)
    
    // Headers
    table.cell(info_table, 0, 0, 'Category', text_color=color.black, text_size=table_text_size, bgcolor=color.new(color.blue, 70))
    table.cell(info_table, 1, 0, 'Indicator', text_color=color.black, text_size=table_text_size, bgcolor=color.new(color.blue, 70))
    table.cell(info_table, 2, 0, 'Value', text_color=color.black, text_size=table_text_size, bgcolor=color.new(color.blue, 70))
    
    // Key Momentum Indicators
    table.cell(info_table, 0, 1, 'MOMENTUM', text_color=color.purple, text_size=table_text_size, bgcolor=color.new(color.purple, 90))
    table.cell(info_table, 1, 1, 'RSI Centered', text_color=color.purple, text_size=table_text_size)
    table.cell(info_table, 2, 1, str.tostring(rsi_centered, '0.00'), text_color=color.purple, text_size=table_text_size)
    
    table.cell(info_table, 0, 2, '', text_color=color.blue, text_size=table_text_size)
    table.cell(info_table, 1, 2, 'Stoch Centered', text_color=color.blue, text_size=table_text_size)
    table.cell(info_table, 2, 2, str.tostring(stoch_centered, '0.00'), text_color=color.blue, text_size=table_text_size)
    
    table.cell(info_table, 0, 3, '', text_color=color.red, text_size=table_text_size)
    table.cell(info_table, 1, 3, 'Williams %R', text_color=color.red, text_size=table_text_size)
    table.cell(info_table, 2, 3, str.tostring(williams_r, '0.00'), text_color=color.red, text_size=table_text_size)
    
    table.cell(info_table, 0, 4, '', text_color=color.orange, text_size=table_text_size)
    table.cell(info_table, 1, 4, 'MACD Histogram', text_color=color.orange, text_size=table_text_size)
    table.cell(info_table, 2, 4, str.tostring(macd_histogram, '0.000'), text_color=color.orange, text_size=table_text_size)
    
    table.cell(info_table, 0, 5, '', text_color=color.green, text_size=table_text_size)
    table.cell(info_table, 1, 5, 'CCI', text_color=color.green, text_size=table_text_size)
    table.cell(info_table, 2, 5, str.tostring(cci, '0.00'), text_color=color.green, text_size=table_text_size)
    
    // Key Trend Indicators
    table.cell(info_table, 0, 6, 'TREND', text_color=color.navy, text_size=table_text_size, bgcolor=color.new(color.navy, 90))
    table.cell(info_table, 1, 6, 'SMA Momentum %', text_color=color.navy, text_size=table_text_size)
    table.cell(info_table, 2, 6, str.tostring(sma_momentum, '0.00'), text_color=color.navy, text_size=table_text_size)
    
    table.cell(info_table, 0, 7, '', text_color=color.maroon, text_size=table_text_size)
    table.cell(info_table, 1, 7, 'EMA Momentum %', text_color=color.maroon, text_size=table_text_size)
    table.cell(info_table, 2, 7, str.tostring(ema_momentum, '0.00'), text_color=color.maroon, text_size=table_text_size)
    
    table.cell(info_table, 0, 8, '', text_color=color.teal, text_size=table_text_size)
    table.cell(info_table, 1, 8, 'SAR Trend', text_color=color.teal, text_size=table_text_size)
    table.cell(info_table, 2, 8, str.tostring(sar_trend, '0'), text_color=color.teal, text_size=table_text_size)
    
    table.cell(info_table, 0, 9, '', text_color=color.lime, text_size=table_text_size)
    table.cell(info_table, 1, 9, 'Linear Regression', text_color=color.lime, text_size=table_text_size)
    table.cell(info_table, 2, 9, str.tostring(lr_slope, '0.000'), text_color=color.lime, text_size=table_text_size)
    
    // Key Volatility Indicators
    table.cell(info_table, 0, 10, 'VOLATILITY', text_color=color.yellow, text_size=table_text_size, bgcolor=color.new(color.yellow, 90))
    table.cell(info_table, 1, 10, 'ATR %', text_color=color.yellow, text_size=table_text_size)
    table.cell(info_table, 2, 10, str.tostring(atr_pct, '0.00'), text_color=color.yellow, text_size=table_text_size)
    
    table.cell(info_table, 0, 11, '', text_color=color.aqua, text_size=table_text_size)
    table.cell(info_table, 1, 11, 'BB Position', text_color=color.aqua, text_size=table_text_size)
    table.cell(info_table, 2, 11, str.tostring(bb_position, '0.00'), text_color=color.aqua, text_size=table_text_size)
    
    table.cell(info_table, 0, 12, '', text_color=color.olive, text_size=table_text_size)
    table.cell(info_table, 1, 12, 'KC Position', text_color=color.olive, text_size=table_text_size)
    table.cell(info_table, 2, 12, str.tostring(kc_position, '0.00'), text_color=color.olive, text_size=table_text_size)
    
    // Key Volume Indicators
    table.cell(info_table, 0, 13, 'VOLUME', text_color=color.blue, text_size=table_text_size, bgcolor=color.new(color.blue, 90))
    table.cell(info_table, 1, 13, 'Volume ROC', text_color=color.blue, text_size=table_text_size)
    table.cell(info_table, 2, 13, str.tostring(vroc, '0.00'), text_color=color.blue, text_size=table_text_size)
    
    table.cell(info_table, 0, 14, '', text_color=color.red, text_size=table_text_size)
    table.cell(info_table, 1, 14, 'EOM', text_color=color.red, text_size=table_text_size)
    table.cell(info_table, 2, 14, str.tostring(eom_sma, '0.000'), text_color=color.red, text_size=table_text_size)
    
    // Key Oscillators
    table.cell(info_table, 0, 15, 'OSCILLATORS', text_color=color.purple, text_size=table_text_size, bgcolor=color.new(color.purple, 90))
    table.cell(info_table, 1, 15, 'Awesome Osc', text_color=color.blue, text_size=table_text_size)
    table.cell(info_table, 2, 15, str.tostring(ao, '0.000'), text_color=color.blue, text_size=table_text_size)
    
    table.cell(info_table, 0, 16, '', text_color=color.red, text_size=table_text_size)
    table.cell(info_table, 1, 16, 'Fisher Transform', text_color=color.red, text_size=table_text_size)
    table.cell(info_table, 2, 16, str.tostring(fisher, '0.000'), text_color=color.red, text_size=table_text_size)
    
    // Summary Statistics
    table.cell(info_table, 0, 17, 'SUMMARY', text_color=color.black, text_size=table_text_size, bgcolor=color.new(color.gray, 70))
    table.cell(info_table, 1, 17, 'Total Indicators: 52', text_color=color.black, text_size=table_text_size)
    regime_color = rsi_centered > 10 ? color.green : rsi_centered < -10 ? color.red : color.gray
    regime_text = rsi_centered > 10 ? "BULLISH" : rsi_centered < -10 ? "BEARISH" : "NEUTRAL"
    table.cell(info_table, 2, 17, regime_text, text_color=regime_color, text_size=table_text_size) 
This makes it the perfect “indicator backbone” for quantitative and systematic traders who want to prototype, combine, and test new regime detection models—especially in combination with the  Markov Chain   indicator.
 How to use this script with the Markov Chain for research and backtesting: 
 Add the Enhanced Indicator Export to your chart. 
Every calculated indicator is available as an individual data stream.
 Connect the indicator(s) you want as custom input(s) to the Markov Chain’s “Custom Indicators” option. 
In the Markov Chain indicator’s settings, turn ON the custom indicator mode.
For each of the three custom indicator inputs, select the exported plot from the Enhanced Export script—the menu lists all 45+ signals by name.
This creates a powerful, modular regime-detection engine where you can mix-and-match momentum, trend, volume, or custom combinations for advanced filtering.
 Backtest regime logic directly. 
Once you’ve connected your chosen indicators, the Markov Chain script performs regime detection (Bull/Neutral/Bear) based on your selected features—not just price returns.
The regime detection is robust, automatically normalized (using Z-score), and outputs bias (1, -1, 0) for plug-and-play integration.
 Export the regime bias for programmatic use. 
As described above, use  input.source()  in your Pine Script strategy or system and link the bias output.
You can now filter signals, control trade direction/size, or design pairs-trading that respect true, indicator-driven market regimes.
With this framework, you’re not limited to static or simplistic regime filters. You can rigorously define, test, and refine what “market regime” means for your strategies—using the technical features that matter most to you.
Optimize your signal generation by backtesting across a universe of meaningful indicator blends.
Enhance risk management with objective, real-time regime boundaries.
Accelerate your research: iterate quickly, swap indicator components, and see results with minimal code changes.
Automate multi-asset or pairs-trading by integrating regime context directly into strategy logic.
Add both scripts to your chart, connect your preferred features, and start investigating your best regime-based trades—entirely within the TradingView ecosystem.
 References & Further Reading 
Ang, A., & Bekaert, G. (2002). “Regime Switches in Interest Rates.” Journal of Business & Economic Statistics, 20(2), 163–182.
Hamilton, J. D. (1989). “A New Approach to the Economic Analysis of Nonstationary Time Series and the Business Cycle.” Econometrica, 57(2), 357–384.
Markov, A. A. (1906). "Extension of the Limit Theorems of Probability Theory to a Sum of Variables Connected in a Chain." The Notes of the Imperial Academy of Sciences of St. Petersburg.
Guidolin, M., & Timmermann, A. (2007). “Asset Allocation under Multivariate Regime Switching.” Journal of Economic Dynamics and Control, 31(11), 3503–3544.
Murphy, J. J. (1999). Technical Analysis of the Financial Markets. New York Institute of Finance.
Brock, W., Lakonishok, J., & LeBaron, B. (1992). “Simple Technical Trading Rules and the Stochastic Properties of Stock Returns.” Journal of Finance, 47(5), 1731–1764.
Zucchini, W., MacDonald, I. L., & Langrock, R. (2017). Hidden Markov Models for Time Series: An Introduction Using R (2nd ed.). Chapman and Hall/CRC.
 On Quantitative Finance and Markov Models: 
Lo, A. W., & Hasanhodzic, J. (2009). The Heretics of Finance: Conversations with Leading Practitioners of Technical Analysis. Bloomberg Press.  
Patterson, S. (2016). The Man Who Solved the Market: How Jim Simons Launched the Quant Revolution. Penguin Press.  
TradingView Pine Script Documentation: www.tradingview.com
TradingView Blog: “Use an Input From Another Indicator With Your Strategy” www.tradingview.com
GeeksforGeeks: “What is the Difference Between Markov Chains and Hidden Markov Models?” www.geeksforgeeks.org
 What makes this indicator original and unique? 
-  On‑chart, real‑time Markov.  The chain is drawn directly on your chart. You see the current regime, its tendency to  stay  (self‑loop), and the usual next step (arrows) as bars confirm.
-  Source‑agnostic by design.  The engine runs on any series you select via  input.source()  — price, your own oscillator, a composite score, anything you compute in the script.
-  Automatic normalization + regime mapping.  Different inputs live on different scales. The script standardizes your chosen source and maps it into clear regimes (e.g., Bull / Bear / Neutral) without you micromanaging thresholds each time.
-  Rolling, bar‑by‑bar learning.  Transition tendencies are computed from a rolling window of confirmed bars. What you see is exactly what the market did in that window.
-  Fast experimentation.  Switch the source, adjust the window, and the Markov view updates instantly. It’s a rapid way to test ideas and feel regime persistence/switch behavior.
 Integrate your own signals (using input.source()) 
- In settings, choose the  Source . This is powered by  input.source() .
- Feed it price, an indicator you compute inside the script, or a custom composite series.
- The script will automatically normalize that series and process it through the Markov engine, mapping it to regimes and updating the on‑chart spheres/arrows in real time.
 Credits: 
Deep gratitude to @RicardoSantos for both the foundational Markov chain processing engine and inspiring open-source contributions, which made advanced probabilistic market modeling accessible to the TradingView community.
Special thanks to @Alien_Algorithms for the innovative and visually stunning 3D sphere logic that powers the indicator’s animated, regime-based visualization.
 Disclaimer 
This tool summarizes recent behavior. It is not financial advice and not a guarantee of future results.
Seasonality Monte Carlo Forecaster [BackQuant]Seasonality Monte Carlo Forecaster  
 Plain-English overview 
This tool projects a cone of plausible future prices by combining two ideas that traders already use intuitively: seasonality and uncertainty. It watches how your market typically behaves around this calendar date, turns that seasonal tendency into a small daily “drift,” then runs many randomized price paths forward to estimate where price could land tomorrow, next week, or a month from now. The result is a probability cone with a clear expected path, plus optional overlays that show how past years tended to move from this point on the calendar. It is a planning tool, not a crystal ball: the goal is to quantify ranges and odds so you can size, place stops, set targets, and time entries with more realism.
 What Monte Carlo is and why quants rely on it 
•  Definition . Monte Carlo simulation is a way to answer “what might happen next?” when there is randomness in the system. Instead of producing a single forecast, it generates thousands of alternate futures by repeatedly sampling random shocks and adding them to a model of how prices evolve.
•  Why it is used . Markets are noisy. A single point forecast hides risk. Monte Carlo gives a  distribution  of outcomes so you can reason in probabilities: the median path, the 68% band, the 95% band, tail risks, and the chance of hitting a specific level within a horizon.
•  Core strengths in quant finance .
–  Path-dependent questions : “What is the probability we touch a stop before a target?” “What is the expected drawdown on the way to my objective?”
–  Pricing and risk : Useful for path-dependent options, Value-at-Risk (VaR), expected shortfall (CVaR), stress paths, and scenario analysis when closed-form formulas are unrealistic.
–  Planning under uncertainty : Portfolio construction and rebalancing rules can be tested against a cloud of plausible futures rather than a single guess.
•  Why it fits trading workflows . It turns gut feel like “seasonality is supportive here” into quantitative ranges: “median path suggests +X% with a 68% band of ±Y%; stop at Z has only ~16% odds of being tagged in N days.”
 How this indicator builds its probability cone 
 1) Seasonal pattern discovery 
The script builds two day-of-year maps as new data arrives:
• A  return map  where each calendar day stores an exponentially smoothed average of that day’s log return (yesterday→today). The smoothing (90% old, 10% new) behaves like an EWMA, letting older seasons matter while adapting to new information.
• A  volatility map  that tracks the typical absolute return for the same calendar day.
It calculates the day-of-year carefully (with leap-year adjustment) and indexes into a 365-slot seasonal array so “March 18” is compared with past March 18ths. This becomes the  seasonal bias  that gently nudges simulations up or down on each forecast day.
 2) Choice of randomness engine 
You can pick how the future shocks are generated:
•  Daily mode  uses a Gaussian draw with the seasonal bias as the mean and a volatility that comes from realized returns, scaled down to avoid over-fitting. It relies on the Box–Muller transform internally to turn two uniform random numbers into one normal shock.
•  Weekly mode  uses  bootstrap sampling  from the seasonal return history (resampling actual historical daily drifts and then blending in a fraction of the seasonal bias). Bootstrapping is robust when the empirical distribution has asymmetry or fatter tails than a normal distribution.
Both modes seed their random draws deterministically per path and day, which makes plots reproducible bar-to-bar and avoids flickering bands.
 3) Volatility scaling to current conditions 
Markets do not always live in average volatility. The engine computes a simple  volatility factor  from ATR(20)/price and scales the simulated shocks up or down within sensible bounds (clamped between 0.5× and 2.0×). When the current regime is quiet, the cone narrows; when ranges expand, the cone widens. This prevents the classic mistake of projecting calm markets into a storm or vice versa.
 4) Many futures, summarized by percentiles 
The model generates a matrix of price paths (capped at 100 runs for performance inside TradingView), each path stepping forward for your selected horizon. For each forecast day it sorts the simulated prices and pulls key percentiles:
•  5th and 95th  → approximate 95% band (outer cone).
•  16th and 84th  → approximate 68% band (inner cone).
•  50th  → the median or “expected path.”
These are drawn as polylines so you can immediately see central tendency and dispersion.
 5) A historical overlay (optional) 
Turn on the overlay to sketch a dotted path of what a purely seasonal projection would look like for the next ~30 days using only the return map, no randomness. This is not a forecast; it is a visual reminder of the seasonal drift you are biasing toward.
 Inputs you control and how to think about them 
 Monte Carlo Simulation 
•  Price Series for Calculation . The source series, typically close.
•  Enable Probability Forecasts . Master switch for simulation and drawing.
•  Simulation Iterations . Requested number of paths to run. Internally capped at 100 to protect performance, which is generally enough to estimate the percentiles for a trading chart. If you need ultra-smooth bands, shorten the horizon.
•  Forecast Days Ahead . The length of the cone. Longer horizons dilute seasonal signal and widen uncertainty.
•  Probability Bands . Draw all bands, just 95%, just 68%, or a custom level (display logic remains 68/95 internally; the custom number is for labeling and color choice).
•  Pattern Resolution .  Daily  leans on day-of-year effects like “turn-of-month” or holiday patterns.  Weekly  biases toward day-of-week tendencies and bootstraps from history.
•  Volatility Scaling . On by default so the cone respects today’s range context.
 Plotting & UI 
•  Probability Cone . Plots the outer and inner percentile envelopes.
•  Expected Path . Plots the median line through the cone.
•  Historical Overlay . Dotted seasonal-only projection for context.
•  Band Transparency/Colors . Customize primary (outer) and secondary (inner) band colors and the mean path color. Use higher transparency for cleaner charts.
 What appears on your chart 
• A  cone  starting at the most recent bar, fanning outward. The outer lines are the ~95% band; the inner lines are the ~68% band.
• A  median path  (default blue) running through the center of the cone.
• An  info panel  on the final historical bar that summarizes simulation count, forecast days, number of seasonal patterns learned, the current day-of-year, expected percentage return to the median, and the approximate 95% half-range in percent.
• Optional  historical seasonal path  drawn as dotted segments for the next 30 bars.
 How to use it in trading 
 1) Position sizing and stop logic 
The cone translates “volatility plus seasonality” into distances.
• Put stops  outside  the inner band if you want only ~16% odds of a stop-out due to noise before your thesis can play.
• Size positions so that a test of the inner band is survivable and a test of the outer band is rare but acceptable.
• If your target sits  inside  the 68% band at your horizon, the payoff is likely modest; outside the 68% but inside the 95% can justify “one-good-push” trades; beyond the 95% band is a low-probability flyer—consider scaling plans or optionality.
 2) Entry timing with seasonal bias 
When the median path slopes up from this calendar date and the cone is relatively narrow, a pullback toward the lower inner band can be a high-quality entry with a tight invalidation. If the median slopes down, fade rallies toward the upper band or step aside if it clashes with your system.
 3) Target selection 
Project your time horizon to N bars ahead, then pick targets around the median or the opposite inner band depending on your style. You can also anchor dynamic take-profits to the moving median as new bars arrive.
 4) Scenario planning & “what-ifs” 
Before events, glance at the cone: if the 95% band already spans a huge range, trade smaller, expect whips, and avoid placing stops at obvious band edges. If the cone is unusually tight, consider breakout tactics and be ready to add if volatility expands beyond the inner band with follow-through.
 5) Options and vol tactics 
•  When the cone is tight : Prefer long gamma structures (debit spreads) only if you expect a regime shift; otherwise premium selling may dominate.
•  When the cone is wide : Debit structures benefit from range; credit spreads need wider wings or smaller size. Align with your separate IV metrics.
 Reading the probability cone like a pro 
•  Cone slope  = seasonal drift. Upward slope means the calendar has historically favored positive drift from this date, downward slope the opposite.
•  Cone width  = regime volatility. A widening fan tells you that uncertainty grows fast; a narrow cone says the market typically stays contained.
•  Mean vs. price gap . If spot trades well above the median path and the upper band, mean-reversion risk is high. If spot presses the lower inner band in an up-sloping cone, you are in the “buy fear” zone.
•  Touches and pierces . Touching the inner band is common noise; piercing it with momentum signals potential regime change; the outer band should be rare and often brings snap-backs unless there is a structural catalyst.
 Methodological notes (what the code actually does) 
•  Log returns  are used for additivity and better statistical behavior: sim_ret is applied via exp(sim_ret) to evolve price.
•  Seasonal arrays  are updated online with EWMA (90/10) so the model keeps learning as each bar arrives.
•  Leap years  are handled; indexing still normalizes into a 365-slot map so the seasonal pattern remains stable.
•  Gaussian engine  (Daily mode) centers shocks on the seasonal bias with a conservative standard deviation.
•  Bootstrap engine  (Weekly mode) resamples from observed seasonal returns and adds a fraction of the bias, which captures skew and fat tails better.
•  Volatility adjustment  multiplies each daily shock by a factor derived from ATR(20)/price, clamped between 0.5 and 2.0 to avoid extreme cones.
•  Performance guardrails : simulations are capped at 100 paths; the probability cone uses polylines (no heavy fills) and only draws on the last confirmed bar to keep charts responsive.
•  Prerequisite data : at least ~30 seasonal entries are required before the model will draw a cone; otherwise it waits for more history.
 Strengths and limitations 
•  Strengths :
– Probabilistic thinking replaces single-point guessing.
– Seasonality adds a small but meaningful directional bias that many markets exhibit.
– Volatility scaling adapts to the current regime so the cone stays realistic.
•  Limitations :
– Seasonality can break around structural changes, policy shifts, or one-off events.
– The number of paths is performance-limited; percentile estimates are good for trading, not for academic precision.
– The model assumes tomorrow’s randomness resembles recent randomness; if regime shifts violently, the cone will lag until the EWMA adapts.
– Holidays and missing sessions can thin the seasonal sample for some assets; be cautious with very short histories.
 Tuning guide 
•  Horizon : 10–20 bars for tactical trades; 30+ for swing planning when you care more about broad ranges than precise targets.
•  Iterations : The default 100 is enough for stable 5/16/50/84/95 percentiles. If you crave smoother lines, shorten the horizon or run on higher timeframes.
•  Daily vs. Weekly : Daily for equities and crypto where month-end and turn-of-month effects matter; Weekly for futures and FX where day-of-week behavior is strong.
•  Volatility scaling : Keep it on. Turn off only when you intentionally want a “pure seasonality” cone unaffected by current turbulence.
 Workflow examples 
•  Swing continuation : Cone slopes up, price pulls into the lower inner band, your system fires. Enter near the band, stop just outside the outer line for the next 3–5 bars, target near the median or the opposite inner band.
•  Fade extremes : Cone is flat or down, price gaps to the upper outer band on news, then stalls. Favor mean-reversion toward the median, size small if volatility scaling is elevated.
•  Event play : Before CPI or earnings on a proxy index, check cone width. If the inner band is already wide, cut size or prefer options structures that benefit from range.
 Good habits 
• Pair the cone with your entry engine (breakout, pullback, order flow). Let Monte Carlo do range math; let your system do signal quality.
• Do not anchor blindly to the median; recalc after each bar. When the cone’s slope flips or width jumps, the plan should adapt.
• Validate seasonality for your symbol and timeframe; not every market has strong calendar effects.
 Summary 
The Seasonality Monte Carlo Forecaster wraps institutional risk planning into a single overlay: a data-driven seasonal drift, realistic volatility scaling, and a probabilistic cone that answers “where could we be, with what odds?” within your trading horizon. Use it to place stops where randomness is less likely to take you out, to set targets aligned with realistic travel, and to size positions with confidence born from distributions rather than hunches. It will not predict the future, but it will keep your decisions anchored to probabilities—the language markets actually speak.
Trishul Tap Signals (v6) — Liquidity Sweep + Imbalanced RetestTrishul Tap Signals — Liquidity Sweep + Imbalanced Retest
Type: Signal-only indicator (non-repainting)
Style: Price-action + Liquidity + Trend-following
Best for: Intraday & Swing Trading — any liquid market (stocks, futures, crypto, FX)
Timeframes: Any (5m–1D recommended)
Concept
The Trishul Tap setup is a liquidity-driven retest play inspired by order-flow and Smart Money Concepts.
It identifies one-sided impulse candles that also sweep liquidity (grab stops above/below a recent swing), then waits for price to retest the origin of that candle to enter in the trend direction.
Think of it as the three points of a trident:
Trend filter — Only signals with the prevailing trend.
Liquidity sweep — Candle takes out a recent swing high/low (stop-hunt).
Imbalanced retest — Price taps the candle’s open/low (bull) or open/high (bear).
Bullish Setup
Trend Filter: Price above EMA(200).
Impulse Candle:
Green close.
Upper wick ≥ (wickRatio × lower wick).
Lower wick ≤ (oppWickMaxFrac × full range).
Liquidity Sweep: Candle’s high exceeds the highest high of the last sweepLookback bars (excluding current).
Tap Entry: Buy signal triggers when price later taps the candle’s low or open (user choice) within expireBars.
Bearish Setup
Trend Filter: Price below EMA(200).
Impulse Candle:
Red close.
Lower wick ≥ (wickRatio × upper wick).
Upper wick ≤ (oppWickMaxFrac × full range).
Liquidity Sweep: Candle’s low breaks the lowest low of the last sweepLookback bars (excluding current).
Tap Entry: Sell signal triggers when price later taps the candle’s high or open (user choice) within expireBars.
Inputs
Trend EMA Length: Default 200.
Sweep Lookback: Number of bars for liquidity sweep check (default 20).
Wick Ratio: Required size ratio of dominant wick to opposite wick (default 2.0).
Opposite Wick Max %: Opposite wick must be ≤ this fraction of the candle’s range (default 25%).
Tap Tolerance (ticks): How close price must come to the level to count as a tap.
Expire Bars: Max bars after setup to allow a valid tap.
One Signal per Level: If ON, a base is “consumed” after first signal.
Plot Tap Levels: Show horizontal lines for active bases.
Show Setup Labels: Mark the origin sweep candle.
Plots & Visuals
EMA Trend Line — trend filter reference.
Tap Levels —
Green = bullish base (origin candle’s low/open).
Red = bearish base (origin candle’s high/open).
Labels — Show where the setup candle formed.
Signals —
BUY: triangle-up below bar at bullish tap.
SELL: triangle-down above bar at bearish tap.
Alerts
Two built-in conditions:
BUY Signal (Trishul Tap) — triggers on bullish tap.
SELL Signal (Trishul Tap) — triggers on bearish tap.
Set via Alerts panel → Condition = this indicator → Choose signal type.
How to Trade It
Use in liquid markets with clean price structure.
Confirm with HTF structure, volume spikes, or other confluence if desired.
Place stop just beyond the tap level (or ATR-based).
Target 1–2R or trail behind structure.
Why It Works
Liquidity sweep traps traders entering late (breakout buyers or panic sellers) and forces them to exit in the opposite direction, fueling your entry.
Wick imbalance confirms directional aggression by one side.
Trend filter keeps you aligned with the market’s dominant flow.
Retest entry lets you enter at a better price with reduced risk.
Non-Repainting
Setups form only on confirmed bar closes.
Signals trigger only on later bars that tap the stored level.
No lookahead functions are used.
Disclaimer
This script is for educational purposes only and does not constitute financial advice. Test thoroughly in a simulator or demo before using in live markets. Trading involves risk.
Ichimoku Cloud Signals [sgbpulse] Ichimoku Cloud Signals – Your Advanced Trading Tool  
Meet Ichimoku Cloud Signals, the enhanced and interactive version of the classic Ichimoku Cloud indicator, designed specifically for TradingView traders seeking precision and flexibility in their trading decisions. This indicator allows you to maximize the Ichimoku's potential by customizing trend criteria, receiving clear visual signals for entering and exiting positions, and getting alerts to keep you informed.
 Introduction to the Ichimoku Cloud 
The Ichimoku Cloud, also known as Ichimoku Kinko Hyo, is a comprehensive technical analysis tool developed in Japan. It provides a broad view of the market: trend direction, momentum, and support and resistance levels. "Ichimoku Cloud Signals" takes this power and amplifies it with advanced features.
 Key Components of the Ichimoku Cloud  
The indicator displays all five familiar Ichimoku lines, along with the "Cloud" (Kumo):
 
 Tenkan-sen (Conversion Line):  Calculated as the average of the highest high and lowest low over the past 9 periods. A fast, short-term indicator used as a measure of immediate momentum.
 Kijun-sen (Base Line):  Calculated as the average of the highest high and lowest low over the past 26 periods. A medium-term reference line serving as a significant support/resistance level.
 Senkou Span A (Leading Span A):  The average of the Tenkan-sen and Kijun-sen, shifted 26 periods forward into the future.
 Senkou Span B (Leading Span B):  The average of the highest high and lowest low over the past 52 periods, also shifted 26 periods forward into the future.
 Kumo (Cloud):  The area between Senkou Span A and Senkou Span B. Its color changes: green for an uptrend (when Senkou Span A is above Senkou Span B) and red for a downtrend (when Senkou Span B is above Senkou Span A). The Cloud serves as a dynamic area of support/resistance and a tool for forecasting future trends.
 Chikou Span (Lagging Span):  The current closing price, shifted 26 periods backward into the past. It serves as a powerful trend confirmation tool.
 
 How the Ichimoku Cloud Works and How to Interpret It 
 
 Trend Identification :
 - Uptrend (Bullish):  The price is above the Cloud. The higher the price is above the Cloud, the stronger the trend.
 - Downtrend (Bearish):  The price is below the Cloud. The lower the price is below the Cloud, the stronger the trend.
 - Range/Consolidation:  The price is within the Cloud. This indicates a market without a clear direction or one that is consolidating.
 Support and Resistance: 
- The Cloud itself acts as a dynamic area of support and resistance. In an uptrend, the Cloud serves as support. In a downtrend, it serves as resistance.
- A thick Cloud indicates stronger support/resistance levels, while a thin Cloud indicates weaker levels.
 The Cloud as a Predictive Indicator: 
The uniqueness of the Kumo (Cloud) lies in its ability to be shifted 26 periods forward. This part of the Cloud provides forecasts for future support and resistance levels and even suggests expected trend changes (like a "Kumo Twist" – a change in Cloud color), giving you a planning advantage.
 
 
 Unique Advantages of Ichimoku Cloud Signals: 
Ichimoku Cloud Signals takes the classic Ichimoku principles and gives you unprecedented control:
 
 Focused Trend Selection: 
Choose whether you want to analyze a bullish (uptrend) or bearish (downtrend) trend. The indicator will focus on the relevant criteria for your selection.
 Customizable Trend Confirmation Criteria (8 Criteria):  
The indicator relies on 8 key criteria for clear trend confirmation. You can enable or disable each criterion individually based on your trading strategy and desired risk level. Each criterion plays a vital role in confirming the strength of the trend:
 - Price position relative to the Cloud (Kumo)  (Default: true): Determines the main trend direction and whether it's bullish or bearish.
 - Price position relative to Kijun-sen (Base Line)  (Default: true): Indicates the medium-term trend and acts as a critical equilibrium level.
 - Price position relative to Tenkan-sen (Conversion Line)  (Default: false): Provides quick confirmation of current momentum and short-term market changes.
 - Tenkan-sen (Conversion Line) / Kijun-sen (Base Line) Crossover  (Default: true): A classic signal for momentum change, crucial for identifying entry points.
 - Current Cloud trend (Kumo)  (Default: false): Cloud color confirms the main trend direction in real-time.
 - Projected Future Cloud trend (Kumo)  (Default: true): Indicates an expected future change in the Cloud's trend, providing strong visual insight.
 - Chikou Span (Lagging Span) position relative to the Cloud (Kumo)  (Default: true): Confirms the current trend strength by comparing the price to the Ichimoku 26 periods ago.
 - Chikou Span (Lagging Span) position relative to the Price  (Default: false): Additional confirmation of trend strength, indicating buyer/seller dominance.
 Full Customization of Ichimoku Parameters: 
You can change the period lengths for each Ichimoku component, depending on your strategy:
 - Conversion Line Length  (Default: 9)
 - Base Line Length  (Default: 26)
 - Leading Span Length  (Default: 52)
 - Cloud Lagging Length  (Default: 26)
 - Lagging Span Length  (Default: 26)
 Visual Criteria Table on the Chart:  
Get immediate and clear feedback! A visual table is placed on the chart, showing in real-time which of the 8 criteria you have defined are met for your chosen trend. Criteria you have enabled will be highlighted with a blue color and a "➤" symbol, while disabled criteria will appear in a subtle gray shade. For each criterion, the table shows its real-time status with a "✔" symbol if the condition is met and an "✘" symbol if it is not met. This powerful visual tool provides a quick assessment, helps with learning, and allows for strategy optimization at the click of a button.
 Precise Criteria Details in the Data Window:  
Beyond the visual table, the indicator provides an additional critical layer of detail: for any point on the chart, you can hover over a candle and see in TradingView's Data Window the precise status and values of all eight criteria. For each criterion, you'll see a clear numerical value (1 or 0) indicating whether it's fully met (1) or not met (0). Additionally, you can inspect the exact numerical values of the Ichimoku lines (Tenkan-sen, Kijun-sen, etc.) at that specific moment. This comprehensive data supports in-depth analysis, strategy debugging, and long-term optimization, providing complete transparency regarding every component of the signal.
 
 Smart and Customizable Alerts: 
Ichimoku Cloud Signals provides a powerful alert system to keep you informed of key market movements, so you never miss an opportunity. There are eight unique alerts you can enable in TradingView's alert panel:
 
 Uptrend Entry Alert:  Triggers when all of your selected criteria for an uptrend are met on a new candle.
 Uptrend Exit Alert:  Triggers when one of your selected uptrend criteria is no longer met, signaling a potential exit point.
 Downtrend Entry Alert:  Triggers when all of your selected criteria for a downtrend are met on a new candle.
 Downtrend Exit Alert:  Triggers when one of your selected downtrend criteria is no longer met, signaling a potential exit point.
 Bullish Crossover Alert:  Triggers when the Conversion Line (Tenkan-sen) crosses above the Base Line (Kijun-sen), a classic signal for an upward momentum shift.
 Bearish Crossover Alert:  Triggers when the Conversion Line (Tenkan-sen) crosses below the Base Line (Kijun-sen), signaling a potential shift to downward momentum.
 Bullish Cloud Breakout Alert:  Triggers when the price closes above the Ichimoku Cloud (Kumo), indicating a strong bullish trend.
 Bearish Cloud Breakout Alert:  Triggers when the price closes below the Ichimoku Cloud (Kumo), indicating a strong bearish trend.
 
Each alert can be independently configured in TradingView's alert panel, allowing you to tailor your notifications to fit your exact trading strategy and risk management preferences.
 Summary:  
Ichimoku Cloud Signals is an essential tool for TradingView traders seeking control, clarity, and precision. It combines the power of the classic Ichimoku Cloud indicator with advanced customization capabilities, a convenient visual table, and clear signals, empowering you to make informed trading decisions and stay focused on managing your positions.
 Important Note: Trading Risk 
This indicator is intended for educational and informational purposes only and does not constitute investment advice or a recommendation for trading in any form whatsoever.
Trading in financial markets involves significant risk of capital loss. It is important to remember that past performance is not indicative of future results. All trading decisions are your sole responsibility. Never trade with money you cannot afford to lose.
[Pandora][Swarm] Rapid Exponential Moving AverageENVISIONING POSSIBILITY 
What is the theoretical pinnacle of possibility? The current state of algorithmic affairs falls far short of my aspirations for achievable feasibility. I'm lifting the lid off of Pandora's box once again, very publicly this time, as a brute force challenge to conventional 'wisdom'. The unfolding series of time mandates a transcendental systemic alteration...
 THE MOVING AVERAGE ZOO: 
The realm of digital signal processing for trading is filled with familiar antiquated filtering tools. Two families of filtration, being 'infinite impulse response' (EMA, RMA, etc.) and 'finite impulse response' (WMA, SMA, etc.), are prevalently employed without question. These filter types are the mules and donkeys of data analysis, broadly accepted for use in finance.
At first glance, they appear sufficient for most tasks, offering a basic straightforward way to reduce noise and highlight trends. Yet, beneath their simplistic facade lies a constellation of limitations and impediments, each having its own finicky quirks. Upon closer inspection, identifiable drawbacks render them far from ideal for many real-world applications in today's volatile markets.
 KNOWN FUNDAMENTAL FLAWS: 
Despite commonplace moving average (MA) popularity, these conventional filters suffer from an assortment of fundamental flaws. Most of them don't genuinely address core challenges of how to preserve the true dynamics of a signal while suppressing noise and retaining cutoff frequency compliance. Their simple cookie cutter structures make them ill-suited in actuality for dynamic market environments. In reality, they often trade one problem for another dilemma, forsaking analytics to choose between distortion and delay.
A deeper seeded issue remains within frequency compliance, how adequately a filter respects (or disrespects) the underlying signal’s spectral properties according to it's assigned periodic parameter. Traditional MAs habitually distort phase relationships, causing delayed reactions with surplus lag or exaggerations with excessive undershoot/overshoot. For applications requiring timely resilience, such as algorithmic trading, these shortcomings are often functionally unacceptable. What’s needed is vigorous filters that can more accurately retain signal behaviors while minimizing lag without sacrificing smoothness and uniformity. Until then, the public MA zoo remains as a collection of corny compromises, rather than a favorable toolbelt of solutions.
P.S.: In PSv7+, in my opinion, many of these geriatric MAs deserve no future with ease of access for the naive, simply not knowing these filters are most likely creating bigger problems than solving any.
 R.E.M.A. 
What is this? I prefer to think of it as the "radical EMA", definitely along my lines of a retire everything morte algorithm. This isn't your run of the mill average from the petting zoo. I would categorize it as a paradigm shifting rampant economic masochistic annihilator, sufficiently good enough to begin ruthlessly executing moving averages left and right. Um, yeah... that kind of moving average destructor as you may soon recognize with a few 'Filters+' settings adjustments, realizing ordinary EMA has been doing us an injustice all this time.
Does it possess the capability to relentlessly exterminate most averaging filters in existence? Well, it's about time we find out, by uncaging it on the loose into the greater economic wilderness. Only then can we truly find out if it is indeed a radical exponential market accelerant whose time has come. If it is, then it may eventually become a reality erasing monolithic anomaly destined for greatness, ultimately changing the entire landscape of trading in perpetuity.
 UNLEASHING NEXT-GEN: 
This lone next generation exoweapon algorithm is intended to initiate the transformative beginning stages of mass filtration deprecation. However, it won't be the only one, just the first arrival of it's alien kind from me. Welcome to notion #1 of my future filtration frontier, on this episode of the algorithmic twilight zone. Where reality takes a twisting turn one dimension beyond practical logic, after persistent models of mindset disintegrate into insignificance, followed by illusory perception confronted into cognitive dissonance.
An evolutionary path to genuine advancement resides outside the prison of preconceptions, manifesting only after divergence from persistent binding restrictions of dogmatic doctrines. Such a genesis in transformative thinking will catalyze unbounded cognitive potential, plowing the way for the cultivation of total redesigns of thought. Futuristic innovative breakthroughs demand the surrender of legacy and outmoded understandings.
Now that the world's largest assembly of investors has been ensembled, there are additional tasks left to perform. I'm compelled to deploy this mathematical-weapon of mass financial creation into it's rightful destined hands, to "WE THE PEOPLE" of TV.
 SCRIPT INTENTION: 
Deprecate anything and everything as any non-commercial member sees desirably fit. This includes your existing code formulations already in working functional modes of operation AND/OR future projects in the works. Swapping is nearly as simple as copying and pasting with meager modifications, after you have identified comparable likeness in this indicators settings with a visual assessment. Results may become eye opening, but only if you dare to look and test.
Where you may suspect a ta.filter() is lacking sufficient luster or may be flat out majorly deficient, employing rema, drema, trema, or qrema configurations may be a more suitable replacement. That's up to you to discern. My code satire already identifies likely bottom of the barrel suspects that either belong in the extinction record or have already been marked for deprecation. They are ordered more towards the bottom by rank where they belong. SuperSmoother is a masterpiece here to stay, being my original go-to reference filter. Everything you see here is already deprecated, including REMA...
 REMA CHARACTERISTICS 
- VERY low lag
- No overshoot
- Frequency compliant
- Proper initialization at bar_index==0
- Period parameter accepts poitive floating point numerics (AND integers!)
- Infinite impulse response (IIR) filter
- Compact code footprint
- Minimized computational overhead
Savages Supply and Demand LevelsThis supply and demand indicator in my opinion is one of the best S&D indicators on trading view. It is clean, organized and just simple. I have spent thousands of hours determining the best and most reliable ways to identify supply and demand, on every time frame! I am going to explain exactly what I look for. 
When looking for a supply level meaning, there is potential for more supply of the following stock to hit the marker, what does that mean? People are going to sell. SO, it represents possible sell ordered at that supply level. So lets get into the grit of this, there are two candles that form when a supply level is formed. The first candle needs to be green, it will have a high, a low , an open and a close. The specifics come into play with the next candle which needs to be red, that candle can NOT break the previous green candles high, and needs to close below the previous candles low. THATS IT! That is a supply level. Now, for a demand level, its the same thing just switched, we need a red candle, that will have a high,low, open and a close. Same thing now, the next candle is going to be green, that green candle can NOT break that previous red candles low and needs to close above that previous red candles high. THATS A DEMAND! 
 I have spent countless hours back testing and studying this, I am extremely confident that this will be a game changer for whoever uses this. I have marked different types of opening and closes and highs and lows and this specific type of setup has worked countless times for me, the only time it will not work is when there is a liquidity sweep or some sort of news where it causes the price action to swing several points. Also do not use only one time frame and only this indicator, try to use some fair value gap levels and break of structure indicators, there are really good ones on here. I have also built the indicator to get rid of supply and demand levels that have already been hit so you always have a clean and fresh supply and demand level that has not been eaten into yet. I also threw some clean labels on there so it is easy to identify. So once price action hits that supply or demand level, it goes away, it either worked or it gets invalidated. 
I hope you enjoy!
Not financial advice
-Savage
Hurst Exponent Adaptive Filter (HEAF) [PhenLabs]📊 PhenLabs - Hurst Exponent Adaptive Filter (HEAF) 
 Version: PineScript™ v6 
 📌 Description 
The Hurst Exponent Adaptive Filter (HEAF) is an advanced Pine Script indicator designed to dynamically adjust moving average calculations based on real time market regimes detected through the Hurst Exponent. The intention behind the creation of this indicator was not a buy/sell indicator but rather a tool to help sharpen traders ability to distinguish regimes in the market mathematically rather than guessing.  By analyzing price persistence, it identifies whether the market is trending, mean-reverting, or exhibiting random walk behavior, automatically adapting the MA length to provide more responsive alerts in volatile conditions and smoother outputs in stable ones. This helps traders avoid false signals in choppy markets and capitalize on strong trends, making it ideal for adaptive trading strategies across various timeframes and assets.
Unlike traditional moving averages, HEAF incorporates fractal dimension analysis via the Hurst Exponent to create a self-tuning filter that evolves with market conditions. Traders benefit from visual cues like color coded regimes, adaptive bands for volatility channels, and an information panel that suggests appropriate strategies, enhancing decision making without constant manual adjustments by the user.
 🚀 Points of Innovation 
 
 Dynamic MA length adjustment using Hurst Exponent for regime-aware filtering, reducing lag in trends and noise in ranges.
 Integrated market regime classification (trending, mean-reverting, random) with visual and alert-based notifications.
 Customizable color themes and adaptive bands that incorporate ATR for volatility-adjusted channels.
 Built-in information panel providing real-time strategy recommendations based on detected regimes.
 Power sensitivity parameter to fine-tune adaptation aggressiveness, allowing personalization for different trading styles.
 Support for multiple MA types (EMA, SMA, WMA) within an adaptive framework.
 
 🔧 Core Components 
 
 Hurst Exponent Calculation: Computes the fractal dimension of price series over a user-defined lookback to detect market persistence or anti-persistence.
 Adaptive Length Mechanism: Maps Hurst values to MA lengths between minimum and maximum bounds, using a power function for sensitivity control.
 Moving Average Engine: Applies the chosen MA type (EMA, SMA, or WMA) to the adaptive length for the core filter line.
 Adaptive Bands: Creates upper and lower channels using ATR multiplied by a band factor, scaled to the current adaptive length.
 Regime Detection: Classifies market state with thresholds (e.g., >0.55 for trending) and triggers alerts on regime changes.
 Visualization System: Includes gradient fills, regime-colored MA lines, and an info panel for at-a-glance insights.
 
 🔥 Key Features 
 
 Regime-Adaptive Filtering: Automatically shortens MA in mean-reverting markets for quick responses and lengthens it in trends for smoother signals, helping traders stay aligned with market dynamics.
 Custom Alerts: Notifies on regime shifts and band breakouts, enabling timely strategy adjustments like switching to trend-following in bullish regimes.
 Visual Enhancements: Color-coded MA lines, gradient band fills, and an optional info panel that displays market state and trading tips, improving chart readability.
 Flexible Settings: Adjustable lookback, min/max lengths, sensitivity power, MA type, and themes to suit various assets and timeframes.
 Band Breakout Signals: Highlights potential overbought/oversold conditions via ATR-based channels, useful for entry/exit timing.
 
 🎨 Visualization 
 
 Main Adaptive MA Line: Plotted with regime-based colors (e.g., green for trending) to visually indicate market state and filter position relative to price.
 Adaptive Bands: Upper and lower lines with gradient fills between them, showing volatility channels that widen in random regimes and tighten in trends.
 Price vs. MA Fills: Color-coded areas between price and MA (e.g., bullish green above MA in trending modes) for quick trend strength assessment.
 Information Panel: Top-right table displaying current regime (e.g., "Trending Market") and strategy suggestions like "Follow trends" or "Trade ranges."
 
 📖 Usage Guidelines 
 Core Settings 
Hurst Lookback Period
 
 Default: 100
 Range: 20-500
 Description: Sets the period for Hurst Exponent calculation; longer values provide more stable regime detection but may lag, while shorter ones are more responsive to recent changes.
 
Minimum MA Length
 
 Default: 10
 Range: 5-50
 Description: Defines the shortest possible adaptive MA length, ideal for fast responses in mean-reverting conditions.
 
Maximum MA Length
 
 Default: 200
 Range: 50-500
 Description: Sets the longest adaptive MA length for smoothing in strong trends; adjust based on asset volatility.
 
Sensitivity Power
 
 Default: 2.0
 Range: 1.0-5.0
 Description: Controls how aggressively the length adapts to Hurst changes; higher values make it more sensitive to regime shifts.
 
MA Type
 
 Default: EMA
 Options: EMA, SMA, WMA
 Description: Chooses the moving average calculation method; EMA is more responsive, while SMA/WMA offer different weighting.
 
 🖼️ Visual Settings 
Show Adaptive Bands
 
 Default: True
 Description: Toggles visibility of upper/lower bands for volatility channels.
 
Band Multiplier
 
 Default: 1.5
 Range: 0.5-3.0
 Description: Scales band width using ATR; higher values create wider channels for conservative signals.
 
Show Information Panel
 
 Default: True
 Description: Displays regime info and strategy tips in a top-right panel.
 
MA Line Width
 
 Default: 2
 Range: 1-5
 Description: Adjusts thickness of the main MA line for better visibility.
 
Color Theme
 
 Default: Blue
 Options: Blue, Classic, Dark Purple, Vibrant
 Description: Selects color scheme for MA, bands, and fills to match user preferences.
 
 🚨 Alert Settings 
Enable Alerts
 
 Default: True
 Description: Activates notifications for regime changes and band breakouts.
 
 ✅ Best Use Cases 
 
 Trend-Following Strategies: In detected trending regimes, use the adaptive MA as a trailing stop or entry filter for momentum trades.
 Range Trading: During mean-reverting periods, monitor band breakouts for buying dips or selling rallies within channels.
 Risk Management in Random Markets: Reduce exposure when random walk is detected, using tight stops suggested in the info panel.
 Multi-Timeframe Analysis: Apply on higher timeframes for regime confirmation, then drill down to lower ones for entries.
 Volatility-Based Entries: Use upper/lower band crossovers as signals in adaptive channels for overbought/oversold trades.
 
 ⚠️ Limitations 
 
 Lagging in Transitions: Regime detection may delay during rapid market shifts, requiring confirmation from other tools.
 Not a Standalone System: Best used in conjunction with other indicators; random regimes can lead to whipsaws if traded aggressively.
 Parameter Sensitivity: Optimal settings vary by asset and timeframe, necessitating backtesting.
 
 💡 What Makes This Unique 
 
 Hurst-Driven Adaptation: Unlike static MAs, it uses fractal analysis to self-tune, providing regime-specific filtering that's rare in standard indicators.
 Integrated Strategy Guidance: The info panel offers actionable tips tied to regimes, bridging analysis and execution.
 Multi-Regime Visualization: Combines adaptive bands, colored fills, and alerts in one tool for comprehensive market state awareness.
 
 🔬 How It Works 
Hurst Exponent Computation:
 
 Calculates log returns over the lookback period to derive the rescaled range (R/S) ratio.
 Normalizes to a 0-1 value, where >0.55 indicates trending, <0.45 mean-reverting, and in-between random.
 
Length Adaptation:
 
 Maps normalized Hurst to an MA length via a power function, clamping between min and max.
 Applies the selected MA type to close prices using this dynamic length.
 
Visualization and Signals:
 
 Plots the MA with regime colors, adds ATR-based bands, and fills areas for trend strength.
 Triggers alerts on regime changes or band crosses, with the info panel suggesting strategies like momentum riding in trends.
 
 💡 Note: 
For optimal results, backtest settings on your preferred assets and combine with volume or momentum indicators. Remember, no indicator guarantees profits—use with proper risk management. Access premium features and support at PhenLabs.
TZtraderTZtrader 
This is a TrendZones version with features to set stoploss and targets in short and long positions meant for use in intraday charts. It aims to provide signals for opening and closing long and short positions. In the comments under the TrendZones publication several people expressed a need for features for a short position similar to those for a long position as implemented in TrendZones, some want to use it for scalping, some asked for alerts. When I proposed to create a version for day trading with target lines based on ATR, several people liked the idea. 
Full disclosure: I don’t do day trading, because, after I lost a lot of money, I had to promise my wife to stay away from it. I restrict myself to long term investing in stocks which are in uptrend. However I understand what a day trader needs. I gather from my experience that day trading or scalping is an attempt to earn something by opening a position in the morning and close, reopen and close it again during the day with a profit. It is usually done with leveraged instruments like CFD’s, futures, options, and what have you. Opening and closing positions is done within minutes, so the trader needs a quick and efficient way to set proper stoploss and target. TZtrader supports this by showing only three or four numbers on the price bar: The price of the instrument, The logical stop level (gray or green or maroon dots), and the target level (navy). All other numbers are suppressed to prevent mistakes. Also a clear feedback for current settings at the top-center of the pane and an alert feedback at bottom that flashes alerts during the development of the current bar and gives suppression status.
The script
First I made a bare bones version of TrendZones to which I added code for long and short trading setups and a bare setup for no position. The code for the logical stops in long setup had to be reviewed, after which this became the basis for stops in short setup. 
Then I added code for 10 alert messages, which was a hassle, because this is the first time I coded alerts and the first time I used an array as a stack to avoid a complicated if-then construction. During testing the array caused a runtime error which I solved by adding ‘array.clear’ to the code, also I discovered that in TradingView separate alerts have to be created for all three setups - short, long and bare. Flipping setups is done in the inputs with a dropdown menu because Pine Script has no function for a clickable button.  
One visual with three setups.
The visual has the TrendZones structure: Three near parallel very smooth curves, which border the moderate uptrend (green) and downtrend (orange) zone over and under the curve in the middle, the COG (Center Of Gravity). Where the price breaks out of these curves, strong trend zones show up over and under the curves, respectively strong uptrend (blue) and strong downtrend (red).
Three setups were made clearly different to avoid confusion and to provide oversight in case of multiple trades going on simultaneously which I imagine are monitored in one screen. You have to see which one is long, which short and which have no position. The long setup should not trigger short signals, nor should the short trigger long signals nor the bare setup exclusive long or short signals. 
The Long setup is default, shown on the example chart. In this setup the Stoploss suggestions (green, gray and maroon dots) are under the price bars and the target line (navy) at a set distance above the High Border. A zone with a width of 1 ATR is drawn under the Low Border. In this setup 5 specific alerts are provided
The Short setup has the Stoploss suggestions over the price bars, the target line at a set distance under the Low Border. A zone with a width of 1 ATR is drawn above the High Border. This setup also has 5 specific alerts.
The Bare setup has no Stoploss suggestions, no target line and supports 4 alerts, 2 in common with the Long setup and 2 with Short.
The table below gives a summary of scripted alerts:
Setup = Where = When = Purpose
Long, Bare = Green Zone = Bars come from lower zones = Uptrend starts
Long, Bare = Green Zone = Sideways ends in uptrend = Uptrend resumes
Long	 = COG = First crossing = Uptrend might end warning
Long	 = Orange Zone = Bars come from higher zones = Uptrend  ended take care
Long	 = Red Zone = Bars come from higher zones = Strong downtrend->close Long 
Short, Bare = Orange Zone	 = Bars come from higher zones = Downtrend starts
Short, Bare = Orange Zone	 = Sideways ends in downtrend = Downtrend resumes
Short = COG = First crossing = Downtrend might end warning
Short = Green Zone = Bars come from lower zones = Downtrend ended take care
Short = Blue Zone = Bars come from lower zones = Strong uptrend -> close short
You can use script alerts in TradingView by clicking the clock in the sidebar, then ‘create alert’ or plus, as condition you choose ‘Tztrader’ in the dialog box, then the “Any alert() function call” option (the first item in the list). The script lets the valid alert trigger by TradingView after the bar is completed, this can differ from the flashed messages during its formation. 
When you create alerts in Tradingview, I advice to do that for each setup, then to make only the alert active which matches the current setup, pause the other ones.
Suppressing false and annoying signals
The script has two ways to suppress such signals, which have to do with the numbers in the alert feedback. The numbers left and right of the message with a colored background, depict the zones in which the previous (left) and current (right) bar move. 1 is the strong downtrend zone (red), 2 the moderate downtrend zone (orange), 3 the sideways zones (gray), 4 the COG (gray), 5 the moderate uptrend zone (green), 6 the strong uptrend zone (blue), 7 something went wrong with assigning a zone (black). In extensive testing the number 7 never occurs, because I catch that error in the code. The idea is that an alert is only triggered if the previous bar was in a different zone. When the bars are in the same zone, no alert is possible. This way all annoying signals are suppressed and long, short and bare get the appropriate alerts. 
The third number is a counter. It counts how often the COG is crossed without touching the outer curves. The counter will reset to zero when the upper or lower curve is touched. When the count is 1 you have zone situation 4 and appropriate alerts are flashed. When the count is 2 or higher, a sideways situation (3) is called and while the recrossings are going on, no alerts can be flashed. This suppresses false signals. The ATR zone and curves are brownish-gray where sideways happens(ed). When the channel is narrowed down to just the three curves, some false signals still might occur.
Inputs
“Setup”, default is long, drop down menu provides long, short and bare. 
“Target ATR”, default is 2, sets the amount of ATR for the target line. In 1 minute charts 4 seems an appropriate setting, you have to learn by experience which setting works.
“show feedback …” default is on, This creates two feedback labels, a Setup feedback on top of the pane, which shows charted instrument, Setup type, Trend and timeframe of the chart. Background color of Trend feedback is green when it matches the setup, red when mismatches and gray when no match. The alert feedback at the bottom of the pane shows a number, a message and two numbers. The numbers will be explained in the chapter about false and annoying signals below. During formation of the bar, valid alerts are flashed with a blue background, otherwise the message ‘alerts for current bar suppressed’. 
Logical Stops
The curves are the logical place to put stops, because, as  these are averages of the high and low border of a Donchian channel, they signify the ‘natural’ current highest, lowest and main level in the lookback period that fit the monitored trend setup. A downtrend turns into an uptrend when a breakout of the upper curve occurs. If you are short, that is where you want to close position, so the logical place for the stoploss is the upper curve. Vice versa, when you are long, the logical stop is on the lower curve. The stops show up as green or gray dots on the curves, the green dots signify a nice entry level, the gray stops are there to suggest levels where unrealized profits might be secured, the maroon dots indicate that the trend mismatches the setup.
 
COG versus other lines
Any line used to identify a trend, be it some MA or some other line, is interpreted the same way: When the bars move above the line there is an uptrend and when below, a downtrend. COG is not different in that sense. If you put such a line in the same chart as TZtrader, you can see situations in which the other line shows uptrend or downtrend earlier than COG, also some other lines, e.g. Hull MA, are very good at showing tops and bottoms, while COG ignores these. On the other hand the other lines are usually a little nervous and let you shake out of position too soon. Just like the other lines, COG gives false signals when it is near horizontal. The advantage of the placement COG is the tolerance for pull backs. This way TZtrader keeps you longer in the trend. Such pull backs are often ‘flags’ which are interpreted in TA as confirming the trend. Tztrader aims to get you in position reasonably soon when a trend begins and out of position as soon as the trend turns against you. The placement of COG is done with a fundamentally different algorithm than other lines as it is not an average of prices, but the middle of two averages of borders of a Donchian channel. This gives the two zones between the curves the same quality as the two zones above and below the middle line of a standard Donchian Channel. 
A multi timeframe application.
In this scenario you put a 5 minutes and 1 minute chart with Tztrader side by side. If the 5 minutes shows uptrend, set the 1 minute on long trading and open positions when the trend matches uptrend en close when it mismatches. Don’t open short positions. Once the 5 minute changes to downtrend, set Tztrader in the 1 minute to short trading and open positions when the trend matches downtrend and close when it mismatches.  
The idea is that in a long ‘context’, provided by the 5 minutes, the uptrends in the 1 minute will last longer and go further, vice versa for the short ‘context’. This way you do swing trading in the 5 minute in a smart way, maximizing profits. 
You can do this with any timeframe pairs with a proportion of around 5:1, 4:1, 6:1, like e.g. 60 minutes and 15 minutes or weeks and days (5 trading days in a week).
Dear day-traders, may this tool be helpful and may your days be blessed.
Take care
MA Crossover Detector
The Moving Average Crossover Detector is a custom indicator that visually shows buy and sell signals clearly on the chart. based on the crossing of two moving averages — a popular and beginner-friendly tool in technical analysis. 
It plots two moving averages — One fast (short period) and one slow (long period) — and highlights crossover points:
✅  Buy Signal (Golden Cross)  – When the fast MA crosses above the slow MA.
❌  Sell Signal (Death Cross)  – When the fast MA crosses below the slow MA.
✅  Features 
Visual: Clearly shows crossovers on the chart.
Customizable: Choose periods, types, styles, etc.
Alert-ready: You can set alerts for crossovers.
The Moving Average (MA) Crossover Strategy is one of the simplest and most widely used strategies in technical analysis for trading stocks, forex, crypto, and other markets. It relies on the interaction between two moving averages to generate buy and sell signals.
 Core Components 
 Short-Term Moving Average (Fast MA) : Reacts quickly to price changes (e.g., 9-period or 20-period).
 Long-Term Moving Average (Slow MA) : Reacts more slowly to price changes (e.g., 21-period or 200-period).
 How the Strategy Works 
 Bullish Crossover (Golden Cross): 
Occurs when the fast MA crosses above the slow MA. Interpreted as a buy signal, indicating a potential uptrend.
 Bearish Crossover (Death Cross): 
Occurs when the fast MA crosses below the slow MA. Interpreted as a sell signal, indicating a potential downtrend.
 Common Variants 
Short-term trading
9 EMA
21 EMA
Swing trading
20 SMA
50 SMA
Long-term investing
50 SMA
200 SMA
 Pros 
Easy to understand and implement
Works well in trending markets
Can be automated for backtesting and execution
 Cons 
Lagging indicator: MAs are based on past prices, so signals come after the move has started.
Choppy markets = whipsaws: Generates false signals in sideways/range-bound conditions.
May underperform in volatile or mean-reverting environments
 Tips for Improvement 
Use  confirmation tools : e.g., RSI, MACD, volume analysis, price action
Add  filters : Trend filter (ADX), volatility filter (ATR), or time filter (session-based)
Combine with  price structure : Support/resistance, breakouts, pullbacks






















