Bitcoin Cycles IndicatorTrack Bitcoin's cyclical price patterns across multiple timeframes with this cycle analysis tool. The indicator automatically identifies cycle lows and highs, marking them with clear visual labels that show cycle day counts and failed cycle detection.
Key Features:
Multi-Time frame Support - Optimized settings for Daily, Weekly, Monthly, and Custom time frames
Cycle Tracking - Identifies and labels cycle lows (green) and highs (red) with day counts
Failed Cycle Detection - Highlights when cycles break below previous lows
Customizable Settings - Adjust cycle lengths, colors, and display options for each timeframe
Info Box - Real-time cycle information display with current cycle day count
Projection Boxes - Visual cycle length projections for better analysis
Perfect for Bitcoin traders and analysts who want to understand market cycles and timing. Works best on Daily charts for short-term cycles and Weekly/Monthly charts for longer-term analysis.
Trend Analysis
ZigZag+4 EMA89 Trend Candles + BUY/SELL SCALPThis script combines ZigZag patterns, EMA89 trend detection, and custom buy/sell scalp signals. It helps identify trend direction and potential entry points in trending markets.
Features:
- ZigZag structure points
- EMA89 as dynamic trend filter
- Buy/Sell scalp markers
- HL/HH swing labels
- Works best on 15m–4h timeframes
Fractal Model (TTrades)Fractal Model - Higher Timeframe Analysis with TTFM Labeling
A higher timeframe candle visualization tool enhanced with TTFM (The Fractal Model) labeling system for pivot-based price action analysis, made popular by Youtuber TTrades
What This Script Does:
This indicator displays higher timeframe candles on your current chart and identifies key pivot formations using the TTFM labeling system. It helps traders understand market structure and potential reversal points through systematic pivot analysis.
Key Features:
Higher Timeframe Visualization : Shows HTF candles without switching timeframes
TTFM Labeling System : Identifies pivot components with C2, C3, and C4 labels
T-Spot Detection : Marks areas where price is likely to form wicks based on pivot logic
Sweep Confirmation : Detects when price sweeps previous levels but closes opposite
Fair Value Gap Detection : Identifies imbalance zones between candle ranges
Alert System : Sends alerts when T-spot formations are confirmed using pivot logic
Silver T-Spot Alerts : Special alerts during specific market hours
How TTFM Labeling Works:
The TTFM system labels pivot formations based on their structure:
C2 : The candle that "sticks out" - the initial move that creates the pivot
C3 / C4 : The distribution candle that continues the reversal (standard pivots)
Alert System:
The indicator provides alerts when:
T-spot formations are created and confirmed
Price sweeps tspot levels with proper confirmation (This signal tries to alert you when a potential wick has formed in the tspot location
Silver T-spot patterns occur during specific market hours
T-spot sweep confirmations are triggered
Practical Usage:
Add the indicator to your chart
Watch for T-spot formations (highlighted zones)
Look for C2, C3, C4 labels to understand pivot structure
Use sweep confirmations for entry timing
Set up alerts for T-spot confirmations and sweeps
Technical Implementation:
Logarithmic Midpoint Calculation:
The T-spot levels are calculated using logarithmic midpoint analysis:
Log Values : log_high = ln(high), log_low = ln(low), log_open = ln(open), log_close = ln(close)
Wick Analysis : upper_wick = log_high - max(log_open, log_close), lower_wick = min(log_open, log_close) - log_low
Body Size : body_size = |log_close - log_open|
Midpoint Logic : If max(upper_wick, lower_wick) > body_size, use wick-based midpoint; otherwise use (log_high + log_low)/2
Final Level : T-spot level = exp(log_mid_level)
T-Spot Formation Conditions:
Standard Bearish : last_closed.h > prev_closed.h AND last_closed.c < prev_closed.h
Standard Bullish : last_closed.l < prev_closed.l AND last_closed.c > prev_closed.l
Expansive Bearish : prev_closed.h > prev_prev_closed.h AND last_closed.c < max(prev_closed.o, prev_closed.c)
Expansive Bullish : prev_closed.l < prev_prev_closed.l AND last_closed.c > min(prev_closed.o, prev_closed.c)
Pro-trend Bearish : last_closed.h > mid_level AND last_closed.h < prev_closed.o AND last_closed.c < prev_closed.l
Pro-trend Bullish : last_closed.l < mid_level AND last_closed.l > prev_closed.o AND last_closed.c > prev_closed.h
Sweep Confirmation Logic:
Pivot Detection : Uses ta.pivothigh(high, 1, 2) and ta.pivotlow(low, 1, 2)
Touch Detection : Price must touch T-spot level (high > level OR open > level) AND close opposite
Confirmation Requirements : Pivot must form before touch, close must break beyond pivot level
Alert Trigger : Sweep confirmed when all conditions are met
Silver T-Spot Conditions:
Special T-spots during specific market hours (4th-5th candle of day or 4th candle after 1PM ET) with additional confirmation requirements.
HTF Auto-Detection:
Automatically selects appropriate higher timeframes: 1m→15m, 3m→30m, 5m→1h, 15m→4h, 30m-1h→1D, 4h-8h→1W, 1D→1M.
Based on HTF Candles by Fadi, enhanced with T-spot detection, sweep logic, TTFM labeling system, and comprehensive alert functionality.
Note: This tool is for educational purposes and should be used in conjunction with proper risk management and market analysis.
The Maker StrategyDESCRIPTION
The Maker Strategy is a trend-following system built around exponential moving averages (EMAs). By analyzing the alignment of multiple EMAs, the strategy identifies strong bullish or bearish momentum and generates precise entry signals. This method is designed to capture sustained trends while filtering out sideways or noisy market conditions.
USER INPUTS :
• EMA 1 Length (Default: 30)
• EMA 2 Length (Default: 35)
• EMA 3 Length (Default: 40)
• EMA 4 Length (Default: 45)
• EMA 5 Length (Default: 50)
• EMA 6 Length (Default: 60)
LONG CONDITION :
A long signal is triggered when all EMAs are perfectly aligned in ascending order:
EMA1 > EMA2 > EMA3 > EMA4 > EMA5 > EMA6
SHORT CONDITION :
A short signal is triggered when all EMAs are perfectly aligned in descending order:
EMA1 < EMA2 < EMA3 < EMA4 < EMA5 < EMA6
WHY IT IS UNIQUE:
Unlike traditional EMA crossover systems that rely on just 2 or 3 moving averages, The Maker Strategy uses 6 EMAs in sequence. This ensures that trades are only taken when there is clear and strong market momentum. The approach minimizes false signals in ranging markets and focuses on capturing trends with higher probability setups.
HOW USER CAN BENEFIT FROM IT :
• Clear entry alerts for both long and short positions.
• Visual confirmation through candle coloring and EMA band fills.
• Works on multiple timeframes and instruments (stocks, forex, crypto, indices).
• Helps traders stay on the right side of the trend while avoiding whipsaws.
• A simple yet effective tool for those who want a disciplined, rules-based strategy.
EITS - Market StructureThis script marks the Swing Lows and Highs of a chosen pair. H,HH,L,LL,HL,LH will be marked on chart. Have fun!!
Double Median SD Bands | MisinkoMasterThe Double Median SD Bands is a new trend following tool designed to help traders/investors identify trends, follow them and improve their trend following strategies.
How does it work?
1. Calculate the Standard Deviation over n period of the source (this can be the close, high, low, hl2 and so on)
2. Calculate the basic bands like so:
Upper = Source + SD*Multiplier
Lower = Source - SD*Multiplier
3. Get the special lengths (which we will soon need):
half length = n/2 (if it returns a number like 8.5, it will be rounded up to 9)
square root length = √n (if it returns a number with decimals, it will be rounded to the closest integer)
4. Smooth the bands using the medians
1x Median SD Band Upper = median over half length period on the SD Upper Band
1x Median SD Band Lower = median over half length period on the SD Lower Band
Double Median SD Bands is then finished by applying the median to both but with the square root length.
Trend Logic :
If source crosses over the upper band = uptrend reversal
If source crosses below the lower band = downtrend reversal
Why choose this indicator?
Smooth and fast trend capture => this indicator combines the median with the SD Bands in such way to give you the highest amount of speed possible, while making you suffer as low amount of noise as possible.
Easy trend identification => Thanks to the colors changing with trends, it makes it very easy for users to identify signals within or below 1-2 seconds
Hope you all enjoy Gs, if you have any questions are requests DM me :)
Intraday Buy/Sell/Average Zones by Chaitu50cIntraday Buy/Sell/Average Zones by chaitu50c
Timeframe:
Tested on the 5-minute chart.
Recommended timeframe: 5-minute
What it does
This indicator marks intraday Buy (green) and Sell (red) zones made by strong close-confirmed breakouts. These zones act as support/resistance. If price later closes through a zone, the zone changes color from that bar forward (support ↔ resistance). It can flip more than once.
How zones form
Single breakout: an opposite-type candle closes beyond the previous candle’s high/low.
Double breakout: a base candle, then two opposite-type candles, and the second one closes beyond the base high/low.
Zone size
Buy zone: from the combo lowest low up to the nearest open/close of the combo.
Sell zone: from the combo highest high down to the nearest open/close of the combo.
Color shift (optional)
If price closes through a zone, it flips color at that bar and behaves as the other side (support ↔ resistance). Flips can happen again later.
Overlap control
When a new zone overlaps an existing same-color zone in the same session, choose:
Merge (combine), or
Suppress (ignore the new one).
Flipped zones use their current color for this.
Right edge & session
All zones extend to the right (your offset). Detection is limited to your chosen session, and you can show only the last N sessions.
---
How to trade (simple)
A) Initial breakout trade
When a new zone forms, that breakout itself can be a trade idea in the breakout direction, The stoploss will be the zone.
B) Zone breakout trade (flip)
If price later closes out of a zone and it changes color, that breakout is another trade opportunity in the new direction.
C) Retrace & average trade
When price retests a zone, wait for a confirmation candle in the zone’s favor
— bullish close for a green zone, bearish close for a red zone — then average entries inside/near the zone.
Place stops just beyond the opposite edge of the zone.
If the zone flips color, stop averaging; bias changed.
---
Key settings
Breakout type: Single and/or Double
Confirm on Close: strict mode (no intrabar preview) or allow intrabar preview that auto-removes if fail
Color Shift on Breaks: on/off
Same-Type Overlap: Merge/Suppress
Session, Sessions to Display, Right Offset, Colors, Max Zones
Reminder: Best results on the 5-minute timeframe (tested and recommended).
FXHacker BUY SELL SIGNAL V2“FXHacker BUY SELL SIGNAL V2 marks key Nairobi session blocks and detects liquidity sweeps. Traders can choose between Strict CHoCH (confirmation on structure break) or Immediate Sweep (signal at first sweep). Designed to highlight high-probability reversal zones within important time windows.”
VCP-Minervini v2This indicator is based on the famous Volatility Contraction Pattern (VCP) developed by Mark Minervini. It is designed to detect breakout setups in stocks and indices and provides a complete framework for identifying and managing them.
VCP Detection: Uses ATR to measure contracting volatility and highlights potential setups with yellow markers.
Pivot Level: Once a VCP is detected, the script automatically fixes a pivot resistance level and plots it as a red line.
Breakout Signal: When price closes above the pivot and remains above the EMA, a green marker confirms that a breakout is active.
Exit Logic: If momentum fades (volume drops below average and True Range contracts), the green marker disappears, signaling it may be time to secure profits or adjust stops.
EMA Filter: Ensures that setups are only valid in the direction of the prevailing trend by requiring price to trade above the selected EMA.
How to use it
This tool is best suited for swing traders and position traders looking for clean breakout opportunities. It is not a simple mashup of indicators but an original combination specifically built for VCP setups.
Use primarily on daily or weekly charts of liquid stocks.
Build a watchlist from yellow markers (potential setups).
Watch for price closing above the pivot line to confirm the breakout.
Manage trades while the green marker is active, and take caution when it disappears.
Adjust the parameters to fine-tune detection sensitivity for your market or trading style.
Adaptive Log Trend ChannelOne-line Summary / 一句话简介
EN: Adaptive log-scale trend channel using Pearson-optimized regression and deviation bands.
中文:基于皮尔逊优化回归的自适应对数趋势通道,带标准差波动带。
Full Description / 完整介绍
What it does / 功能
EN: This indicator fits a log-linear regression to price and builds a trend channel with ±k·σ deviation bands. It automatically selects the period with the highest Pearson correlation (R), ensuring the channel best matches the dominant market trend.
中文:该指标通过价格的对数线性回归拟合趋势,并在中线上下绘制 ±k·σ 偏差通道。它会自动选择皮尔逊相关系数 (R) 最高的周期,从而保证通道与主要趋势最贴合。
Why it’s useful / 适用价值
EN:
Naturally fits assets with multiplicative growth (crypto, tech stocks).
Adapts dynamically to different market regimes.
Provides CAGR estimates on Daily/Weekly charts for trend strength evaluation.
中文:
自然适用于呈现乘法增长的资产(如加密货币与科技股)。
可动态适应不同的市场阶段。
在日线/周线图上提供 趋势年化收益率 (CAGR),帮助评估趋势强度。
How it works / 工作原理
EN:
Computes log(price) → regression slope & intercept.
Draws a midline (log regression projection).
Upper & lower bands = ±k·σ in log space.
Info panel shows: Auto-Selected Period, Trend Strength (or Pearson’s R), and CAGR.
中文:
对价格取对数 → 计算回归斜率与截距。
绘制 中线(对数回归投影)。
上下轨 = 对数空间中的 ±k·σ。
信息面板显示:自动选择周期、趋势强度(或皮尔逊 R 值)、以及 CAGR 年化收益率。
Key Settings / 主要参数
EN:
Long-Term Mode: Uses extended periods (300–1200).
Deviation Multiplier (k): Controls channel width (default 2.0).
Styles: Colors, line type, and extension.
Panel Options: Toggle auto-period, Pearson’s R, and CAGR.
中文:
长期模式:采用更长周期 (300–1200)。
偏差倍数 (k):控制通道宽度(默认 2.0)。
样式:可设置颜色、线型、延长方式。
信息面板:可开关自动周期、皮尔逊 R、CAGR。
Notes / 注意事项
EN:
CAGR is only available on Daily/Weekly timeframes.
Regression-based tools may repaint as new bars form; treat it as context, not signals.
中文:
CAGR 仅在日线与周线周期可用。
回归类指标在新K线形成时可能重绘,仅用于趋势参考而非交易信号。
ZigZag++ + 4 EMA89 Trend Candles + BUY/SELL LabelsThis script combines ZigZag patterns, EMA89 trend detection, and custom buy/sell scalp signals. It helps identify trend direction and potential entry points in trending markets.
Features:
- ZigZag structure points
- EMA89 as dynamic trend filter
- Buy/Sell scalp markers
- HL/HH swing labels
- Works best on 15m–4h timeframes
Renko Trend Indicator with High/LowRenko Trend Indicator with High/Low
Version: 1.0
Pine Script Version: 5
Type: Indicator
Overlay: Yes
Description
The Renko Trend Indicator with High/Low provides a visual representation of market trends using Renko-style calculations based on either a fixed brick size or ATR (Average True Range). It helps traders identify trend direction, potential reversals, and key support/resistance levels.
The indicator plots Renko-based trend signals directly on your chart and provides a colored Renko close line, making trend analysis simpler and clearer.
Features
Customizable Renko Brick Size
Fixed brick size or dynamic ATR-based bricks.
Step input for precise control over brick size.
Trend Identification
Detects uptrend and downtrend based on Renko logic.
Plots visual signals for trend direction:
Green triangle below bars → Uptrend
Red triangle above bars → Downtrend
Renko Close Line
Shows the Renko-adjusted closing price as a line.
Line color changes with trend (green for uptrend, red for downtrend).
Inputs
Name Type Default Description
Brick Size float 50 Size of Renko bricks (price units)
Use ATR for Brick Size? bool false Enable ATR-based dynamic brick sizing
ATR Period int 14 Number of periods for ATR calculation if enabled
How It Works
The indicator calculates Renko bricks using either a fixed size or ATR.
It maintains internal variables:
renko_close → Current Renko price
renko_high → Highest point of the current trend
renko_low → Lowest point of the current trend
trend → Current trend direction (1 for uptrend, -1 for downtrend)
last_extreme → Last extreme point to detect trend reversal
When price moves above or below the Renko threshold, the trend is updated.
Trend signals are plotted on the chart for easy visualization.
Plots
Plot Name Description Color
Up Trend Triangle below bar when trend is up Green
Down Trend Triangle above bar when trend is down Red
Renko Close Line connecting Renko-adjusted close prices Green (up) / Red (down)
Usage
Add the indicator to any chart with your preferred timeframe.
Configure the brick size or enable ATR-based bricks for dynamic calculation.
Observe the trend triangles and Renko line to identify trend direction and potential reversals.
Can be used in combination with other indicators or strategies for trading decisions.
Notes
This indicator is for analysis purposes only and does not place trades automatically.
ATR-based bricks adapt to market volatility, while fixed bricks provide a static reference.
Works best on liquid markets with regular price movements.
Example Chart
Green triangles below bars signal a buying trend.
Red triangles above bars signal a selling trend.
The colored Renko line shows the trend progression visually.
Author
DB
Pine Script Version: 5
License: MIT
TPO Levels [VAH/POC/VAL] with Poor H/L, Single Prints & NPOCs### 🎯 Advanced Market Profile & Key Level Analysis
This script is a unique and comprehensive technical analysis tool designed to help traders understand market structure, value, and key liquidity levels using the principles of **Auction Market Theory** and **Market Profile**.
This script is unique (and shouldn't be censored) because :
It allows large history of levels to be displayed
Accurate as possible tick size
Doesn't draw a profile but only the actual levels
Supports multi-timeframe levels even on the daily mode giving macro context
There is no indicator out there that does it
While these concepts are universal, this indicator was built primarily for the dynamic, 24/7 nature of the **cryptocurrency market**. It helps you move beyond simple price action to understand *why* the market is moving, which is especially crucial in the volatile crypto space.
### ## 📊 The Concepts Behind the Calculations
To use this script effectively, it's important to understand the core concepts it is built upon. The entire script is self-contained and does not require other indicators.
* **What is Market Profile?**
Market Profile is a unique charting technique that organizes price and time data to reveal market structure. It's built from **Time Price Opportunities (TPOs)**, which are 30-minute periods of market activity. By stacking these TPOs, the script builds a distribution, showing which price levels were most accepted (heavily traded) and which were rejected (lightly traded) during a session.
* **What is the Value Area (VA)?**
The Value Area is the heart of the profile. It represents the price range where **70%** of the session's trading volume occurred. This is considered the "fair value" zone where both buyers and sellers were in general agreement.
* **Point of Control (POC):** The single price level with the most TPOs. This was the most accepted or "fairest" price of the session and acts as a gravitational line for price.
* **Value Area High (VAH):** The upper boundary of the 70% value zone.
* **Value Area Low (VAL):** The lower boundary of the 70% value zone.
VAH and VAL are dynamic support and resistance levels. Trading outside the previous session's value area can signal the start of a new trend.
***
### ## 📈 Key Features Explained
This script automatically calculates and displays the following critical market-generated information:
* **Multi-Timeframe Market Profile**
Automatically draws Daily, Weekly, and Monthly profiles, allowing you to analyze market structure across different time horizons. The script preserves up to 20 historical sessions to provide deep market context.
* **Naked Point of Control (nPOC)**
A "Naked" POC is a Point of Control from a previous session that has **not** been revisited by price. These levels often act as powerful magnets for price, representing areas of unfinished business that the market may seek to retest. The script tracks and displays Daily, Weekly, and Monthly nPOCs until they are touched.
* **Single Prints (Imbalance Zones)**
A Single Print is a price level where only one TPO traded during the session's development. This signifies a rapid, aggressive price move and an imbalanced market. These areas, like gaps in a traditional chart, are frequently revisited as the market seeks to "fill in" these thin parts of the profile.
* **Poor Structure (Unfinished Auctions)**
A **Poor High** or **Poor Low** occurs when the top or bottom of a profile is flat, with two or more TPOs at the extreme price. This suggests that the auction in that direction was weak and inconclusive. These weak structures often signal a high probability that price will eventually break that high or low.
***
### ## 💡 How to Use This Indicator
This tool is not a signal generator but an analytical framework to improve your trading decisions.
1. **Determine Market Context:** Start by asking: Is the current price trading *inside* or *outside* the previous session's Value Area?
* **Inside VA:** The market is in a state of balance or range-bound. Look for trades between the VAH and VAL.
* **Outside VA:** The market is in a state of imbalance and may be starting a trend. Look for continuation or acceptance of prices outside the prior value.
2. **Identify Key Levels:**
* Use historical **nPOCs** as potential profit targets or areas to watch for a price reaction.
* Treat historical **VAH** and **VAL** levels as significant support and resistance zones.
* Note where **Single Prints** are. These are often price magnets that may get "filled" in the future.
3. **Spot Weakness:**
* A **Poor High** suggests weak resistance that may be easily broken.
* A **Poor Low** suggests weak support, signaling a potential for a continued move lower if broken.
***
### ## ⚙️ Customization & Crypto Presets
The indicator is highly customizable, allowing you to change colors, transparency, the number of historical sessions, and more.
To help traders get started quickly, the indicator includes **built-in layout presets** specifically calibrated for major cryptocurrencies: ** BINANCE:BTCUSDT.P , BINANCE:ETHUSDT.P , and BINANCE:SOLUSDT.P **. These presets automatically adjust key visual parameters to better suit the unique price characteristics and volatility of each asset, providing an optimized view right out of the box.
***
### ## ⚠️ Disclaimer
This indicator is a tool for market analysis and should not be interpreted as direct buy or sell signals. It provides information based on historical price action, which does not guarantee future results. Trading involves significant risk, and you should always use proper risk management. This script is designed for use on standard chart types (e.g., Candlesticks, Bar) and may produce misleading information on non-standard charts.
Mayfair FX Scalper V-10 Price Action + SMC//@version=5
indicator("Mayfair FX Scalper V-10 Price Action + SMC", overlay=true)
// === INPUTS ===
rsiLength = input.int(14, title="RSI Length")
overbought = input.float(73, title="SELL Level")
oversold = input.float(31, title="BUY Level")
rsiSrc = input.source(open, title="RSI Source")
// === Color Inputs ===
entryLineColor = input.color(color.white, title="entry Label Color")
entryLabelColor = input.color(color.white, title="entry Lable Color")
slLineColor = input.color(color.red, title="Stop Loss Line Color")
slLabelColor = input.color(color.red, title="Stop Loss Label Color")
tpLineColor = input.color(color.blue, title="Take Profit Line Color")
tpLabelColor = input.color(color.blue, title="Take Profit Color")
entryTextColor = input.color(color.rgb(0, 0, 0) , title="entry Text Color")
slTextColor = input.color(color.white, title="Stop Lose Color")
tpTextColor = input.color(color.white, title="Take Profit Text Color")
//indicator("Author Info Display"
// Create table
var table infoTable = table.new(position.top_right, 2, 6, bgcolor=color.new(#000000, 1), border_width=1)
if barstate.islast
table.cell(infoTable, 0, 0, "Author:", text_color=color.white, text_size=size.small)
table.cell(infoTable, 1, 0, "MR WOW", text_color=color.rgb(255, 251, 0), text_size=size.large)
table.cell(infoTable, 0, 1, "YouTube:", text_color=color.white, text_size=size.small)
table.cell(infoTable, 1, 1, "www.youtube.com/@iammrwow", text_color=color.rgb(255, 251, 0), text_size=size.small)
table.cell(infoTable, 0, 3, "Website:", text_color=color.white, text_size=size.small)
table.cell(infoTable, 1, 3, "www.mrwowea.com", text_color=color.rgb(255, 251, 0), text_size=size.small)
// === RSI CALCULATION ===
rsi = ta.rsi(rsiSrc, rsiLength)
rawBuySignal = rsi < oversold
rawSellSignal = rsi > overbought
// === Confirmed Signals ===
isBullish = close > open
isBearish = close < open
newBuy = rawBuySignal and isBullish and close > open == false
newSell = rawSellSignal and isBearish and close < open == false
// === Trade State Variables ===
var bool inPosition = false
var bool isBuy = false
var float entryPrice = na
var float slPrice = na
var float tp1Price = na
var float tp2Price = na
var float tp3Price = na
var int entryBarIndex = na
var label labels = array.new()
var line lines = array.new()
// === Instrument & Timeframe SL/TP Setup ===
isGold = str.contains(syminfo.ticker, "XAU") or str.contains(syminfo.ticker, "GOLD")
instrumentType = syminfo.type == "crypto" ? "Crypto" : isGold ? "Gold" : syminfo.currency == "JPY" ? "JPY" : "Forex"
tf = timeframe.period
slPipsGold = tf == "1" ? 30 : tf == "3" ? 45 : tf == "5" ? 50 : tf == "15" ? 60 : 70
slPipsCrypto = tf == "1" ? 5 : tf == "3" ? 8 : tf == "5" ? 12 : tf == "15" ? 15 : 10
slPipsForex = tf == "1" ? 6 : tf == "3" ? 9 : tf == "5" ? 11 : tf == "15" ? 15 : 15
gold_slDist = 0.1 * slPipsGold
gold_tp1Dist = gold_slDist
gold_tp2Dist = gold_slDist * 2
gold_tp3Dist = gold_slDist * 3
pipSize = instrumentType == "Crypto" ? 1.0 : instrumentType == "Gold" or instrumentType == "JPY" ? 0.01 : 0.0001
slPips = instrumentType == "Crypto" ? slPipsCrypto : instrumentType == "Gold" ? slPipsGold : slPipsForex
slDist = slPips * pipSize
tp1Dist = slDist
tp2Dist = slDist * 2
tp3Dist = slDist * 3
// === Draw Line & Label ===
drawLine(y, txt, col, lblCol, extendToCurrent) =>
int lineEnd = extendToCurrent ? bar_index : entryBarIndex + 2
array.push(lines, line.new(entryBarIndex, y, lineEnd, y, color=col, width=2, extend=extend.none))
textCol = str.contains(txt, "Entry") ? entryTextColor : str.contains(txt, "Stop") ? slTextColor : tpTextColor
array.push(labels, label.new(lineEnd, y, txt, style=label.style_label_left, color=color.new(lblCol, 0), textcolor=textCol, size=size.small))
// === Check Exit ===
slHit = inPosition and ((isBuy and low <= slPrice) or (not isBuy and high >= slPrice))
tp3Hit = inPosition and ((isBuy and high >= tp3Price) or (not isBuy and low <= tp3Price))
shouldExit = slHit or tp3Hit
if shouldExit
for l in labels
label.delete(l)
array.clear(labels)
for ln in lines
line.delete(ln)
array.clear(lines)
inPosition := false
entryPrice := na
slPrice := na
tp1Price := na
tp2Price := na
tp3Price := na
entryBarIndex := na
// === Confirmed Signal with No Position ===
confirmedBuy = not inPosition and newBuy
confirmedSell = not inPosition and newSell
// === Signal Markers ===
plotshape(series=confirmedBuy, location=location.belowbar, color=color.rgb(33, 150, 243), style=shape.triangleup, text="BUY", textcolor=color.rgb(33, 150, 243))
plotshape(series=confirmedSell, location=location.abovebar, color=color.rgb(254, 254, 255), style=shape.triangledown, text="SELL", textcolor=color.rgb(239, 238, 247))
// === Entry Execution ===
if confirmedBuy or confirmedSell
entryPrice := close
entryBarIndex := bar_index
isBuy := confirmedBuy
inPosition := true
if isGold
slPrice := isBuy ? entryPrice - gold_slDist : entryPrice + gold_slDist
tp1Price := isBuy ? entryPrice + gold_tp1Dist : entryPrice - gold_tp1Dist
tp2Price := isBuy ? entryPrice + gold_tp2Dist : entryPrice - gold_tp2Dist
tp3Price := isBuy ? entryPrice + gold_tp3Dist : entryPrice - gold_tp3Dist
else
slPrice := isBuy ? entryPrice - slDist : entryPrice + slDist
tp1Price := isBuy ? entryPrice + tp1Dist : entryPrice - tp1Dist
tp2Price := isBuy ? entryPrice + tp2Dist : entryPrice - tp2Dist
tp3Price := isBuy ? entryPrice + tp3Dist : entryPrice - tp3Dist
drawLine(entryPrice, "Entry Price - After Candle Above Entry Price Then Place Trade: " + str.tostring(entryPrice), entryLineColor, entryLabelColor, false)
drawLine(slPrice, "Stop Loss: " + str.tostring(slPrice), slLineColor, slLabelColor, false)
drawLine(tp1Price, "(1:1) Take Profit: " + str.tostring(tp1Price), tpLineColor, tpLabelColor, false)
drawLine(tp2Price, "(2:1) Take Profit: " + str.tostring(tp2Price), tpLineColor, tpLabelColor, false)
drawLine(tp3Price, "(3:1) Take Profit: " + str.tostring(tp3Price), tpLineColor, tpLabelColor, false)
// === Update TP/SL Lines if Still in Trade ===
if inPosition and not (confirmedBuy or confirmedSell)
for ln in lines
line.delete(ln)
array.clear(lines)
for l in labels
label.delete(l)
array.clear(labels)
drawLine(entryPrice, "After Candle Closed Above Entry Line Buy & Below Sell :Entry Price-" + str.tostring(entryPrice), entryLineColor, entryLabelColor, true)
drawLine(slPrice, "Stop Loss: " + str.tostring(slPrice), slLineColor, slLabelColor, true)
drawLine(tp1Price, "(1:1) Take Profit: " + str.tostring(tp1Price), tpLineColor, tpLabelColor, true)
drawLine(tp2Price, "(2:1) Take Profit: " + str.tostring(tp2Price), tpLineColor, tpLabelColor, true)
drawLine(tp3Price, "(3:1) Take Profit: " + str.tostring(tp3Price), tpLineColor, tpLabelColor, true)
// === Bollinger Bands Inputs ===
bb_length = input.int(20, title="SMA & StdDev Length")
src = input.source(close, title="Source")
// === Bollinger Band Colors ===
color_upper_2_3 = input.color(color.new(#0db107, 64), title="Upper Band 2–3 Color")
color_upper_3_4 = input.color(color.new(#05c41f, 58), title="Upper Band 3–4 Color")
color_lower_2_3 = input.color(color.new(#bdbc9d, 80), title="Lower Band 2–3 Color")
color_lower_3_4 = input.color(color.new(#e9e6bf, 63), title="Lower Band 3–4 Color")
// === Bollinger Band Calculations ===
sma = ta.sma(src, bb_length)
stdev = ta.stdev(src, bb_length)
bb2_upper = sma + 2 * stdev
bb2_lower = sma - 2 * stdev
bb3_upper = sma + 3 * stdev
bb3_lower = sma - 3 * stdev
bb4_upper = sma + 4 * stdev
bb4_lower = sma - 4 * stdev
// === Hidden Plots for Fill ===
p_bb2_upper = plot(bb2_upper, color=na)
p_bb3_upper = plot(bb3_upper, color=na)
p_bb4_upper = plot(bb4_upper, color=na)
p_bb2_lower = plot(bb2_lower, color=na)
p_bb3_lower = plot(bb3_lower, color=na)
p_bb4_lower = plot(bb4_lower, color=na)
// === Band Zone Fills ===
fill(p_bb2_upper, p_bb3_upper, color=color_upper_2_3)
fill(p_bb3_upper, p_bb4_upper, color=color_upper_3_4)
fill(p_bb2_lower, p_bb3_lower, color=color_lower_2_3)
fill(p_bb3_lower, p_bb4_lower, color=color_lower_3_4)
//SMc
BULLISH_LEG = 1
BEARISH_LEG = 0
BULLISH = +1
BEARISH = -1
GREEN = #9c9c9c
RED = #9c9c9c
BLUE = #9c9c9c
GRAY = #ffffff
MONO_BULLISH = #b2b5be
MONO_BEARISH = #5d606b
HISTORICAL = 'Historical'
PRESENT = 'Present'
COLORED = 'Colored'
MONOCHROME = 'Monochrome'
ALL = 'All'
BOS = 'BOS'
CHOCH = 'CHoCH'
TINY = size.tiny
SMALL = size.small
NORMAL = size.normal
ATR = 'Atr'
RANGE = 'Cumulative Mean Range'
CLOSE = 'Close'
HIGHLOW = 'High/Low'
SOLID = '⎯⎯⎯'
DASHED = '----'
DOTTED = '····'
SMART_GROUP = 'Smart Money Concepts'
INTERNAL_GROUP = 'Real Time Internal Structure'
SWING_GROUP = 'Real Time Swing Structure'
BLOCKS_GROUP = 'Order Blocks'
EQUAL_GROUP = 'EQH/EQL'
GAPS_GROUP = 'Fair Value Gaps'
LEVELS_GROUP = 'Highs & Lows MTF'
ZONES_GROUP = 'Premium & Discount Zones'
modeTooltip = 'Allows to display historical Structure or only the recent ones'
styleTooltip = 'Indicator color theme'
showTrendTooltip = 'Display additional candles with a color reflecting the current trend detected by structure'
showInternalsTooltip = 'Display internal market structure'
internalFilterConfluenceTooltip = 'Filter non significant internal structure breakouts'
showStructureTooltip = 'Display swing market Structure'
showSwingsTooltip = 'Display swing point as labels on the chart'
showHighLowSwingsTooltip = 'Highlight most recent strong and weak high/low points on the chart'
showInternalOrderBlocksTooltip = 'Display internal order blocks on the chart Number of internal order blocks to display on the chart'
showSwingOrderBlocksTooltip = 'Display swing order blocks on the chart Number of internal swing blocks to display on the chart'
orderBlockFilterTooltip = 'Method used to filter out volatile order blocks It is recommended to use the cumulative mean range method when a low amount of data is available'
orderBlockMitigationTooltip = 'Select what values to use for order block mitigation'
showEqualHighsLowsTooltip = 'Display equal highs and equal lows on the chart'
equalHighsLowsLengthTooltip = 'Number of bars used to confirm equal highs and equal lows'
equalHighsLowsThresholdTooltip = 'Sensitivity threshold in a range (0, 1) used for the detection of equal highs & lows Lower values will return fewer but more pertinent results'
showFairValueGapsTooltip = 'Display fair values gaps on the chart'
fairValueGapsThresholdTooltip = 'Filter out non significant fair value gaps'
fairValueGapsTimeframeTooltip = 'Fair value gaps timeframe'
fairValueGapsExtendTooltip = 'Determine how many bars to extend the Fair Value Gap boxes on chart'
showPremiumDiscountZonesTooltip = 'Display premium, discount, and equilibrium zones on chart'
modeInput = input.string( HISTORICAL, 'Mode', group = SMART_GROUP, tooltip = modeTooltip, options = )
styleInput = input.string( COLORED, 'Style', group = SMART_GROUP, tooltip = styleTooltip,options = )
showTrendInput = input( false, 'Color Candles', group = SMART_GROUP, tooltip = showTrendTooltip)
showInternalsInput = input( true, 'Show Internal Structure', group = INTERNAL_GROUP, tooltip = showInternalsTooltip)
showInternalBullInput = input.string( ALL, 'Bullish Structure', group = INTERNAL_GROUP, inline = 'ibull', options = )
internalBullColorInput = input( GREEN, '', group = INTERNAL_GROUP, inline = 'ibull')
showInternalBearInput = input.string( ALL, 'Bearish Structure' , group = INTERNAL_GROUP, inline = 'ibear', options = )
internalBearColorInput = input( RED, '', group = INTERNAL_GROUP, inline = 'ibear')
internalFilterConfluenceInput = input( false, 'Confluence Filter', group = INTERNAL_GROUP, tooltip = internalFilterConfluenceTooltip)
internalStructureSize = input.string( TINY, 'Internal Label Size', group = INTERNAL_GROUP, options = )
showStructureInput = input( true, 'Show Swing Structure', group = SWING_GROUP, tooltip = showStructureTooltip)
showSwingBullInput = input.string( ALL, 'Bullish Structure', group = SWING_GROUP, inline = 'bull', options = )
swingBullColorInput = input( GREEN, '', group = SWING_GROUP, inline = 'bull')
showSwingBearInput = input.string( ALL, 'Bearish Structure', group = SWING_GROUP, inline = 'bear', options = )
swingBearColorInput = input( RED, '', group = SWING_GROUP, inline = 'bear')
swingStructureSize = input.string( SMALL, 'Swing Label Size', group = SWING_GROUP, options = )
showSwingsInput = input( false, 'Show Swings Points', group = SWING_GROUP, tooltip = showSwingsTooltip,inline = 'swings')
swingsLengthInput = input.int( 50, '', group = SWING_GROUP, minval = 10, inline = 'swings')
showHighLowSwingsInput = input( true, 'Show Strong/Weak High/Low',group = SWING_GROUP, tooltip = showHighLowSwingsTooltip)
showInternalOrderBlocksInput = input( true, 'Internal Order Blocks' , group = BLOCKS_GROUP, tooltip = showInternalOrderBlocksTooltip, inline = 'iob')
internalOrderBlocksSizeInput = input.int( 5, '', group = BLOCKS_GROUP, minval = 1, maxval = 20, inline = 'iob')
showSwingOrderBlocksInput = input( false, 'Swing Order Blocks', group = BLOCKS_GROUP, tooltip = showSwingOrderBlocksTooltip, inline = 'ob')
swingOrderBlocksSizeInput = input.int( 5, '', group = BLOCKS_GROUP, minval = 1, maxval = 20, inline = 'ob')
orderBlockFilterInput = input.string( 'Atr', 'Order Block Filter', group = BLOCKS_GROUP, tooltip = orderBlockFilterTooltip, options = )
orderBlockMitigationInput = input.string( HIGHLOW, 'Order Block Mitigation', group = BLOCKS_GROUP, tooltip = orderBlockMitigationTooltip, options = )
internalBullishOrderBlockColor = input.color(color.new(#808080, 80), 'Internal Bullish OB', group = BLOCKS_GROUP)
internalBearishOrderBlockColor = input.color(color.new(#808080, 80), 'Internal Bearish OB', group = BLOCKS_GROUP)
swingBullishOrderBlockColor = input.color(color.new(#808080, 80), 'Bullish OB', group = BLOCKS_GROUP)
swingBearishOrderBlockColor = input.color(color.new(#808080, 80), 'Bearish OB', group = BLOCKS_GROUP)
showEqualHighsLowsInput = input( true, 'Equal High/Low', group = EQUAL_GROUP, tooltip = showEqualHighsLowsTooltip)
equalHighsLowsLengthInput = input.int( 3, 'Bars Confirmation', group = EQUAL_GROUP, tooltip = equalHighsLowsLengthTooltip, minval = 1)
equalHighsLowsThresholdInput = input.float( 0.1, 'Threshold', group = EQUAL_GROUP, tooltip = equalHighsLowsThresholdTooltip, minval = 0, maxval = 0.5, step = 0.1)
equalHighsLowsSizeInput = input.string( TINY, 'Label Size', group = EQUAL_GROUP, options = )
showFairValueGapsInput = input( false, 'Fair Value Gaps', group = GAPS_GROUP, tooltip = showFairValueGapsTooltip)
fairValueGapsThresholdInput = input( true, 'Auto Threshold', group = GAPS_GROUP, tooltip = fairValueGapsThresholdTooltip)
fairValueGapsTimeframeInput = input.timeframe('', 'Timeframe', group = GAPS_GROUP, tooltip = fairValueGapsTimeframeTooltip)
fairValueGapsBullColorInput = input.color(color.new(#00ff68, 70), 'Bullish FVG' , group = GAPS_GROUP)
fairValueGapsBearColorInput = input.color(color.new(#ff0008, 70), 'Bearish FVG' , group = GAPS_GROUP)
fairValueGapsExtendInput = input.int( 1, 'Extend FVG', group = GAPS_GROUP, tooltip = fairValueGapsExtendTooltip, minval = 0)
showDailyLevelsInput = input( false, 'Daily', group = LEVELS_GROUP, inline = 'daily')
dailyLevelsStyleInput = input.string( SOLID, '', group = LEVELS_GROUP, inline = 'daily', options = )
dailyLevelsColorInput = input( BLUE, '', group = LEVELS_GROUP, inline = 'daily')
showWeeklyLevelsInput = input( false, 'Weekly', group = LEVELS_GROUP, inline = 'weekly')
weeklyLevelsStyleInput = input.string( SOLID, '', group = LEVELS_GROUP, inline = 'weekly', options = )
weeklyLevelsColorInput = input( BLUE, '', group = LEVELS_GROUP, inline = 'weekly')
showMonthlyLevelsInput = input( false, 'Monthly', group = LEVELS_GROUP, inline = 'monthly')
monthlyLevelsStyleInput = input.string( SOLID, '', group = LEVELS_GROUP, inline = 'monthly', options = )
monthlyLevelsColorInput = input( BLUE, '', group = LEVELS_GROUP, inline = 'monthly')
showPremiumDiscountZonesInput = input( false, 'Premium/Discount Zones', group = ZONES_GROUP , tooltip = showPremiumDiscountZonesTooltip)
premiumZoneColorInput = input.color( RED, 'Premium Zone', group = ZONES_GROUP)
equilibriumZoneColorInput = input.color( GRAY, 'Equilibrium Zone', group = ZONES_GROUP)
discountZoneColorInput = input.color( GREEN, 'Discount Zone', group = ZONES_GROUP)
//---------------------------------------------------------------------------------------------------------------------}
//DATA STRUCTURES & VARIABLES
//---------------------------------------------------------------------------------------------------------------------{
// @type UDT representing alerts as bool fields
// @field internalBullishBOS internal structure custom alert
// @field internalBearishBOS internal structure custom alert
// @field internalBullishCHoCH internal structure custom alert
// @field internalBearishCHoCH internal structure custom alert
// @field swingBullishBOS swing structure custom alert
// @field swingBearishBOS swing structure custom alert
// @field swingBullishCHoCH swing structure custom alert
// @field swingBearishCHoCH swing structure custom alert
// @field internalBullishOrderBlock internal order block custom alert
// @field internalBearishOrderBlock internal order block custom alert
// @field swingBullishOrderBlock swing order block custom alert
// @field swingBearishOrderBlock swing order block custom alert
// @field equalHighs equal high low custom alert
// @field equalLows equal high low custom alert
// @field bullishFairValueGap fair value gap custom alert
// @field bearishFairValueGap fair value gap custom alert
type alerts
bool internalBullishBOS = false
bool internalBearishBOS = false
bool internalBullishCHoCH = false
bool internalBearishCHoCH = false
bool swingBullishBOS = false
bool swingBearishBOS = false
bool swingBullishCHoCH = false
bool swingBearishCHoCH = false
bool internalBullishOrderBlock = false
bool internalBearishOrderBlock = false
bool swingBullishOrderBlock = false
bool swingBearishOrderBlock = false
bool equalHighs = false
bool equalLows = false
bool bullishFairValueGap = false
bool bearishFairValueGap = false
// @type UDT representing last swing extremes (top & bottom)
// @field top last top swing price
// @field bottom last bottom swing price
// @field barTime last swing bar time
// @field barIndex last swing bar index
// @field lastTopTime last top swing time
// @field lastBottomTime last bottom swing time
type trailingExtremes
float top
float bottom
int barTime
int barIndex
int lastTopTime
int lastBottomTime
// @type UDT representing Fair Value Gaps
// @field top top price
// @field bottom bottom price
// @field bias bias (BULLISH or BEARISH)
// @field topBox top box
// @field bottomBox bottom box
type fairValueGap
float top
float bottom
int bias
box topBox
box bottomBox
// @type UDT representing trend bias
// @field bias BULLISH or BEARISH
type trend
int bias
// @type UDT representing Equal Highs Lows display
// @field l_ine displayed line
// @field l_abel displayed label
type equalDisplay
line l_ine = na
label l_abel = na
// @type UDT representing a pivot point (swing point)
// @field currentLevel current price level
// @field lastLevel last price level
// @field crossed true if price level is crossed
// @field barTime bar time
// @field barIndex bar index
type pivot
float currentLevel
float lastLevel
bool crossed
int barTime = time
int barIndex = bar_index
// @type UDT representing an order block
// @field barHigh bar high
// @field barLow bar low
// @field barTime bar time
// @field bias BULLISH or BEARISH
type orderBlock
float barHigh
float barLow
int barTime
int bias
// @variable current swing pivot high
var pivot swingHigh = pivot.new(na,na,false)
// @variable current swing pivot low
var pivot swingLow = pivot.new(na,na,false)
// @variable current internal pivot high
var pivot internalHigh = pivot.new(na,na,false)
// @variable current internal pivot low
var pivot internalLow = pivot.new(na,na,false)
// @variable current equal high pivot
var pivot equalHigh = pivot.new(na,na,false)
// @variable current equal low pivot
var pivot equalLow = pivot.new(na,na,false)
// @variable swing trend bias
var trend swingTrend = trend.new(0)
// @variable internal trend bias
var trend internalTrend = trend.new(0)
// @variable equal high display
var equalDisplay equalHighDisplay = equalDisplay.new()
// @variable equal low display
var equalDisplay equalLowDisplay = equalDisplay.new()
// @variable storage for fairValueGap UDTs
var array fairValueGaps = array.new()
// @variable storage for parsed highs
var array parsedHighs = array.new()
// @variable storage for parsed lows
var array parsedLows = array.new()
// @variable storage for raw highs
var array highs = array.new()
// @variable storage for raw lows
var array lows = array.new()
// @variable storage for bar time values
var array times = array.new()
// @variable last trailing swing high and low
var trailingExtremes trailing = trailingExtremes.new()
// @variable storage for orderBlock UDTs (swing order blocks)
var array swingOrderBlocks = array.new()
// @variable storage for orderBlock UDTs (internal order blocks)
var array internalOrderBlocks = array.new()
// @variable storage for swing order blocks boxes
var array swingOrderBlocksBoxes = array.new()
// @variable storage for internal order blocks boxes
var array internalOrderBlocksBoxes = array.new()
// @variable color for swing bullish structures
var swingBullishColor = styleInput == MONOCHROME ? MONO_BULLISH : swingBullColorInput
// @variable color for swing bearish structures
var swingBearishColor = styleInput == MONOCHROME ? MONO_BEARISH : swingBearColorInput
// @variable color for bullish fair value gaps
var fairValueGapBullishColor = styleInput == MONOCHROME ? color.new(MONO_BULLISH,70) : fairValueGapsBullColorInput
// @variable color for bearish fair value gaps
var fairValueGapBearishColor = styleInput == MONOCHROME ? color.new(MONO_BEARISH,70) : fairValueGapsBearColorInput
// @variable color for premium zone
var premiumZoneColor = styleInput == MONOCHROME ? MONO_BEARISH : premiumZoneColorInput
// @variable color for discount zone
var discountZoneColor = styleInput == MONOCHROME ? MONO_BULLISH : discountZoneColorInput
// @variable bar index on current script iteration
varip int currentBarIndex = bar_index
// @variable bar index on last script iteration
varip int lastBarIndex = bar_index
// @variable alerts in current bar
alerts currentAlerts = alerts.new()
// @variable time at start of chart
var initialTime = time
// we create the needed boxes for displaying order blocks at the first execution
if barstate.isfirst
if showSwingOrderBlocksInput
for index = 1 to swingOrderBlocksSizeInput
swingOrderBlocksBoxes.push(box.new(na,na,na,na,xloc = xloc.bar_time,extend = extend.right))
if showInternalOrderBlocksInput
for index = 1 to internalOrderBlocksSizeInput
internalOrderBlocksBoxes.push(box.new(na,na,na,na,xloc = xloc.bar_time,extend = extend.right))
// @variable source to use in bearish order blocks mitigation
bearishOrderBlockMitigationSource = orderBlockMitigationInput == CLOSE ? close : high
// @variable source to use in bullish order blocks mitigation
bullishOrderBlockMitigationSource = orderBlockMitigationInput == CLOSE ? close : low
// @variable default volatility measure
atrMeasure = ta.atr(200)
// @variable parsed volatility measure by user settings
volatilityMeasure = orderBlockFilterInput == ATR ? atrMeasure : ta.cum(ta.tr)/bar_index
// @variable true if current bar is a high volatility bar
highVolatilityBar = (high - low) >= (2 * volatilityMeasure)
// @variable parsed high
parsedHigh = highVolatilityBar ? low : high
// @variable parsed low
parsedLow = highVolatilityBar ? high : low
// we store current values into the arrays at each bar
parsedHighs.push(parsedHigh)
parsedLows.push(parsedLow)
highs.push(high)
lows.push(low)
times.push(time)
//---------------------------------------------------------------------------------------------------------------------}
//USER-DEFINED FUNCTIONS
//---------------------------------------------------------------------------------------------------------------------{
// @function Get the value of the current leg, it can be 0 (bearish) or 1 (bullish)
// @returns int
leg(int size) =>
var leg = 0
newLegHigh = high > ta.highest( size)
newLegLow = low < ta.lowest( size)
if newLegHigh
leg := BEARISH_LEG
else if newLegLow
leg := BULLISH_LEG
leg
// @function Identify whether the current value is the start of a new leg (swing)
// @param leg (int) Current leg value
// @returns bool
startOfNewLeg(int leg) => ta.change(leg) != 0
// @function Identify whether the current level is the start of a new bearish leg (swing)
// @param leg (int) Current leg value
// @returns bool
startOfBearishLeg(int leg) => ta.change(leg) == -1
// @function Identify whether the current level is the start of a new bullish leg (swing)
// @param leg (int) Current leg value
// @returns bool
startOfBullishLeg(int leg) => ta.change(leg) == +1
// @function create a new label
// @param labelTime bar time coordinate
// @param labelPrice price coordinate
// @param tag text to display
// @param labelColor text color
// @param labelStyle label style
// @returns label ID
drawLabel(int labelTime, float labelPrice, string tag, color labelColor, string labelStyle) =>
var label l_abel = na
if modeInput == PRESENT
l_abel.delete()
l_abel := label.new(chart.point.new(labelTime,na,labelPrice),tag,xloc.bar_time,color=color(na),textcolor=labelColor,style = labelStyle,size = size.small)
// @function create a new line and label representing an EQH or EQL
// @param p_ivot starting pivot
// @param level price level of current pivot
// @param size how many bars ago was the current pivot detected
// @param equalHigh true for EQH, false for EQL
// @returns label ID
drawEqualHighLow(pivot p_ivot, float level, int size, bool equalHigh) =>
equalDisplay e_qualDisplay = equalHigh ? equalHighDisplay : equalLowDisplay
string tag = 'EQL'
color equalColor = swingBullishColor
string labelStyle = label.style_label_up
if equalHigh
tag := 'EQH'
equalColor := swingBearishColor
labelStyle := label.style_label_down
if modeInput == PRESENT
line.delete( e_qualDisplay.l_ine)
label.delete( e_qualDisplay.l_abel)
e_qualDisplay.l_ine := line.new(chart.point.new(p_ivot.barTime,na,p_ivot.currentLevel), chart.point.new(time ,na,level), xloc = xloc.bar_time, color = equalColor, style = line.style_dotted)
labelPosition = math.round(0.5*(p_ivot.barIndex + bar_index - size))
e_qualDisplay.l_abel := label.new(chart.point.new(na,labelPosition,level), tag, xloc.bar_index, color = color(na), textcolor = equalColor, style = labelStyle, size = equalHighsLowsSizeInput)
// @function store current structure and trailing swing points, and also display swing points and equal highs/lows
// @param size (int) structure size
// @param equalHighLow (bool) true for displaying current highs/lows
// @param internal (bool) true for getting internal structures
// @returns label ID
getCurrentStructure(int size,bool equalHighLow = false, bool internal = false) =>
currentLeg = leg(size)
newPivot = startOfNewLeg(currentLeg)
pivotLow = startOfBullishLeg(currentLeg)
pivotHigh = startOfBearishLeg(currentLeg)
if newPivot
if pivotLow
pivot p_ivot = equalHighLow ? equalLow : internal ? internalLow : swingLow
if equalHighLow and math.abs(p_ivot.currentLevel - low ) < equalHighsLowsThresholdInput * atrMeasure
drawEqualHighLow(p_ivot, low , size, false)
p_ivot.lastLevel := p_ivot.currentLevel
p_ivot.currentLevel := low
p_ivot.crossed := false
p_ivot.barTime := time
p_ivot.barIndex := bar_index
if not equalHighLow and not internal
trailing.bottom := p_ivot.currentLevel
trailing.barTime := p_ivot.barTime
trailing.barIndex := p_ivot.barIndex
trailing.lastBottomTime := p_ivot.barTime
if showSwingsInput and not internal and not equalHighLow
drawLabel(time , p_ivot.currentLevel, p_ivot.currentLevel < p_ivot.lastLevel ? 'LL' : 'HL', swingBullishColor, label.style_label_up)
else
pivot p_ivot = equalHighLow ? equalHigh : internal ? internalHigh : swingHigh
if equalHighLow and math.abs(p_ivot.currentLevel - high ) < equalHighsLowsThresholdInput * atrMeasure
drawEqualHighLow(p_ivot,high ,size,true)
p_ivot.lastLevel := p_ivot.currentLevel
p_ivot.currentLevel := high
p_ivot.crossed := false
p_ivot.barTime := time
p_ivot.barIndex := bar_index
if not equalHighLow and not internal
trailing.top := p_ivot.currentLevel
trailing.barTime := p_ivot.barTime
trailing.barIndex := p_ivot.barIndex
trailing.lastTopTime := p_ivot.barTime
if showSwingsInput and not internal and not equalHighLow
drawLabel(time , p_ivot.currentLevel, p_ivot.currentLevel > p_ivot.lastLevel ? 'HH' : 'LH', swingBearishColor, label.style_label_down)
// @function draw line and label representing a structure
// @param p_ivot base pivot point
// @param tag test to display
// @param structureColor base color
// @param lineStyle line style
// @param labelStyle label style
// @param labelSize text size
// @returns label ID
drawStructure(pivot p_ivot, string tag, color structureColor, string lineStyle, string labelStyle, string labelSize) =>
var line l_ine = line.new(na,na,na,na,xloc = xloc.bar_time)
var label l_abel = label.new(na,na)
if modeInput == PRESENT
l_ine.delete()
l_abel.delete()
l_ine := line.new(chart.point.new(p_ivot.barTime,na,p_ivot.currentLevel), chart.point.new(time,na,p_ivot.currentLevel), xloc.bar_time, color=structureColor, style=lineStyle)
l_abel := label.new(chart.point.new(na,math.round(0.5*(p_ivot.barIndex+bar_index)),p_ivot.currentLevel), tag, xloc.bar_index, color=color(na), textcolor=structureColor, style=labelStyle, size = labelSize)
// @function delete order blocks
// @param internal true for internal order blocks
// @returns orderBlock ID
deleteOrderBlocks(bool internal = false) =>
array orderBlocks = internal ? internalOrderBlocks : swingOrderBlocks
for in orderBlocks
bool crossedOderBlock = false
if bearishOrderBlockMitigationSource > eachOrderBlock.barHigh and eachOrderBlock.bias == BEARISH
crossedOderBlock := true
if internal
currentAlerts.internalBearishOrderBlock := true
else
currentAlerts.swingBearishOrderBlock := true
else if bullishOrderBlockMitigationSource < eachOrderBlock.barLow and eachOrderBlock.bias == BULLISH
crossedOderBlock := true
if internal
currentAlerts.internalBullishOrderBlock := true
else
currentAlerts.swingBullishOrderBlock := true
if crossedOderBlock
orderBlocks.remove(index)
// @function fetch and store order blocks
// @param p_ivot base pivot point
// @param internal true for internal order blocks
// @param bias BULLISH or BEARISH
// @returns void
storeOrdeBlock(pivot p_ivot,bool internal = false,int bias) =>
if (not internal and showSwingOrderBlocksInput) or (internal and showInternalOrderBlocksInput)
array a_rray = na
int parsedIndex = na
if bias == BEARISH
a_rray := parsedHighs.slice(p_ivot.barIndex,bar_index)
parsedIndex := p_ivot.barIndex + a_rray.indexof(a_rray.max())
else
a_rray := parsedLows.slice(p_ivot.barIndex,bar_index)
parsedIndex := p_ivot.barIndex + a_rray.indexof(a_rray.min())
orderBlock o_rderBlock = orderBlock.new(parsedHighs.get(parsedIndex), parsedLows.get(parsedIndex), times.get(parsedIndex),bias)
array orderBlocks = internal ? internalOrderBlocks : swingOrderBlocks
if orderBlocks.size() >= 100
orderBlocks.pop()
orderBlocks.unshift(o_rderBlock)
// @function draw order blocks as boxes
// @param internal true for internal order blocks
// @returns void
drawOrderBlocks(bool internal = false) =>
array orderBlocks = internal ? internalOrderBlocks : swingOrderBlocks
orderBlocksSize = orderBlocks.size()
if orderBlocksSize > 0
maxOrderBlocks = internal ? internalOrderBlocksSizeInput : swingOrderBlocksSizeInput
array parsedOrdeBlocks = orderBlocks.slice(0, math.min(maxOrderBlocks,orderBlocksSize))
array b_oxes = internal ? internalOrderBlocksBoxes : swingOrderBlocksBoxes
for in parsedOrdeBlocks
orderBlockColor = styleInput == MONOCHROME ? (eachOrderBlock.bias == BEARISH ? color.new(MONO_BEARISH,80) : color.new(MONO_BULLISH,80)) : internal ? (eachOrderBlock.bias == BEARISH ? internalBearishOrderBlockColor : internalBullishOrderBlockColor) : (eachOrderBlock.bias == BEARISH ? swingBearishOrderBlockColor : swingBullishOrderBlockColor)
box b_ox = b_oxes.get(index)
b_ox.set_top_left_point( chart.point.new(eachOrderBlock.barTime,na,eachOrderBlock.barHigh))
b_ox.set_bottom_right_point(chart.point.new(last_bar_time,na,eachOrderBlock.barLow))
b_ox.set_border_color( internal ? na : orderBlockColor)
b_ox.set_bgcolor( orderBlockColor)
// @function detect and draw structures, also detect and store order blocks
// @param internal true for internal structures or order blocks
// @returns void
displayStructure(bool internal = false) =>
var bullishBar = true
var bearishBar = true
if internalFilterConfluenceInput
bullishBar := high - math.max(close, open) > math.min(close, open - low)
bearishBar := high - math.max(close, open) < math.min(close, open - low)
pivot p_ivot = internal ? internalHigh : swingHigh
trend t_rend = internal ? internalTrend : swingTrend
lineStyle = internal ? line.style_dashed : line.style_solid
labelSize = internal ? internalStructureSize : swingStructureSize
extraCondition = internal ? internalHigh.currentLevel != swingHigh.currentLevel and bullishBar : true
bullishColor = styleInput == MONOCHROME ? MONO_BULLISH : internal ? internalBullColorInput : swingBullColorInput
if ta.crossover(close,p_ivot.currentLevel) and not p_ivot.crossed and extraCondition
string tag = t_rend.bias == BEARISH ? CHOCH : BOS
if internal
currentAlerts.internalBullishCHoCH := tag == CHOCH
currentAlerts.internalBullishBOS := tag == BOS
else
currentAlerts.swingBullishCHoCH := tag == CHOCH
currentAlerts.swingBullishBOS := tag == BOS
p_ivot.crossed := true
t_rend.bias := BULLISH
displayCondition = internal ? showInternalsInput and (showInternalBullInput == ALL or (showInternalBullInput == BOS and tag != CHOCH) or (showInternalBullInput == CHOCH and tag == CHOCH)) : showStructureInput and (showSwingBullInput == ALL or (showSwingBullInput == BOS and tag != CHOCH) or (showSwingBullInput == CHOCH and tag == CHOCH))
if displayCondition
drawStructure(p_ivot,tag,bullishColor,lineStyle,label.style_label_down,labelSize)
if (internal and showInternalOrderBlocksInput) or (not internal and showSwingOrderBlocksInput)
storeOrdeBlock(p_ivot,internal,BULLISH)
p_ivot := internal ? internalLow : swingLow
extraCondition := internal ? internalLow.currentLevel != swingLow.currentLevel and bearishBar : true
bearishColor = styleInput == MONOCHROME ? MONO_BEARISH : internal ? internalBearColorInput : swingBearColorInput
if ta.crossunder(close,p_ivot.currentLevel) and not p_ivot.crossed and extraCondition
string tag = t_rend.bias == BULLISH ? CHOCH : BOS
if internal
currentAlerts.internalBearishCHoCH := tag == CHOCH
currentAlerts.internalBearishBOS := tag == BOS
else
currentAlerts.swingBearishCHoCH := tag == CHOCH
currentAlerts.swingBearishBOS := tag == BOS
p_ivot.crossed := true
t_rend.bias := BEARISH
displayCondition = internal ? showInternalsInput and (showInternalBearInput == ALL or (showInternalBearInput == BOS and tag != CHOCH) or (showInternalBearInput == CHOCH and tag == CHOCH)) : showStructureInput and (showSwingBearInput == ALL or (showSwingBearInput == BOS and tag != CHOCH) or (showSwingBearInput == CHOCH and tag == CHOCH))
if displayCondition
drawStructure(p_ivot,tag,bearishColor,lineStyle,label.style_label_up,labelSize)
if (internal and showInternalOrderBlocksInput) or (not internal and showSwingOrderBlocksInput)
storeOrdeBlock(p_ivot,internal,BEARISH)
// @function draw one fair value gap box (each fair value gap has two boxes)
// @param leftTime left time coordinate
// @param rightTime right time coordinate
// @param topPrice top price level
// @param bottomPrice bottom price level
// @param boxColor box color
// @returns box ID
fairValueGapBox(leftTime,rightTime,topPrice,bottomPrice,boxColor) => box.new(chart.point.new(leftTime,na,topPrice),chart.point.new(rightTime + fairValueGapsExtendInput * (time-time ),na,bottomPrice), xloc=xloc.bar_time, border_color = boxColor, bgcolor = boxColor)
// @function delete fair value gaps
// @returns fairValueGap ID
deleteFairValueGaps() =>
for in fairValueGaps
if (low < eachFairValueGap.bottom and eachFairValueGap.bias == BULLISH) or (high > eachFairValueGap.top and eachFairValueGap.bias == BEARISH)
eachFairValueGap.topBox.delete()
eachFairValueGap.bottomBox.delete()
fairValueGaps.remove(index)
// @function draw fair value gaps
// @returns fairValueGap ID
drawFairValueGaps() =>
= request.security(syminfo.tickerid, fairValueGapsTimeframeInput, [close , open , time , high , low , time , high , low ],lookahead = barmerge.lookahead_on)
barDeltaPercent = (lastClose - lastOpen) / (lastOpen * 100)
newTimeframe = timeframe.change(fairValueGapsTimeframeInput)
threshold = fairValueGapsThresholdInput ? ta.cum(math.abs(newTimeframe ? barDeltaPercent : 0)) / bar_index * 2 : 0
bullishFairValueGap = currentLow > last2High and lastClose > last2High and barDeltaPercent > threshold and newTimeframe
bearishFairValueGap = currentHigh < last2Low and lastClose < last2Low and -barDeltaPercent > threshold and newTimeframe
if bullishFairValueGap
currentAlerts.bullishFairValueGap := true
fairValueGaps.unshift(fairValueGap.new(currentLow,last2High,BULLISH,fairValueGapBox(lastTime,currentTime,currentLow,math.avg(currentLow,last2High),fairValueGapBullishColor),fairValueGapBox(lastTime,currentTime,math.avg(currentLow,last2High),last2High,fairValueGapBullishColor)))
if bearishFairValueGap
currentAlerts.bearishFairValueGap := true
fairValueGaps.unshift(fairValueGap.new(currentHigh,last2Low,BEARISH,fairValueGapBox(lastTime,currentTime,currentHigh,math.avg(currentHigh,last2Low),fairValueGapBearishColor),fairValueGapBox(lastTime,currentTime,math.avg(currentHigh,last2Low),last2Low,fairValueGapBearishColor)))
// @function get line style from string
// @param style line style
// @returns string
getStyle(string style) =>
switch style
SOLID => line.style_solid
DASHED => line.style_dashed
DOTTED => line.style_dotted
// @function draw MultiTimeFrame levels
// @param timeframe base timeframe
// @param sameTimeframe true if chart timeframe is same as base timeframe
// @param style line style
// @param levelColor line and text color
// @returns void
drawLevels(string timeframe, bool sameTimeframe, string style, color levelColor) =>
= request.security(syminfo.tickerid, timeframe, [high , low , time , time],lookahead = barmerge.lookahead_on)
float parsedTop = sameTimeframe ? high : topLevel
float parsedBottom = sameTimeframe ? low : bottomLevel
int parsedLeftTime = sameTimeframe ? time : leftTime
int parsedRightTime = sameTimeframe ? time : rightTime
int parsedTopTime = time
int parsedBottomTime = time
if not sameTimeframe
int leftIndex = times.binary_search_rightmost(parsedLeftTime)
int rightIndex = times.binary_search_rightmost(parsedRightTime)
array timeArray = times.slice(leftIndex,rightIndex)
array topArray = highs.slice(leftIndex,rightIndex)
array bottomArray = lows.slice(leftIndex,rightIndex)
parsedTopTime := timeArray.size() > 0 ? timeArray.get(topArray.indexof(topArray.max())) : initialTime
parsedBottomTime := timeArray.size() > 0 ? timeArray.get(bottomArray.indexof(bottomArray.min())) : initialTime
var line topLine = line.new(na, na, na, na, xloc = xloc.bar_time, color = levelColor, style = getStyle(style))
var line bottomLine = line.new(na, na, na, na, xloc = xloc.bar_time, color = levelColor, style = getStyle(style))
var label topLabel = label.new(na, na, xloc = xloc.bar_time, text = str.format('P{0}H',timeframe), color=color(na), textcolor = levelColor, size = size.small, style = label.style_label_left)
var label bottomLabel = label.new(na, na, xloc = xloc.bar_time, text = str.format('P{0}L',timeframe), color=color(na), textcolor = levelColor, size = size.small, style = label.style_label_left)
topLine.set_first_point( chart.point.new(parsedTopTime,na,parsedTop))
topLine.set_second_point( chart.point.new(last_bar_time + 20 * (time-time ),na,parsedTop))
topLabel.set_point( chart.point.new(last_bar_time + 20 * (time-time ),na,parsedTop))
bottomLine.set_first_point( chart.point.new(parsedBottomTime,na,parsedBottom))
bottomLine.set_second_point(chart.point.new(last_bar_time + 20 * (time-time ),na,parsedBottom))
bottomLabel.set_point( chart.point.new(last_bar_time + 20 * (time-time ),na,parsedBottom))
// @function true if chart timeframe is higher than provided timeframe
// @param timeframe timeframe to check
// @returns bool
higherTimeframe(string timeframe) => timeframe.in_seconds() > timeframe.in_seconds(timeframe)
// @function update trailing swing points
// @returns int
updateTrailingExtremes() =>
trailing.top := math.max(high,trailing.top)
trailing.lastTopTime := trailing.top == high ? time : trailing.lastTopTime
trailing.bottom := math.min(low,trailing.bottom)
trailing.lastBottomTime := trailing.bottom == low ? time : trailing.lastBottomTime
// @function draw trailing swing points
// @returns void
drawHighLowSwings() =>
var line topLine = line.new(na, na, na, na, color = swingBearishColor, xloc = xloc.bar_time)
var line bottomLine = line.new(na, na, na, na, color = swingBullishColor, xloc = xloc.bar_time)
var label topLabel = label.new(na, na, color=color(na), textcolor = swingBearishColor, xloc = xloc.bar_time, style = label.style_label_down, size = size.tiny)
var label bottomLabel = label.new(na, na, color=color(na), textcolor = swingBullishColor, xloc = xloc.bar_time, style = label.style_label_up, size = size.tiny)
rightTimeBar = last_bar_time + 20 * (time - time )
topLine.set_first_point( chart.point.new(trailing.lastTopTime, na, trailing.top))
topLine.set_second_point( chart.point.new(rightTimeBar, na, trailing.top))
topLabel.set_point( chart.point.new(rightTimeBar, na, trailing.top))
topLabel.set_text( swingTrend.bias == BEARISH ? 'Strong High' : 'Weak High')
bottomLine.set_first_point( chart.point.new(trailing.lastBottomTime, na, trailing.bottom))
bottomLine.set_second_point(chart.point.new(rightTimeBar, na, trailing.bottom))
bottomLabel.set_point( chart.point.new(rightTimeBar, na, trailing.bottom))
bottomLabel.set_text( swingTrend.bias == BULLISH ? 'Strong Low' : 'Weak Low')
// @function draw a zone with a label and a box
// @param labelLevel price level for label
// @param labelIndex bar index for label
// @param top top price level for box
// @param bottom bottom price level for box
// @param tag text to display
// @param zoneColor base color
// @param style label style
// @returns void
drawZone(float labelLevel, int labelIndex, float top, float bottom, string tag, color zoneColor, string style) =>
var label l_abel = label.new(na,na,text = tag, color=color(na),textcolor = zoneColor, style = style, size = size.small)
var box b_ox = box.new(na,na,na,na,bgcolor = color.new(zoneColor,80),border_color = color(na), xloc = xloc.bar_time)
b_ox.set_top_left_point( chart.point.new(trailing.barTime,na,top))
b_ox.set_bottom_right_point(chart.point.new(last_bar_time,na,bottom))
l_abel.set_point( chart.point.new(na,labelIndex,labelLevel))
// @function draw premium/discount zones
// @returns void
drawPremiumDiscountZones() =>
drawZone(trailing.top, math.round(0.5*(trailing.barIndex + last_bar_index)), trailing.top, 0.95*trailing.top + 0.05*trailing.bottom, 'Premium', premiumZoneColor, label.style_label_down)
equilibriumLevel = math.avg(trailing.top, trailing.bottom)
drawZone(equilibriumLevel, last_bar_index, 0.525*trailing.top + 0.475*trailing.bottom, 0.525*trailing.bottom + 0.475*trailing.top, 'Equilibrium', equilibriumZoneColorInput, label.style_label_left)
drawZone(trailing.bottom, math.round(0.5*(trailing.barIndex + last_bar_index)), 0.95*trailing.bottom + 0.05*trailing.top, trailing.bottom, 'Discount', discountZoneColor, label.style_label_up)
//---------------------------------------------------------------------------------------------------------------------}
//MUTABLE VARIABLES & EXECUTION
//---------------------------------------------------------------------------------------------------------------------{
parsedOpen = showTrendInput ? open : na
candleColor = internalTrend.bias == BULLISH ? swingBullishColor : swingBearishColor
plotcandle(parsedOpen,high,low,close,color = candleColor, wickcolor = candleColor, bordercolor = candleColor)
if showHighLowSwingsInput or showPremiumDiscountZonesInput
updateTrailingExtremes()
if showHighLowSwingsInput
drawHighLowSwings()
if showPremiumDiscountZonesInput
drawPremiumDiscountZones()
if showFairValueGapsInput
deleteFairValueGaps()
getCurrentStructure(swingsLengthInput,false)
getCurrentStructure(5,false,true)
if showEqualHighsLowsInput
getCurrentStructure(equalHighsLowsLengthInput,true)
if showInternalsInput or showInternalOrderBlocksInput or showTrendInput
displayStructure(true)
if showStructureInput or showSwingOrderBlocksInput or showHighLowSwingsInput
displayStructure()
if showInternalOrderBlocksInput
deleteOrderBlocks(true)
if showSwingOrderBlocksInput
deleteOrderBlocks()
if showFairValueGapsInput
drawFairValueGaps()
if barstate.islastconfirmedhistory or barstate.islast
if showInternalOrderBlocksInput
drawOrderBlocks(true)
if showSwingOrderBlocksInput
drawOrderBlocks()
lastBarIndex := currentBarIndex
currentBarIndex := bar_index
newBar = currentBarIndex != lastBarIndex
if barstate.islastconfirmedhistory or (barstate.isrealtime and newBar)
if showDailyLevelsInput and not higherTimeframe('D')
drawLevels('D',timeframe.isdaily,dailyLevelsStyleInput,dailyLevelsColorInput)
if showWeeklyLevelsInput and not higherTimeframe('W')
drawLevels('W',timeframe.isweekly,weeklyLevelsStyleInput,weeklyLevelsColorInput)
if showMonthlyLevelsInput and not higherTimeframe('M')
drawLevels('M',timeframe.ismonthly,monthlyLevelsStyleInput,monthlyLevelsColorInput)
//---------------------------------------------------------------------------------------------------------------------}
//ALERTS
//---------------------------------------------------------------------------------------------------------------------{
alertcondition(currentAlerts.internalBullishBOS, 'Internal Bullish BOS', 'Internal Bullish BOS formed')
alertcondition(currentAlerts.internalBullishCHoCH, 'Internal Bullish CHoCH', 'Internal Bullish CHoCH formed')
alertcondition(currentAlerts.internalBearishBOS, 'Internal Bearish BOS', 'Internal Bearish BOS formed')
alertcondition(currentAlerts.internalBearishCHoCH, 'Internal Bearish CHoCH', 'Internal Bearish CHoCH formed')
alertcondition(currentAlerts.swingBullishBOS, 'Bullish BOS', 'Internal Bullish BOS formed')
alertcondition(currentAlerts.swingBullishCHoCH, 'Bullish CHoCH', 'Internal Bullish CHoCH formed')
alertcondition(currentAlerts.swingBearishBOS, 'Bearish BOS', 'Bearish BOS formed')
alertcondition(currentAlerts.swingBearishCHoCH, 'Bearish CHoCH', 'Bearish CHoCH formed')
alertcondition(currentAlerts.internalBullishOrderBlock, 'Bullish Internal OB Breakout', 'Price broke bullish internal OB')
alertcondition(currentAlerts.internalBearishOrderBlock, 'Bearish Internal OB Breakout', 'Price broke bearish internal OB')
alertcondition(currentAlerts.swingBullishOrderBlock, 'Bullish Swing OB Breakout', 'Price broke bullish swing OB')
alertcondition(currentAlerts.swingBearishOrderBlock, 'Bearish Swing OB Breakout', 'Price broke bearish swing OB')
alertcondition(currentAlerts.equalHighs, 'Equal Highs', 'Equal highs detected')
alertcondition(currentAlerts.equalLows, 'Equal Lows', 'Equal lows detected')
alertcondition(currentAlerts.bullishFairValueGap, 'Bullish FVG', 'Bullish FVG formed')
alertcondition(currentAlerts.bearishFairValueGap, 'Bearish FVG', 'Bearish FVG formed')
//---------------------------------------------------------------------------------------------------------------------}
Harmonic Super GuppyHarmonic Super Guppy – Harmonic & Golden Ratio Trend Analysis Framework
Overview
Harmonic Super Guppy is a comprehensive trend analysis and visualization tool that evolves the classic Guppy Multiple Moving Average (GMMA) methodology, pioneered by Daryl Guppy to visualize the interaction between short-term trader behavior and long-term investor trends. into a harmonic and phase-based market framework. By combining harmonic weighting, golden ratio phasing, and multiple moving averages, it provides traders with a deep understanding of market structure, momentum, and trend alignment. Fast and slow line groups visually differentiate short-term trader activity from longer-term investor positioning, while adaptive fills and dynamic coloring clearly illustrate trend coherence, expansion, and contraction in real time.
Traditional GMMA focuses primarily on moving average convergence and divergence. Harmonic Super Guppy extends this concept, integrating frequency-aware harmonic analysis and golden ratio modulation, allowing traders to detect subtle cyclical forces and early trend shifts before conventional moving averages would react. This is particularly valuable for traders seeking to identify early trend continuation setups, preemptive breakout entries, and potential trend exhaustion zones. The indicator provides a multi-dimensional view, making it suitable for scalping, intraday trading, swing setups, and even longer-term position strategies.
The visual structure of Harmonic Super Guppy is intentionally designed to convey trend clarity without oversimplification. Fast lines reflect short-term trader sentiment, slow lines capture longer-term investor alignment, and fills highlight compression or expansion. The adaptive color coding emphasizes trend alignment: strong green for bullish alignment, strong red for bearish, and subtle gray tones for indecision. This allows traders to quickly gauge market conditions while preserving the granularity necessary for sophisticated analysis.
How It Works
Harmonic Super Guppy uses a combination of harmonic averaging, golden ratio phasing, and adaptive weighting to generate its signals.
Harmonic Weighting : Each moving average integrates three layers of harmonics:
Primary harmonic captures the dominant cyclical structure of the market.
Secondary harmonic introduces a complementary frequency for oscillatory nuance.
Tertiary harmonic smooths higher-frequency noise while retaining meaningful trend signals.
Golden Ratio Phase : Phases of each harmonic contribution are adjusted using the golden ratio (default φ = 1.618), ensuring alignment with natural market rhythms. This reduces lag and allows traders to detect trend shifts earlier than conventional moving averages.
Adaptive Trend Detection : Fast SMAs are compared against slow SMAs to identify structural trends:
UpTrend : Fast SMA exceeds slow SMA.
DownTrend : Fast SMA falls below slow SMA.
Frequency Scaling : The wave frequency setting allows traders to modulate responsiveness versus smoothing. Higher frequency emphasizes short-term moves, while lower frequency highlights structural trends. This enables adaptation across asset classes with different volatility characteristics.
Through this combination, Harmonic Super Guppy captures micro and macro market cycles, helping traders distinguish between transient noise and genuine trend development. The multi-harmonic approach amplifies meaningful price action while reducing false signals inherent in standard moving averages.
Interpretation
Harmonic Super Guppy provides a multi-dimensional perspective on market dynamics:
Trend Analysis : Alignment of fast and slow lines reveals trend direction and strength. Expanding harmonics indicate momentum building, while contraction signals weakening conditions or potential reversals.
Momentum & Volatility : Rapid expansion of fast lines versus slow lines reflects short-term bullish or bearish pressure. Compression often precedes breakout scenarios or volatility expansion. Traders can quickly gauge trend vigor and potential turning points.
Market Context : The indicator overlays harmonic and structural insights without dictating entry or exit points. It complements order blocks, liquidity zones, oscillators, and other technical frameworks, providing context for informed decision-making.
Phase Divergence Detection : Subtle divergence between harmonic layers (primary, secondary, tertiary) often signals early exhaustion in trends or hidden strength, offering preemptive insight into potential reversals or sustained continuation.
By observing both structural alignment and harmonic expansion/contraction, traders gain a clear sense of when markets are trending with conviction versus when conditions are consolidating or becoming unpredictable. This allows for proactive trade management, rather than reactive responses to lagging indicators.
Strategy Integration
Harmonic Super Guppy adapts to various trading methodologies with clear, actionable guidance.
Trend Following : Enter positions when fast and slow lines are aligned and harmonics are expanding. The broader the alignment, the stronger the confirmation of trend persistence. For example:
A fast line crossover above slow lines with expanding fills confirms momentum-driven continuation.
Traders can use harmonic amplitude as a filter to reduce entries against prevailing trends.
Breakout Trading : Periods of line compression indicate potential volatility expansion. When fast lines diverge from slow lines after compression, this often precedes breakouts. Traders can combine this visual cue with structural supports/resistances or order flow analysis to improve timing and precision.
Exhaustion and Reversals : Divergences between harmonic components, or contraction of fast lines relative to slow lines, highlight weakening trends. This can indicate liquidity exhaustion, trend fatigue, or corrective phases. For example:
A flattening fast line group above a rising slow line can hint at short-term overextension.
Traders may use these signals to tighten stops, take partial profits, or prepare for contrarian setups.
Multi-Timeframe Analysis : Overlay slow lines from higher timeframes on lower timeframe charts to filter noise and trade in alignment with larger market structures. For example:
A daily bullish alignment combined with a 15-minute breakout pattern increases probability of a successful intraday trade.
Conversely, a higher timeframe divergence can warn against taking counter-trend trades in lower timeframes.
Adaptive Trade Management : Harmonic expansion/contraction can guide dynamic risk management:
Stops may be adjusted according to slow line support/resistance or harmonic contraction zones.
Position sizing can be modulated based on harmonic amplitude and compression levels, optimizing risk-reward without rigid rules.
Technical Implementation Details
Harmonic Super Guppy is powered by a multi-layered harmonic and phase calculation engine:
Harmonic Processing : Primary, secondary, and tertiary harmonics are calculated per period to capture multiple market cycles simultaneously. This reduces noise and amplifies meaningful signals.
Golden Ratio Modulation : Phase adjustments based on φ = 1.618 align harmonic contributions with natural market rhythms, smoothing lag and improving predictive value.
Adaptive Trend Scaling : Fast line expansion reflects short-term momentum; slow lines provide structural trend context. Fills adapt dynamically based on alignment intensity and harmonic amplitude.
Multi-Factor Trend Analysis : Trend strength is determined by alignment of fast and slow lines over multiple bars, expansion/contraction of harmonic amplitudes, divergences between primary, secondary, and tertiary harmonics and phase synchronization with golden ratio cycles.
These computations allow the indicator to be highly responsive yet smooth, providing traders with actionable insights in real time without overloading visual complexity.
Optimal Application Parameters
Asset-Specific Guidance:
Forex Majors : Wave frequency 1.0–2.0, φ = 1.618–1.8
Large-Cap Equities : Wave frequency 0.8–1.5, φ = 1.5–1.618
Cryptocurrency : Wave frequency 1.2–3.0, φ = 1.618–2.0
Index Futures : Wave frequency 0.5–1.5, φ = 1.618
Timeframe Optimization:
Scalping (1–5min) : Emphasize fast lines, higher frequency for micro-move capture.
Day Trading (15min–1hr) : Balance fast/slow interactions for trend confirmation.
Swing Trading (4hr–Daily) : Focus on slow lines for structural guidance, fast lines for entry timing.
Position Trading (Daily–Weekly) : Slow lines dominate; harmonics highlight long-term cycles.
Performance Characteristics
High Effectiveness Conditions:
Clear separation between short-term and long-term trends.
Moderate-to-high volatility environments.
Assets with consistent volume and price rhythm.
Reduced Effectiveness:
Flat or extremely low volatility markets.
Erratic assets with frequent gaps or algorithmic dominance.
Ultra-short timeframes (<1min), where noise dominates.
Integration Guidelines
Signal Confirmation : Confirm alignment of fast and slow lines over multiple bars. Expansion of harmonic amplitude signals trend persistence.
Risk Management : Place stops beyond slow line support/resistance. Adjust sizing based on compression/expansion zones.
Advanced Feature Settings :
Frequency tuning for different volatility environments.
Phase analysis to track divergences across harmonics.
Use fills and amplitude patterns as a guide for dynamic trade management.
Multi-timeframe confirmation to filter noise and align with structural trends.
Disclaimer
Harmonic Super Guppy is a trend analysis and visualization tool, not a guaranteed profit system. Optimal performance requires proper wave frequency, golden ratio phase, and line visibility settings per asset and timeframe. Traders should combine the indicator with other technical frameworks and maintain disciplined risk management practices.
ZigZag++ + 4 EMA89 Trend Candles + BUY/SELL LabelsThis script combines ZigZag patterns, EMA89 trend detection, and custom buy/sell scalp signals. It helps identify trend direction and potential entry points in trending markets.
Features:
- ZigZag structure points
- EMA89 as dynamic trend filter
- Buy/Sell scalp markers
- HL/HH swing labels
- Works best on 15m–4h timeframes
MTF QFG (Quarter Fib Grid)The MTF QFG (Quarter Fib Grid) calculates quarter Fibonacci levels based on the previous daily, weekly, or monthly high/low. These levels act as potential support and resistance zones. Suitable for scalping, swing trading, or identifying key price reactions.
AlgoGram Trend Identifier📊 Algogram Trend Identifier (ATI)
The Algogram Trend Identifier (ATI) is a powerful trend-following oscillator designed to help traders identify market direction, momentum strength, divergences, and consolidation zones across multiple timeframes.
🔑 Key Features:
Multi-Timeframe Presets – Choose from 5m, 15m (default), 30m, 1h, and Daily for optimized settings.
Adaptive ALMA Calculation – Uses ALMA smoothing with dynamic thresholds to detect clean trend shifts.
Trend Highlighting – Visual coloring of oscillator and optional bar coloring for quick market bias recognition.
Customizable Thresholds & Bands – Fine-tune upper/lower thresholds, consolidation zones, and band multipliers.
Consolidation Detection – Highlights when the market is moving sideways with adjustable parameters.
Divergence Detection – Automatically detects bullish & bearish divergences with optional lines and dots.
Dynamic Alerts – Built-in alerts for:
Crossing thresholds
Zero line crosses
Uptrend / Downtrend detection
Bullish / Bearish divergences
RMS consolidation breakouts
🎯 How to Use:
Above Zero Line → Bullish trend bias.
Below Zero Line → Bearish trend bias.
Consolidation Zone → Market may range or prepare for breakout.
Bullish Divergence → Potential reversal to upside.
Bearish Divergence → Potential reversal to downside.
⚡ Best For:
Swing Traders, Scalpers, and Positional Traders
Identifying trend strength, early reversals, and breakout opportunities
Works on stocks, crypto, forex, and indices
PSDIGreen Zone → Potential Buy Area
Price is near support.
Red Zone → Potential Sell Area
Price is near resistance.
EMA Lines
Blue (EMA50) above Orange (EMA200): Trend up → favors buys.
Blue below Orange: Trend down → favors sells.
How to Use
Look at zones and trend.
Price near green + trend up → consider long.
Price near red + trend down → consider short.
NOTE: When in uptrend, only follow green zones. When in down trend only follow red zones.
Triple RSI | MisinkoMasterThe Triple Relative Strength Index is a new trend following tool designed to capture reversals in trends, minimize noise while maximizing speed using borrowed concepts from other MAs that were enhanced for maximum efficiency!
How does it work?
The TRSI is designed to capture reversals, while maintaining low noise like so:
Calculate RSIs over 3 lengths:
1. n (default)
2. n/2 (default length divided by 2)
3. √n (square root of n)
Then it adds together RSIs of √n and n/2 periods and subtracts the RSI with the default length.
This is pretty noisy, so we smooth it like so:
First apply RMA with n/2 length
Then we apply on top of that RMA with √n length
And then finish it of with using HMA with √n length
This provides us with smooth, responsive, accurate signals that can enhance our strategy, tell us what is going on in the market right now, capture big moves and so on.
Methodology
The RSI is a really good and robust indicator which works really well for both mean reversion and trend following, by enhancing it in the way I described above, we can enhance its power even further, gaining an edge in the market that is quite significant
I left it open source so you all can code it in your strategys and make it the best,
Good luck Gs, see you soon :)
Target Trend+vova13this indicator shows trend plus alerts
The Target Trend indicator is a trend-following tool designed to assist traders in capturing directional moves while managing entry, stop loss, and profit targets visually on the chart. Using adaptive SMA bands as the core trend detection method, this indicator dynamically identifies shifts in trend direction and provides structured exit points through customizable target levels.
EMA Trend Bars + Optional VWAP GateIndicator: EMA Trend Bars + Optional VWAP Gate
What it does
• Colors your bars green (up), red (down), or gray (neutral) based on whether price is above or below a chosen EMA.
• Adds an optional VWAP filter (gate): only confirms green if price is above both EMA and VWAP, red if below both.
• Lets you pick source (HLC3, Close, or Heikin Ashi) to align with your charting style.
• Plots the EMA and (optionally) VWAP for reference.
• Includes alerts when the trend flips from down → up or up → down (static text, TradingView-friendly).
• Has an optional buffer (in ticks) so you don’t get whipsawed right at the EMA line.
⸻
KISS (Keep It Simple, Stupid)
The whole idea is to strip away noise and keep the system as lean as possible:
• One trend line (EMA) → simple bias filter.
• One value anchor (VWAP) → session’s fair price.
• Clean colors (green/red/gray) → quick glance = instant bias.
• No complex confluence stacks → less decision fatigue.
• Optional buffer → avoids chop without adding unnecessary rules.
The KISS principle here: price vs EMA + optional VWAP gate = trend bias. That’s it.
⸻
How to use it
1. Pick your EMA length:
• 34 is a balanced default for intraday scalping.
• Shorter (e.g., 21) = faster, more flips.
• Longer (e.g., 55/89) = slower, smoother trend.
2. Decide if VWAP filter stays ON:
• VWAP ON = fewer trades, higher confluence (good for patient entries).
• VWAP OFF = more trades, may catch earlier flips (good for fast scalping).
3. Read the bars:
• Green = only look for longs.
• Red = only look for shorts.
• Gray = stand aside (conflict or chop).
4. Alerts:
• Add “Trend Up” or “Trend Down” alerts for quick bias changes.
• Best used for heads-up, not blind auto-entries.
5. Buffer setting:
• 0 ticks = raw flips at EMA.
• 1–2 ticks = prevents micro whipsaws.
• Adjust depending on your instrument’s volatility (NQ is spikier, MES smoother).