Ultimate VWAP Bands- Ultimate VWAP Bands is a script that helps to decide and further clarify areas of oversold and overbought conditions.
- For example, when the price is in the lowest band it is extremely oversold relative to the VWAP . Hence it should be considered a good place to buy with a high risk to reward payoff.
- Each band is set at a fixed offset away from the VWAP . The "VWAP Band Multiplier" adjusts this and is a key part of the script. This allows the indicator to be adjusted based on the assets volatility . For example, with Crypto. A multiplier of 1 would be strongly advised. Whilst a multiplier of 0.1-0.25 would be useful for currency pairs.
- This indicator can be used for all manners of trading. However, it is most effective when used for scalping and swing trading.
Cari dalam skrip untuk "swing trading"
L1 Mid-Term Swing Oscillator v1Level: 1
Background
Oscillators are widely used set of technical analysis indicators. They are popular primarily for their ability to alert of a possible trend change before that change manifests itself in price and volume . They should work best in times of sideways markets.
Function
L1 Short-Mid-Long-Term Swing Oscillator puts three terms of oscillators to cover short-term, middle-term and long-term oscillators at the same time. By resonating all these three oscillators, short-term scalping signal and middle term swing signal are disclosed. You can see both short and mid term signal under one indicator which give you more confidence to follow the trend.
Key Signal
I didn't handle the key signals well. I piled up all the useful signals I found, and it is really difficult to classify them one by one. I feel tired when I think about this problem. Therefore, the code of the overall signal is rather confusing, sorry.
Pros and Cons
Pros:
1. Three oscillators are used to cover short, mid, long term oscillations.
2. Short-Mid term resonance can be observed to have higher confidence level.
3. Use single indicator for scalping and swing trading is possible.
Cons:
1. No deep dive into very accurate long and short entries.
2. A trade off between sensitivity and stability may be needed by traders' subjective judge.
Remarks
I enjoyed the fun of put three different oscillator together to cover short, mid, long terms. But how to use them perfectly is really more brainstorming.
Readme
In real life, I am a prolific inventor. I have successfully applied for more than 60 international and regional patents in the past 12 years. But in the past two years or so, I have tried to transfer my creativity to the development of trading strategies. Tradingview is the ideal platform for me. I am selecting and contributing some of the hundreds of scripts to publish in Tradingview community. Welcome everyone to interact with me to discuss these interesting pine scripts.
The scripts posted are categorized into 5 levels according to my efforts or manhours put into these works.
Level 1 : interesting script snippets or distinctive improvement from classic indicators or strategy. Level 1 scripts can usually appear in more complex indicators as a function module or element.
Level 2 : composite indicator/strategy. By selecting or combining several independent or dependent functions or sub indicators in proper way, the composite script exhibits a resonance phenomenon which can filter out noise or fake trading signal to enhance trading confidence level.
Level 3 : comprehensive indicator/strategy. They are simple trading systems based on my strategies. They are commonly containing several or all of entry signal, close signal, stop loss, take profit, re-entry, risk management, and position sizing techniques. Even some interesting fundamental and mass psychological aspects are incorporated.
Level 4 : script snippets or functions that do not disclose source code. Interesting element that can reveal market laws and work as raw material for indicators and strategies. If you find Level 1~2 scripts are helpful, Level 4 is a private version that took me far more efforts to develop.
Level 5 : indicator/strategy that do not disclose source code. private version of Level 3 script with my accumulated script processing skills or a large number of custom functions. I had a private function library built in past two years. Level 5 scripts use many of them to achieve private trading strategy.
Why is it ok to backtest on TradingView from now on!TradingView backtester has bad reputation. For a good reason - it was producing wrong results, and it was clear at first sight how bad they were.
But this has changed. Along with many other improvements in its PineScript coding capabilities, TradingView fixed important bug, which was the main reason for miscalculations. TradingView didn't really speak out about this fix, so let me try :)
Have a look at this short code of a swing trading strategy (PLEASE DON'T FOCUS ON BACKTEST RESULTS ATTACHED HERE - THEY DO NOT MATTER). Sometimes entry condition happens together with closing condition for the already ongoing trade. Example: the condition to close Long entry is the same as a condition to enter Short. And when these two aligned, not only a Long was closed and Short was entered (as intended), but also a second Short was entered, too!!! What's even worse, that second short was not controlled with closing conditions inside strategy.exit() function and it very often lead to losses exceeding whatever was declared in "loss=" parameter. This could not have worked well...
But HOORAY!!! - it has been fixed and won't happen anymore. So together with other improvements - TradingView's backtester and PineScript is now ok to work with on standard candlesticks :)
Yep, no need to code strategies and backtest them on other platforms anymore.
----------------
Having said the above, there are still some pitfalls remaining, which you need to be aware of and avoid:
Don't backtest on HeikenAshi, Renko, Kagi candlesticks. They were not invented with backtesting in mind. There are still using wrong price levels for entries and therefore producing always too good backtesting results. Only standard candlesticks are reliable to backtest on.
Don't use Trailing Stop in your code. TradingView operates only on closed candlesticks, not on tick data and because of that, backtester will always assume price has first reached its favourable extreme (so 'high' when you are in Long trade and 'low' when you are in Short trade) before it starts to pull back. Which is rarely the truth in reality. Therefore strategies using Trailing Stop are also producing too good backtesting results. It is especially well visible on higher timeframe strategies - for some reason your strategy manages to make gains on those huge, fat candlesticks :) But that's not reality.
"when=" inside strategy.exit() does not work as you would intuitively expect. If you want to have logical condition to close your trade (for example - crossover(rsi(close,14),20)) you need to place it inside strategy.close() function. And leave StopLoss + TakeProfit conditions inside strategy.exit() function. Just as in attached code.
If you're working with pyramiding, add "process_orders_on_close=ANY" to your strategy() script header. Default setting ("=FIFO") will first close the trade, which was opened first, not the one which was hit by Stop-Loss condidtion.
----------------
That's it, I guess :) If you are noticing other issues with backtester and would like to share, let everyone know in comments. If the issue is indeed a bug, there is a chance TradingView dev team will hear your voice and take it into account when working on other improvements. Just like they heard about the bug I described above.
P.S. I know for a fact that more improvements in the backtesting area are coming. Some will change the game even for non-coding traders. If you want to be notified quickly and with my comment - gimme "follow".
Investing - Weekly EMA's mapped to Daily ChartWhen there isn't enough time in your day to day-trade, yet you want to utilise all the technical analysis skills you have... why not make a long term investing or swing trading indicator set to help you along the way!
So I did....
When it comes to long term investing and swing trading, I often find the weekly 12/26/52 EMA's do a great job in capturing the main market swings from bull to bear.
However, I like to use the Daily chart to see the candle patterns and shapes with more detail and divergences often show up better on the daily chart.
So I have decided to combine the two!
I have basically taken the EMA 12/26/52 from the weekly and transferred them over to the daily (mathematically they are not exact, but for me they are close enough).
I have also developed a simple scale in / scale out strategy for using these exponential moving averages. It isn't as simple as buying in on each signal, however I use my own special strategy to take advantage of the alerts.
Enjoy!
Complete Trend Trading System [Fhenry0331]This system was designed for the beginner trader to make money swing trading. Your losses will be small and your gains will be mostly large. You will show consistent profit. Period.
The system works on any security you like to trade. I used GBPUSD as an example because of the up swing and down swing it had recently. I tried to put as much information of how the system works in the chart. Hope it helps and is not to cluttered.
I will reiterate how the system works here: Everything is based off of closed price.
Legend
Uptrend: Buy
Green bar: initial start of an uptrend or uptrend continuing. Place order above that bar. If the initial bar does not stray too far from the MVWAP , I will place orders above subsequent bars if no filled occurred.
If initial start of the trend is missed, I will wait for the pullback. A pullback is a close below the MVWAP, and a close above the EMA (Low), RSI is above 50. Orders are placed above the pullback bars with plotted char "B" and also plotted green triangle up. Again orders are placed above those bars. the bars do not notate automatic buys. Don't chase anything. You will miss the initial bar on something because of news or earnings and it rocket up. Just wait, it will pullback. If it doesn't, to hell with it, on to the next.
Take profits: In the indicator you will see "T." That notates to take some profits. It is a suggestion. I was always told to take profits into spikes, as well as you can never lose money if you take profits. Up to you if you want to scale out and take the suggested profits or not.
Exit Completely: In an uptrend, close your entire position on bars colored yellow or red. (Again, closed bars)
In uptrend bars colored orange and black, do nothing, they are just pullback bars. Look for the buy pullback signal, then follow pullback buy rules for an uptrend.
Downtrend: Short
Red bar: initial start of a downtrend or downtrend continuing. Place order below the bar. If the initial bar does not stray too far fro the MVWAP, place orders below subsequent bars.
If initial start on the downtrend is missed, wait for the pullback. A pullback is a close above the MVWAP, and close below the EMA(Low). RSI is below 50. Orders are placed below the pullback bars with the plotted char "S" and also plotted red triangle. Again those bars are not automatic shorts, orders are placed below them. Don't chase anything. Wait for price to come into your plan. The idea FOMO is the stupidest thing ever, how can you miss out on something when it is always there. The market is always there and something will come into your zone. Chill.
"T": same as in uptrend, suggestion to take some profits.
Exit Completely: In a downtrend, close your entire position on bars colored orange or green.
In downtrend you will see bars colored yellow and black, do nothing, they are pullback bars. Look for the pullback short signal and follow pullback short rules.
If you have any questions get at me. Take a look at it on what you trade. Flip it through different securities.
Best of luck in all you do.
P.S. You should not take a trade right before earnings. You should also exit a trade right before earnings.
Binque's Multi-Moving Average Binque's Multi-Moving Average - One indicator with four simple moving average and four exponential moving averages, plus as a bonus a Day High moving average and a Day Low Moving Average.
Simple Moving Average or MA(14), MA(50), MA(100) and MA(200) all in one indicator
Exponential Moving Average or EMA(8), EMA(14), EMA(20) and EMA(33) all in one indicator
Day High Moving Average - Tracks the Daily High versus most moving averages track the daily close.
Day Low Moving Average - Tracks the Daily Low versus most moving average track the daily close.
To Disable moving averages, Set the color to the chart background and then set the length to 1 and uncheck.
I Use the Daily High Moving Average to track upward resistance in a stock movement for Swing Trading.
I Use the Daily Low Moving Average to track my trailing stop in a stock movement for Swing Trading.
Big Snapper Alerts R2.0 by JustUncleLThis is a diversified Binary Option or Scalping Alert indicator originally designed for lower Time Frame Trend or Swing trading. Although you will find it a useful tool for higher time frames as well.
The Alerts are generated by the changing direction of the ColouredMA (HullMA by default), you then have the choice of selecting the Directional filtering on these signals or a Bollinger swing reversal filter.
The filters include:
Type 1 - The three MAs (EMAs 21,55,89 by default) in various combinations or by themselves. When only one directional MA selected then direction filter is given by ColouredMA above(up)/below(down) selected MA. If more than one MA selected the direction is given by MAs being in correct order for trend direction.
Type 2 - The SuperTrend direction is used to filter ColouredMA signals.
Type 3 - Bollinger Band Outside In is used to filter ColouredMA for swing reversals.
Type 4 - No directional filtering, all signals from the ColouredMA are shown.
Notes:
Each Type can be combined with another type to form more complex filtration.
Alerts can also be disabled completely if you just want one indicator with one colouredMA and/or 3xMAs and/or Bollinger Bands and/or SuperTrend painted on the chart.
Warning:
Be aware that combining Bollinger OutsideIn swing filter and a directional filter can be counter productive as they are opposites. So careful consideration is needed when combining Bollinger OutsideIn with any of the directional filters.
Hints:
For Binary Options try ColouredMA = HullMA(13) or HullMA(8) with Type 2 or 3 Filter.
When using Trend filters SuperTrend and/or 3xMA Trend, you will find if price reverses and breaks back through the Big Fat Signal line, then this can be a good reversal trade.
Some explanation about the what Hull Moving average and ideas of how the generated in Big Snapper can be used:
tradingsim.com
forextradingstrategies4u.com
Inspiration from @vdubus
Big Snapper's Bollinger OutsideIn Swing filter in Action:
Colored Volume Bars [LazyBear]Edgar Kraut proposed this simple colored volume bars strategy for swing trading.
This is how the colors are determined:
- If today’s closing price and volume are greater than 'n' days ago, color today’s volume bar green.
- If today’s closing price is greater than 'n' days ago but volume is not, color today’s volume bar blue.
- Similarly, if today’s closing price and volume is less than 'n' days ago, color today’s volume bar orange.
- If today’s closing price is less than 'n' days ago but volume is not, color today’s volume bar red.
Buy the green or blue volume bars, use a 1% trailing stop, and stand aside on red or orange bars.
As you see, this is more for entry confirmation. I have not tested this on any instrument.
You may have to tune the lookback period for your instrument. Default is 10.
More info:
"A color-based system for short-term trading" - www.traders.com
List of all my indicators:
PumpC PAC & MAsPumpC – PAC & MAs (Open Source)
A complete Price Action Candles (PAC) toolkit combining classical price action patterns (Fair Value Gaps, Inside Bars, Hammers, Inverted Hammers, and Volume Imbalances) with a flexible Moving Averages (MAs) module and an advanced bar-coloring system.
This script highlights supply/demand inefficiencies and micro-patterns with forward-extending boxes, recolors zones when mitigated, qualifies patterns with a global High-Volume filter, and ships with ready-to-use alerts. It works across intraday through swing trading on any market (e.g., NASDAQ:QQQ , $CME:ES1!, FX:EURUSD , BITSTAMP:BTCUSD ).
This is an open-source script. The description is detailed so users understand what the script does, how it works, and how to use it. It makes no performance claims and does not provide trade advice.
Acknowledgment & Credits
This script originates from the structural and box-handling logic found in the Super OrderBlock / FVG / BoS Tools by makuchaku & eFe. Their pioneering framework provided the base methods for managing arrays of boxes, extending zones forward, and recoloring once mitigated.
Building on that foundation, I have substantially expanded and adapted the code to create a unified Price Action Candles toolkit . This includes Al Brooks–inspired PAC logic, additional patterns like Inside Bars, Hammers, Inverted Hammers, and the new Volume Imbalance module, along with strong-bar coloring, close-threshold detection, a flexible global High-Volume filter, and a multi-timeframe Moving Averages system.
What it does
Fair Value Gaps (FVG) : Detects 3-bar displacement gaps, plots forward-extending boxes, and optionally recolors them once mitigated.
Inside Bars (IB) : Highlights bars fully contained within the prior candle’s range, with optional high-volume filter.
Hammers (H) & Inverted Hammers (IH) : Identifies rejection candles using configurable body/upper/lower wick thresholds. High-volume qualification optional.
Volume Imbalances (VI) : Detects inter-body gaps where one candle’s body does not overlap the prior candle’s body. Boxes extend forward until wick-based mitigation occurs (only after the two-bar formation completes). Alerts available for creation and mitigation.
Mitigation Recolor : Each pattern can flip to a mitigated color once price trades back through its vertical zone.
Moving Averages (MAs) : Four configurable EMAs/SMAs, with per-MA timeframe, length, color, and clutter-free plotting rules.
Strong Bar Coloring : Highlights bullish/bearish engulfing reversals with different colors for high-volume vs low-volume cases.
Close Threshold Bars : Marks candles that close in the top or bottom portion of their range, even if the body is small. Helps spot continuation pressure before a full trend bar forms.
Alerts : Notifications available for FVG+, FVG−, IB, H, IH, VI creation, and VI mitigation.
Connection to Al Brooks’ PAC teachings
This script reflects Al Brooks’ Price Action Candle methodology. PAC patterns like Inside Bars, Hammers, and Inverted Hammers are not trade signals on their own—they gain meaning in context of trend, failed breakouts, and effort vs. result.
By layering in volume imbalances, strong-bar reversals, and volume filters, this script focuses attention on the PACs that show true participation and conviction, aligning with Brooks’ emphasis on reading crowd psychology through price action.
Why the High-Volume filter matters
Volume is a key proxy for conviction. A PAC or VI formed on light volume can be misleading noise; one formed on above-average volume carries more weight.
Elevates Inside Bars that show absorption/compression with heavy activity.
Distinguishes Hammers that reject price aggressively vs. weak drifts.
Filters Inverted Hammers to emphasize true supply pressure.
Highlights VI zones where institutional order flow left inefficiencies.
Differentiates strong engulfing reversals from weaker, low-participation moves.
Inputs & Customization
Inputs are grouped logically for fast configuration:
High-Volume Filter : Global lookback & multiple, per-pattern toggles.
FVG : Visibility, mitigated recolor, box style/transparency, label controls.
IB : Visibility, require high volume, mitigated recolor, colors, label settings.
Hammer / IH : Visibility, require high volume, mitigated recolor, wick/body thresholds.
VI : Visibility, require high volume, mitigated recolor, box style, labels, mitigation alerts.
Strong Bars : Enable/disable, separate colors for high-volume and low-volume outcomes.
Close Threshold Bars : Customizable close thresholds, labels, optional count markers.
MAs : EMA/SMA type, per-MA toggle, length, timeframe, color.
Alerts
New Bullish FVG (+)
New Bearish FVG (−)
New Inside Bar (IB)
New Hammer (H)
New Inverted Hammer (IH)
New Volume Imbalance (VI)
VI Mitigated
Strong Bullish Engulfing / Bearish Engulfing (high- and low-volume variants)
Suggested workflow
Choose your market & timeframe (script works across equities, futures, FX, crypto).
Toggle only the PACs you actually trade. Assign distinct colors for clarity.
Use MAs for directional bias and higher timeframe structure.
Enable High-Volume filters when you want to emphasize conviction.
Watch mitigation recolors to see which levels/zones have been interacted with.
Use alerts selectively for setups aligned with your plan.
Originality
Builds upon Super OrderBlock / FVG / BoS Tools (makuchaku & eFe) for FVG/box framework.
Expanded into a unified PAC toolkit including IB, H, IH, and VI patterns.
Brooks-inspired design: Patterns contextualized with volume and trend, not isolated.
Flexible high-volume gating with per-pattern toggles.
New VI integration with wick-based mitigation.
Strong Bar Coloring differentiates conviction vs weak reversals.
MTF-aware MAs prevent clutter while providing structure.
Open-source: Transparent for learning, editing, and extension.
Disclaimer
For educational and informational purposes only. This script is not financial advice. Trading carries risk—always test thoroughly before live use.
LogPressure Envelope [BOSWaves]LogPressure Envelope – Adaptive Volatility & Trend Visualizer
Overview
LogPressure Envelope is a specialized trading tool designed to normalize market behavior using logarithmic price scaling while providing an adaptive framework for volatility and trend detection. The indicator calculates a log-based moving average midline, surrounds it with asymmetric volatility envelopes, and replaces the conventional cloud with progressive fan lines to present price action in a more interpretable form.
By integrating rate-of-change midline coloring, fading trend strength, and structured buy/sell markers, LogPressure Envelope simplifies the reading of complex market dynamics. Its design makes it suitable for multiple trading approaches, including scalping, intraday, and swing trading, where volatility behavior and trend shifts must be understood quickly and objectively.
Unlike static envelope indicators, LogPressure Envelope adapts continuously to price scale and volatility conditions. It evaluates log-transformed prices, applies configurable moving average methods (EMA, SMA, WMA), and derives asymmetric standard-deviation bands for both upside and downside moves. These envelopes are projected as fan lines with adjustable opacity, producing a layered volatility map that evolves with the market.
This system ensures each visual element—midline shading, candle coloring, fan structure, and signal markers—reflects real-time market conditions, allowing traders to interpret volatility expansion, contraction, and directional bias with clarity.
How It Works
The foundation of LogPressure Envelope is the logarithmic transformation of price. By operating in log space, the indicator removes distortions caused by large nominal price differences across assets, enabling consistent analysis of both low-priced and high-priced instruments.
A moving average of log prices is calculated (EMA, SMA, or WMA depending on user input) and then re-converted to normal price scale, forming the log midline. Standard deviation of log prices is then measured over a separate period, with independent multipliers for upside and downside deviations. This asymmetry captures the fact that markets often expand differently in bullish versus bearish phases.
Instead of plotting a filled cloud, the envelope is expressed as ten equidistant fan lines stretching from the lower to upper boundary. Each line is shaded progressively to visualize volatility clustering and directional strength without overloading the chart.
Trend determination is smoothed using a fade mechanism: shifts in bias do not flip instantly but gradually move toward the new state, producing fewer false transitions. Buy and sell markers are generated when trend strength crosses confirmation thresholds, ensuring signals are event-driven and contextually meaningful.
Signals and Visuals
LogPressure Envelope provides multiple layers of structured signals:
Midline Bias – Central moving average colored by rate-of-change, reflecting directional acceleration or deceleration.
Volatility Fan – Ten progressive lines forming a gradient between lower and upper bands, visually encoding volatility spread.
Buy Signals – Labels below bars when upward trend strength is confirmed.
Sell Signals – Labels above bars when downward trend strength is confirmed.
Candle Coloring – Optional shading of candles based on trend alignment with the log midline, highlighting bullish, bearish, or neutral conditions.
These signals remain clear even during high-volatility phases, with visual hierarchy maintained through progressive opacity control.
Interpretation
Trend Analysis : Midline direction and candle coloring provide continuous feedback on prevailing bias. Upward-sloping midlines with blue shading indicate bullish phases, while downward slopes with orange shading confirm bearish conditions.
Volatility and Risk Assessment : Expansion of fan lines indicates rising volatility and potential breakout conditions; contraction indicates consolidation and possible mean reversion.
Signal Confirmation : Buy and sell markers validate transitions when trend strength thresholds are crossed, aligning with volatility envelope dynamics.
Market Context : Asymmetric envelopes allow traders to see where bearish acceleration differs from bullish expansion, improving interpretation of liquidity conditions and institutional pressure.
Strategy Integration
LogPressure Envelope can be applied across trading styles:
Trend Following : Enter trades in the direction of midline bias, confirmed by buy or sell markers.
Pullback Entries : Use midline retests during trending conditions as lower-risk continuation points.
Volatility Breakouts : Identify sharp expansions in fan line spacing as early signals of directional moves.
Reversal Strategies : Fade extreme envelope touches when momentum shows exhaustion and fan contraction begins.
Multi-Timeframe Confirmation : Align signals from higher and lower timeframes to reduce noise and validate trade setups.
Stop-loss levels can be set near the opposite envelope boundary, while targets may be managed through progressive volatility zones or midline convergence.
Advanced Techniques
For greater precision, LogPressure Envelope can be combined with other analytical tools:
Pair with volume or liquidity measures to validate breakout or reversal conditions.
Use momentum indicators to confirm ROC-based midline bias.
Track sequences of fan line expansions and contractions to anticipate regime shifts in volatility.
Apply across multiple timeframes to monitor how volatility clusters align at different market scales.
Adjusting parameters such as envelope multipliers, moving average type, and fade bars allows the indicator to adapt to diverse asset classes and volatility environments.
Inputs and Customization
Midline Type : Select EMA, SMA, or WMA.
Line Opacity : Control visibility of fan lines.
Enable Candle Coloring : Toggle trend-based bar shading.
MA Length / StdDev Length : Define periods for midline and volatility calculation.
Multipliers : Set asymmetric scaling for upside and downside envelopes.
Fade Bars : Control smoothness of trend strength transitions.
Fan Lines : Adjust number of envelope subdivisions for visualization granularity.
Why Use LogPressure Envelope
LogPressure Envelope translates complex volatility and trend interactions into a structured and adaptive framework. By combining logarithmic normalization, asymmetric standard deviation envelopes, and smoothed trend confirmation, it allows traders to:
Normalize price analysis across assets of different scales.
Visualize volatility expansion and contraction in real time.
Identify and confirm directional shifts with objective signal markers.
Apply a disciplined system for trend, breakout, and reversal strategies.
This indicator is designed for traders who want a systematic, visually clear approach to volatility-based market analysis without relying on static bands or arbitrary scaling.
Colored Trix with spike detectionColored TRIX with Spike Detection
This indicator combines multiple TRIX oscillators (periods 5, 7, 10, 14) with advanced spike detection capabilities. Key features:
Dynamic Color Coding: TRIX lines change color based on value (positive/negative) and slope direction, providing instant visual feedback on momentum shifts
Multi-Period Analysis: Four different TRIX periods offer comprehensive momentum analysis across various timeframes
Intelligent Spike Detection: Automatically identifies significant TRIX spikes using percentile-based thresholds and distance measurements from recent highs/lows
Visual Markers: Highlights important levels with yellow dots and reference lines showing lowest, median, and average TRIX values during spike periods
Customizable Parameters: Adjustable spike thresholds, distance percentiles, and color schemes to fit your trading style
Alert System: Built-in alerts for positive and negative spike detection
The indicator helps traders identify momentum changes, oversold/overbought conditions, and potential reversal points through sophisticated spike analysis. Perfect for swing trading and trend following strategies.
DAILY LOW POSITION SIZEDAILY LOW POSITION CALCULATOR, for swing trading.
Tells you exactly how much stocks to buy when stop loss is at low of day.
DBG X WOLONG📊 USER GUIDE – DBG X WOLONG ALGORITHM
🎯 OVERVIEW
The DBG X WOLONG Future Algorithm is a Pine Script v5 that integrates multiple advanced technical indicators, enabling traders to analyze markets and make precise trading decisions.
⚙️ MAIN SETTINGS
🔹 Sensitivity
Value: 1–20 (Default: 6)
Function: Adjusts the sensitivity of the SuperTrend signal
Guidelines:
Low value (1–5): Fewer signals, higher accuracy
High value (15–20): More signals, but with possible noise
🎨 DISPLAY SETTINGS
🔹 Candle Colors
Version 1: Based on MACD histogram
Version 2: Based on SuperTrend
🔹 Color Themes
Theme 1: Traditional Green/Red
Theme 2: Gold/Purple
Theme 3: Blue/Orange
No Fill: No background color displayed
📊 TRADING SIGNALS
🔹 Buy/Sell Signals
BUY 🚀 appears when:
SuperTrend shifts from bearish to bullish
Closing price > SMA 13
Braid Filter confirms
SELL appears when:
SuperTrend shifts from bullish to bearish
Closing price < SMA 13
Braid Filter confirms
🔹 Reversal Signals
▲ (Up Arrow): Buy signal when RSI crosses above 30
▼ (Down Arrow): Sell signal when RSI crosses below 70
🔹 Pullback Signals
▲ Purple: Pullback in bullish trend
▼ Purple: Pullback in bearish trend
🎯 TAKE PROFIT & STOP LOSS
🔹 TP Modes
Version 1: TP based on pivot points
Version 2: TP based on regression line
Close Price: TP at candle close
🔹 TP/SL Settings
TP Ratio: 2.0 (Default)
TP Length: 150 (Default)
ATR SL Length: 10
ATR SL Risk: 1.9
🔹 Labels Displayed
ENTRY: Entry point
STOP LOSS: Stop loss point
TP 1/2/3: 3 take profit levels
☁️ MOVING AVERAGE CLOUD
🔹 Supported MA Types
SMA – Simple Moving Average
EMA – Exponential Moving Average
WMA – Weighted Moving Average
HMA – Hull Moving Average
ALMA – Arnaud Legoux Moving Average
McGinley – McGinley Dynamic
FRAMA – Fractal Adaptive Moving Average
🔹 Cloud Cycles
Default: 2, 6, 11, 18, 21, 24, 28, 34
Customizable: All 8 cycles
🔹 Ribbon Cycles
Default: 6, 13, 20, 28, 36, 45, 55, 444
Customizable: All 8 cycles
🔧 BRAID FILTER
🔹 Function
Filters out noise signals
Confirms strong trends
🔹 Settings
MA Filter: McGinley (Recommended)
Filter Strength: 80% (Default)
📈 TRENDS & INDICATORS
🔹 SuperTrend
Main trend indicator
Generates primary buy/sell signals
🔹 Advanced Ichimoku
Tenkan-Sen: Blue line
Kijun-Sen: Orange line
Senkou Span A/B: Ichimoku cloud
🔹 Trend Tracking
Based on EMA 10 vs EMA 20
Candle colors follow trend direction
🔹 Trend Catcher
Range Filter with multiple options
Adjustable sensitivity
📊 MULTI-TIMEFRAME TREND PANEL
🔹 Displayed Timeframes
1m, 3m, 5m
15m, 30m, 1H
2H, 4H, 8H, Daily
🔹 Displayed Info
Current Position: Bullish/Bearish
Trend: Per timeframe
Volume: Current trading volume
🔹 Panel Positioning
9 selectable positions
Sizes: Large, Normal, Small, Extra Small
🚀 TRADE EXECUTION
📈 LONG ENTRY
✅ Entry Conditions
BUY 🚀 signal appears
SuperTrend turns from red to green
Price > SMA 13
Braid Filter confirms (green)
Trend Panel shows "Bullish" across multiple TFs
📊 Additional Confirmations
MACD Histogram > 0 and rising
RSI crosses above 30 (if reversal signal)
EMA Pullback shows ▲ purple
🎯 Trade Management
Entry: According to ENTRY label
Stop Loss: According to STOP LOSS label
Take Profit: TP1 → TP2 → TP3
📉 SHORT ENTRY
✅ Entry Conditions
SELL signal appears
SuperTrend turns from green to red
Price < SMA 13
Braid Filter confirms (red)
Trend Panel shows "Bearish" across multiple TFs
📊 Additional Confirmations
MACD Histogram < 0 and declining
RSI crosses below 70 (if reversal signal)
EMA Pullback shows ▼ purple
🎯 Trade Management
Entry: According to ENTRY label
Stop Loss: According to STOP LOSS label
Take Profit: TP1 → TP2 → TP3
🎛️ RECOMMENDED SETTINGS
👥 For Beginners
Sensitivity: 6
Candle Colors: Version 1
Buy/Sell Signals: ON
Reversal Signals: OFF
Trend Panel: ON
🏆 For Experienced Traders
Sensitivity: 4–8 (depending on market)
Reversal Signals: ON
Pullback: ON
All indicators: ON
ATR SL Risk: 1.5–2.0
⚡ For Scalping
Sensitivity: 8–12
Timeframes: 1m, 3m, 5m
Use only: SuperTrend + Braid Filter
Quick TP: Only TP1
📊 For Swing Trading
Sensitivity: 4–6
Timeframes: 1H, 4H, 1D
Use all: Full signals
TP: All 3 levels (TP1, TP2, TP3)
⚠️ IMPORTANT NOTES
🔴 Avoid Trading When
Signals conflict across timeframes
Market is strongly ranging/sideways
Abnormally low volume
Price is at major support/resistance zones
🟢 Prefer Trading When
At least 2–3 confirmations align
Clear trend across multiple timeframes
Strong volume surge
Breakout from consolidation zone
💡 Usage Tips
Always wait for confirmation: Never enter with just 1 signal
Risk management: Place SL according to STOP LOSS label
Follow trend panel: Prioritize overall trend
Use multiple timeframes: Analyze top-down
Backtest first: Test strategy on historical data
🛠️ TROUBLESHOOTING
❓ No signals appear
Check if inputs are enabled
Adjust sensitivity
Try switching timeframe
❓ Too many false signals
Lower sensitivity
Increase Braid Filter strength
Trade only with main trend
❓ Trend panel not showing
Enable "Display Dashboard"
Select proper panel position
Adjust panel size
📞 SUPPORT
If you encounter issues using this script, please:
Carefully read this guide
Practice on a demo account
Backtest thoroughly before live trading
📈 Wishing you successful trading! 🚀
[Top] Simple ATR TP/SLSimple TP/SL from ATR (Locked per Bar) - Advanced Position Management Tool
What This Indicator Does:
Automatically calculates and displays Take Profit (TP) and Stop Loss (SL) levels based on Average True Range (ATR)
Locks ATR values and direction signals at the start of each bar to prevent repainting and provide consistent levels
Offers multiple direction detection modes including real-time candle-based positioning for dynamic trading approaches
Displays entry, TP, and SL levels as clean horizontal lines that extend from the current bar
Original Features That Make This Script Unique:
Bar-Locked ATR System: ATR values are captured and frozen at bar open, ensuring levels remain stable throughout the bar's progression
Multi-Modal Direction Detection: Four distinct modes for determining TP/SL positioning - Trend Following (EMA-based), Bullish Only, Bearish Only, and real-time Candle Based
Real-Time Candle Flipping: In Candle Based mode, TP/SL levels flip immediately when the current candle changes from bullish to bearish or vice versa
Persistent Line Management: Uses efficient line object management to prevent ghost lines and maintain clean visual presentation
Flexible Base Price Selection: Choose between Open (static), Close (dynamic), or midpoint (H+L)/2 for entry level calculation
How The Algorithm Works:
ATR Calculation: Captures ATR value at each bar open using specified length parameter, maintaining consistency throughout the bar
Direction Determination: Uses different methods based on selected mode - EMA crossover for trend following, or real-time candle color for dynamic positioning
Level Calculation: TP level = Base Price + (Direction × TP Multiplier × ATR), SL level = Base Price - (Direction × SL Multiplier × ATR)
Visual Management: Creates persistent line objects once, then updates their positions every bar for optimal performance
Direction Modes Explained:
Trend Following: Uses 5-period and 12-period EMA relationship to determine trend direction (locked at bar open)
Bullish Only: Always places TP above and SL below entry (traditional long setup)
Bearish Only: Always places TP below and SL above entry (traditional short setup)
Candle Based: Dynamically adjusts based on current candle direction - flips in real-time as candle develops
Key Input Parameters:
ATR Length: Period for ATR calculation (default 14) - longer periods provide smoother volatility measurement
TP Multiplier: Take profit distance as multiple of ATR (default 1.0) - higher values target larger profits
SL Multiplier: Stop loss distance as multiple of ATR (default 1.0) - higher values allow more room for price movement
Base Price: Reference point for level calculations - Open for static entry, Close for dynamic tracking
Direction Mode: Method for determining whether TP goes above or below entry level
How To Use This Indicator:
For Position Sizing: Use the displayed SL distance to calculate appropriate position size based on your risk tolerance
For Entry Timing: Wait for price to approach the entry level before taking positions
For Risk Management: Set your actual stop loss orders at or near the displayed SL level
For Profit Taking: Use the TP level as initial profit target, consider scaling out at this level
Mode Selection: Choose Candle Based for scalping and quick reversals, Trend Following for swing trading
Visual Style Customization:
Line Colors: Customize TP line color (default teal) and SL line color (default orange) for easy identification
Line Widths: Adjust TP/SL line thickness (1-5) and entry line thickness (1-3) for visibility preferences
Clean Display: Lines extend 3 bars forward from current bar and update position dynamically
Best Practices:
Use on clean charts without multiple overlapping indicators for clearest visual interpretation
Combine with volume analysis and key support/resistance levels for enhanced decision making
Adjust ATR length based on your trading timeframe - shorter for scalping, longer for position trading
Test different TP/SL multipliers based on the volatility characteristics of your chosen instruments
Consider using Trend Following mode during strong trending periods and Candle Based during ranging markets
Cruzamento Mágico-EMA 5/21 + Stop ATR + Filtro BTC 30mOf course, here is a brief description of the strategy in English.
**Triple Confirmation Swing Trading Strategy**
This strategy aims to capture trend-based movements in crypto assets by using a triple confirmation system to filter entry signals and increase the probability of success.
The conditions for a trade are:
1. **Entry Trigger (Timing):** The primary signal occurs when the 5-period Exponential Moving Average (EMA) crosses the 21-period EMA. A cross above suggests a buy, while a cross below suggests a sell.
2. **Asset Trend Filter:** An entry is only considered if the asset's own trend, as measured by the **ATR Stop** indicator, is moving in the same direction as the EMA crossover. This avoids entering trades against the local trend.
3. **Market Trend Filter (Bitcoin):** As a final confirmation, the strategy checks the trend of **Bitcoin (BTC) on a fixed 30-minute timeframe**, also using the ATR Stop. A trade is only executed if the BTC trend aligns with the asset's signal.
In short, the strategy only opens a **long** position if the EMAs cross up, the asset's ATR Stop is bullish, and the Bitcoin's ATR Stop is also bullish. The reverse applies for a **short** position.
MFI × RSI × VWAP Multi-Timeframe Suite# MFI × RSI × VWAP Multi-Timeframe Suite - Usage Guide & Precautions
## 📊 Indicator Overview
This indicator integrates **RSI (Relative Strength Index)**, **MFI (Money Flow Index)**, and **VWAP (Volume Weighted Average Price)** for comprehensive multi-timeframe analysis. It provides high-precision trading signals through confluence analysis.
## 🎯 Primary Objectives
- **Comprehensive trend analysis across short, medium, and long-term timeframes**
- **Enhanced accuracy through multi-indicator confluence**
- **Optimized entry and exit timing**
---
## 📈 Basic Interpretation
### 1. Main Plot Lines
- **Blue Line (RSI)**: Price momentum
- **Purple Line (MFI)**: Money flow momentum
- **Orange Line (VWAP Relative)**: Relative position to VWAP (0-100 scale)
### 2. Background Color Meaning
- **Green**: All indicators aligned bullishly (buying dominance)
- **Red**: All indicators aligned bearishly (selling dominance)
- **Color Intensity**: Strength of confluence
### 3. Signal Arrows
- **🔼 Green Up Arrow**: Long signal
- **🔽 Red Down Arrow**: Short signal
- **🟠 Small Circles**: VWAP crossover signals
---
## 🎛️ Configuration Settings
### Basic Parameters
```
RSI Length: 14 (standard)
MFI Length: 14 (standard)
RSI Overbought: 70
RSI Oversold: 30
MFI Overbought: 80
MFI Oversold: 20
```
### VWAP Settings
```
VWAP Anchor: Session (use "Week" or "Month" for daily charts)
Std Dev Multiplier: 2.0 (Bollinger Band-style application)
```
### Multi-Timeframe Configuration
```
TF1: 15min (short-term)
TF2: 1hour (medium-term)
TF3: 4hour (long-term)
TF4: Daily (trend)
```
---
## 📋 Dashboard Interpretation
### Trend Strength Scores
- **+70 to +100**: 💪 Very strong uptrend
- **+30 to +69**: 🟢 Uptrend
- **-29 to +29**: ➖ Sideways/No clear direction
- **-30 to -69**: 🔴 Downtrend
- **-70 to -100**: ⚠️ Very strong downtrend
### Consensus (Overall Assessment)
Average score across all timeframes. **Absolute value ≥50** indicates strong trend.
---
## 🎯 Practical Trading Methods
### 🔵 Long Entry Conditions
1. **RSI crosses above MFI** OR **synchronized oversold exit**
2. **Price above VWAP**
3. **Multi-timeframe consensus is positive (+)**
4. **Green background (confluence present)**
### 🔴 Short Entry Conditions
1. **RSI crosses below MFI** OR **synchronized overbought exit**
2. **Price below VWAP**
3. **Multi-timeframe consensus is negative (-)**
4. **Red background (confluence present)**
### ⚡ Strongest Signals
- **All timeframes align in trend direction**
- **Consensus score ±70 or higher**
- **🚀 STRONG display**
---
## ⏰ Timeframe-Specific Applications
### Scalping (1min-5min charts)
- Focus on RSI/MFI crossovers
- Target VWAP bounces
- Require 15min+ timeframe trend filter
### Day Trading (15min-1hour charts)
- Emphasize overbought/oversold exit signals
- Follow 1hour to daily trend direction
- Confirm with confluence background color
### Swing Trading (4hour-daily charts)
- Prioritize daily+ consensus
- Use weekly VWAP for big picture
- Wait for multi-timeframe alignment
---
## 🚨 Alert Utilization
### Basic Alerts
- **Long/Short Signal**: Basic entry signals
- **Strong Consensus**: Powerful signals with multi-timeframe confluence
- **VWAP Cross**: Important support/resistance breakouts
### Alert Configuration Example
```
Long Signal → Begin monitoring as candidate
Strong Consensus + Long → Consider aggressive entry
VWAP Bullish Cross → Potential trend reversal
```
---
## ⚠️ Important Precautions & Limitations
### Avoiding False Signals
1. **Wait for multiple conditions to align simultaneously**
2. **Never trade against higher timeframe trends**
3. **Avoid major economic news releases**
4. **Exercise caution during extremely low volatility**
### Market Environment Adjustments
- **Trending Markets**: Emphasize crossover signals
- **Range-bound Markets**: Focus on overbought/oversold levels
- **High Volatility**: Strengthen filters
- **Low Volatility**: Adjust sensitivity
### Risk Management Rules
1. **Never risk more than 2% per trade**
2. **Always set stop-loss before entry**
3. **Use proper position sizing**
4. **Maintain trading journal**
---
## 🎓 Learning & Improvement Guidelines
### Backtesting Recommendations
- **Test on 6+ months of historical data**
- **Verify performance across different market conditions**
- **Adapt settings to your trading style**
### Continuous Optimization
- **Track win rate and risk-reward ratios**
- **Analyze performance by timeframe**
- **Measure impact of parameter adjustments**
---
## 🚫 Critical Don'ts
### Never Do These:
❌ **Trade during major news events** (FOMC, NFP, CPI)
❌ **Ignore higher timeframe bias**
❌ **Chase signals after they've already moved significantly**
❌ **Override risk management rules**
❌ **Trade when emotionally compromised**
### Red Flags - Stop Trading When:
⚠️ **Consensus shows conflicting signals across timeframes**
⚠️ **VWAP shows choppy, directionless movement**
⚠️ **Multiple false signals occur consecutively**
⚠️ **Market volatility exceeds 300% of normal levels**
---
## 📊 Performance Monitoring
### Daily Checklist
```
□ Check overall market sentiment
□ Verify economic calendar for news events
□ Review multi-timeframe alignment
□ Confirm proper risk management setup
□ Monitor position sizing appropriateness
```
### Weekly Review
```
□ Analyze win rate by timeframe
□ Review entry/exit execution quality
□ Assess adherence to trading rules
□ Identify pattern improvements
□ Adjust parameters if necessary
```
### Monthly Evaluation
```
□ Calculate overall profitability
□ Review maximum drawdown periods
□ Assess emotional discipline
□ Update trading plan based on results
□ Consider strategy refinements
```
---
## 🎖️ Advanced Tips for Professionals
### Multi-Monitor Setup
```
Primary Screen: Main chart with indicator
Secondary Screen: Multi-timeframe view
Third Screen: Economic calendar + news
Mobile Device: Alert notifications
```
### Professional Entry Techniques
1. **Wait for 2+ confluence factors**
2. **Confirm with volume analysis**
3. **Use limit orders near VWAP levels**
4. **Scale into positions on strong signals**
### Exit Strategy Optimization
1. **Take partial profits at key levels**
2. **Trail stops on trending moves**
3. **Exit immediately on trend reversal signals**
4. **Honor predetermined risk-reward ratios**
---
## ⚡ Quick Reference Card
### Best Practices Summary
✅ **Always check higher timeframe first**
✅ **Wait for confluence of multiple indicators**
✅ **Use proper position sizing**
✅ **Set stops before entering**
✅ **Follow your trading plan strictly**
### Signal Reliability Ranking
1. **🚀 Strong Consensus** (Highest reliability)
2. **Multi-timeframe alignment** (High reliability)
3. **VWAP + RSI/MFI confluence** (Medium-high reliability)
4. **Single timeframe signals** (Medium reliability)
5. **Isolated crossovers** (Lowest reliability)
---
## 🔧 Troubleshooting Common Issues
### If Signals Are Too Frequent:
- Increase RSI/MFI periods
- Tighten overbought/oversold levels
- Add more confluence requirements
- Use higher timeframe bias
### If Signals Are Too Rare:
- Decrease RSI/MFI periods
- Widen overbought/oversold levels
- Reduce confluence requirements
- Lower signal smoothing value
### If Accuracy Is Poor:
- Review market conditions compatibility
- Strengthen higher timeframe filters
- Improve risk management
- Consider different timeframe combinations
**Remember**: This indicator is a comprehensive analysis tool. It's **not perfect in isolation** and must be used with proper **risk management** and **market understanding**!
EMA 1/8 Cross - Fixed Pip TP/SLEMA 1/8 Cross – Fixed Pip TP/SL
This strategy is based on the crossover between EMA 8 and EMA 14 as trading signals:
Long entry → when EMA 1 crosses above EMA 8
Short entry → when EMA 1 crosses below EMA 8
Features:
Fixed pip Take Profit (TP) and Stop Loss (SL), fully adjustable in the settings.
Customizable EMA Fast/Slow lengths for optimization.
Pip size input to match different broker definitions (e.g., XAUUSD often uses 0.10 as one pip).
Suitable for testing scalping or swing trading across multiple timeframes.
⚠️ Disclaimer:
This script is intended for backtesting and educational purposes only. Please optimize parameters and apply proper risk management before using it on live accounts.
Trading Stats BarSimple statistics bar designed to give important values for swing trading
Most of the values are self explanatory
Float Grade
Combines float and float % designed to give a sense if the stock has the potential to move quickly. If the float is less than 20 million and float % less than 50, this has a high potential to make fast moves.
Volume Run Rate
Concept is to focus on the opening x minutes and average this value over the previous y days
Fair Value Gaps BOOSTED [LuxAlgo & mqsxn] Fair Value Gaps BOOSTED
This enhanced version of LuxAlgo’s Fair Value Gap indicator takes market imbalance detection to the next level. Built on the trusted foundation of the original, this extension introduces powerful new features designed for traders who want deeper insight and more control:
Extended Visualization – Fair Value Gaps now stretch farther into the past with customizable bar extensions, so you can easily track unmitigated gaps over longer distances of time.
Intersection Highlights – Automatically identify and shade overlapping bullish/bearish FVGs, giving instant visual clarity on high-confluence zones.
Center Lines & Mitigation Tracking – Optional center lines improve precision, while mitigation markers help confirm when gaps are filled.
Advanced Filtering – Control visibility with minimum gap sizes, custom start dates for gap formations, and per-direction display limits.
Dashboard Stats – On-chart metrics show the number of detected and mitigated gaps, plus percentages, at a glance.
Alerts Ready – Set up alerts for fresh FVG formation or mitigation events, so you never miss a key signal.
Whether you’re scalping, day trading, or swing trading, Fair Value Gaps BOOSTED helps you pinpoint institutional price imbalances and trade around them with confidence.
------
Inputs & Settings
Threshold % / Auto
Defines the minimum gap size as a percentage of price. Enable Auto to let the script automatically adapt thresholding based on volatility.
Unmitigated Lines (combined)
Draws guide lines for a set number of the most recent unmitigated gaps.
Mitigation Levels
Shows dashed lines where gaps have been fully mitigated (filled).
Timeframe
Lets you calculate Fair Value Gaps on a higher or lower timeframe than the chart you’re viewing.
Style
Dynamic Mode
Keeps the most recent gap area actively updating with price as long as it remains unmitigated.
Extend Right (bars)
Controls how many bars into the future each gap visualization will project.
Bullish / Bearish Colors
Customize the fill colors of bullish and bearish gaps.
Center Line & Width
Adds a dotted line through the midpoint of each gap for visual precision.
Filter
Min Gap Size (ticks)
Only display gaps greater than or equal to this size.
Min Formation Date (days ago)
Show gaps formed within a given lookback window (e.g., only last 4 days).
Display
Show Last Bullish / Bearish (unmitigated)
Limit how many recent bullish or bearish gaps appear at once (set to 0 for unlimited).
Intersections
Show Intersections
Highlight overlapping bullish and bearish gaps as shaded zones.
Show Intersections Only
Hide individual gaps and show only the overlapping regions.
Intersection Color
Customize the fill for overlap areas.
Intersection Center Line / Width
Optionally plot a midpoint line through the overlap zone.
Dashboard
Show Dashboard
Display a compact on-chart table of bullish vs bearish counts and mitigation percentages.
Location
Choose where the dashboard sits (top right, bottom right, bottom left).
Size
Adjust text size (Tiny, Small, Normal).
Frozen 4H VWAP – Precision AnchoredFrozen 4H VWAP – Precision Anchored Like Ice
The Frozen 4H VWAP – Precision Anchored delivers a clean, stable, and reliable view of the 4-hour Volume Weighted Average Price, designed for traders who want higher timeframe insights without intrabar noise or repainting.
🔹 Key Features:
Non-Repainting: VWAP value is “frozen” at the close of each 4H candle — no mid-bar updates or flickering.
4H Timeframe Anchoring: Seamlessly pulls 4-hour VWAP values into any timeframe you’re trading on.
Clear Trend Reference: Updates only when a new 4H candle begins, acting as a trustworthy anchor for support/resistance.
Custom Source Option: Choose from different price sources (default: HLC3) to fit your strategy.
Whether you're scalping, day trading, or swing trading, this indicator gives you a powerful edge by grounding your decisions in higher timeframe VWAP data — clear, calm, and frozen in time.
Rolling Correlation BTC vs Hedge AssetsRolling Correlation BTC vs Hedge Assets
Overview
This indicator calculates and plots the rolling correlation between Bitcoin (BTC) returns and several key hedge assets:
• XAUUSD (Gold)
• EURUSD (proxy for DXY, U.S. Dollar Index)
• VIX (Volatility Index)
• TLT (20y U.S. Treasury Bonds ETF)
By monitoring these dynamic correlations, traders can identify whether BTC is moving in sync with risk assets or decoupling as a hedge, and adjust their trading strategy accordingly.
How it works
1. Computes returns for BTC and each asset using percentage change.
2. Uses the rolling correlation function (ta.correlation) over a configurable window length (default = 12 bars).
3. Plots each correlation as a separate colored line (Gold = Yellow, EURUSD = Blue, VIX = Red, TLT = Green).
4. Adds threshold levels at +0.3 and -0.3 to help classify correlation regimes.
How to use it
• High positive correlation (> +0.3): BTC is moving together with the asset (risk-on behavior).
• Near zero (-0.3 to +0.3): BTC is showing little to no correlation — neutral/independent moves.
• Negative correlation (< -0.3): BTC is moving in the opposite direction — potential hedge opportunity.
Practical strategies:
• Watch BTC vs VIX: a spike in volatility (VIX ↑) usually coincides with BTC selling pressure.
• Track BTC vs EURUSD: stronger USD often puts downside pressure on BTC.
• Observe BTC vs Gold: during “flight to safety” events, gold rises while BTC weakens.
• Monitor BTC vs TLT: rising yields (falling TLT) often align with BTC weakness.
Inputs
• Window Length (bars): Number of bars used to calculate rolling correlations (default = 12).
• Comparison Timeframe: Default = 5m. Can be changed to align with your intraday or swing trading style.
Notes
• Works best on intraday charts (1m, 5m, 15m) for scalping and short-term setups.
• Use correlations as context, not standalone signals — combine with volume, VWAP, and price action.
• Correlations are dynamic; they can switch regimes quickly during macro events (CPI, NFP, FOMC).
This tool is designed for traders who want to manage risk exposure by monitoring whether BTC is behaving as a risk-on asset or hedge, and to exploit opportunities during decoupling phases.
Psych Zones – Continuous 250-pip Bands (clamped boxes)Market Makers liquidation and reversal zones for swing trading
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.