PSP Indicator [Elbaz]Precision Swing Point or PSP is a unique technical analysis tool designed to compare the price action of three tickers that are in sync.
It highlights moments when the price structure diverges between the markets, identifying ideal entry points for trades - We would like to enter a trade when we found PSP and one of the tickers took the wick while others didn't.
This strategy provides an edge by focusing on periods of desynchronization between the indices, where one index may be showing strength while another is lagging. The idea is to find the moments where the candle colors (bullish or bearish) differ across the markets, then wait for one of the tickers to "take" the wick of the PSP while other didn't and enter a trade.
Once a divergence is detected, the indicator plots an arrow on the chart, signaling a potential trade entry. To minimize risk, a good place to put stop loss will at the end of the wick of the PSP — the high or low wick of the candle where the divergence occurs.
The PSP Indicator allows for several custom inputs:
- Tickers: Customize the tickers to compare. The default values are S&P 500 E-mini, NASDAQ E-mini, and Dow Jones E-mini, if you trade Crypto you might want to use BTC, ETH, TOTAL3.
- Lookback Period: The lookback input defines how far back the indicator should evaluate to calculate the price structure point.
- Highlight Bar Times: Users can specify particular times during the trading day to highlight, such as the market open or significant news events. This helps traders focus on key trading windows.
Cerca negli script per "如何用wind搜索股票的发行价和份数"
Specific Time CandlesSpecific Time Candles Indicator
The Specific Time Candles indicator is a powerful tool designed for traders who want to focus on specific time intervals within their charts. This custom indicator allows you to highlight and analyze price action during user-defined time periods, providing clarity and precision in your trading strategy.
Key Features:
Custom Time Intervals: Select any start and end time to create candles that focus on your preferred trading hours. This is particularly useful for traders who want to concentrate on market sessions, such as the London or New York session, or any other specific time frame relevant to their trading plan.
Enhanced Visualization: By isolating specific time periods, this indicator helps reduce noise and provides a clearer view of market movements during key trading hours. This can be beneficial for identifying trends, reversals, and potential breakout opportunities.
Flexible Configuration: Easily adjust the indicator settings to match your trading schedule. Whether you are a day trader, swing trader, or scalper, you can customize the time frames to suit your needs.
Compatibility: The indicator is compatible with multiple asset classes, including forex, stocks, commodities, and cryptocurrencies, making it a versatile tool for any trader.
User-Friendly Interface: Designed with simplicity in mind, the Specific Time Candles indicator is easy to set up and use, even for those who are new to TradingView.
How to Use:
Add the indicator to your chart from the TradingView library.
Set your desired start and end times in the indicator settings.
Observe the newly formed candles that represent the specified time intervals.
Use these candles to make informed trading decisions based on the focused analysis of market activity during your chosen periods.
Benefits:
Precision Trading: Focus on the most relevant market data, eliminating distractions from other time periods.
Improved Decision-Making: Gain insights into market behavior during critical times, enhancing your ability to make strategic trades.
Time Management: Efficiently manage your trading by concentrating on specific times, allowing for better planning and execution.
The Specific Time Candles indicator is a must-have for traders looking to refine their strategies by concentrating on precise market windows. Whether you are targeting high-volatility periods or specific trading sessions, this indicator provides the tools you need to succeed.
Time Range### Indicator Name: **Time Range**
#### Description:
The **Time Range** indicator allows users to highlight specific time ranges on a chart for each day of the week. It uses customizable time inputs for every day (Monday to Sunday), allowing the user to define trading sessions or any time-based range. These sessions are visualized by shading the background of the chart within the defined periods.
#### Key Features:
- **Custom Sessions**: For each day of the week (Monday to Sunday), the user can define a unique time session by specifying the start time using the input fields.
- **Day-wise Session Activation**: The user can toggle the activation of sessions for each day by using checkboxes. If the session for a particular day is disabled, no background shading will appear for that day.
- **Background Highlighting**: When a session is active, the background of the chart during the specified session period will be shaded in gray with a 70% transparency. This helps the user visually identify active time ranges across multiple days.
#### Use Cases:
- **Highlighting Trading Sessions**: Traders can use this indicator to easily visualize specific market sessions such as the New York or London trading sessions.
- **Visualizing Custom Time Blocks**: Can be used to highlight any custom time blocks that are important for the trader, such as key trading hours, news release periods, or other time-based strategies.
#### Customizable Parameters:
- **Day Toggles**: Checkboxes to activate or deactivate sessions for each day of the week.
- **Time Range Inputs**: Time range inputs allow the user to set start times for each session, which are applied based on the user's selection for the day.
This indicator helps streamline chart analysis by giving clear visual markers for time-based events or trading windows.
Exponential Smoothing FilterThe digital exponential filter, in finance known as Exponential Moving Average (EMA) , can be used as a technical indicator for chart analysis to visualize uptrends and downtrends in the market. Unlike the classic simple moving average, the EMA requires only two values for its calculation: the last calculated exponential average price and the current price. This is a simple and fast calculation - even for wide smoothing windows. For further details and the math please refer to the "exponential smoothing" article on Wikipedia.
Here are some additional key points about the exponential moving average:
The EMA can react more quickly to price changes because it can give more weight to current prices - depending on your parameter settings.
Short-term, disruptive price fluctuations are smoothed out well, making prevailing trends more visible.
Despite good smoothing properties, it delays the input values slightly, so it can follow sudden trend changes well.
The EMA is well suited to dynamic markets and trading strategies.
The filter is a good basis for further processing such as gradient analysis.
How to use
When you add the script to your charts, you'll immediately see a thin orange line across your time series, smoothing out price fluctuations.
There are only two parameters to set
smoothing factor between 0.0000 = no smoothing and 0.9999 = strong smoothing
input source : open, high, low, close hl2, etc.
Chart output
In the example chart above, you can see that the orange line follows the highs and lows better than the blue line , which is a simple moving average (SMA).
Additionally, the orange line has a shorter lag, or reacts faster when the trend of the original price data suddenly changes. These characteristics are critical for buying and selling decisions: quickly reacting and tracking highs and lows while providing a smooth line that filters out distracting noise.
[blackcat] L1 Fibonacci CounterLevel: 1
Background
I believe that many traders must be familiar with the Fibonacci sequence. In live trading, we also use the Fibonacci sequence to predict the probability of a change in direction at an important stage of the market. , In the market analysis method, the Fibonacci sequence appears frequently.
Function
Drawing Fibonacci cycles manually is usually more labor-intensive. Here I tentatively implement a technical indicator that automatically draws Fibonacci time windows. It can automatically locate the high and low points of historical prices, and count them. When the period displayed by the counter is a Fibonacci number, it will be highlighted with a yellow background color and marked with the Fibonacci number. value.
Inputs
Counter Max Lookback --> Default 987.
Key Signal
Red bgcolor --> historical high with Fib hits
Green bgcolor --> historical low with Fib hits
Remarks
This is a Level 1 free and open source indicator.
Feedbacks are appreciated.
Key Session & LevelsThis indicator helps traders track key price levels for multiple timeframes and trading sessions. It plots:
Previous Day's High and Low (PD): Highlighting the high and low of the previous trading day.
Previous Week's High and Low (PW): Plotting the highest and lowest price levels for the past week.
Tokyo Session High and Low (Today): Displays the high and low levels for the Tokyo trading session (adjustable to your preferred time window).
London Session High and Low (Today): Tracks the high and low for the London trading session (also adjustable for your timezone and desired session window).
Features:
Customizable Time Zones: The indicator uses your preferred timezone to calculate session highs/lows.
Extendable Lines: Lines for each level extend to the right of the chart, providing continuous reference throughout the trading day.
Adjustable Settings: Fine-tune the visibility and width of the lines, and choose which levels to display (Previous Day, Previous Week, Tokyo, and London sessions).
Non-Repainting: This script uses historical data and only updates when new bars are confirmed, ensuring accurate and reliable signals.
Whether you're a day trader, swing trader, or just tracking key levels for strategic entries and exits, this tool provides quick visual reference to important price points across different trading sessions.
Key Session & LevelsThis indicator helps traders track key price levels for multiple timeframes and trading sessions. It plots:
Previous Day's High and Low (PD): Highlighting the high and low of the previous trading day.
Previous Week's High and Low (PW): Plotting the highest and lowest price levels for the past week.
Tokyo Session High and Low (Today): Displays the high and low levels for the Tokyo trading session (adjustable to your preferred time window).
London Session High and Low (Today): Tracks the high and low for the London trading session (also adjustable for your timezone and desired session window).
Features:
Customizable Time Zones: The indicator uses your preferred timezone to calculate session highs/lows.
Extendable Lines: Lines for each level extend to the right of the chart, providing continuous reference throughout the trading day.
Adjustable Settings: Fine-tune the visibility and width of the lines, and choose which levels to display (Previous Day, Previous Week, Tokyo, and London sessions).
Non-Repainting: This script uses historical data and only updates when new bars are confirmed, ensuring accurate and reliable signals.
Whether you're a day trader, swing trader, or just tracking key levels for strategic entries and exits, this tool provides quick visual reference to important price points across different trading sessions.
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.
Sweep2Trade Pro [CHE]Sweep2Trade Pro \ — Liquidity Sweep → Trend → Confirmation
Sweep2Trade Pro \ helps you catch high-probability reversals or continuations that start with a liquidity sweep, align with the T3 trend, and finalize with a structure confirmation (BOS). It’s designed to reduce noise, time your entries, and keep you out of weak, chop-driven signals.
What’s a “sweep”?
A liquidity sweep happens when price briefly breaks a prior swing high/low (where many stops sit), triggers those stops, and then snaps back. This “stop-hunt” creates liquidity for bigger players and often precedes a sharp move in the opposite direction if the break fails, or fuels continuation if structure actually shifts.
What’s a BOS (Break of Structure)?
A BOS is a price action event where the market takes out a recent swing level in the trend’s direction, signaling continuation and confirming that structure has shifted (bullish BOS through a recent swing high, bearish BOS through a recent swing low).
How the indicator works (at a glance)
1. Regime Filter (T3 + R²)
T3 Moving Average: A smoother, faster-responding moving average that aims to reduce lag while filtering noise, so trend direction changes are clearer.
R² (Coefficient of Determination): Measures how “linear” the recent price path is (0→1). Higher values = stronger, cleaner trend; lower values = more chop. Used here to allow trades only when trend quality exceeds a user-set threshold.
2. Sweep Detection
Bullish sweep: price pokes below a prior swing low and closes back above it.
Bearish sweep: price pokes above a prior swing high and closes back below it.
Lookback length is configurable.
3. Sequence Lock (built-in FSM)
The script manages state in phases so you don’t jump the gun:
Phase 1: Sweep detected → wait for T3 to turn in the corresponding direction.
Phase 2: T3 direction confirmed → show “SWEEP OK” and wait for final confirmation.
Trade Signal: Only fires if confirmation arrives before a timeout.
4. Confirmation Layer
BOS via wick or close (you choose),
Strong close toward the signal (top/bottom quartile of the candle),
Optional “close above/below T3” condition.
These checks help avoid weak sweeps that immediately fade.
5. Alerts & Visuals
“SWEEP OK” markers show when the sweep + T3 direction align.
Final BUY/SELL arrows appear only when the confirmation layer passes.
Ready-made alert conditions for automation.
What you can do with it
Time reversals after sweeps: Enter when a stop-hunt fades and structure confirms.
Ride continuations: Use BOS with the T3 trend to pyramid or re-enter with structure on your side.
Filter chop: Let R² gate entries to periods with cleaner directional drift.
Automate: Use the included alerts with your platform or webhook setup.
Inputs (key settings)
Regime Filter
T3 Length / Volume Factor: Controls smoothness and responsiveness. Smaller length → faster, more sensitive; higher volume factor → smoother curve.
R² Lookback & Threshold: Length of the linear fit window and the minimum “trend quality” required. Higher thresholds mean fewer, cleaner signals.
Sweep / Sequence
Swing Lookback: How far back to define the “reference” high/low for sweeps.
Timeout: Maximum bars allowed between phases to keep signals fresh.
Restart timeout on Phase 2: Optional safety so entries don’t go stale.
Confirmation
BOS Lookback: Micro-pivot window for structure breaks.
Wick vs Close BOS: Conservative traders may prefer close.
Require close above/below T3: Tightens confirmation with trend alignment.
Practical guide (quick start)
1. Timeframe & markets: Works across majors, indices, and crypto. Start with 5m–1h intraday or 1h–4h swing; adjust R² threshold upward on noisier pairs.
2. Entry recipe (Long):
Bullish sweep of a prior low → T3 turns up → BOS/strong close.
Optional: enable “close above T3” for extra confirmation.
3. Entry recipe (Short): Mirror the above.
4. Stops: Common choices are just beyond the sweep wick (tighter) or past the BOS invalidation (safer).
5. Targets: Previous structural levels, measured move, or a T3 trail (exit when price closes back through T3).
6. Avoid low-quality contexts: If R² is very low, market is likely ranging erratically—skip or widen filters.
Tips & best practices
Context first: The same sweep means different things in a strong trend vs. flat regime; that’s why the T3+R² filter exists.
BOS choice: Wick-based BOS is earlier but noisier; close-based BOS is slower but cleaner. Tune per market.
Backtest -> Forward test: Validate settings per symbol/timeframe; then paper trade before going live.
Risk: Fixed fractional risk with asymmetric R\:R (e.g., 1:1.5–1:3) generally performs better than “all-in” discretionary sizing.
Behind the scenes (for the curious)
T3 is a multi-stage EMA construction that produces a smooth curve with reduced lag versus simple/standard EMAs.
R² is the square of correlation (0–1). Here it’s used as a moving gauge of how well price aligns to a linear path—our “trend quality” dial.
Stop-hunts / sweeps are a recognized microstructure phenomenon where clustered stops provide the liquidity that fuels the next move.
Disclaimer
No indicator guarantees profits. Sweep2Trade Pro \ is a decision aid; always combine with solid risk management and your own judgment. Backtest, forward test, and size responsibly.
The content provided, including all code and materials, is strictly for educational and informational purposes only. It is not intended as, and should not be interpreted as, financial advice, a recommendation to buy or sell any financial instrument, or an offer of any financial product or service. All strategies, tools, and examples discussed are provided for illustrative purposes to demonstrate coding techniques and the functionality of Pine Script within a trading context.
Any results from strategies or tools provided are hypothetical, and past performance is not indicative of future results. Trading and investing involve high risk, including the potential loss of principal, and may not be suitable for all individuals. Before making any trading decisions, please consult with a qualified financial professional to understand the risks involved.
By using this script, you acknowledge and agree that any trading decisions are made solely at your discretion and risk.
Enhance your trading precision and confidence 🚀
Happy trading
Chervolino
Buy Sell Volume with delta value📄 Script Description
This indicator decomposes total traded volume into buying and selling volume, and displays their relative ratios.
🔎 Key Features
Buying vs. Selling Volume Separation
Uses the candle’s high, low, and close to split total volume into buying volume and selling volume.
Formula:
Buy = volume * (close - low) / (high - low)
Sell = volume * (high - close) / (high - low)
Volume Histogram Visualization
Plots overall volume (upper/lower) and separated buy/sell volumes as color-coded columns.
UPPER V / LOWER V: total volume
BUY V: buying volume (teal)
SELL V: selling volume (red)
Buy/Sell Ratio Calculation
Computes the percentage of buy and sell volume relative to total volume.
Buy Ratio = buyVolume / totalVolume * 100
Sell Ratio = sellVolume / totalVolume * 100
Ratio Display
Shows the latest Buy Ratio in a table (top-right corner of the chart).
Adds a label above the most recent bar displaying:
"Buy XX% / Sell YY%"
Historical ratios can be inspected through the TradingView Data Window or tooltip.
🛠️ Usage
Quickly identify whether volume during each candle is dominated by buyers or sellers.
Helps to assess market pressure and confirm potential trend direction, entries, or exits.
⚠️ Notes
Labels are shown only on the most recent bar (Pine cannot track mouse cursor events).
To see historical values, use the TradingView Data Window or hover tooltips.
This method provides an approximate split of volume and does not perfectly capture all market order flows.
RRG Relative Strength# RRG Relative Strength (RRG RS)
Compare any symbol to a benchmark using two RRG-style lines: **RS-Ratio** (trend of relative strength) and **RS-Momentum** (momentum of that trend). Both are centered at **100**:
- **RS-Ratio > 100** → outperforming the benchmark
- **RS-Ratio < 100** → underperforming
- **RS-Momentum** often **leads** RS-Ratio (crosses 100 earlier)
# How it works
1) Relative Strength (RS): RS = Close(symbol) / Close(benchmark)
2) Normalize around 100: smooth RS with EMA and divide RS by that EMA
3) RS-Ratio: EMA( RS / EMA(RS, Length), LenSmooth ) * 100
4) RS-Momentum: RS-Ratio / EMA(RS-Ratio, LenSmooth) * 100
# Inputs
- Length (default 14): normalization window for RS
- Length Smooth (default 20): smoothing window for RS-Ratio & RS-Momentum
# Benchmark (auto)
- US: SP:SPX (S&P 500)
- Vietnam: HOSE:VNINDEX
- Crypto: INDEX:BTCUSD
(Modify the mapping if needed, or replace with your own input.symbol().)
# How to read
- Improving: RS-Momentum crosses above 100 while RS-Ratio turns up
- Leading: RS-Ratio > 100 with RS-Momentum ≥ 100
- Weakening: RS-Momentum drops below 100; RS-Ratio often follows
# Timeframes & presets
- Works on Daily and Weekly charts
- Daily (fast): 14 / 20
- Approx. weekly behavior on Daily: 50 / 60
Note: Values usually hover near 100 (e.g., ~90–110) but are not strictly bounded. Ensure your symbol and benchmark trade in comparable sessions/currencies.
CleanBreak Lines (Break + First Retest)CleanBreak lines draws one robust support line (green) from swing lows and one robust resistance line (red) from swing highs, then optionally signals a confirmed break and the first clean retest back to that line. Lines are scored with a transparent W-Score (0–100) so traders can judge quality at a glance. The script is non-repainting and uses only confirmed bar data.
What it does
Auto-builds two trendlines that aim to represent meaningful support and resistance.
Uses a median-based slope so outliers and single spikes do not distort the line.
Computes a W-Score per line from three things: touches, span (how long it held), and respect (staying on the correct side).
Optionally triggers a single, tightly-gated signal on Break + First Retest.
How it works (plain English)
Detect recent swing highs and swing lows.
Fit one line through highs and one through lows using a robust, median-style slope estimate.
Score each line: more clean touches and longer span raise the W-Score; frequent violations lower it.
A break requires a candle close beyond the line by a small ATR margin.
A first retest requires price to come back to the line within a limited number of bars and hold on close.
A single arrow may print on that confirmed retest, with optional alerts.
What it is not
Not a prediction model and not a promises-of-profit tool.
Not a multi-signal spammer: by design it aims to allow one retest entry per break.
Not a regression channel or machine-learning system.
How to use
At a glance: treat the green line as candidate support and the red line as candidate resistance.
Conservative approach: wait for a break on close and then the first retest to hold; use the arrow as a prompt, not a command.
Context-only mode: hide arrows in Style if you want the lines and W-Score only.
Inputs (brief)
Core: Swing Length, Max Pivots, Min Touches, Min Span Bars.
Scoring: Touches Max (cap), Weights for touches vs span, Min W-Score to arm.
Break and Retest: Break Margin x ATR, Retest Tolerance x ATR, Retest Window (bars).
Visuals: Show Labels, Show Table, Line Width, Fade When Refit.
Recommended presets
Cleaner, fewer signals: Min Touches 4–5, Min Span Bars 100–150, Min W-Score 70–80, Break Margin 0.40–0.60 ATR, Retest Tolerance 0.10–0.15 ATR, Retest Window 8–12 bars.
Lines-only: keep defaults and uncheck the two plotshapes in Style.
Alerts
CB Long Retest: break above the red line and first retest holds.
CB Short Retest: break below the green line and first retest holds.
Use “Once per bar close” for consistency.
On-chart table (if enabled)
RES / SUP: W-Score and distance from price in ATR terms.
Status: “Waiting Long RT”, “Waiting Short RT”, or “Idle”.
Thresholds: MinScore and Retest bars for quick context.
Timeframes
Works well on 1h to 1D. On very low timeframes, raise Break Margin x ATR to reduce whipsaw effects. On higher timeframes, increase Min Touches and Min Span Bars.
Non-repainting policy
All logic uses confirmed pivots and confirmed bar closes.
Breaks and retests are validated on close; alerts reference only confirmed conditions.
No lookahead in any request.security call.
Original implementation focused on a median-based robust slope for auto trendlines, plus a transparent W-Score and a single retest gate.
Disclosure
This script is for education and charting. It does not guarantee outcomes, and past behavior does not imply future results. Always validate on historical data and practice risk management.
Multiple Session Pre-market High/LowThis indicator marks each day’s pre-market range and projects it into the opening move so you can see how price reacts after the bell. It tracks the **pre-market high/low** within a user-defined window (default **04:00–09:29 ET**) and, at **09:30 ET**, draws two solid horizontal lines from **09:30 to 11:00 ET** at those levels. For additional context, you can optionally show matching **dotted lines** across the pre-market window itself. Everything is anchored to **America/New\_York** time (DST-safe), and colors/widths for both the RTH and pre-market lines are fully customizable.
It’s built for **back testing and review**: levels are finalized at 09:30 and **do not repaint**, so what you see historically is what you would have had live. Use it to study opening drive behavior, VWAP/OR confluence, gap fills, and rejection/acceptance around the pre-market extremes. Works on any intraday timeframe; for stocks, enable **Extended Hours** so the 04:00–09:29 bars are available (futures usually include them by default). Adjust the pre-market start/end inputs to match your playbook (e.g., 07:00–09:29) and evaluate your strategies consistently across months of data.
Buy & Sell Volume (OWI)📊 Buy & Sell Volume (OWI) Indicator Guide
The Buy & Sell Volume (OWI) indicator is designed to provide a visual breakdown of buying and selling pressure in each candle, helping traders identify volume surges and potential market moves. It also includes a time filter to focus analysis during key trading hours.
⚙️ Setup & Inputs
When adding the indicator to your chart, you'll see several configurable inputs:
SMA Length : Sets the period for the Simple Moving Average (SMA) of total volume.
Enable Time Filter : Toggles whether to restrict analysis to US market hours (Eastern Time). |
Start Hour/Minute : Defines the beginning of the time filter window (default: 9:45 ET). |
End Hour/Minute : Defines the end of the time filter window (default: 16:15 ET). |
📈 How It Works
🔍 Volume Breakdown
Buy Volume: Estimated volume attributed to buyers, calculated based on candle position.
Sell Volume: Estimated volume attributed to sellers.
Total Volume SMA: A moving average of total volume to benchmark current activity.
⏰ Time Filter (Optional)
When enabled, the indicator only highlights volume spikes during the specified US market hours. This helps filter out noise from pre-market or after-hours trading.
🚨 Highlight Conditions
The indicator flags significant volume spikes with labels above the volume bars:
| Label | Condition |
| V+ | Volume is between 1.5× and 2× the SMA, during market hours (if enabled). |
| V++ | Volume exceeds 2× the SMA, during market hours (if enabled). |
💡 Tips
- Use shorter SMA lengths for more reactive volume analysis.
- Change the time filter if you're trading outside US market hours.
- Combine with candlestick patttern to confirm breakout or reversal signals.
Open Range Breakout Strategy With Multi TakeProfitHello everyone,
For a while, I’ve been wanting to develop new scripts, but I couldn’t decide what to create. Eventually, I came up with the idea of coding traditional and well-known trading strategies—while adding modern features such as multi–take profit options. For the first strategy in this series, I chose the Open Range Strategy .
For those unfamiliar with it, the Open Range Strategy is a trading approach where you define a specific time period at the beginning of a trading session—such as the first 15 minutes, 30 minutes, or 1 hour—and mark the highest and lowest prices within that range. These levels then act as reference points for potential breakouts: if the price breaks above the range, it may signal a long entry; if it breaks below, it may indicate a short entry. This method is popular among day traders for capturing early momentum in the market.
Since this strategy is generally used as an intraday strategy , I added a Trade Session feature. This allows you to define the exact time window during which trades can be opened. Once the session ends, all positions are automatically closed, ensuring trades remain within your chosen intraday period.
Even though it’s a relatively simple concept, I’ve come across many different variations of it. That’s why I created a highly customizable project. Under the Session Settings, you can select the time window you want to define as your range. Whether it’s the first 15-minute candle or the entire first hour, the choice is entirely yours.
For stop-loss placement, there are two different options:
Middle of the Range – The stop loss is placed at the midpoint between the high and low of the defined range, offering a balanced buffer for both bullish and bearish setups.
Top/Bottom of the Range – The stop loss is placed just beyond the range’s high for short trades or just below the range’s low for long trades, providing a more conservative risk approach.
I’ve always been a big fan of the multi take-profit feature, so I added two different take-profit targets to this project. Take profits are calculated based on a Risk-to-Reward Ratio, which you can adjust in the settings. You can also set different position sizes for each target, allowing you to scale out of trades in a way that suits your strategy.
The result is a flexible, user-friendly strategy script that brings together a classic approach with modern risk management tools—ready to be tailored to your trading style
Dip Hunter [BackQuant]Dip Hunter
What this tool does in plain language
Dip Hunter is a pullback detector designed to find high quality buy-the-dip opportunities inside healthy trends and to avoid random knife catches. It watches for a quick drop from a recent high, checks that the drop happened with meaningful participation and volatility, verifies short-term weakness inside a larger uptrend, then scores the setup and paints the chart so you can act with confidence. It also draws clean entry lines, provides a meter that shows dip strength at a glance, and ships with alerts that match common execution workflows.
How Dip Hunter thinks
It defines a recent swing reference, measures how far price has dipped off that high, and only looks at candidates that meet your minimum percentage drop.
It confirms the dip with real activity by requiring a volume spike and a volatility spike.
It checks structure with two EMAs. Price should be weak in the short term while the larger context remains constructive.
It optionally requires a higher-timeframe trend to be up so you focus on pullbacks in trending markets.
It bundles those checks into a score and shows you the score on the candles and on a gradient meter.
When everything lines up it paints a green triangle below the bar, shades the background, and (if you wish) draws a horizontal entry line at your chosen level.
Inputs and what they mean
Dip Hunter Settings
• Vol Lookback and Vol Spike : The script computes an average volume over the lookback window and flags a spike when current volume is a multiple of that average. A multiplier of 2.0 means today’s volume must be at least double the average. This helps filter noise and focuses on dips that other traders actually traded.
• Fast EMA and Slow EMA : Short-term and medium-term structure references. A dip is more credible if price closes below the fast EMA while the fast EMA is still below the slow EMA during the pullback. That is classic corrective behavior inside a larger trend.
• Price Smooth : Optional smoothing length for price-derived series. Use this if you trade very noisy assets or low timeframes.
• Volatility Len and Vol Spike (volatility) : The script checks both standard deviation and true range against their own averages. If either expands beyond your multiplier the market confirms the move with range.
• Dip % and Lookback Bars : The engine finds the highest high over the lookback window, then computes the percentage drawdown from that high to the current close. Only dips larger than your threshold qualify.
Trend Filter
• Enable Trend Filter : When on, Dip Hunter will only trigger if the market is in an uptrend.
• Trend EMA Period : The longer EMA that defines the session’s backbone trend.
• Minimum Trend Strength : A small positive slope requirement. In practice this means the trend EMA should be rising, and price should be above it. You can raise the value to be more selective.
Entries
• Show Entry Lines : Draws a horizontal guide from the signal bar for a fixed number of bars. Great for limit orders, scaling, or re-tests.
• Line Length (bars) : How far the entry guide extends.
• Min Gap (bars) : Suppresses new entry lines if another dip fired recently. Prevents clutter during choppy sequences.
• Entry Price : Choose the line level. “Low” anchors at the signal candle’s low. “Close” anchors at the signal close. “Dip % Level” anchors at the theoretical level defined by recent_high × (1 − dip%). This lets you work resting orders at a consistent discount.
Heat / Meter
• Color Bars by Score : Colors each candle using a red→white→green gradient. Red is overheated, green is prime dip territory, white is neutral.
• Show Meter Table : Adds a compact gradient strip with a pointer that tracks the current score.
• Meter Cells and Meter Position : Resolution and placement of the meter.
UI Settings
• Show Dip Signals : Plots green triangles under qualifying bars and tints the background very lightly.
• Show EMAs : Plots fast, slow, and the trend EMA (if the trend filter is enabled).
• Bullish, Bearish, Neutral colors : Theme controls for shapes, fills, and bar painting.
Core calculations explained simply
Recent high and dip percent
The script finds the highest high over Lookback Bars , calls it “recent high,” then calculates:
dip% = (recent_high − close) ÷ recent_high × 100.
If dip% is larger than Dip % , condition one passes.
Volume confirmation
It computes a simple moving average of volume over Vol Lookback . If current volume ÷ average volume > Vol Spike , we have a participation spike. It also checks 5-bar ROC of volume. If ROC > 50 the spike is forceful. This gets an extra score point.
Volatility confirmation
Two independent checks:
• Standard deviation of closes vs its own average.
• True range vs ATR.
If either expands beyond Vol Spike (volatility) the move has range. This prevents false triggers from quiet drifts.
Short-term structure
Price should close below the Fast EMA and the fast EMA should be below the Slow EMA at the moment of the dip. That is the anatomy of a pullback rather than a full breakdown.
Macro trend context (optional)
When Enable Trend Filter is on, the Trend EMA must be rising and price must be above it. The logic prefers “micro weakness inside macro strength” which is the highest probability pattern for buying dips.
Signal formation
A valid dip requires:
• dip% > threshold
• volume spike true
• volatility spike true
• close below fast EMA
• fast EMA below slow EMA
If the trend filter is enabled, a rising trend EMA with price above it is also required. When all true, the triangle prints, the background tints, and optional entry lines are drawn.
Scoring and visuals
Binary checks into a continuous score
Each component contributes to a score between 0 and 1. The script then rescales to a centered range (−50 to +50).
• Low or negative scores imply “overheated” conditions and are shaded toward red.
• High positive scores imply “ripe for a dip buy” conditions and are shaded toward green.
• The gradient meter repeats the same logic, with a pointer so you can read the state quickly.
Bar coloring
If you enable “Color Bars by Score,” each candle inherits the gradient. This makes sequences obvious. Red clusters warn you not to buy. White means neutral. Increasing green suggests the pullback is maturing.
EMAs and the trend EMA
• Fast EMA turns down relative to the slow EMA inside the pullback.
• Trend EMA stays rising and above price once the dip exhausts, which is your cue to focus on long setups rather than bottom fishing in downtrends.
Entry lines
When a fresh signal fires and no other signal happened within Min Gap (bars) , the indicator draws a horizontal level for Line Length bars. Use these lines for limit entries at the low, at the close, or at the defined dip-percent level. This keeps your plan consistent across instruments.
Alerts and what they mean
• Market Overheated : Score is deeply negative. Do not chase. Wait for green.
• Close To A Dip : Score has reached a healthy level but the full signal did not trigger yet. Prepare orders.
• Dip Confirmed : First bar of a fresh validated dip. This is the most direct entry alert.
• Dip Active : The dip condition remains valid. You can scale in on re-tests.
• Dip Fading : Score crosses below 0.5 from above. Momentum of the setup is fading. Tighten stops or take partials.
• Trend Blocked Signal : All dip conditions passed but the trend filter is offside. Either reduce risk or skip, depending on your plan.
How to trade with Dip Hunter
Classic pullback in uptrend
Turn on the trend filter.
Watch for a Dip Confirmed alert with green triangle.
Use the entry line at “Dip % Level” to stage a limit order. This keeps your entries consistent across assets and timeframes.
Initial stop under the signal bar’s low or under the next lower EMA band.
First target at prior swing high, second target at a multiple of risk.
If you use partials, trail the remainder under the fast EMA once price reclaims it.
Aggressive intraday scalps
Lower Dip % and Lookback Bars so you catch shallow flags.
Keep Vol Spike meaningful so you only trade when participation appears.
Take quick partials when price reclaims the fast EMA, then exit on Dip Fading if momentum stalls.
Counter-trend probes
Disable the trend filter if you intentionally hunt reflex bounces in downtrends.
Require strong volume and volatility confirmation.
Use smaller size and faster targets. The meter should move quickly from red toward white and then green. If it does not, step aside.
Risk management templates
Stops
• Conservative: below the entry line minus a small buffer or below the signal bar’s low.
• Structural: below the slow EMA if you aim for swing continuation.
• Time stop: if price does not reclaim the fast EMA within N bars, exit.
Position sizing
Use the distance between the entry line and your structural stop to size consistently. The script’s entry lines make this distance obvious.
Scaling
• Scale at the entry line first touch.
• Add only if the meter stays green and price reclaims the fast EMA.
• Stop adding on a Dip Fading alert.
Tuning guide by market and timeframe
Equities daily
• Dip %: 1.5 to 3.0
• Lookback Bars: 5 to 10
• Vol Spike: 1.5 to 2.5
• Volatility Len: 14 to 20
• Trend EMA: 100 or 200
• Keep trend filter on for a cleaner list.
Futures and FX intraday
• Dip %: 0.4 to 1.2
• Lookback Bars: 3 to 7
• Vol Spike: 1.8 to 3.0
• Volatility Len: 10 to 14
• Use Min Gap to avoid clusters during news.
Crypto
• Dip %: 3.0 to 6.0 for majors on higher timeframes, lower on 15m to 1h
• Lookback Bars: 5 to 12
• Vol Spike: 1.8 to 3.0
• ATR and stdev checks help in erratic sessions.
Reading the chart at a glance
• Green triangle below the bar: a validated dip.
• Light green background: the current bar meets the full condition.
• Bar gradient: red is overheated, white is neutral, green is dip-friendly.
• EMAs: fast below slow during the pullback, then reclaim fast EMA on the bounce for quality continuation.
• Trend EMA: a rising spine when the filter is on.
• Entry line: a fixed level to anchor orders and risk.
• Meter pointer: right side toward “Dip” means conditions are maturing.
Why this combination reduces false positives
Any single criterion will trigger too often. Dip Hunter demands a dip off a recent high plus a volume surge plus a volatility expansion plus corrective EMA structure. Optional trend alignment pushes odds further in your favor. The score and meter visualize how many of these boxes you are actually ticking, which is more reliable than a binary dot.
Limitations and practical tips
• Thin or illiquid symbols can spoof volume spikes. Use larger Vol Lookback or raise Vol Spike .
• Sideways markets will show frequent small dips. Increase Dip % or keep the trend filter on.
• News candles can blow through entry lines. Widen stops or skip around known events.
• If you see many back-to-back triangles, raise Min Gap to keep only the best setups.
Quick setup recipes
• Clean swing trader: Trend filter on, Dip % 2.0 to 3.0, Vol Spike 2.0, Volatility Len 14, Fast 20 EMA, Slow 50 EMA, Trend 100 EMA.
• Fast intraday scalper: Trend filter off, Dip % 0.7 to 1.0, Vol Spike 2.5, Volatility Len 10, Fast 9 EMA, Slow 21 EMA, Min Gap 10 bars.
• Crypto swing: Trend filter on, Dip % 4.0, Vol Spike 2.0, Volatility Len 14, Fast 20 EMA, Slow 50 EMA, Trend 200 EMA.
Summary
Dip Hunter is a focused pullback engine. It quantifies a real dip off a recent high, validates it with volume and volatility expansion, enforces corrective structure with EMAs, and optionally restricts signals to an uptrend. The score, bar gradient, and meter make reading conditions instant. Entry lines and alerts turn that read into an executable plan. Tune the thresholds to your market and timeframe, then let the tool keep you patient in red, selective in white, and decisive in green.
Linh's Anomaly Radar v2What this script does
It’s an event detector for price/volume anomalies that often precede or confirm moves.
It watches a bunch of patterns (Wyckoff tests, squeezes, failed breakouts, turnover bursts, etc.), applies robust z-scores, optional trend filters, cooldowns (to avoid spam), and then fires:
A shape/label on the bar,
A row in the mini panel (top-right),
A ready-made alertcondition you can hook into.
How to add & set up (TradingView)
Paste the script → Save → Add to chart on Daily first (works on any TF).
Open Settings → Inputs:
General
• Use Robust Z (MAD): more outlier-resistant; keep on.
• Z Lookback: 60 bars is ~3 months; bump to 120 for slower regimes.
• Cooldown: min bars to wait before the same signal can fire again (default 5).
• Use trend filter: if on, “bullish” signals only fire above SMA(tfLen), “bearish” below.
Thresholds: fine-tune sensitivity (defaults are sane).
To create alerts: Right-click chart → Add alert
Condition: Linh’s Anomaly Radar v2 → choose a specific signal or Composite (Σ).
Options: “Once per bar close” (recommended).
Customize message if you want ticker/timeframe in your phone push.
The mini panel (top-right)
Signal column: short code (see cheat sheet below).
Fired column: a dot “•” means that on the latest bar this signal fired.
Score (right column): total count of signals that fired this bar.
Σ≥N shows your composite threshold (how many must fire to trigger the “Composite” alert).
Shapes & codes (what’s what)
Code Name (category) What it’s looking for Why it matters
STL Stealth Volume z(volume)>5 & ** z(return)
EVR Effort vs Result squeeze z(vol)>3 & z(TR)<−0.5 Heavy effort, tiny spread → absorption
TGV Tight+Heavy (HL/ATR)<0.6 & z(vol)>3 Tight bar + heavy tape → pro activity
CLS Accumulation cluster ≥3 of last 5 bars: up, vol↑, close near high Classic accumulation footprint
GAP Open drive failure Big gap not filled (≥80%) & vol↑ One-sided open stalls → fade risk
BB↑ BB squeeze breakout Squeeze (z(BBWidth)<−1.3) → close > upperBB & vol↑ Regime shift with confirmation
ER↑ Effort→Result inversion Down day on vol then next bar > prior high Demand overwhelms supply
OBV OBV divergence OBV slope up & ** z(ret20)
WER Wide Effort, Opposite Result z(vol)>3, close+1 Selling into strength / distribution
NS No-Supply (Wyckoff) Down bar, HL<0.6·ATR, vol << avg Sellers absent into weakness
ND No-Demand (Wyckoff) Up bar, HL<0.6·ATR, vol << avg Buyers absent into strength
VAC Liquidity Vacuum z(vol)<−1.5 & ** z(ret)
UTD UTAD (failed breakout) Breaks swing-high, closes back below, vol↑ Stop-run, reversal risk
SPR Spring (failed breakdown) Breaks swing-low, closes back above, vol↑ Bear trap, reversal risk
PIV Pocket Pivot Up bar; vol > max down-vol in lookback Quiet base → sudden demand
NR7 Narrow Range 7 + Vol HL is 7-bar low & z(vol)>2 Coiled spring with participation
52W 52-wk breakout quality New 52-wk close high + squeeze + vol↑ High-quality breakouts
VvK Vol-of-Vol kink z(ATR20,200)>0.5 & z(ATR5,60)<0 Long-vol wakes up, short-vol compresses
TAC Turnover acceleration SMA3 vol / SMA20 vol > 1.8 & muted return Participation surging before move
RBd RSI Bullish div Price LL, RSI HL, vol z>1 Exhaustion of sellers
RS↑ RSI Bearish div Price HH, RSI LH, vol z>1 Exhaustion of buyers
Σ Composite Count of all fired signals ≥ threshold High-conviction bar
Placement:
Triangles up (below bar) → bullish-leaning events.
Triangles down (above bar) → bearish-leaning events.
Circles → neutral context (VAC, VvK, Composite).
Key inputs (quick reference)
General
Use Robust Z (MAD): keep on for noisy tickers.
Z Lookback (lenZ): 60 default; 120 if you want fewer alerts.
Trend filter: when on, bullish signals require close > SMA(tfLen), bearish require <.
Cooldown: prevents repeated firing of the same signal within N bars.
Phase-1 thresholds (core)
Stealth: vol z > 5, |ret z| < 1.
EVR: vol z > 3, TR z < −0.5.
Tight+Heavy: (HL/ATR) < 0.6, vol z > 3.
Cluster: window=5, min=3 strong bars.
GapFail: gap/ATR ≥1.5, fill <80%, vol z > 2.
BB Squeeze: z(BBWidth)<−1.3 then breakout with vol z > 2.
Eff→Res Up: prev bar heavy down → current bar > prior high.
OBV Div: OBV uptrend + |z(ret20)|<0.3.
Phase-2 thresholds (extras)
WER: vol z > 3, close1.
No-Supply/No-Demand: tight bar & very light volume vs SMA20.
Vacuum: vol z < −1.5, |ret z|>1.5.
UTAD/Spring: swing lookback N (default 20), vol z > 2.
Pocket Pivot: lookback for prior down-vol max (default 10).
NR7: 7-bar narrowest range + vol z > 2.
52W Quality: new 52-wk high + squeeze + vol z > 2.
VoV Kink: z(ATR20,200)>0.5 AND z(ATR5,60)<0.
Turnover Accel: SMA3/SMA20 > 1.8 and |ret z|<1.
RSI Divergences: compare to n bars back (default 14).
How to use it (playbooks)
A) Daily scan workflow
Run on Daily for your VN watchlist.
Turn Composite (Σ) alert on with Σ≥2 or ≥3 to reduce noise.
When a bar fires Σ (or a fav combo like STL + BB↑), drop to 60-min to time entries.
B) Breakout quality check
Look for 52W together with BB↑, TAC, and OBV.
If WER/ND appear near highs → downgrade the breakout.
C) Spring/UTAD reversals
If SPR fires near major support and RBd confirms → long bias with stop below spring low.
If UTD + WER/RS↑ near resistance → short/fade with stop above UTAD high.
D) Accumulation basing
During bases, you want CLS, OBV, TGV, STL, NR7.
A pocket pivot (PIV) can be your early add; manage risk below base lows.
Tuning tips
Too many signals? Raise stealthVolZ to 5.5–6, evrVolZ to 3.5, use Σ≥3.
Fast movers? Lower bbwZthr to −1.0 (less strict squeeze), keep trend filter on.
Illiquid tickers? Keep MAD z-scores on, increase lookbacks (e.g., lenZ=120).
Limitations & good habits
First lenZ bars on a new symbol are less reliable (incomplete z-window).
Some ideas (VWAP magnet, close auction spikes, ETF/foreign flows, options skew) need intraday/external feeds — not included here.
Pine can’t “screen” across the whole market; set alerts or cycle your watchlist.
Quick troubleshooting
Compilation errors: make sure you’re on Pine v6; don’t nest functions in if blocks; each var int must be declared on its own line.
No shapes firing: check trend filter (maybe price is below SMA and you’re waiting for bullish signals), and verify thresholds aren’t too strict.
EZ FX Zones (OR Pro + Auto Alerts) v6.3Purpose:
This indicator automatically calculates and plots ORH (Opening Range High) and ORL (Opening Range Low) based on the first X minutes of trading (customizable), then uses those levels to:
Mark clear Buy and Sell Zones on the chart
Show targets based on ATR (Average True Range) or fixed pip/point settings
Automatically trigger alerts when price crosses important levels so you can enter trades in TopstepFX within your 5-minute execution window
What It Plots on the Chart:
Opening Range High (ORH) – top of the initial range (green line)
Opening Range Low (ORL) – bottom of the initial range (red line)
Midpoint – average of ORH and ORL (dotted white line)
Target Levels – projected profit targets above ORH and below ORL (gray dashed lines)
Labels – “BUY ABOVE” and “SELL BELOW” text for instant clarity
How to Use It (Third Grader Mode):
If price breaks above ORH → BUY.
If price breaks below ORL → SELL.
Your target is the nearest dashed line in the trade direction.
Alerts are sent to your phone when:
Price crosses ORH (BUY alert)
Price crosses ORL (SELL alert)
Price hits target levels
Alerts Included:
"BUY Signal – Price Crossed ORH"
"SELL Signal – Price Crossed ORL"
"Target Hit – Long"
"Target Hit – Short"
Why This Helps in TopstepFX:
No guesswork — you only react to breakouts of the first range.
You can trade with confidence in your 5-minute reaction window because the script does all calculations automatically.
You get push alerts on your phone so you don’t have to stare at charts all day.
Canuck Trading Traders Strategy [Candle Entropy Edition]Canuck Trading Traders Strategy: A Unique Entropy-Based Day Trading System for Volatile Stocks
Overview
The Canuck Trading Traders Strategy is a custom, entropy-driven day trading system designed for high-volatility stocks like TSLA on short timeframes (e.g., 15m). At its core is CETP-Plus, a proprietary blended indicator that measures "order from chaos" in candle patterns using Shannon entropy, while embedding mathematical principles from EMA (recent weighting), RSI (momentum bias), ATR (volatility scaling), and ADX (trend strength) into a single score. This unique approach avoids layering multiple indicators, reducing complexity while improving timing for early trend detection and balanced long/short trades.
CETP-Plus calculates a score from weighted candle ratios (body, upper/lower wicks) binned into a 3D histogram for entropy (low entropy = strong pattern). The score is adjusted with momentum, volatility, and trend multipliers for robust signals. Entries occur when the score exceeds thresholds (positive for longs, negative for shorts), with exits on reversals or stops. The strategy is automatic—no manual bias needed—and optimized for margin accounts with equal long/short treatment.
Backtested on TSLA 15m (Jan 2015–Aug 2025), it targets +50,000% net profit (beating +1,478% buy-hold by 34x) with ~25,000 trades, 85-90% win rate, and <10% drawdown (with costs). Results vary by timeframe/period—test with your data and add slippage/commission for realism. Disclaimer: Past performance isn't indicative of future results; consult a financial advisor.
Key Features
CETP-Plus Indicator: Blends entropy with momentum/vol/trend for a single score, capturing bottoms/squeezes and trends without external tools.
Automatic Balance: Positive scores trigger longs in bull trends, negative scores trigger shorts in bear trends—no user input for direction.
Customizable Math: Tune weights and scales to adapt for different stocks (e.g., lower thresholds for NVDA's smoother trends).
Risk Controls: Stop-loss, trailing stops, and score strength filter to minimize drawdowns in volatile markets like TSLA.
Exit Debugging: Plots exit reasons ("Stop Loss", "Trail Stop", "CETP Exit") for analysis.
Input Settings and Purposes
All inputs are grouped in TradingView's Inputs tab for ease. Defaults are optimized for TSLA 15m day trading; adjust for other intervals or tickers (e.g., increase window for 1h, lower thresholds for NVDA).
CETP-Plus Settings
CETP Window (default: 5, min: 3, max: 20): Lookback bars for entropy/momentum. Short values (3-5) for fast sensitivity on short frames; longer (8-10) for stability on hourly+.
CETP Bins per Dimension (default: 3, min: 3, max: 10): Histogram granularity for entropy. Low (3) for speed/simple patterns; high (5+) for detail in complex markets.
Long Threshold (default: 0.15, min: 0.1, max: 0.8, step: 0.05): CETP score for long entries. Lower (0.1) for more longs in mild bull trends; higher (0.2) to filter noise.
Short Threshold (default: -0.05, min: -0.8, max: -0.1, step: 0.05): CETP score for short entries. Less negative (-0.05) for more shorts in mild bear trends; more negative (-0.2) for strong signals.
CETP Momentum Weight (default: 0.8, min: 0.1, max: 1.0, step: 0.1): Emphasizes momentum in score. High (0.9) for aggressive in fast moves; low (0.5) for entropy focus.
Momentum Scale (default: 1.6, min: 0.1, max: 2.0, step: 0.1): Amplifies momentum. High (2.0) for short intervals; low (1.0) for stability.
Body Ratio Weight (default: 1.2, min: 0.0, max: 2.0, step: 0.1): Weights candle body in entropy (trend focus). High (1.5) for strong trends; low (0.8) for wick emphasis.
Upper Wick Ratio Weight (default: 0.8, min: 0.0, max: 2.0, step: 0.1): Weights upper wick (reversal noise). Low (0.5) to reduce false ups.
Lower Wick Ratio Weight (default: 0.8, min: 0.0, max: 2.0, step=0.1): Weights lower wick. Low (0.5) to reduce false downs.
Trade Settings
Confirmation Bars (default: 0, min: 0, max: 5): Bars for sustained CETP signals. 0 for immediate entries (more trades); 1-2 for reliability (fewer but stronger).
Min CETP Score Strength (default: 0.04, min: 0.0, max: 0.5, step: 0.05): Min absolute score for entry. Low (0.04) for more trades; high (0.15) for quality.
Risk Management
Stop Loss (%) (default: 0.5, min: 0.1, max: 5.0, step: 0.1): % from entry for stop. Tight (0.4) for quick exits; wide (0.8) for trends.
ATR Multiplier (default: 1.5, min: 0.5, max: 3.0, step: 0.1): Scales ATR for stops/trails. Low (1.0) for tight; high (2.0) for room.
Trailing ATR Mult (default: 3.5, min: 0.5, max: 5.0, step: 0.1): ATR mult for trails. High (4.0) for longer holds; low (2.0) for profits.
Trail Start Offset (%) (default: 1.0, min: 0.5, max: 2.0, step: 0.1): % profit before trailing. Low (0.8) for early lock-in; high (1.5) for bigger moves.
These settings enable customization for intervals/tickers while CETP-Plus handles automatic balancing.
Risk Disclosure
Trading involves significant risk and may result in losses exceeding your initial capital. The Canuck Trading Trader Strategy is provided for educational and informational purposes only. Users are responsible for their own trading decisions and should conduct thorough testing before using in live markets. The strategy’s high trade frequency requires reliable execution infrastructure to minimize slippage and latency.
SMC Structures and FVGสวัสดีครับ! ผมจะอธิบายอินดิเคเตอร์ "SMC Structures and FVG + MACD" ที่คุณให้มาอย่างละเอียดในแต่ละส่วน เพื่อให้คุณเข้าใจการทำงานของมันอย่างถ่องแท้ครับ
อินดิเคเตอร์นี้เป็นการผสมผสานแนวคิดของ Smart Money Concept (SMC) ซึ่งเน้นการวิเคราะห์โครงสร้างตลาด (Market Structure) และ Fair Value Gap (FVG) เข้ากับอินดิเคเตอร์ MACD เพื่อใช้เป็นตัวกรองหรือตัวยืนยันสัญญาณ Choch/BoS (Change of Character / Break of Structure)
1. ภาพรวมอินดิเคเตอร์ (Overall Purpose)
อินดิเคเตอร์นี้มีจุดประสงค์หลักคือ:
ระบุโครงสร้างตลาด: ตีเส้นและป้ายกำกับ Choch (Change of Character) และ BoS (Break of Structure) บนกราฟโดยอัตโนมัติ
ผสานการยืนยันด้วย MACD: สัญญาณ Choch/BoS จะถูกพิจารณาก็ต่อเมื่อ MACD Histogram เกิดการตัดขึ้นหรือลง (Zero Cross) ในทิศทางที่สอดคล้องกัน
แสดง Fair Value Gap (FVG): หากเปิดใช้งาน จะมีการตีกล่อง FVG บนกราฟ
แสดงระดับ Fibonacci: คำนวณและแสดงระดับ Fibonacci ที่สำคัญตามโครงสร้างตลาดปัจจุบัน
ปรับตาม Timeframe: การคำนวณและการแสดงผลทั้งหมดจะปรับตาม Timeframe ที่คุณกำลังใช้งานอยู่โดยอัตโนมัติ
2. ส่วนประกอบหลักของโค้ด (Code Breakdown)
โค้ดนี้สามารถแบ่งออกเป็นส่วนหลัก ๆ ได้ดังนี้:
2.1 Inputs (การตั้งค่า)
ส่วนนี้คือตัวแปรที่คุณสามารถปรับแต่งได้ในหน้าต่างการตั้งค่าของอินดิเคเตอร์ (คลิกที่รูปฟันเฟืองข้างชื่ออินดิเคเตอร์บนกราฟ)
MACD Settings (ตั้งค่า MACD):
fast_len: ความยาวของ Fast EMA สำหรับ MACD (ค่าเริ่มต้น 12)
slow_len: ความยาวของ Slow EMA สำหรับ MACD (ค่าเริ่มต้น 26)
signal_len: ความยาวของ Signal Line สำหรับ MACD (ค่าเริ่มต้น 9)
= ta.macd(close, fast_len, slow_len, signal_len): คำนวณค่า MACD Line, Signal Line และ Histogram โดยใช้ราคาปิด (close) และค่าความยาวที่กำหนด
is_bullish_macd_cross: ตรวจสอบว่า MACD Histogram ตัดขึ้นเหนือเส้น 0 (จากค่าลบเป็นบวก)
is_bearish_macd_cross: ตรวจสอบว่า MACD Histogram ตัดลงใต้เส้น 0 (จากค่าบวกเป็นลบ)
Fear Value Gap (FVG) Settings:
isFvgToShow: (Boolean) เปิด/ปิดการแสดง FVG บนกราฟ
bullishFvgColor: สีสำหรับ Bullish FVG
bearishFvgColor: สีสำหรับ Bearish FVG
mitigatedFvgColor: สีสำหรับ FVG ที่ถูก Mitigate (ลดทอน) แล้ว
fvgHistoryNbr: จำนวน FVG ย้อนหลังที่จะแสดง
isMitigatedFvgToReduce: (Boolean) เปิด/ปิดการลดขนาด FVG เมื่อถูก Mitigate
Structures (โครงสร้างตลาด) Settings:
isStructBodyCandleBreak: (Boolean) หากเป็น true การ Break จะต้องเกิดขึ้นด้วย เนื้อเทียน ที่ปิดเหนือ/ใต้ Swing High/Low หากเป็น false แค่ไส้เทียนทะลุก็ถือว่า Break
isCurrentStructToShow: (Boolean) เปิด/ปิดการแสดงเส้นโครงสร้างตลาดปัจจุบัน (เส้นสีน้ำเงินในภาพตัวอย่าง)
pivot_len: ความยาวของแท่งเทียนที่ใช้ในการมองหาจุด Pivot (Swing High/Low) ยิ่งค่าน้อยยิ่งจับ Swing เล็กๆ ได้, ยิ่งค่ามากยิ่งจับ Swing ใหญ่ๆ ได้
bullishBosColor, bearishBosColor: สีสำหรับเส้นและป้าย BOS ขาขึ้น/ขาลง
bosLineStyleOption, bosLineWidth: สไตล์ (Solid, Dotted, Dashed) และความหนาของเส้น BOS
bullishChochColor, bearishChochColor: สีสำหรับเส้นและป้าย CHoCH ขาขึ้น/ขาลง
chochLineStyleOption, chochLineWidth: สไตล์ (Solid, Dotted, Dashed) และความหนาของเส้น CHoCH
currentStructColor, currentStructLineStyleOption, currentStructLineWidth: สี, สไตล์ และความหนาของเส้นโครงสร้างตลาดปัจจุบัน
structHistoryNbr: จำนวนการ Break (Choch/BoS) ย้อนหลังที่จะแสดง
Structure Fibonacci (จากโค้ดต้นฉบับ):
เป็นชุด Input สำหรับเปิด/ปิด, กำหนดค่า, สี, สไตล์ และความหนาของเส้น Fibonacci Levels ต่างๆ (0.786, 0.705, 0.618, 0.5, 0.382) ที่จะถูกคำนวณจากโครงสร้างตลาดปัจจุบัน
2.2 Helper Functions (ฟังก์ชันช่วยทำงาน)
getLineStyle(lineOption): ฟังก์ชันนี้ใช้แปลงค่า String ที่เลือกจาก Input (เช่น "─", "┈", "╌") ให้เป็นรูปแบบ line.style_ ที่ Pine Script เข้าใจ
get_structure_highest_bar(lookback): ฟังก์ชันนี้พยายามหา Bar Index ของแท่งเทียนที่ทำ Swing High ภายในช่วง lookback ที่กำหนด
get_structure_lowest_bar(lookback): ฟังก์ชันนี้พยายามหา Bar Index ของแท่งเทียนที่ทำ Swing Low ภายในช่วง lookback ที่กำหนด
is_structure_high_broken(...): ฟังก์ชันนี้ตรวจสอบว่าราคาปัจจุบันได้ Break เหนือ _structureHigh (Swing High) หรือไม่ โดยพิจารณาจาก _highStructBreakPrice (ราคาปิดหรือราคา High ขึ้นอยู่กับการตั้งค่า isStructBodyCandleBreak)
FVGDraw(...): ฟังก์ชันนี้รับ Arrays ของ FVG Boxes, Types, Mitigation Status และ Labels มาประมวลผล เพื่ออัปเดตสถานะของ FVG (เช่น ถูก Mitigate หรือไม่) และปรับขนาด/ตำแหน่งของ FVG Box และ Label บนกราฟ
2.3 Global Variables (ตัวแปรทั่วทั้งอินดิเคเตอร์)
เป็นตัวแปรที่ประกาศด้วย var ซึ่งหมายความว่าค่าของมันจะถูกเก็บไว้และอัปเดตในแต่ละแท่งเทียน (persists across bars)
structureLines, structureLabels: Arrays สำหรับเก็บอ็อบเจกต์ line และ label ของเส้น Choch/BoS ที่วาดบนกราฟ
fvgBoxes, fvgTypes, fvgLabels, isFvgMitigated: Arrays สำหรับเก็บข้อมูลของ FVG Boxes และสถานะต่างๆ
structureHigh, structureLow: เก็บราคาของ Swing High/Low ที่สำคัญของโครงสร้างตลาดปัจจุบัน
structureHighStartIndex, structureLowStartIndex: เก็บ Bar Index ของจุดเริ่มต้นของ Swing High/Low ที่สำคัญ
structureDirection: เก็บสถานะของทิศทางโครงสร้างตลาด (1 = Bullish, 2 = Bearish, 0 = Undefined)
fiboXPrice, fiboXStartIndex, fiboXLine, fiboXLabel: ตัวแปรสำหรับเก็บข้อมูลและอ็อบเจกต์ของเส้น Fibonacci Levels
isBOSAlert, isCHOCHAlert: (Boolean) ใช้สำหรับส่งสัญญาณ Alert (หากมีการตั้งค่า Alert ไว้)
2.4 FVG Processing (การประมวลผล FVG)
ส่วนนี้จะตรวจสอบเงื่อนไขการเกิด FVG (Bullish FVG: high < low , Bearish FVG: low > high )
หากเกิด FVG และ isFvgToShow เป็น true จะมีการสร้าง box และ label ใหม่เพื่อแสดง FVG บนกราฟ
มีการจัดการ fvgBoxes และ fvgLabels เพื่อจำกัดจำนวน FVG ที่แสดงตาม fvgHistoryNbr และลบ FVG เก่าออก
ฟังก์ชัน FVGDraw จะถูกเรียกเพื่ออัปเดตสถานะของ FVG (เช่น การถูก Mitigate) และปรับการแสดงผล
2.5 Structures Processing (การประมวลผลโครงสร้างตลาด)
Initialization: ที่ bar_index == 0 (แท่งเทียนแรกของกราฟ) จะมีการกำหนดค่าเริ่มต้นให้กับ structureHigh, structureLow, structureHighStartIndex, structureLowStartIndex
Finding Current High/Low: highest, highestBar, lowest, lowestBar ถูกใช้เพื่อหา High/Low ที่สุดและ Bar Index ของมันใน 10 แท่งล่าสุด (หรือทั้งหมดหากกราฟสั้นกว่า 10 แท่ง)
Calculating Structure Max/Min Bar: structureMaxBar และ structureMinBar ใช้ฟังก์ชัน get_structure_highest_bar และ get_structure_lowest_bar เพื่อหา Bar Index ของ Swing High/Low ที่แท้จริง (ไม่ใช่แค่ High/Low ที่สุดใน lookback แต่เป็นจุด Pivot ที่สมบูรณ์)
Break Price: lowStructBreakPrice และ highStructBreakPrice จะเป็นราคาปิด (close) หรือราคา Low/High ขึ้นอยู่กับ isStructBodyCandleBreak
isStuctureLowBroken / isStructureHighBroken: เงื่อนไขเหล่านี้ตรวจสอบว่าราคาได้ทำลาย structureLow หรือ structureHigh หรือไม่ โดยพิจารณาจากราคา Break, ราคาแท่งก่อนหน้า และ Bar Index ของจุดเริ่มต้นโครงสร้าง
Choch/BoS Logic (ส่วนสำคัญที่ถูกผสานกับ MACD):
if(isStuctureLowBroken and is_bearish_macd_cross): นี่คือจุดที่ MACD เข้ามามีบทบาท หากราคาทำลาย structureLow (สัญญาณขาลง) และ MACD Histogram เกิด Bearish Zero Cross (is_bearish_macd_cross เป็น true) อินดิเคเตอร์จะพิจารณาว่าเป็น Choch หรือ BoS
หาก structureDirection == 1 (เดิมเป็นขาขึ้น) หรือ 0 (ยังไม่กำหนด) จะตีเป็น "CHoCH" (เปลี่ยนทิศทางโครงสร้างเป็นขาลง)
หาก structureDirection == 2 (เดิมเป็นขาลง) จะตีเป็น "BOS" (ยืนยันโครงสร้างขาลง)
มีการสร้าง line.new และ label.new เพื่อวาดเส้นและป้ายกำกับ
structureDirection จะถูกอัปเดตเป็น 1 (Bullish)
structureHighStartIndex, structureLowStartIndex, structureHigh, structureLow จะถูกอัปเดตเพื่อกำหนดโครงสร้างใหม่
else if(isStructureHighBroken and is_bullish_macd_cross): เช่นกันสำหรับขาขึ้น หากราคาทำลาย structureHigh (สัญญาณขาขึ้น) และ MACD Histogram เกิด Bullish Zero Cross (is_bullish_macd_cross เป็น true) อินดิเคเตอร์จะพิจารณาว่าเป็น Choch หรือ BoS
หาก structureDirection == 2 (เดิมเป็นขาลง) หรือ 0 (ยังไม่กำหนด) จะตีเป็น "CHoCH" (เปลี่ยนทิศทางโครงสร้างเป็นขาขึ้น)
หาก structureDirection == 1 (เดิมเป็นขาขึ้น) จะตีเป็น "BOS" (ยืนยันโครงสร้างขาขึ้น)
มีการสร้าง line.new และ label.new เพื่อวาดเส้นและป้ายกำกับ
structureDirection จะถูกอัปเดตเป็น 2 (Bearish)
structureHighStartIndex, structureLowStartIndex, structureHigh, structureLow จะถูกอัปเดตเพื่อกำหนดโครงสร้างใหม่
การลบเส้นเก่า: d.delete_line (หากไลบรารีทำงาน) จะถูกเรียกเพื่อลบเส้นและป้ายกำกับเก่าออกเมื่อจำนวนเกิน structHistoryNbr
Updating Structure High/Low (else block): หากไม่มีการ Break เกิดขึ้น แต่ราคาปัจจุบันสูงกว่า structureHigh หรือต่ำกว่า structureLow ในทิศทางที่สอดคล้องกัน (เช่น ยังคงเป็นขาขึ้นและทำ High ใหม่) structureHigh หรือ structureLow จะถูกอัปเดตเพื่อติดตาม High/Low ที่สุดของโครงสร้างปัจจุบัน
Current Structure Display:
หาก isCurrentStructToShow เป็น true อินดิเคเตอร์จะวาดเส้น structureHighLine และ structureLowLine เพื่อแสดงขอบเขตของโครงสร้างตลาดปัจจุบัน
Fibonacci Display:
หาก isFiboXToShow เป็น true อินดิเคเตอร์จะคำนวณและวาดเส้น Fibonacci Levels ต่างๆ (0.786, 0.705, 0.618, 0.5, 0.382) โดยอิงจาก structureHigh และ structureLow ของโครงสร้างตลาดปัจจุบัน
Alerts:
alertcondition: ใช้สำหรับตั้งค่า Alert ใน TradingView เมื่อเกิดสัญญาณ BOS หรือ CHOCH
plot(na):
plot(na) เป็นคำสั่งที่สำคัญในอินดิเคเตอร์ที่ไม่ได้ต้องการพล็อต Series ของข้อมูลบนกราฟ (เช่น ไม่ได้พล็อตเส้น EMA หรือ RSI) แต่ใช้วาดอ็อบเจกต์ (Line, Label, Box) โดยตรง
การมี plot(na) ช่วยให้ Pine Script รู้ว่าอินดิเคเตอร์นี้มีเอาต์พุตที่แสดงผลบนกราฟ แม้ว่าจะไม่ได้เป็น Series ที่พล็อตตามปกติก็ตาม
3. วิธีใช้งาน
คัดลอกโค้ดทั้งหมด ที่อยู่ในบล็อก immersive ด้านบน
ไปที่ TradingView และเปิดกราฟที่คุณต้องการ
คลิกที่เมนู "Pine Editor" ที่อยู่ด้านล่างของหน้าจอ
ลบโค้ดเดิมที่มีอยู่ และ วางโค้ดที่คัดลอกมา ลงไปแทน
คลิกที่ปุ่ม "Add to Chart"
อินดิเคเตอร์จะถูกเพิ่มลงในกราฟของคุณโดยอัตโนมัติ คุณสามารถคลิกที่รูปฟันเฟืองข้างชื่ออินดิเคเตอร์บนกราฟเพื่อเข้าถึงหน้าต่างการตั้งค่าและปรับแต่งตามความต้องการของคุณได้
Hello! I will explain the "SMC Structures and FVG + MACD" indicator you provided in detail, section by section, so you can fully understand how it works.This indicator combines the concepts of Smart Money Concept (SMC), which focuses on analyzing Market Structure and Fair Value Gaps (FVG), with the MACD indicator to serve as a filter or confirmation for Choch (Change of Character) and BoS (Break of Structure) signals.1. Overall PurposeThe main purposes of this indicator are:Identify Market Structure: Automatically draw lines and label Choch (Change of Character) and BoS (Break of Structure) on the chart.Integrate MACD Confirmation: Choch/BoS signals will only be considered when the MACD Histogram performs a cross (Zero Cross) in the corresponding direction.Display Fair Value Gap (FVG): If enabled, FVG boxes will be drawn on the chart.Display Fibonacci Levels: Calculate and display important Fibonacci levels based on the current market structure.Adapt to Timeframe: All calculations and displays will automatically adjust to the timeframe you are currently using.2. Code BreakdownThis code can be divided into the following main sections:2.1 Inputs (Settings)This section contains variables that you can adjust in the indicator's settings window (click the gear icon next to the indicator's name on the chart).MACD Settings:fast_len: Length of the Fast EMA for MACD (default 12)slow_len: Length of the Slow EMA for MACD (default 26)signal_len: Length of the Signal Line for MACD (default 9) = ta.macd(close, fast_len, slow_len, signal_len): Calculates the MACD Line, Signal Line, and Histogram using the closing price (close) and the specified lengths.is_bullish_macd_cross: Checks if the MACD Histogram crosses above the 0 line (from negative to positive).is_bearish_macd_cross: Checks if the MACD Histogram crosses below the 0 line (from positive to negative).Fear Value Gap (FVG) Settings:isFvgToShow: (Boolean) Enables/disables the display of FVG on the chart.bullishFvgColor: Color for Bullish FVG.bearishFvgColor: Color for Bearish FVG.mitigatedFvgColor: Color for FVG that has been mitigated.fvgHistoryNbr: Number of historical FVG to display.isMitigatedFvgToReduce: (Boolean) Enables/disables reducing the size of FVG when mitigated.Structures (โครงสร้างตลาด) Settings:isStructBodyCandleBreak: (Boolean) If true, the break must occur with the candle body closing above/below the Swing High/Low. If false, a wick break is sufficient.isCurrentStructToShow: (Boolean) Enables/disables the display of the current market structure lines (blue lines in the example image).pivot_len: Lookback length for identifying Pivot points (Swing High/Low). A smaller value captures smaller, more frequent swings; a larger value captures larger, more significant swings.bullishBosColor, bearishBosColor: Colors for bullish/bearish BOS lines and labels.bosLineStyleOption, bosLineWidth: Style (Solid, Dotted, Dashed) and width of BOS lines.bullishChochColor, bearishChochColor: Colors for bullish/bearish CHoCH lines and labels.chochLineStyleOption, chochLineWidth: Style (Solid, Dotted, Dashed) and width of CHoCH lines.currentStructColor, currentStructLineStyleOption, currentStructLineWidth: Color, style, and width of the current market structure lines.structHistoryNbr: Number of historical breaks (Choch/BoS) to display.Structure Fibonacci (from original code):A set of inputs to enable/disable, define values, colors, styles, and widths for various Fibonacci Levels (0.786, 0.705, 0.618, 0.5, 0.382) that will be calculated from the current market structure.2.2 Helper FunctionsgetLineStyle(lineOption): This function converts the selected string input (e.g., "─", "┈", "╌") into a line.style_ format understood by Pine Script.get_structure_highest_bar(lookback): This function attempts to find the Bar Index of the Swing High within the specified lookback period.get_structure_lowest_bar(lookback): This function attempts to find the Bar Index of the Swing Low within the specified lookback period.is_structure_high_broken(...): This function checks if the current price has broken above _structureHigh (Swing High), considering _highStructBreakPrice (closing price or high price depending on isStructBodyCandleBreak setting).FVGDraw(...): This function takes arrays of FVG Boxes, Types, Mitigation Status, and Labels to process and update the status of FVG (e.g., whether it's mitigated) and adjust the size/position of FVG Boxes and Labels on the chart.2.3 Global VariablesThese are variables declared with var, meaning their values are stored and updated on each bar (persists across bars).structureLines, structureLabels: Arrays to store line and label objects for Choch/BoS lines drawn on the chart.fvgBoxes, fvgTypes, fvgLabels, isFvgMitigated: Arrays to store FVG box data and their respective statuses.structureHigh, structureLow: Stores the price of the significant Swing High/Low of the current market structure.structureHighStartIndex, structureLowStartIndex: Stores the Bar Index of the start point of the significant Swing High/Low.structureDirection: Stores the status of the market structure direction (1 = Bullish, 2 = Bearish, 0 = Undefined).fiboXPrice, fiboXStartIndex, fiboXLine, fiboXLabel: Variables to store data and objects for Fibonacci Levels.isBOSAlert, isCHOCHAlert: (Boolean) Used to trigger alerts in TradingView (if alerts are configured).2.4 FVG ProcessingThis section checks the conditions for FVG formation (Bullish FVG: high < low , Bearish FVG: low > high ).If FVG occurs and isFvgToShow is true, a new box and label are created to display the FVG on the chart.fvgBoxes and fvgLabels are managed to limit the number of FVG displayed according to fvgHistoryNbr and remove older FVG.The FVGDraw function is called to update the FVG status (e.g., whether it's mitigated) and adjust its display.2.5 Structures ProcessingInitialization: At bar_index == 0 (the first bar of the chart), structureHigh, structureLow, structureHighStartIndex, and structureLowStartIndex are initialized.Finding Current High/Low: highest, highestBar, lowest, lowestBar are used to find the highest/lowest price and its Bar Index of it in the last 10 bars (or all bars if the chart is shorter than 10 bars).Calculating Structure Max/Min Bar: structureMaxBar and structureMinBar use get_structure_highest_bar and get_structure_lowest_bar functions to find the Bar Index of the true Swing High/Low (not just the highest/lowest in the lookback but a complete Pivot point).Break Price: lowStructBreakPrice and highStructBreakPrice will be the closing price (close) or the Low/High price, depending on the isStructBodyCandleBreak setting.isStuctureLowBroken / isStructureHighBroken: These conditions check if the price has broken structureLow or structureHigh, considering the break price, previous bar prices, and the Bar Index of the structure's starting point.Choch/BoS Logic (Key Integration with MACD):if(isStuctureLowBroken and is_bearish_macd_cross): This is where MACD plays a role. If the price breaks structureLow (bearish signal) AND the MACD Histogram performs a Bearish Zero Cross (is_bearish_macd_cross is true), the indicator will consider it a Choch or BoS.If structureDirection == 1 (previously bullish) or 0 (undefined), it will be labeled "CHoCH" (changing structure direction to bearish).If structureDirection == 2 (already bearish), it will be labeled "BOS" (confirming bearish structure).line.new and label.new are used to draw the line and label.structureDirection will be updated to 1 (Bullish).structureHighStartIndex, structureLowStartIndex, structureHigh, structureLow will be updated to define the new structure.else if(isStructureHighBroken and is_bullish_macd_cross): Similarly for bullish breaks. If the price breaks structureHigh (bullish signal) AND the MACD Histogram performs a Bullish Zero Cross (is_bullish_macd_cross is true), the indicator will consider it a Choch or BoS.If structureDirection == 2 (previously bearish) or 0 (undefined), it will be labeled "CHoCH" (changing structure direction to bullish).If structureDirection == 1 (already bullish), it will be labeled "BOS" (confirming bullish structure).line.new and label.new are used to draw the line and label.structureDirection will be updated to 2 (Bearish).structureHighStartIndex, structureLowStartIndex, structureHigh, structureLow will be updated to define the new structure.Deleting Old Lines: d.delete_line (if the library works) will be called to delete old lines and labels when their number exceeds structHistoryNbr.Updating Structure High/Low (else block): If no break occurs, but the current price is higher than structureHigh or lower than structureLow in the corresponding direction (e.g., still bullish and making a new high), structureHigh or structureLow will be updated to track the highest/lowest point of the current structure.Current Structure Display:If isCurrentStructToShow is true, the indicator draws structureHighLine and structureLowLine to show the boundaries of the current market structure.Fibonacci Display:If isFiboXToShow is true, the indicator calculates and draws various Fibonacci Levels (0.786, 0.705, 0.618, 0.5, 0.382) based on the structureHigh and structureLow of the current market structure.Alerts:alertcondition: Used to set up alerts in TradingView when BOS or CHOCH signals occur.plot(na):plot(na) is an important statement in indicators that do not plot data series directly on the chart (e.g., not plotting EMA or RSI lines) but instead draw objects (Line, Label, Box).Having plot(na) helps Pine Script recognize that this indicator has an output displayed on the chart, even if it's not a regularly plotted series.3. How to UseCopy all the code in the immersive block above.Go to TradingView and open your desired chart.Click on the "Pine Editor" menu at the bottom of the screen.Delete any existing code and paste the copied code in its place.Click the "Add to Chart" button.The indicator will be added to your chart automatically. You can click the gear icon next to the indicator's name on the chart to access the settings window and customize it to your needs.I hope this explanation helps you understand this indicator in detail. If anything is unclear, or you need further adjustments, please let me know.
Currency Weekend - shading weekend trading// ─────────────────────────────────────────────────────────────────────────────
// © 2025, Steve / Steven Anthony – "Currency Weekend"
// This script highlights the low-liquidity weekend window that often affects
// both fiat currency markets and cryptocurrencies like Bitcoin.
//
// ╭─────────────────────────────── DESCRIPTION ───────────────────────────────╮
// | This indicator shades a customizable time window on your chart, |
// | originally set to highlight the **forex weekend lull** from |
// | **Friday 21:00 UTC to Sunday 21:00 UTC**, when traditional fiat |
// | currency markets close. |
// | |
// | Traders who observe Bitcoin, Ethereum, or other crypto assets may |
// | notice reduced liquidity or increased erratic moves during this time, |
// | due to overlapping behaviors from professional forex traders who |
// | trade both markets. |
// ╰──────────────────────────────────────────────────────────────────────────╯
//
// 🔧 Flexible Configuration:
// - Define your own start and end **day + time** for shading
// - Useful for shading other custom quiet periods or session transitions
//
// 💡 Use Cases:
// - Avoid trading during low-liquidity periods
// - Spot potential weekend traps or price gaps
// - Align crypto behavior with fiat market hours
//
// 📍 Default Settings:
// - Start: Friday 21:00 UTC
// - End: Sunday 21:00 UTC
//
// Timezone is normalized to the chart’s timezone for seamless integration.
//
// ─────────────────────────────────────────────────────────────────────────────
Canonical Momenta Indicator [T1][T69]📌 Overview
The Canonical Momenta Indicator models trend pressure using a Lagrangian-based momentum engine combined with reflexivity theory to detect bursts in price movement influenced by herd behavior and volume acceleration.
🧠 Features
Lagrangian-based kinetic model combining velocity and acceleration
Reflexivity burst detection with directional scoring
Adaptive momentum-weighted output (adaptiveCMI)
Buy 🐋 / Sell 🐻 labels when reflexivity confirms direction
Fully parameterized for customization
⚙️ How to Use
This indicator helps traders:
Detect reflexive bursts in market activity driven by sharp price movement + volume spikes
Capture herd-driven directional moves early.
Gauge market pressure using a kinetic-potential energy model.
Suggested signals:
🐋 Reflexive Up: Strong bullish momentum spike confirmed by volume and positive lagrangian pressure
🐻 Reflexive Down: Strong bearish dump confirmed by volume and negative lagrangian burst
🔧 Configuration
MA Lookback Length - Smoothing for baseline price & energy calculation
Reflexivity Momentum Threshold - Price momentum trigger for burst detection
Reflexivity Lookback - Period over which bursts are counted
Reflexivity Window - Minimum burst sum to trigger signal label
Volume Spike Threshold - % above average volume to qualify as burst
📊 Behavior Description
The indicator computes a Lagrangian energy:
Kinetic Energy = (velocity² + 0.5 * acceleration²)
Potential Energy = deviation from moving average (distance²)
Lagrangian = Potential − Kinetic (higher = overextension)
Then, reflexive bursts are triggered when:
Price is rising or falling over short window (burstMvmnt)
Volume is above average by a user-defined multiple
Each bar gets a burst score:
+1 for up-burst
−1 for down-burst
0 otherwise
⚠️ Risk Profile Based on Lookback Settings
Risk Level | Description | Recommended Lookback
🟥 High | Extremely sensitive to bursts, prone to false signals | 7–10
🟨 Moderate | Balanced reflexivity with trend confirmation | 11–20
🟩 Low | Filters out most noise, slower to react | 21+
🧪 Advanced Tips
Combine with moving average slope for trend filtering
Use divergence between adaptiveCMI and price to detect exhaustion
Works well in crypto, commodities, and volatile assets
⚠️ Limitations
Sensitive to high volatility noise if volMult is too low
Designed for higher timeframes (1H, 4H, Daily) for reliability
Doesn’t confirm direction in sideways markets — pair with other filters
📝 Disclaimer
This tool is provided for educational and informational purposes. Always do your own backtesting and use proper risk management.
Trigonometric StochasticTrigonometric Stochastic - Mathematical Smoothing Oscillator
Overview
A revolutionary approach to stochastic oscillation using sine wave mathematical smoothing. This indicator transforms traditional stochastic calculations through trigonometric functions, creating an ultra-smooth oscillator that reduces noise while maintaining sensitivity to price changes.
Mathematical Foundation
Unlike standard stochastic oscillators, this version applies sine wave smoothing:
• Raw Stochastic: (close - lowest_low) / (highest_high - lowest_low) × 100
• Trigonometric Smoothing: 50 + 50 × sin(2π × raw_stochastic / 100)
• Result: Naturally smooth oscillator with mathematical precision
Key Features
Advanced Smoothing Technology
• Sine Wave Filter: Eliminates choppy movements while preserving signal integrity
• Natural Boundaries: Mathematically constrained between 0-100
• Reduced False Signals: Trigonometric smoothing filters market noise effectively
Traditional Stochastic Levels
• Overbought Zone: 80 level (dashed line)
• Oversold Zone: 20 level (dashed line)
• Midline: 50 level (dotted line) - equilibrium point
• Visual Clarity: Clean oscillator panel with clear level markings
Smart Signal Generation
• Anti-Repaint Logic: Uses confirmed previous bar values
• Buy Signals: Generated when crossing above 30 from oversold territory
• Sell Signals: Generated when crossing below 70 from overbought territory
• Crossover Detection: Precise entry/exit timing
Professional Presentation
• Separate Panel: Dedicated oscillator window (overlay=false)
• Price Format: Formatted as price indicator with 2-decimal precision
• Theme Adaptive: Automatically matches your chart color scheme
Parameters
• Cycle Length (5-200): Period for highest/lowest calculations
- Shorter periods = more sensitive, more signals
- Longer periods = smoother, fewer but stronger signals
Trading Applications
Momentum Analysis
• Overbought/Oversold: Clear visual identification of extreme levels
• Momentum Shifts: Early detection of momentum changes
• Trend Strength: Monitor oscillator position relative to midline
Signal Trading
• Long Entries: Buy when crossing above 30 (oversold bounce)
• Short Entries: Sell when crossing below 70 (overbought rejection)
• Confirmation Tool: Use with trend indicators for higher probability trades
Divergence Detection
• Bullish Divergence: Price makes lower lows, oscillator makes higher lows
• Bearish Divergence: Price makes higher highs, oscillator makes lower highs
• Early Warning: Spot potential trend reversals before they occur
Trading Strategies
Scalping (5-15min timeframes)
• Use cycle length 10-14 for quick signals
• Focus on 20/80 level bounces
• Combine with price action confirmation
Swing Trading (1H-4H timeframes)
• Use cycle length 20-30 for reliable signals
• Wait for clear crossovers with momentum
• Monitor divergences for reversal setups
Position Trading (Daily+ timeframes)
• Use cycle length 50+ for major signals
• Focus on extreme readings (below 10, above 90)
• Combine with fundamental analysis
Advantages Over Standard Stochastic
1. Smoother Action: Sine wave smoothing reduces whipsaws
2. Mathematical Precision: Trigonometric functions provide consistent behavior
3. Maintained Sensitivity: Smoothing doesn't compromise signal quality
4. Reduced Noise: Cleaner signals in volatile markets
5. Visual Appeal: More aesthetically pleasing oscillator movement
Best Practices
• Market Context: Consider overall trend direction
• Multiple Timeframe: Confirm signals on higher timeframes
• Risk Management: Always use proper position sizing
• Backtesting: Test parameters on your preferred instruments
• Combination: Works excellently with trend-following indicators
Built-in Alerts
• Buy Alert: Trigonometric stochastic oversold crossover
• Sell Alert: Trigonometric stochastic overbought crossunder
Technical Specifications
• Pine Script Version: v6
• Panel: Separate oscillator window
• Format: Price indicator with 2-decimal precision
• Performance: Optimized for all timeframes
• Compatibility: Works with all instruments
Free and open-source indicator. Modify, improve, and share with the community!
Educational Value: Perfect for traders wanting to understand how mathematical smoothing improves oscillators and trigonometric applications in technical analysis.