INFLECTION NEXUS - Shadow Portfolio AdaptiveINFLECTION NEXUS - SPA (Shadow Portfolio Adaptive)
Foreword: The Living Algorithm
For decades, technical analysis has been a conversation between a trader and a static chart. We draw our lines, we apply our indicators with their fixed-length inputs, and we hope that our rigid tools can somehow capture the essence of a market that is fluid, chaotic, and perpetually evolving. When our tools fail, we are told to "adapt." But what if the tools themselves could learn that lesson? What if our indicators could adapt not just for us, but with us?
This script, INFLECTION NEXUS - SPA, is the first step in that direction. It is an experimental framework, a research project shared publicly, built around a radical new core: the Shadow Portfolio Adaptive (SPA) Engine . Let's be clear from the outset: the signal logic you see—the buy and sell labels—is a refined version from my previous work, "Turning Point." The signals are not the star of this show. This entire publication is a showcase of the groundbreaking, self-learning engine that now powers them.
You will likely feel that this system is overwhelmingly complex when you first load it. That is by design. This is not another simple crossover indicator. This is a look under the hood of a system designed to emulate the perpetual learning cycle of a human mind. My goal with this document is to break down every single component, every color, every number, into simple, understandable pieces. We will go through this step-by-step, so that by the end, you will not only understand how it works, but you will appreciate the depth of the analysis it performs on your behalf.
This is a beta release. Not all planned features are fully functional, and I will be updating it as the research continues. But the core engine is here, and it represents a new paradigm. Prepare to engage with a script that doesn't just analyze the market—it actively seeks to understand it.
Chapter 1: The Paradigm Shift - Why the SPA Engine is a Leap Forward
To grasp the innovation here, we must first deconstruct the old way of thinking about "adaptive" indicators.
Part A: The Traditional Model - Driving by the Rear-View Mirror
Imagine a self-driving car that can only make adjustments after it has already completed a trip. This is, in essence, how most "adaptive" trading systems work. Their process is fundamentally reactive and inefficient:
Wait for a Signal: The system is idle until its specific, hard-coded logic (e.g., a moving average crossover) generates a buy or sell signal.
Wait for an Outcome: It then waits for that entire trade to play out and close, resulting in a win or a loss.
Collect Limited Data: It only learns from the performance of its own signals. If the market is moving but not generating signals, the system is blind and learns nothing.
Require a Massive Sample Size: To avoid making changes based on random luck, it must wait for a huge number of trades—often 50, 100, or even more—before it has a statistically significant sample of wins and losses.
Make a Belated Adjustment: Finally, after this long "warm-up" period, it will make a tiny, retrospective adjustment to its parameters.
The fatal flaw is obvious: this model is always adapting to a market that no longer exists. It is slow, data-starved, and hopelessly biased by its own signal logic.
Part B: The SPA Model - The Proactive Co-Pilot
The Shadow Portfolio Adaptive (SPA) engine is a complete re-imagining of this process. It is not a reactive historian; it is a proactive, ever-present co-pilot, constantly learning and recalibrating.
It Never Waits: The SPA engine does not wait for a signal to learn. From the moment you load it on the chart, its Shadow Portfolio begins running constant, 5-bar long and short trades in the background. It is not testing a "signal"; it is testing the very fabric of the market, bar by bar.
It is Data-Saturated: Because it learns from every 5-bar slice of price action, the SPA engine gathers a colossal amount of unbiased data. While a traditional system might learn from one trade every 50 bars, the SPA engine learns from a long and a short trade every single bar after its initial cycle.
Instantaneous Market Awareness - The End of the "Warm-Up": This is the core innovation. A traditional adaptive system is effectively useless for the first 50-100 trades. The SPA engine's warm-up period is exactly five bars . On the 6th bar of the chart, the first shadow trade closes, a data point is generated, and the learning process begins. From the 6th bar onward, the engine is market-aware and capable of making intelligent adjustments. The SPA engine isn't adapting to old wins and losses. It is adapting, in near real-time, to the market's ever-shifting character, volatility, and personality.
Chapter 2: The Anatomy of the SPA Engine - A Toddler's Guide to a Complex Brain
The engine is composed of three primary systems that work in a beautiful, interconnected symphony. Let's break them down.
Section 1: The Shadow Portfolio (The Information Harvester)
What it is, Simply: Think of this as the script's eyes and ears. It's a team of 10 virtual traders (5 long, 5 short) who are constantly taking small, quick trades to feel out the market.
How it Works, Simply: On every new bar, a new "long" trader and a new "short" trader enter the market. Exactly 5 bars later, they close their positions. This cycle is perpetual and relentless.
The Critical 'Why': Because these virtual traders enter and exit based on a fixed time (5 bars), not on a "good" or "bad" signal, their results are completely unbiased . They are simply measuring: "What happened to price over the last 5 bars?" This provides the raw, untainted truth about the market's behavior that the rest of the system needs to learn effectively.
The Golden Metric (ATR Normalization): The engine doesn't just look at dollar P&L. It's smarter than that. It asks a more intelligent question: "How much did this trade make relative to the current volatility?"
Analogy: Imagine a flea and an elephant. If they both jump 1 inch, who is more impressive? The flea. The SPA engine understands this. A $10 profit when the market is dead quiet is far more significant than a $10 profit during a wild, volatile swing.
The Formula: realized_atr = (close - trade.entry) / trade.atr_entry. It takes the raw profit and divides it by the Average True Range (a measure of volatility) at the moment of entry. This gives a pure, "apples-to-apples" score for every single trade, which is the foundational data point for all learning.
Section 2: The Cognitive Map (The Long-Term Brain)
What it is, Simply: This is the engine's deep memory, its library of experiences. Imagine a giant, 64-square chessboard (8x8 grid). Each square on the board represents a very specific type of market environment.
The Two Dimensions of Thought (The 'How'): How does it know which square we are on? It looks at two things:
The Market's Personality (X-Axis): Is the market behaving like a disciplined soldier, marching in a clear trend? Or is it like a chaotic, unpredictable child, running all over the place? The engine calculates a "Regime" score to figure this out.
The Market's Energy Level (Y-Axis): Is the market sleepy and quiet, or is it wide-awake and hyperactive? The engine measures "Normalized Volatility" to determine this.
The Power of Generalization (The 'Why'): When a Shadow Portfolio trade closes, its result is recorded in the corresponding square on the chessboard. But here's the clever part: it also shares a little bit of that lesson with the squares immediately next to it (using a Gaussian Kernel).
Analogy: If you touch a hot stove and learn "don't touch," your brain is smart enough to know you probably shouldn't touch the hot oven door next to it either, even if you haven't touched it directly. The Cognitive Map does the same thing, allowing it to make intelligent inferences even in market conditions it has seen less frequently. Each square remembers what indicator settings worked best in that specific environment.
Section 3: The Adaptive Engine (The Central Nervous System)
What it is, Simply: This is the conductor of the orchestra. It takes information from all other parts of the system and decides exactly what to do.
The Symphony of Inputs: It listens to three distinct sources of information before making a decision:
The Short-Term Memory (Rolling Stats): It looks at the performance of the last rollN shadow trades. This is its immediate, recent experience.
The Long-Term Wisdom (Cognitive Map): It consults the grand library of the Cognitive Map to see what has worked best in the current market type over the long haul.
The Gut Instinct (Bin Learning): It keeps a small "mini-batch" of the most recent trades. If this batch shows a very strong, sudden pattern, it can trigger a rapid, reflexive adjustment, like pulling your hand away from a flame.
The Fusion Process: It then blends these three opinions together in a sophisticated way. It gives more weight to the opinions it's more confident in (e.g., a Cognitive Map square with hundreds of trades of experience) and uses your Adaptation Intensity (dialK) input to decide how much to listen to its "gut instinct." The final decision is then smoothed to ensure the indicator's parameters change in a stable, intelligent way.
Chapter 3: The Control Panel - A Granular Guide to the Inputs
Every input is a lever to tune the engine. Let's demystify them.
🧾 Signal Engine (Original): These inputs control the "Turning Point" signal logic.
What they are: Toggles for Reversal Mode (catch tops/bottoms) and Breakout Mode (follow the trend), plus filters like Require New Extreme to ensure signals come from points of extension.
How to use them: For a ranging market, you might favor Reversal mode. For a strongly trending market, Breakout mode might be better. These settings fine-tune the final alert, which is powered by the adaptive engine.
🎛️ Master Control:
Adaptation Intensity (dialK): THIS IS THE MOST IMPORTANT INPUT. It controls the personality of the learning engine.
Low Setting (1-5): Creates a "Wise Old Professor" engine. It's patient, learns from larger batches of data, and makes slow, deliberate, and highly confident adjustments. Use this for stable assets like indices or blue-chip stocks.
High Setting (15-20): Creates a "Hyper-Reactive Day Trader" engine. It learns from tiny samples, trusts its gut instinct, and makes large, aggressive adjustments to keep up with a frantic market. Use this for highly volatile assets like crypto or meme stocks.
🧠 Adaptive Engine & 🎯 Learning:
What they are: The deep mechanics of the learning process. Base Learn Rate is the fundamental step size of adjustments. Rolling Window Size is the length of its "short-term memory." Adaptation Momentum controls how smoothly the parameters transition to their new learned values.
How to use them: For most users, the defaults are well-balanced. Advanced users can tweak these to make the engine even more or less sensitive to new information.
🗺️ Cognitive Map, STM & Checkpoints:
What they are: Controls for the engine's brain. Enable Cognitive Map turns on the long-term memory.
The Checkpoint System - Your "Save Game" Feature: This is incredibly powerful.
To Save: Toggle Emit Checkpoint Now. Go to your alert log, and you will see a very long string of text. Copy this entire string.
To Load: Paste that string into the Memory Checkpoint input box. Toggle Apply Checkpoint On Next Bar. The script will instantly load its entire "brain"—every learned parameter and all 64 cells of the Cognitive Map. You can train the engine on one chart and transfer its intelligence to another.
Chapter 4: The Command Center - Decoding the Dashboard
This is your window into the engine's mind. Do not be intimidated. Let's break it down.
PANEL A (INFLECTION NEXUS): The high-level overview.
Market Context: See how the engine classifies the market's Trend and Regime (personality).
Shadow Portfolio Summary: The engine's report card. Watch the Win Rate and Avg P&L to see the quality of the raw data it's learning from.
PANEL B (SHADOW PORTFOLIO ADAPTIVE): The deep diagnostics.
Performance Metrics: Advanced stats like Sharpe Ratio (return vs. risk) and Sortino Ratio (return vs. downside risk). This tells you about the quality and consistency of the market movements the engine is analyzing.
Adaptive Parameters (Live vs Base): THIS IS THE MOST IMPORTANT SECTION. It shows the engine's Live parameters right next to your (Base) inputs.
How to interpret it: If you see the Live ATR Len is 45 while your Base input is 20, the engine is telling you: "The market is in a long, smooth trend right now. Short-term noise is a trap. I have learned that we must use a longer-term perspective to see clearly." This section translates the engine's learning directly into actionable insight.
Memory Log: A live ticker of the engine's thoughts, showing every trade it learns from and every adaptation it makes.
Chapter 5: Reading the Canvas - On-Chart Visuals
The Bands (Green/Blue Lines): These are not static Supertrend lines. They are the
physical manifestation of the engine's current thinking. As the engine learns and adapts its ATR Period and Multiplier, you will see these bands widen, tighten, and adjust their distance from price. They are alive.
The Labels (BUY/SELL): These are the final output of the "Turning Point" logic, now supercharged and informed by the fully adaptive SPA engine.
The Purple Pulse (Dot and Background Glow): This is your visual cue that the engine is "thinking." Every time you see this pulse, it means the SPA has just completed a learning cycle and updated its parameters. It is actively recalibrating itself to the market.
Chapter 6: A Personal Manifesto on Innovation
I want to conclude with a personal note on why I dedicate countless hours to building systems like this and sharing them openly.
My purpose is to drive innovation, period. I am not in this space to follow the crowd or to re-package old ideas. The world does not need a 100th version of a slightly modified MACD. Real progress comes from venturing into the wilderness, from asking difficult questions, and from pursuing concepts that lie at the very edge of possibility.
I am not afraid of being wrong. I am not afraid of being bested by my peers. In fact, I welcome it. If another developer takes an idea from this engine, improves it, and builds something even more magnificent, that is a profound win for our entire community. The only failure I recognize is the failure to try. The only trap I fear is the creative complacency of producing sterile, recycled work just to appease the status quo.
I love this community, and I believe with every fiber of my being that we have barely scratched the surface of what can be discovered and created. This script is my contribution to that shared journey. It is a tool, an idea, and a challenge to all of us: let's keep pushing.
DISCLAIMER: This script is an experimental framework provided for educational and research purposes ONLY. It is not financial advice. All trading involves substantial risk of loss. Past performance is not indicative of future results. Please use this tool responsibly and as part of a comprehensive trading plan.
As the great computer scientist Herbert A. Simon, a pioneer of artificial intelligence, famously said:
"Learning is any process by which a system improves performance from experience."
May this engine enhance your experience.
— Dskyz, for DAFE Trading Systems
Statistics
SFI MAGIC
// Join our channel for more free tools: t.me
//@version=5
indicator("SFI MAGIC", overlay=true, max_labels_count=500)
//------------------------------------------------------------------------------
// Input Settings
useBody = input(false, 'Use Candle Body')
signalMode = input.string('Simple Entry + Exits', 'Signal Strategy', , tooltip='Change Your Signal Appearance And Strategies')
sensitivity = input.float(2.3, "Sensitivity", 0.6, 15.1, step=0.1, tooltip='Change Your Signal Sensitivity And Accuracy')
strongSignalOnly = input(false, "STRONG Only", inline='BasicFilters')
noRepainting = input(false, 'No Repainting', inline='BasicFilters', tooltip='Disables all signals except strong signals Disables repainting for signals')
Multiplier = input.float(1.5, "ATR Multiplier", step=0.1)
align_with_supertrend = input.bool(false, "Align Signals with Supertrend", tooltip="Enable to align buy/sell signals with Supertrend direction")
//------------------------------------------------------------------------------
// ATR and Supertrend Calculation
atr = ta.atr(14)
st_atr_length = input.int(10, "Supertrend ATR Length", minval=1)
st_multiplier = input.float(3.0, "Supertrend Multiplier", step=0.1)
upper_band = ta.sma(close, st_atr_length) + st_multiplier * atr
lower_band = ta.sma(close, st_atr_length) - st_multiplier * atr
var float supertrend = na
supertrend := close > nz(supertrend ) ? math.max(lower_band, nz(supertrend )) : math.min(upper_band, nz(supertrend ))
supertrend_up = close > supertrend
supertrend_down = close < supertrend
//------------------------------------------------------------------------------
// Signal Logic
src = close
smoothrng(x, t, m) =>
wper = t * 2 - 1
avrng = ta.ema(math.abs(x - x ), t)
smoothrng = ta.ema(avrng, wper) * m
smoothrng
smrng = smoothrng(close, 100, sensitivity)
rngfilt(x, r) =>
rngfilt = x
rngfilt := x > nz(rngfilt ) ? x - r < nz(rngfilt ) ? nz(rngfilt ) : x - r : x + r > nz(rngfilt ) ? nz(rngfilt ) : x + r
rngfilt
filt = rngfilt(src, smrng)
var float upward = na
var float downward = na
var int CondIni = na
upward := filt > filt ? nz(upward ) + 1 : filt < filt ? 0 : nz(upward )
downward := filt < filt ? nz(downward ) + 1 : filt > filt ? 0 : nz(downward )
longCond = src > filt and src > src and upward > 0 or src > filt and src < src and upward > 0
shortCond = src < filt and src < src and downward > 0 or src < filt and src > src and downward > 0
CondIni := longCond ? 1 : shortCond ? -1 : nz(CondIni )
buyCond = longCond and CondIni == -1
strongBuyCond = buyCond and close <= filt - smrng
sellCond = shortCond and CondIni == 1
strongSellCond = sellCond and open >= filt + smrng
if noRepainting
buyCond := buyCond and barstate.isconfirmed
strongBuyCond := strongBuyCond and barstate.isconfirmed
sellCond := sellCond and barstate.isconfirmed
strongSellCond := strongSellCond and barstate.isconfirmed
//------------------------------------------------------------------------------
// Tradingview indicators. Join ->>> t.me
// -------------------- 👆👆👆👆👆👆 ---------------
//------------------------------------------------------------------------------
// ATR-Based Book Profit and Wait for Supertrend Break
var float buy_entry_price = na
var float sell_entry_price = na
var bool buy_profit_plotted = false
var bool sell_profit_plotted = false
if (buyCond or strongBuyCond)
buy_entry_price := close
buy_profit_plotted := false
if (sellCond or strongSellCond)
sell_entry_price := close
sell_profit_plotted := false
buy_target = buy_entry_price + (atr * Multiplier)
sell_target = sell_entry_price - (atr * Multiplier)
if (not na(buy_entry_price) and close >= buy_target and not buy_profit_plotted)
label.new(bar_index, high, "Book Profit", color=#00db0a, style=label.style_label_down, textcolor=color.white, size=size.normal)
buy_profit_plotted := true
label.new(bar_index, high - atr, "Wait for Supertrend to break", color=color.orange, style=label.style_label_down, textcolor=color.white, size=size.normal)
if (not na(sell_entry_price) and close <= sell_target and not sell_profit_plotted)
label.new(bar_index, low, "Book Profit", color=#ff0000, style=label.style_label_up, textcolor=color.white, size=size.normal)
sell_profit_plotted := true
label.new(bar_index, low + atr, "Wait for Supertrend to break", color=color.orange, style=label.style_label_up, textcolor=color.white, size=size.normal)
//------------------------------------------------------------------------------
// Candle Coloring
barcolor_cond = src > filt and upward > 0 ? color.new(#00db0a, 5) : src < filt and downward > 0 ? color.new(#c90505, 5) : na
barcolor(barcolor_cond, title='Candle Colors')
// Plot Signals
plotshape(buyCond and not strongSignalOnly, 'Buy', shape.labelup, location.belowbar, color.new(#21ff30, 0), size=size.small, textcolor=color.black, text='BUY')
plotshape(strongBuyCond, 'Strong Buy', shape.labelup, location.belowbar, color.new(#09ff00, 0), size=size.small, textcolor=color.black, text='BUY')
plotshape(sellCond and not strongSignalOnly, 'Sell', shape.labeldown, location.abovebar, color.new(#ff0000, 0), size=size.small, textcolor=color.black, text='SELL')
plotshape(strongSellCond, 'Strong Sell', shape.labeldown, location.abovebar, color.new(#ff0000, 0), size=size.small, textcolor=color.black, text='SELL')
// Supertrend Plot
plot(supertrend, color=supertrend_up ? color.green : color.red, title="Supertrend", linewidth=2)
// ==========================================================================================
// === Dashboard with Telegram Link ===
var table myTable = table.new(position.top_center, 1, 1, border_width=1, frame_color=color.black, bgcolor=color.white)
// Add Telegram Message to Dashboard
table.cell(myTable, 0, 0, "Join Telegram @mrexpert_ai", bgcolor=color.blue, text_color=color.white, text_size=size.normal)
Pairs Trading Scanner [BackQuant]Pairs Trading Scanner
What it is
This scanner analyzes the relationship between your chart symbol and a chosen pair symbol in real time. It builds a normalized “spread” between them, tracks how tightly they move together (correlation), converts the spread into a Z-Score (how far from typical it is), and then prints clear LONG / SHORT / EXIT prompts plus an at-a-glance dashboard with the numbers that matter.
Why pairs at all?
Markets co-move. When two assets are statistically related, their relationship (the spread) tends to oscillate around a mean.
Pairs trading doesn’t require calling overall market direction you trade the relative mispricing between two instruments.
This scanner gives you a robust, visual way to find those dislocations, size their significance, and structure the trade.
How it works (plain English)
Step 1 Pick a partner: Select the Pair Symbol to compare against your chart symbol. The tool fetches synchronized prices for both.
Step 2 Build a spread: Choose a Spread Method that defines “relative value” (e.g., Log Spread, Price Ratio, Return Difference, Price Difference). Each lens highlights a different flavor of divergence.
Step 3 Validate relationship: A rolling Correlation checks if the pair is moving together enough to be tradable. If correlation is weak, the scanner stands down.
Step 4 Standardize & score: The spread is normalized (mean & variability over a lookback) to form a Z-Score . Large absolute Z means “stretched,” small means “near fair.”
Step 5 Signals: When the Z-Score crosses user-defined thresholds with sufficient correlation , entries print:
LONG = long chart symbol / short pair symbol,
SHORT = short chart symbol / long pair symbol,
EXIT = mean reversion into the exit zone or correlation failure.
Core concepts (the three pillars)
Spread Method Your definition of “distance” between the two series.
Guidance:
Log Spread: Focuses on proportional differences; robust when prices live on different scales.
Price Ratio: Classic relative value; good when you care about “X per Y.”
Return Difference: Emphasizes recent performance gaps; nimble for momentum-to-mean plays.
Price Difference: Straight subtraction; intuitive for similar-scale assets (e.g., two ETFs).
Correlation A rolling score of co-movement. The scanner requires it to be above your Min Correlation before acting, so you’re not trading random divergence.
Z-Score “How abnormal is today’s spread?” Positive = chart richer than pair; negative = cheaper. Thresholds define entries/exits with transparent, statistical context.
What you’ll see on the chart
Correlation plot (blue line) with a dashed Min Correlation guide. Above the line = green zone for signals; below = hands off.
Z-Score plot (white line) with colored, dashed Entry bands and dotted Exit bands. Zero line for mean.
Normalized spread (yellow) for a quick “shape read” of recent divergence swings.
Signal markers :
LONG (green label) when Z < –Entry and corr OK,
SHORT (red label) when Z > +Entry and corr OK,
EXIT (gray label) when Z returns inside the Exit band or correlation drops below the floor.
Background tint for active state (faint green for long-spread stance, faint red for short-spread stance).
The two built-in dashboards
Statistics Table (top-right)
Pair Symbol Your chosen partner.
Correlation Live value vs. your minimum.
Z-Score How stretched the spread is now.
Current / Pair Prices Real-time anchors.
Signal State NEUTRAL / LONG / SHORT.
Price Ratio Context for ratio-style setups.
Analysis Table (bottom-right)
Avg Correlation Typical co-movement level over your window.
Max |Z| The recent extremes of dislocation.
Spread Volatility How “lively” the spread has been.
Trade Signal A human-readable prompt (e.g., “LONG A / SHORT B” or “NO TRADE” / “LOW CORRELATION”).
Risk Level LOW / MEDIUM / HIGH based on current stretch (absolute Z).
Signals logic (plain English)
Entry (LONG): The spread is unusually negative (chart cheaper vs pair) and correlation is healthy. Expect mean reversion upward in the spread: long chart, short pair.
Entry (SHORT): The spread is unusually positive (chart richer vs pair) and correlation is healthy. Expect mean reversion downward in the spread: short chart, long pair.
Exit: The spread relaxes back toward normal (inside your exit band), or correlation deteriorates (relationship no longer trusted).
A quick, repeatable workflow
1) Choose your pair in context (same sector/theme or known macro link). Think: “Do these two plausibly co-move?”
2) Pick a spread lens that matches your narrative (ratio for relative value, returns for short-term performance gaps, etc.).
3) Confirm correlation is above your floor no corr, no trade.
4) Wait for a stretch (Z beyond Entry band) and a printed LONG / SHORT .
5) Manage to the mean (EXIT band) or correlation failure; let the scanners’ state/labels keep you honest.
Settings that matter (and why)
Spread Method Defines the “mispricing” you care about.
Correlation Period Longer = steadier regime read, shorter = snappier to regime change.
Z-Score Period The window that defines “normal” for the spread; it sets the yardstick.
Use Percentage Returns Normalizes series when using return-based logic; keep on for mixed-scale assets.
Entry / Exit Thresholds Set your stretch and your target reversion zone. Wider entries = rarer but stronger signals.
Minimum Correlation The gatekeeper. Raising it favors quality over quantity.
Choosing pairs (practical cheat sheet)
Same family: two index ETFs, two oil-linked names, two gold miners, two L1 tokens.
Hedge & proxy: stock vs. sector ETF, BTC vs. BTC index, WTI vs. energy ETF.
Cross-venue or cross-listing: instruments that are functionally the same exposure but price differently intraday.
Reading the cues like a pro
Divergence shape: The yellow normalized spread helps you see rhythm fast spike and snap-back versus slow grind.
Corr-first discipline: Don’t fight the “Min Correlation” line. Good pairs trading starts with a relationship you can trust.
Exit humility: When Z re-centers, let the EXIT do its job. The edge is the journey to the mean, not overstaying it.
Frequently asked (quick answers)
“Long/Short means what exactly?”
LONG = long the chart symbol and short the pair symbol.
SHORT = short the chart symbol and long the pair symbol.
“Do I need same price scales?” No. The spread methods normalize in different ways; choose the one that fits your use case (log/ratio are great for mixed scales).
“What if correlation falls mid-trade?” The scanner will neutralize the state and print EXIT . Relationship first; trade second.
Field notes & patterns
Snap-back days: After a one-sided session, return-difference spreads often flag cleaner intraday mean reversions.
Macro rotations: Ratio spreads shine during sector re-weights (e.g., value vs. growth ETFs); look for steady corr + elevated |Z|.
Event bleed-through: If one symbol reacts to news and its partner lags, Z often flags a high-quality, short-horizon re-centering.
Display controls at a glance
Show Statistics Table Live state & key numbers, top-right.
Show Analysis Table Context/risk read, bottom-right.
Show Correlation / Spread / Z-Score Toggle the sub-charts you want visible.
Show Entry/Exit Signals Turn markers on/off as needed.
Coloring Adjust Long/Short/Neutral and correlation line colors to match your theme.
Alerts (ready to route to your workflow)
Pairs Long Entry Z falls through the long threshold with correlation above minimum.
Pairs Short Entry Z rises through the short threshold with correlation above minimum.
Pairs Trade Exit Z returns to neutral or the relationship fails your correlation floor.
Correlation Breakdown Rolling correlation crosses your minimum; relationship caution.
Final notes
The scanner is designed to keep you systematic: require relationship (correlation), quantify dislocation (Z-Score), act when stretched, stand down when it normalizes or the relationship degrades. It’s a full, visual loop for relative-value trading that stays out of your way when it should and gets loud only when the numbers line up.
ASX Historical Price Projection [360 Days Auto]The ASX Price Projection indicator is a forecasting tool that projects future price movement based on historical price action and user-defined parameters. Inspired by the cyclical nature of markets, this tool helps traders visualize how price could behave in the future — not with certainty, but as a modeled possibility based on past behavior patterns.
What It Does:
This tool replicates the price action from a chosen historical period and projects it into the future, optionally applying a drift factor (growth or contraction). This projection is visualized directly on the chart, helping traders anticipate potential future price paths based on recognizable past behavior.
How It Works:
The indicator automatically uses the most recent 360 bars of historical data as the projection template. This is fixed and not user-selectable.
The selected price segment is replicated and extended into the future to simulate a possible price path.
A Drift Factor (Growth Multiplier) can be applied to simulate bullish (positive) or bearish (negative) price drift.
An Area Width parameter defines how wide the projection zone appears around the forecast line, helping to visualize uncertainty or price range tolerance.
The projected path and its surrounding band are plotted forward from the current bar.
Why It’s Unique:
This script offers a simple yet powerful way to model potential future price action based on automatic historical pattern detection:
No manual selection required — the last 360 bars are always used.
The Drift Factor allows scenario testing for growth or decline.
Area Width gives a realistic band around the projected path.
Designed for visual modeling and hypothetical exploration — not predictive accuracy.
How to Use:
Load the indicator on any chart.
The system automatically pulls the last 360 bars to generate the projection.
Adjust the Drift Factor to simulate optimistic or pessimistic market scenarios.
Set the Area Width to control the visual range around the projected line.
Use the forecast to explore how price might evolve under similar conditions.
Dynamic Stop Loss Optimizer [BackQuant]Dynamic Stop Loss Optimizer
Overview
Stop placement decides expectancy. This tool gives you three professional-grade, adaptive stop engines, ATR, Volatility, and Hybrid. So your exits scale with current conditions instead of guessing fixed ticks. It trails intelligently, redraws as the market evolves, and annotates the chart with clean labels/lines and a compact stats table. Pick the engine that fits the trade, or switch on the fly.
What it does
Calculates three adaptive stops in real time (ATR-based, Volatility-based, and Hybrid) and keeps them trailed as price makes progress.
Shows exactly where your risk lives with on-chart levels, color-coded markers (long/short), and precise “Risk %” labels at the current bar.
Surfaces context you actually use - current ATR, daily volatility, selected method, and the live stop level—in a tidy, movable table.
Fires alerts on stop hits so you can automate exits or journal outcomes without staring at the screen.
Why it matters
Adaptive risk control: Stops expand in fast tape and tighten in quiet tape. You’re not punished for volatility; you’re aligned with it.
Consistency across assets: The same playbook works whether you’re trading indexes, FX, crypto, or equities, because the engine normalizes to each symbol’s behavior.
Cleaner decision-making: One chart shows your entry idea and its invalidation in the same breath. If price trespasses, you know it instantly.
The three methods (choose your engine)
1) ATR Based “Structure-aware” distance
This classic approach keys off Average True Range to set a stop just beyond typical bar-to-bar excursion. It adapts smoothly to changing ranges and respects swing structure.
Use when: you want a steady, intuitive buffer that tracks trend legs without hugging price.
See it in action:
2) Volatility Based “Behavior-aware” distance
This engine derives stop distance from current return volatility (annualized, then scaled back down to the session). It reacts to regime shifts quickly and normalizes risk across symbols with very different prices.
Use when: you want the stop to breathe with realized volatility and respond faster to heat-ups/cool-downs.
See it in action:
3) Hybrid “Best of both worlds”
The Hybrid blends the ATR and Volatility distances into one consensus level, then trails it intelligently. You get the structural common sense of ATR and the regime sensitivity of Vol.
Use when: you want robust, all-weather behavior without micromanaging inputs.
See it in action:
How it trails
Longs: The stop ratchets up with favorable movement and holds its ground on shallow pullbacks. If price closes back into the risk zone, the level refreshes to the newest valid distance.
Shorts: Mirror logic ratchets down with trend, resists noise, and refreshes if price reclaims the zone.
Hybrid trailing: Uses the blended distance and the same “no give-backs” principle to keep gains protected as structure builds.
Reading the chart
Markers: Circles = ATR stops, Crosses = Vol stops, Diamonds = Hybrid. Colors indicate long (red level under price) vs short (green level above price).
Lines: The latest active stop is extended with a dashed line so you can see it at a glance.
Labels: “Long SL / Short SL” shows the exact price and current risk % from the last close no math required.
Table: ATR value, Daily Vol %, your chosen Method, the Current SL, and Risk %—all in one compact block that you can pin top-left/right/center.
Quick workflow
Define the idea: Long or Short, and which engine fits the tape (ATR, Vol, or Hybrid).
Place and trail: Let the optimizer print the level; trail automatically as the move develops.
Manage outcomes: If the line is tagged, you’re out clean. If it holds, you’ve contained heat while giving the trade room to work.
Inputs you’ll actually touch
Calculation Settings
ATR Length / Multiplier: Controls the “structural” cushion.
Volatility Length / Multiplier: Controls the “behavioral” cushion.
Trading Days: 252 or 365 to keep the volatility math aligned with the asset’s trading calendar.
Stop Loss Method
ATR Based | Volatility Based | Hybrid : Switch engines instantly to fit the trade.
Position Type
Long | Short | Both : Show only what you need for the current strategy.
Visual Settings
Show ATR / Vol / Hybrid Stops: Toggle families on/off.
Show Labels: Print price + Risk % at the live stop.
Table Position: Park the metrics where you like.
Coloring
Long/Short/Hybrid colors: Set a palette that matches your theme and stands out on your background.
Practical patterns to watch
Trend-pullback continuation: The stop ratchets behind higher lows (long) or lower highs (short). If price tests the level and rejects, that’s your risk-defined continuation cue.
Break-and-run: After a clean break, the Hybrid will usually sit slightly wider than pure Vol, use it to avoid getting shaken on the first retest.
Range compression: When the ATR and Vol distances converge, the table will show small Risk %. That’s your green light to size up with the same dollar risk, or keep it conservative if you expect expansion.
Alerts
Long Stop Loss Hit : Notifies when price crosses below the live long stop.
Short Stop Loss Hit : Notifies when price crosses above the live short stop.
Why this feels “set-and-serious”
You get a single look that answers three questions in real time: “Where’s my line in the sand?”, “How much heat am I taking right now?”, and “Is this distance appropriate for current conditions?” With ATR, Vol, and Hybrid in one tool, you can run the exact same playbook across symbols and regimes while keeping your chart clean and your risk explicit.
Probas target and touching (points)Probability of Touching Long or Short X nb of point in 10 mins, 20 mins, 30 mins, 60 mins
52WH/last52WHbefore3Months/ATHThis indicator calculates and displays three values:
First, it calculates the current 52-week high and displays it as a line and in a table at the top right with the name, date, and price.
Corresponding color markings are also displayed on the price scale.
Next, the 52-week high that is at least three months ago is determined.
The corresponding candle is also labeled with a date. This past high is also displayed as a line, on the price scale, and in the table.
Finally, the current all-time high is determined and also displayed as a line, in the price scale, and in the table.
All display values can be turned on or off in the view, and the corresponding colors of the displays can also be freely selected.
(This script was developed by J. Heina, jochen.heina(at)gmail, in collaboration with the ChatGPT tool).
=====
SmartSkull 15 minutes//@version=5
indicator("LegendGPT – First 15m Extremes + Second 15m Breakout FVG + Alerts", overlay=true, max_boxes_count=500)
// SETTINGS
boxColor = input.color(color.new(color.gray, 85), "Opening Box Color")
fvgBullColor = input.color(color.new(color.green, 85), "Bullish FVG Color")
fvgBearColor = input.color(color.new(color.red, 85), "Bearish FVG Color")
sessionTZ = "America/New_York"
nasdaqOpenHour = 9
nasdaqOpenMinute = 30
// 15m data for box
time15_tf = request.security(syminfo.tickerid, "15", time, lookahead=barmerge.lookahead_on)
high15_tf = request.security(syminfo.tickerid, "15", high, lookahead=barmerge.lookahead_on)
low15_tf = request.security(syminfo.tickerid, "15", low, lookahead=barmerge.lookahead_on)
// First 15m candle start
isFirst15mActive = (hour(time15_tf, sessionTZ) == nasdaqOpenHour and minute(time15_tf, sessionTZ) == nasdaqOpenMinute)
isSecond15mActive = (hour(time15_tf, sessionTZ) == nasdaqOpenHour and minute(time15_tf, sessionTZ) == nasdaqOpenMinute + 15)
// STATE VARS
var box openingRangeBox = na
var float session1mHigh = na
var int session1mHighBar = na
var float session1mLow = na
var int session1mLowBar = na
var bool extremesMarked = false
var bool bullBreakout = false
var bool bearBreakout = false
var bool fvgDrawn = false
var box fvgBox = na
var label fvgFilledLabel = na
newDay = time("D", sessionTZ) != time("D", sessionTZ)
// RESET DAILY
if newDay
if not na(openingRangeBox)
box.delete(openingRangeBox)
if not na(fvgBox)
box.delete(fvgBox)
if not na(fvgFilledLabel)
label.delete(fvgFilledLabel)
session1mHigh := na
session1mHighBar := na
session1mLow := na
session1mLowBar := na
extremesMarked := false
bullBreakout := false
bearBreakout := false
fvgDrawn := false
// Only run on 1-minute timeframe
if timeframe.multiplier == 1
// CREATE OPENING RANGE BOX for first 15m
if isFirst15mActive and na(openingRangeBox)
openingRangeBox := box.new(left=bar_index, top=high15_tf, right=bar_index + 15, bottom=low15_tf, bgcolor=boxColor, border_color=color.new(color.black, 90))
// Track highest/lowest 1m candle during first 15m
if isFirst15mActive
if na(session1mHigh)
session1mHigh := high
session1mHighBar := bar_index
session1mLow := low
session1mLowBar := bar_index
else
if high > session1mHigh
session1mHigh := high
session1mHighBar := bar_index
if low < session1mLow
session1mLow := low
session1mLowBar := bar_index
// When first 15m ends, mark extremes
if isFirst15mActive and not isFirst15mActive and not extremesMarked
// Green box for highest 1m candle
box.new(left=session1mHighBar, top=session1mHigh, right=session1mHighBar + 1, bottom=session1mHigh, border_color=color.green, bgcolor=color.new(color.green, 80))
// Red box for lowest 1m candle
box.new(left=session1mLowBar, top=session1mLow, right=session1mLowBar + 1, bottom=session1mLow, border_color=color.red, bgcolor=color.new(color.red, 80))
extremesMarked := true
// SECOND 15m: Check breakout of high/low
if isSecond15mActive
// Bullish breakout
if not bullBreakout and high > session1mHigh
bullBreakout := true
bearBreakout := false
alert("LegendGPT: Bullish Breakout above first 15m high", alert.freq_once_per_bar)
// Bearish breakout
if not bearBreakout and low < session1mLow
bearBreakout := true
bullBreakout := false
alert("LegendGPT: Bearish Breakout below first 15m low", alert.freq_once_per_bar)
// After breakout in second 15m, look for first FVG
if isSecond15mActive and not fvgDrawn
// Bullish FVG condition
if bullBreakout and low > high
fvgBox := box.new(left=bar_index - 1, top=high , right=bar_index, bottom=low, bgcolor=fvgBullColor, border_color=color.green)
fvgDrawn := true
alert("LegendGPT: Bullish FVG formed after breakout", alert.freq_once_per_bar)
// Bearish FVG condition
if bearBreakout and high < low
fvgBox := box.new(left=bar_index - 1, top=high, right=bar_index, bottom=low , bgcolor=fvgBearColor, border_color=color.red)
fvgDrawn := true
alert("LegendGPT: Bearish FVG formed after breakout", alert.freq_once_per_bar)
// PERSISTENT FVG: delete when filled
if not na(fvgBox)
fvgTop = box.get_top(fvgBox)
fvgBottom = box.get_bottom(fvgBox)
if high >= fvgBottom and low <= fvgTop
box.delete(fvgBox)
fvgBox := na
fvgDrawn := false
if not na(fvgFilledLabel)
label.delete(fvgFilledLabel)
fvgFilledLabel := label.new(bar_index, close, text="FVG filled", style=label.style_label_center, color=color.blue, textcolor=color.white, size=size.tiny)
alert("LegendGPT: FVG filled (mitigation)", alert.freq_once_per_bar)
Shashwat Khurana (v6) – VWAP ±1SD + RSI + ATR Filter A multi-factor volatility-adjusted mean-reversion model integrating dynamic liquidity thresholds and higher-order momentum filters for asymmetric risk calibration
Japan Yen Carry Trade to Risk Ratio Sharpe Ratio By UncleBFMStep-by-Step Calculation in the ScriptFetch Rates:Pulls rates dynamically using request.security() from user-specified symbols (e.g., TVC:JP10Y for yen, TVC:US10Y for target). If unavailable (NA), uses fallback inputs (e.g., 0.25% for yen, 4.50% for target).
Converts rates to decimals: (target_rate - yen_rate) / 100.
Calculate Carry:Carry = (Target Rate - Yen Rate) / 100
Example: If US 10Y yield is 4.50% and Japan 10Y is 0.25%, carry = (4.50 - 0.25) / 100 = 0.0425 (4.25% annual yield).
Calculate Daily Log Returns:Log Returns = ln(Close / Close ), where Close is the current price of the pair (e.g., USDJPY) and Close is the previous day's price.
This measures daily percentage changes in a way suitable for volatility calculations.
Calculate Annualized Volatility:Volatility = Standard Deviation of Log Returns over a lookback period (default 63 days, ~3 months) × √252.
Example: If the standard deviation of USDJPY log returns is 0.005 (0.5% daily), annualized volatility = 0.005 × √252 ≈ 0.0794 (7.94%).
Compute the Ratio:Ratio = Carry / Volatility
Example: Using above, 0.0425 / 0.0794 ≈ 0.535.
If volatility is zero, the ratio is set to NA to avoid division errors.
Plot:Plots the ratio as a line, with optional thresholds (e.g., 0.2 for "high attractiveness") to guide interpretation.
NotesDynamic Rates: Using bond yields (e.g., TVC:JP10Y) or policy rates (e.g., ECONOMICS:JPINTR) makes the indicator responsive to historical and current rate changes, unlike static inputs.
Context: BIS reports use similar ratios to assess carry trade viability. For USDJPY in 2025, with Fed rates around 4.5% and BoJ at 0.25–0.5%, the carry is positive but sensitive to volatility spikes (e.g., during 2024 unwind events).
Usage: Apply to a yen pair chart (e.g., USDJPY, AUDJPY). Adjust symbols for the target currency (e.g., TVC:AU10Y for AUD). The ratio helps compare carry trade profitability across pairs or over time.
DashBoard 2.3.1📌 Indicator Name:
DashBoard 2.3 – Smart Visual Market Overlay
📋 Description:
DashBoard 2.3 is a clean, efficient, and highly informative market overlay, designed to give you real-time context directly on your chart — without distractions. Whether you're swing trading or investing long-term, this tool keeps critical market data at your fingertips.
🔍 Key Features:
Symbol + Timeframe + Market Cap
Shows the current ticker and timeframe, optionally with real-time market cap.
ATR 14 with Volatility Signal
Displays ATR with color-coded risk levels:
🟢 Low
🟡 Moderate
🔴 High
⚫️ Extreme
You can choose between Daily ATR or timeframe-based ATR (auto-adjusted to chart resolution).
Adaptive Labeling
The ATR label updates to reflect the resolution:
ATR 14d (daily)
ATR 14W (weekly)
ATR 14H (hourly), etc.
Moving Average Tracker
Instantly shows whether price is above or below your selected moving average (e.g., 150 MA), with green/red indication.
Earnings Countdown
Clearly shows how many days remain until the next earnings report.
Industry & Sector Info (optional)
Useful for thematic or sector-based trading strategies.
Fully Customizable UI
Choose positioning, padding, font size, and which data to show. Designed for minimalism and clarity.
✅ Smart Logic:
Color dots appear only in relevant conditions (e.g., ATR color signals shown only on daily when enabled).
ATR display automatically reflects your time frame, if selected.
Clean chart integration – the overlay sits quietly in a corner, enhancing your analysis without intruding.
🧠 Ideal for:
Swing traders, position traders, and investors who want fast, high-impact insights directly from the chart.
Anyone looking for a compact, beautiful, and informative dashboard while they trade.
RSI + Stoch + Bollinger — Tableau compact (coin sup. droit)RSI + Stoch + Bollinger — Tableau compact (coin sup. droit)
Supertrend DashboardOverview
This dashboard is a multi-timeframe technical indicator dashboard based on Supertrend. It combines:
Trend detection via Supertrend
Momentum via RSI and OBV (volume)
Volatility via a basic candle-based metric (bs)
Trend strength via ADX
Multi-timeframe analysis to see whether the trend is bullish across different timeframes
It then displays this info in a table on the chart with colors for quick visual interpretation.
2️⃣ Inputs
Dashboard settings:
enableDashboard: Toggle the dashboard on/off
locationDashboard: Where the table appears (Top right, Bottom left, etc.)
sizeDashboard: Text size in the table
strategyName: Custom name for the strategy
Indicator settings:
factor (Supertrend factor): Controls how far the Supertrend lines are from price
atrLength: ATR period for Supertrend calculation
rsiLength: Period for RSI calculation
Visual settings:
colorBackground, colorFrame, colorBorder: Control dashboard style
3️⃣ Core Calculations
a) Supertrend
Supertrend is a trend-following indicator that generates bullish or bearish signals.
Logic:
Compute ATR (atr = ta.atr(atrLength))
Compute preliminary bands:
upperBand = src + factor * atr
lowerBand = src - factor * atr
Smooth bands to avoid false flips:
lowerBand := lowerBand > prevLower or close < prevLower ? lowerBand : prevLower
upperBand := upperBand < prevUpper or close > prevUpper ? upperBand : prevUpper
Determine direction (bullish / bearish):
dir = 1 → bullish
dir = -1 → bearish
Supertrend line = lowerBand if bullish, upperBand if bearish
Output:
st → line to plot
bull → boolean (true = bullish)
b) Buy / Sell Trigger
Logic:
bull = ta.crossover(close, supertrend) → close crosses above Supertrend → buy signal
bear = ta.crossunder(close, supertrend) → close crosses below Supertrend → sell signal
trigger → checks which signal was most recent:
trigger = ta.barssince(bull) < ta.barssince(bear) ? 1 : 0
1 → Buy
0 → Sell
c) RSI (Momentum)
rsi = ta.rsi(close, rsiLength)
Logic:
RSI > 50 → bullish
RSI < 50 → bearish
d) OBV / Volume Trend (vosc)
OBV tracks whether volume is pushing price up or down.
Manual calculation (safe for all Pine versions):
obv = ta.cum( math.sign( nz(ta.change(close), 0) ) * volume )
vosc = obv - ta.ema(obv, 20)
Logic:
vosc > 0 → bullish
vosc < 0 → bearish
e) Volatility (bs)
Measures how “volatile” the current candle is:
bs = ta.ema(math.abs((open - close) / math.max(high - low, syminfo.mintick) * 100), 3)
Higher % → stronger candle moves
Displayed on dashboard as a number
f) ADX (Trend Strength)
= ta.dmi(14, 14)
Logic:
adx > 20 → Trending
adx < 20 → Ranging
g) Multi-Timeframe Supertrend
Timeframes: 1m, 3m, 5m, 10m, 15m, 30m, 1H, 2H, 4H, 12H, 1D
Logic:
for tf in timeframes
= request.security(syminfo.tickerid, tf, f_supertrend(ohlc4, factor, atrLength))
array.push(tf_bulls, bull_tf ? 1.0 : 0.0)
bull_tf ? 1.0 : 0.0 → converts boolean to number
Then we calculate user rating:
userRating = (sum of bullish timeframes / total timeframes) * 10
0 → Strong Sell, 10 → Strong Buy
4️⃣ Dashboard Table Layout
Row Column 0 (Label) Column 1 (Value)
0 Strategy strategyName
1 Technical Rating textFromRating(userRating) (color-coded)
2 Current Signal Buy / Sell (based on last Supertrend crossover)
3 Current Trend Bullish / Bearish (based on Supertrend)
4 Trend Strength bs %
5 Volume vosc → Bullish/Bearish
6 Volatility adx → Trending/Ranging
7 Momentum RSI → Bullish/Bearish
8 Timeframe Trends 📶 Merged cell
9-19 1m → Daily Bullish/Bearish for each timeframe (green/red)
5️⃣ Color Logic
Green shades → bullish / trending / buy
Red / orange → bearish / weak / sell
Yellow → neutral / ranging
Example:
dashboard_cell_bg(1, 1, colorFromRating(userRating))
dashboard_cell_bg(1, 2, trigger ? color.green : color.red)
dashboard_cell_bg(1, 3, superBull ? color.green : color.red)
Makes the dashboard visually intuitive
6️⃣ Key Logic Flow
Calculate Supertrend on current timeframe
Detect buy/sell triggers based on crossover
Calculate RSI, OBV, Volatility, ADX
Request Supertrend on multiple timeframes → convert to 1/0
Compute user rating (percentage of bullish timeframes)
Populate dashboard table with colors and values
✅ The result: You get a compact, fast, multi-timeframe trend dashboard that shows:
Current signal (Buy/Sell)
Current trend (Bullish/Bearish)
Momentum, volatility, and volume cues
Trend across multiple timeframes
Overall technical rating
It’s essentially a full trend-strength scanner directly on your chart.
Дни недели и торговые сесииIndicator for visual analysis by trading sessions and days.
Индикатор для наглядного анализа по торговым сесиям и дням.
Combined Cluster & Market StructureI barrowed code from the Mxwll Price Action Suite script as appreciated the structure in which the script defined structure, however I renamed variables and reduced the original script to define only the outer structure. I added volume and CVD clustering to define ranges and initiation market structures and add the ADX to assist with determining trend strength prior to labeling market structure breaks.
Combined Cluster & Market Structure indicator, a powerful and comprehensive tool for technical analysis. This script integrates two core concepts to provide a holistic view of market dynamics:
Z-Score Clustering & Volume Analysis: The indicator calculates Z-scores for both volume and Cumulative Volume Delta (CVD) to categorize market activity into six distinct clusters:
High-Conviction Bullish/Bearish: Signals of strong directional momentum based on high volume and corresponding CVD.
Effort vs. Result: High volume with moderate CVD, suggesting potential indecision or absorption.
Quiet Accumulation/Distribution: Low-volume periods with strong CVD, often preceding major moves.
Low Conviction/Noise: Represents periods of low market participation and weak signals.
These clusters are visually marked on the chart to provide real-time insight into market sentiment.
Market Structure Mapping: The indicator automatically detects and labels significant structural points to help you navigate price action. It identifies:
Higher Highs (HH) and Lower Lows (LL) to show the primary trend direction.
Breaks of Structure (BoS), indicating trend continuation.
Changes of Character (CHoCH), signaling a potential trend reversal.
Additionally, the script features consolidation box detection, which automatically highlights periods of low-conviction market activity, helping you avoid choppy, sideways markets. An integrated ADX filter ensures that structural breaks are only labeled during periods of strong trend strength, reducing false signals.
I want to thank Mxwll Capital for their contribution to the Combined Cluster & Market Structure indicator.
FRANJAS POR FECHAS - RSDescription:
This indicator allows you to highlight specific dates on your chart with vertical background stripes, similar to a session indicator.
Input your dates in the format DD.MM.YYYY (you can separate them with commas, spaces, line breaks, or semicolons).
The script automatically normalizes the format and applies a shaded vertical band for each matching day.
Works on daily and intraday charts: in intraday, the shading will cover the full trading day.
Options available to adjust the color and transparency of the stripes.
Optional dotted lines can be enabled at the start and end of each highlighted day.
This is useful for marking important events such as FOMC meetings, earnings releases, economic data announcements, or any custom list of key dates you want to track directly on your chart.
KCandle Strategy 1.0# KCandle Strategy 1.0 - Trading Strategy Description
## Overview
The **KCandle Strategy** is an advanced Pine Script trading system based on bullish and bearish engulfing candlestick patterns, enhanced with sophisticated risk management and position optimization features.
## Core Logic
### Entry Signal Generation
- **Pattern Recognition**: Detects bullish and bearish engulfing candlestick formations
- **EMA Filter**: Uses a customizable EMA (default 25) to filter trades in the direction of the trend
- **Entry Levels**:
- **Long entries** at 25% of the candlestick range from the low
- **Short entries** at 75% of the candlestick range from the low
- **Signal Validation**: Orange candlesticks indicate valid setup conditions
### Risk Management System
#### 1. **Stop Loss & Take Profit**
- Configurable stop loss in pips
- Risk-reward ratio setting (default 2:1)
- Visual representation with colored lines and labels
#### 2. **Break-Even Management**
- Automatically moves stop loss to break-even when specified R:R is reached
- Customizable break-even offset for added protection
- Prevents losing trades after reaching profitability
#### 3. **Trailing Stop System**
- **Activation Trigger**: Activates when position reaches specified R:R level
- **Distance Control**: Maintains trailing stop at defined distance from entry
- **Step Management**: Moves stop loss forward in incremental R steps
- **Dynamic Protection**: Locks in profits while allowing for continued upside
### Advanced Features
#### Position Management
- **Pyramiding Support**: Optional multiple position entries with size reduction
- **Order Expiration**: Pending orders automatically cancel after specified bars
- **Position Sizing**: Percentage-based allocation with pyramid level adjustments
#### Visual Interface
- **Real-time Monitoring**: Comprehensive information panel with all strategy metrics
- **Historical Tracking**: Visual representation of past trades and levels
- **Color-coded Indicators**: Different colors for break-even, trailing, and standard stops
- **Debug Options**: Optional labels for troubleshooting and optimization
## Key Parameters
### Basic Settings
- **EMA Length**: Trend filter period
- **Stop Loss**: Risk per trade in pips
- **Risk/Reward**: Target profit ratio
- **Order Validity**: Duration of pending orders
### Risk Management
- **Break-Even R:R**: Profit level to trigger break-even
- **Trailing Activation**: R:R level to start trailing
- **Trailing Distance**: Stop distance from entry when trailing
- **Trailing Step**: Increment for stop loss advancement
## Strategy Benefits
1. **Objective Entry Signals**: Based on proven candlestick patterns
2. **Trend Alignment**: EMA filter ensures trades align with market direction
3. **Robust Risk Control**: Multiple layers of protection (SL, BE, Trailing)
4. **Profit Optimization**: Trailing stops maximize winning trade potential
5. **Flexibility**: Extensive customization options for different market conditions
6. **Visual Clarity**: Complete visual feedback for trade management
## Ideal Use Cases
- **Swing Trading**: Medium-term positions with trend-following approach
- **Breakout Trading**: Capturing momentum from engulfing patterns
- **Risk-Conscious Trading**: Suitable for traders prioritizing capital preservation
- **Multi-Timeframe**: Adaptable to various timeframes and instruments
---
*The KCandle Strategy combines traditional technical analysis with modern risk management techniques, providing traders with a comprehensive tool for systematic market participation.*
Price Persistence ScreenerPrice Persistence Screener
Pine Script v6 | Inspired by @pradeepbonde on X
This indicator, inspired by the insights of @pradeepbonde , is designed to identify stocks with high price persistence—stocks that consistently close higher than the previous day's close over various lookback periods. As described by Pradeep Bonde, stocks with high persistence are strong candidates for trading pullbacks or consolidations, as they often resume their upward trend due to aggressive buying and low selling pressure. This tool helps traders screen for such stocks and visualize their persistence across multiple timeframes.
Features:
Measures price persistence by counting bars where the closing price exceeds the previous bar’s close for fixed periods: 499, 252, 126, 60, 40, 20, 15, 10, and 5 bars.
Includes a customizable lookback period (1 to 499 bars) for flexible analysis.
Allows users to set a custom persistence threshold (0% to 100%) to highlight strong bullish trends.
How It Works:
For each lookback period, the indicator calculates how many times the closing price is higher than the previous bar’s close.
A higher count indicates stronger bullish persistence, signaling stocks with sustained upward momentum.
Usage:
This screener is aimed to be used on pine screener to see data in columns. Add this indicator to you favorites and in pine screener scan on your watchlist of up to 1000 stocks
Adjust the custom lookback period and threshold via input settings.
Sort columns to compare persistence across timeframes and identify stocks with high persistence for swing trading or long-term holding.
Settings:
Custom Lookback Period (Bars): Set the number of bars for the custom persistence calculation (default: 100).
Custom Persistence Threshold (%): Define the percentage threshold for highlighting high persistence in the custom period (default: 70%).
Credits:
This indicator is based on the price persistence concept shared by @pradeepbonde
in his YouTube video (www.youtube.com). He explains that stocks with high persistence—those consistently closing higher day after day—are strong candidates for trading pullbacks, as they tend to resume their upward trend. This screener automates and visualizes that concept, making it easier for traders to identify such stocks.
Note:
Ensure sufficient historical data is available for accurate calculations, especially for longer periods like 499 bars. if stock is less than 499 bars.
High persistence stocks may eventually lose momentum, signaling potential reversals or shorting opportunities, as noted by @pradeepbonde
.
Use this indicator as part of a broader trading strategy to screen strong trends with custom lookback scan, combining it with other technical or fundamental analysis.
Avg Candle Size (Ticks) – Last 9 Closed BarsWhat it does:
Shows the average candle size in ticks for the last N closed bars (defaults to 9). I built this so I can glance at a 5-min chart and instantly know the typical bar size in ticks, updating only after each bar closes (no intrabar wiggle).
How it works:
Measures each bar’s full range (High–Low), not ATR and not candle body.
Averages the last N closed bars, converts to ticks using syminfo.mintick.
Displays a simple line plus a small readout (e.g., “32 ticks”).
Why I built it:
Gives me a realistic sense of current volatility in ticks so I can size stops/targets quickly without doing mental math.
Extras:
Lookback is configurable (default 9).
Optional rounding (floor/nearest/ceil).
Works on any timeframe/instrument that has a defined tick size.
If you want it to match ATR exactly (in ticks), swap the range calc for ta.atr(len) / syminfo.mintick
Flux Power Dashboard (Updated and Renamed)Flux Power Dashboard is a compact market-state heads-up display for TradingView. It blends trend, momentum, and volume-flow into a single on-chart panel with color-coded cues and minimal lag. You get:
Clean visual trend via fast/slow MA with slope/debounce filters
MACD state and most recent cross (with “freshness” tint)
OBV confirmation and gating to reduce noise
Session awareness (Asia/London/New York + pre-sessions + overlap)
Optional HTF Regime row and regime gate to align signals to higher-timeframe bias
Context from VIX/VXN (volatility regime)
A single Flux Score (0–100) as a top-level read
It is deliberately “dashboard-first”: fast to read, consistent between symbols/timeframes, and designed to limit overtrading in chop.
What it can do (capabilities)
Signal gating: You can require multiple pillars to agree (Trend, MACD, OBV) before a “strong” bias is shown.
Debounced trend: Uses slope + confirmation bars to avoid flip-flopping.
Session presets: Auto-adjust the minimum confirmation bars by session (e.g., NY vs London vs Asia) to better match liquidity/volatility.
MACD presets: Quick switch between Scalp / Classic / Slow or roll your own custom speeds.
OBV confirmation: Volume flow must agree for trend/entries to “count” (optional).
HTF Regime awareness: Shows the higher-timeframe backdrop and (optionally) gates signals so you don’t fight the dominant trend.
Volatility context: VIX/VXN auto-colored cells based on your thresholds.
Top-center Session Title: Broadcasts the active session (or Overlap) with a matched background color.
Customizable UI: Column fonts, params font, transparency, dashboard corner, marker styles, colors, widths—tune it to your chart.
Practical use: Start with Flux Score + Summary for a snapshot, confirm with Trend & MACD, check OBV agreement (implicit in signal strength), glance at Regime to avoid counter-trend trades, and use Session + VIX/VXN for timing and risk context.
How it avoids common pitfalls
Repaint-aware: “Confirm on Close” can be enabled to read prior bar states, reducing intrabar noise.
Auto MA sanity: If fast ≥ slow length, it auto-swaps under the hood to keep calculations valid.
Debounce & confirm: Trend flips only after X bars satisfy conditions, cutting false flips in chop.
Freshness tint: New Cross/Signal rows tint slightly brighter for a few bars, so you can spot recency at a glance.
Every line of the dashboard (what it shows, how it’s colored)
Flux Score
What: Composite 0–100 built from three pillars: Trend (40%), MACD (30%), OBV (30%).
Read: ≥70 Bullish, ≤30 Bearish, else Neutral.
Use: Quick “state of play” gauge—stronger alignment pushes the score toward extremes.
Regime (optional row)
What: Higher-timeframe (your Regime TF) backdrop using the same MA pair with HTF slope/ATR buffer.
Values: Bull / Bear / Range.
Gate (optional): If Regime Gate is ON, Trend/Signals only go directional when HTF agrees.
Summary
What: One-line narrative combining the three pillars: MACD (up/down/flat), OBV (up/down/flat), Trend (up/down/flat).
Use: Human-readable cross-check; should rhyme with Flux Score.
Trend
What: Debounced MA relationship on the current chart.
Strict: needs fast > slow and slow rising (mirror for down) + slope debounce + confirmation bars.
Lenient: allows fast > slow or slow rising (mirror for down) with the same debounce/confirm.
Color: Green = UP, Red = DOWN, Gray = FLAT.
Use: Your structural bias on the trading timeframe.
MACD
What: Current MACD line vs signal, using your selected preset (or custom).
Values: Bull (line above), Bear (below), Flat (equal/indeterminate).
Color: Green/Red/Gray.
Cross
What: Most recent MACD cross and how many bars ago it occurred (e.g., “MACD XUP | 3 bars”).
Freshness: If the cross happened within Fresh Signal Tint bars, the cell brightens slightly.
Use: Timing helper for inflection points.
Signal
What: Latest directional shift (from short-bias to long-bias or vice versa) and age in bars.
Strength:
Strong = Trend + MACD + OBV all align
Weak = partial alignment (e.g., Trend + MACD, or Trend + OBV)
Color: Green for long bias, Red for short bias; fresh signals tint brighter.
Use: Action cue—treat Strong as higher quality; Weak as situational.
MA
What: Your slow MA type and length, plus slope direction (“up”/“down”).
Use: Context even when Trend is FLAT; slope often turns before full trend flips.
Session
What: Current market session by Eastern Time: New York / London / Asia, Pre- windows, Overlap, or Off-hours.
Logic: If ≥2 main sessions are active, shows Overlap (and grays the top title background).
Use: Timing and expectations for liquidity/volatility; also drives session-based confirmation presets if enabled.
VIX
What: Real-time CBOE:VIX on your chosen TF.
Auto-color (if on):
Calm (< Calm) → Green
Watch (< Watch) → Yellow
Elevated (< Elevated) → Orange
Very High (≥ Elevated) → Red
Use: Equity market–wide risk mood; higher = bigger moves, lower = quieter.
VXN
What: CBOE:VXN (Nasdaq volatility index) on your chosen TF.
Auto-color thresholds like VIX.
Use: Tech-heavy risk mood; helpful for growth/QQQ/NDX names.
Footer (params row, bottom-right)
What: Key live settings so you always know the context:
P= Trend Confirmation Bars
O= OBV Confirmation Bars
Strict/Lenient (trend mode)
MACD preset (or “Custom”)
swap if MA lengths were auto-swapped for validity
Regime gate if enabled
Candles for clarity
Use: Quick integrity check when comparing charts/screenshots or changing presets.
Recommended workflow
Start at Flux Score & Summary → snapshot of alignment.
Check Trend (color) and MACD (Bull/Bear).
Look at Signal (Strong vs Weak, and age).
Glance at Regime (and use gate if you’re trend-following).
Use Session + VIX/VXN to adjust expectations (breakout vs mean-revert, risk sizing, patience).
Keep Confirm on Close ON when you want stability; turn it OFF for faster (but noisier) reads.
Notes & limitations
Not advice: This is an informational tool; always combine with your own risk rules.
Repaint vs responsiveness: With “Confirm on Close” OFF you’ll see faster state changes but may get more churn intrabar.
Presets matter: Scalp MACD reacts fastest; Slow reduces whipsaw. Choose for your timeframe.
Session windows depend on the strings you set; adjust if your broker’s feed or DST handling needs tweaks.
Synthetic Point & Figure on RSIHere is a detailed description and user guide for the Synthetic Point & Figure RSI indicator, including how to use it for long and short trade considerations:
*
## Synthetic Point & Figure RSI Indicator – User Guide
### What It Is
This indicator applies classic Point & Figure (P&F) charting logic to the Relative Strength Index (RSI) instead of price. It transforms the RSI into synthetic “P&F candles” that filter out noise and highlight significant momentum moves and reversals based on configurable box size and reversal settings.
### How It Works
- The RSI is calculated normally over the selected length.
- The P&F engine tracks movements in the RSI above or below a defined “box size,” creating columns that switch direction only after a larger reversal.
- The synthetic candles connect these filtered RSI values visually, reducing false noise and emphasizing strong RSI trends.
- Optional EMA and SMA overlays on the synthetic P&F RSI allow smoother trend signals.
- Reference RSI levels at 33, 40, 50, 60, and 66 provide further context for momentum strength.
### How to Use for Trading
#### Long (Buy) Considerations
- The synthetic P&F RSI candle direction flips to *up (green candles)* indicating strength in momentum.
- Look for the RSI P&F value moving above the *40 or 50 level*, suggesting increasing bullish momentum.
- Confirmation is stronger if the synthetic RSI is above the EMA or SMA overlays.
- Ideal entries are after a reversal from a synthetic P&F downtrend (red candles) to an uptrend (green candles) near or above these levels.
#### Short (Sell) Considerations
- The candle direction flips to *down (red candles)*, showing weakening momentum or bearish reversal.
- Monitor if the synthetic RSI falls below the *60 or 50 level*, signaling momentum loss.
- Confirm bearish bias if the price is below the EMA or SMA overlays.
- Exit or short positions are signaled when the synthetic candle reverses from green to red near or below these threshold levels.
### Important RSI Levels to Watch
- *Level 33*: Lower bound indicating deep oversold conditions.
- *Level 40*: Early bullish zone suggesting momentum improvement.
- *Level 50*: Neutral midpoint; crossing above often signals bullish strength, below signals weakness.
- *Level 60*: Advanced bullish momentum; breaking below signals potential reversal.
- *Level 66*: Strong overbought area warning of possible pullback.
### Tips
- Use in conjunction with price action analysis and other volume/trend indicators for higher conviction.
- Adjust box size and reversal settings based on instrument volatility and timeframe for ideal filtering.
- The P&F RSI is best for identifying sustained momentum trends and avoiding false RSI whipsaws.
- Combine this indicator’s signals with stop-loss and risk management strategies.
*
This indicator converts RSI momentum analysis into a simplified, noise-filtered P&F chart format, helping traders better visualize and trade momentum shifts. It is especially useful when RSI signal noise can cause confusion in volatile markets.
Let me know if you want me to generate a shorter summary or code alerts based on these levels!
Sources
Relative Strength Index (RSI) — Indicators and Strategies in.tradingview.com
Indicators and strategies in.tradingview.com
Relative Strength Index (RSI) Indicator: Tutorial www.youtube.com
Stochastic RSI (STOCH RSI) in.tradingview.com
RSI Strategy docs.algotest.in
Stochastic RSI Indicator: Tutorial www.youtube.com
Relative Strength Index (RSI): What It Is, How It Works, and ... www.investopedia.com
rsi — Indicators and Strategies in.tradingview.com
Relative Strength Index (RSI) in.tradingview.com
Relative Strength Index (RSI) — Indicators and Strategies www.tradingview.com
Bar Statistics - DELTA/OI/TOTAL/BUY/SELL/LONGS/SHORTSBar Statistics - Advanced Volume & Open Interest Analysis
Overview
The Bar Statistics indicator is a comprehensive analytical tool designed to provide traders with detailed insights into market microstructure through advanced volume analysis, open interest tracking, and market flow detection. This indicator transforms complex market data into easily digestible visual information, displaying six key metrics in customizable colored boxes that update in real-time.
Unlike traditional volume indicators that only show basic volume data, this indicator combines multiple data sources to reveal the underlying forces driving price movement, including volume delta calculations from lower timeframes, open interest changes, and estimated market positioning.
What Makes This Indicator Unique
1. Multi-Timeframe Volume Delta Precision
The indicator utilizes lower timeframe data (default 1-second) to calculate highly accurate volume delta measurements, providing much more precise buy/sell pressure analysis than standard timeframe-based calculations. This approach captures intraday volume dynamics that are often missed by conventional indicators.
2. Real-Time Updates
Unlike many indicators that only update on bar completion, this tool provides live updates for the developing candle, allowing traders to see evolving market conditions as they happen.
3. Market Flow Analysis
The unique "L/S" (Long/Short) metric combines open interest changes with price/volume direction to estimate net market positioning, helping identify when participants are accumulating or distributing positions.
4. Adaptive Visual Intensity
The gradient color system automatically adjusts based on historical context, making it easy to identify when current values are significant relative to recent market activity.
5. Complete Customization
Every aspect of the display can be customized, from the order of metrics to individual color schemes, allowing traders to adapt the tool to their specific analysis needs.
6.All In One Solution
6 Metrics in one indicator no more using 5 different indicators.
Core Features Explained
DELTA (Volume Delta)
What it shows: Net difference between aggressive buy volume and aggressive sell volume
Calculation: Uses lower timeframe data to determine whether each trade was initiated by buyers or sellers
Interpretation:
Positive values indicate aggressive buying pressure
Negative values indicate aggressive selling pressure
Magnitude indicates the strength of directional pressure
OI Δ (Open Interest Change)
What it shows: Change in open interest from the previous bar
Data source: Fetches open interest data using the "_OI" symbol suffix
Interpretation:
Positive values indicate new positions entering the market
Negative values indicate positions being closed
Combined with price direction, reveals market participant behavior
L/S (Net Long/Short Bias)
What it shows: Estimated net change in long vs short market positions
Calculation method: Combines open interest changes with price/volume direction using configurable logic
Scenarios analyzed:
New Longs: Rising OI + Rising Price/Volume = Long position accumulation
Liquidated Longs: Falling OI + Falling Price/Volume = Long position exits
New Shorts: Rising OI + Falling Price/Volume = Short position accumulation
Covered Shorts: Falling OI + Rising Price/Volume = Short position exits
Result: Net bias toward long (positive) or short (negative) market sentiment
TOTAL (Total Volume)
What it shows: Standard volume for the current bar
Purpose: Provides context for other metrics and baseline activity measurement
Enhanced display: Uses gradient intensity based on recent volume history
BUY (Estimated Buy Volume)
What it shows: Estimated aggressive buy volume
Calculation: (Total Volume + Delta) / 2
Use case: Helps quantify the actual buying pressure in monetary/contract terms
SELL (Estimated Sell Volume)
What it shows: Estimated aggressive sell volume
Calculation: (Total Volume - Delta) / 2
Use case: Helps quantify the actual selling pressure in monetary/contract terms
Configuration Options
Timeframe Settings
Custom Timeframe Toggle: Enable/disable custom lower timeframe selection
Timeframe Selection: Choose the precision level for volume delta calculations
Auto-Selection Logic: Automatically selects optimal timeframe based on chart timeframe
Net Positions Calculation
Direction Method: Choose between Price-based or Volume Delta-based direction determination
Value Method: Select between Open Interest Change or Volume for position size calculations
Display Customization
Row Order: Completely customize which metrics appear and in what order (6 positions available)
Color Schemes: Individual color selection for positive/negative values of each metric
Gradient Intensity: Configurable lookback period (10-200 bars) for relative intensity calculations
Visual Elements
Box Format: Clean, professional box display with clear labels
Color Coding: Intuitive color schemes with customizable transparency gradients
Real-time Updates: Live updating for developing candles with historical stability
How to Use This Indicator
For Day Traders
Volume Confirmation: Use DELTA to confirm breakout validity - strong directional moves should show corresponding volume delta
Entry Timing: Watch for volume delta divergences at key levels to time entries
Exit Signals: Monitor when aggressive volume shifts against your position
For Swing Traders
Market Flow: Focus on the L/S metric to identify when participants are accumulating or distributing
Open Interest Analysis: Use OI Δ to confirm whether moves are backed by new money or position adjustments
Trend Validation: Combine multiple metrics to validate trend strength and sustainability
For Scalpers
Real-time Edge: Utilize the live updates to see developing imbalances before bar completion
Quick Decision Making: Focus on DELTA and BUY/SELL for immediate market pressure assessment
Volume Profile: Use TOTAL volume context for optimal entry/exit sizing
Setup Recommendations
Futures Markets: Enable OI tracking and use Volume Delta direction method
Crypto Markets: Focus on DELTA and volume metrics; OI may not be available
Stock Markets: Use Price direction method with volume value calculations
High-Frequency Analysis: Set lower timeframe to 1S for maximum precision
Technical Implementation
Data Accuracy
Utilizes TradingView's ta.requestVolumeDelta() function for precise buy/sell classification
Implements error checking for data availability
Handles missing data gracefully with fallback calculations
Performance Optimization
Efficient array management with configurable lookback periods
Smart box creation and deletion to prevent memory issues
Optimized real-time updates without historical data corruption
Compatibility
Works on all timeframes from seconds to daily
Compatible with futures, forex, crypto, and stock markets
Automatically adjusts calculation methods based on available data
Risk Disclaimers
This indicator is designed for educational and analytical purposes. It provides statistical analysis of market data but does not guarantee trading success. Users should:
Combine with other forms of analysis
Practice proper risk management
Understand that past performance doesn't predict future results
Be aware that volume delta and open interest data quality varies by market and data provider
Conclusion
The Bar Statistics indicator represents a significant advancement in retail trader access to professional-grade market analysis tools. By combining multiple data sources into a single, customizable display, it provides the depth of analysis needed for comprehensive market microstructure understanding while maintaining the simplicity required for effective decision-making.