Swing Z – Crypto Trading Algorithm | Zillennial Technologies IncSwing Z by Zillennial Technologies Inc. is an advanced algorithmic framework built specifically for cryptocurrency markets. It integrates multiple layers of technical analysis into a single decision-support tool, generating buy and sell signals only when several independent confirmations align.
Core Concept
Swing Z fuses trend structure, momentum oscillators, volatility signals, and price action tools to capture high-probability trading opportunities in volatile crypto environments.
Trend Structure (EMA 9, 21, 50, 200)
Short-term EMAs (9 & 21) detect immediate momentum shifts.
Longer-term EMAs (50 & 200) define the broader trend and dynamic support/resistance.
Momentum & Confirmation Layer
RSI measures relative strength and market conditions.
MACD crossovers confirm momentum shifts and trend continuations.
Volatility & Market Pressure
TTM Squeeze highlights compression zones likely to precede breakouts.
Volume analysis confirms conviction behind directional moves.
VWAP (Volume Weighted Average Price) establishes intraday value zones and institutional benchmarks.
Price Action Filters
Fibonacci retracements are integrated to identify key reversal and continuation levels.
Signals are produced only when multiple conditions agree, reducing noise and improving reliability in fast-moving crypto markets.
Features
Tailored for cryptocurrency trading across major pairs (BTC, ETH, and altcoins).
Works effectively on swing and trend-based timeframes (1H–1D).
Combines trend, momentum, volatility, and price action into a single framework.
Generates clear Buy/Sell markers and integrates with TradingView alerts.
How to Use
Apply to a clean chart for the clearest visualization.
Use Swing Z as a swing trading tool, aligning entries with both trend structure and momentum confirmation.
Combine with your own stop-loss, take-profit, and position sizing rules.
Avoid application on non-standard chart types such as Renko, Heikin Ashi, or Point & Figure, which may distort results.
Disclaimer
Swing Z is designed as a decision-support tool, not financial advice.
All backtesting should use realistic risk, commission, and slippage assumptions.
Past results do not guarantee future performance.
Signals do not repaint but may adjust as new data develops in real-time.
Why Swing Z is original & useful:
Swing Z unifies EMA trend structure, RSI, MACD, TTM Squeeze, VWAP, Fibonacci retracements, and volume analysis into a single algorithmic framework. This multi-confirmation approach improves accuracy by requiring consensus across trend, momentum, volatility, and price action — a design made specifically for the challenges and volatility of cryptocurrency markets.
Indicadores y estrategias
MACD, RSI & Stoch + Divergences
Best results with combination My_EMA_clouds and Market Mood Maker
This script is a comprehensive technical analysis tool that combines several popular indicators and divergence detection features.
The main components of the script include:
* **MACD indicator** with histogram displaying moving averages and their divergence
* **RSI (Relative Strength Index)** for momentum analysis
* **Stochastic Oscillator** for overbought/oversold levels
* **Divergence detection** system identifying both regular and hidden bullish/bearish divergences between price action and oscillators
Key features:
* Customizable settings for each indicator (periods, smoothing parameters)
* Flexible visualization options (lines, arrows, labels)
* Multiple oscillator display modes (RSI, Stochastic, MACD, or Histogram)
* Pivot point detection for accurate divergence identification
* Configurable lookback period for analysis
* Color-coded signals for easy interpretation
* Horizontal levels for overbought/oversold zones
* Interactive settings panel for customization
The script provides traders with a comprehensive toolkit for identifying potential reversal points and confirming trend directions through divergence analysis across multiple timeframes and indicators.
анный скрипт представляет собой комплексный инструмент технического анализа, который объединяет несколько популярных индикаторов и систему обнаружения дивергенций.
Основные компоненты скрипта включают:
Индикатор MACD с гистограммой, отображающей скользящие средние и их расхождения
Индекс относительной силы (RSI) для анализа импульса
Стохастический осциллятор для определения уровней перекупленности/перепроданности
Система обнаружения дивергенций, выявляющая как обычные, так и скрытые бычьи/медвежьи дивергенции между ценовым движением и осцилляторами
Swing Highs/Lows & Candle Patterns[LuxAlgo] [Filtered]Swing Highs/Lows & Candle Patterns - Tweaked Version
This indicator is a customized and enhanced version of LuxAlgo’s original Swing Highs/Lows & Candle Patterns indicator. It identifies and labels critical swing high and swing low points to help visualize market structure, alongside detecting key reversal candlestick patterns such as Hammer, Inverted Hammer, Bullish Engulfing, Hanging Man, Shooting Star, and Bearish Engulfing.
With added options to selectively display only Lower Highs (LH) and Higher Lows (HL), this tweaked version offers greater flexibility for traders focusing on specific market dynamics. Users can also customize the lookback length and label styling to fit their preferences.
Credit to LuxAlgo for the original concept and foundation of this powerful tool, which this script builds upon to support more tailored technical analysis. Ideal for swing traders and technical analysts seeking improved entry and exit signals through a combination of price swings and candlestick pattern recognition.
MultiSessions traderglobal.topEste indicador de sesiones está diseñado para traders intradía que desean visualizar con precisión la actividad y la volatilidad característica de cada mercado. Basado en Pine Script v5 y optimizado para la zona horaria “America/New_York”, divide el día en sub-sesiones configurables y resalta sus rangos de precio en tiempo real. En particular, incorpora tres bloques para New York (NY1, NY2, NY3), dos para Londres (LON1, LON2), dos para Tokio (TKO1, TKO2) y mantiene Sídney como sesión opcional. Cada bloque puede activarse o desactivarse de forma independiente y cuenta con su propio color ajustable, lo que permite construir mapas visuales claros para estrategias basadas en horario, solapamientos y micro-estructuras de mercado.
El panel de inputs incluye la opción “Activate High/Low View”. Cuando está activada, el indicador calcula de manera incremental el mínimo y máximo de cada sub-sesión y sombrea el área entre ambos con fill, proporcionando una referencia inmediata del rango intrasesión (útil para medir compresión/expansión y posibles rompimientos). Cuando está desactivada, emplea un simple bgcolor por bloque, ideal para traders que prefieren un gráfico más limpio y solo desean distinguir visualmente los tramos horarios.
La lógica central utiliza dos funciones auxiliares: is_session(sess), que detecta si la vela actual pertenece a un tramo horario concreto, e is_newbar(sess), que determina el inicio de una nueva barra de referencia según la resolución elegida (D, W o M). Gracias a esta combinación, en cada sub-sesión el indicador reinicia sus contadores de alto y bajo al comenzar el período y los actualiza vela a vela mientras el bloque siga activo. Este enfoque evita mezclas de datos entre sesiones y asegura que el rango que se muestra corresponda estrictamente al segmento horario configurado.
Los horarios por defecto están pensados para Forex y contemplan casos que cruzan medianoche (por ejemplo, Tokio 2 y Sídney). Pine Script admite rangos como 2200-0200; no obstante, si tu bróker o la zona horaria del gráfico generan un sombreado parcial, basta con dividir el tramo en dos: 2200-2359 y 0000-0200. Asimismo, cada input.session incluye el patrón :1234567 para habilitar los siete días; puedes restringir días según tu operativa.
En cuanto al uso práctico, el indicador facilita identificar: (1) la estructura del rango por sub-sesión (útil para estrategias de breakout/mean-reversion), (2) los solapamientos entre Londres y New York, donde suele concentrarse la liquidez, y (3) períodos de menor volatilidad (tramos tardíos de Asia o previos a noticias). El color independiente por bloque te permite codificar visualmente la importancia o tu plan de trading (por ejemplo, tonos más intensos en ventanas de alta probabilidad).
Finalmente, su diseño modular hace sencilla la personalización: puedes ajustar colores, activar/desactivar bloques, cambiar horarios y modificar la resolución de reseteo del rango. Como posible mejora, se pueden añadir alertas de ruptura de máximos/mínimos de sub-sesión o etiquetas con la altura del rango (pips) al cierre. Este indicador no sustituye el juicio del trader ni constituye recomendación financiera, pero ofrece una base visual robusta para integrar el factor tiempo en la toma de decisiones.
This sessions indicator is built for intraday traders who want a precise, time-aware view of market activity and typical volatility patterns across the day. Written in Pine Script v5 and optimized for the “America/New_York” timezone, it divides the trading day into configurable sub-sessions and highlights their price ranges in real time. Specifically, it provides three blocks for New York (NY1, NY2, NY3), two for London (LON1, LON2), two for Tokyo (TKO1, TKO2), and keeps Sydney as an optional session. Each block can be enabled or disabled independently and comes with its own adjustable color, letting you build clear visual maps for time-based strategies, overlaps, and microstructure nuances.
In the inputs panel you’ll find the “Activate High/Low View” option. When enabled, the indicator incrementally computes each sub-session’s low and high and shades the area between them with fill, giving you an immediate reference to the intra-session range (useful for gauging compression/expansion and potential breakouts). When disabled, it switches to a clean bgcolor background by block—ideal if you prefer a minimal chart and simply want to distinguish time windows at a glance.
The core logic relies on two helper functions: is_session(sess), which detects whether the current bar falls within a given time window, and is_newbar(sess), which identifies the start of a new reference bar according to your chosen reset resolution (D, W, or M). With this combination, each sub-session resets its high/low at the beginning of the period and updates them bar by bar while the block remains active. This prevents cross-contamination between sessions and ensures the range you see belongs strictly to the configured segment.
Default hours are suited to Forex and include segments that cross midnight (e.g., Tokyo 2 and Sydney). Pine Script supports ranges like 2200-0200; however, if your broker or chart timezone causes partial shading, simply split the segment into two: 2200-2359 and 0000-0200. Each input.session uses the :1234567 suffix to enable all seven days; you can easily restrict days to match your plan.
Practically speaking, the indicator helps you identify: (1) range structure by sub-session (great for breakout or mean-reversion frameworks), (2) overlaps between London and New York, where liquidity and directional moves often concentrate, and (3) lower-volatility windows (late Asia or pre-news lulls). Independent colors per block let you visually encode priority or your trading plan (for example, richer tones in high-probability windows).
Thanks to its modular design, customization is straightforward: adjust colors, toggle blocks, change hours, and tweak the range-reset resolution to suit your routine. As a natural extension, you can add alerts for sub-session high/low breakouts or labels that display the range height (in pips) at session close. While no indicator replaces trader judgment or constitutes financial advice, this tool offers a robust visual foundation for incorporating the time factor directly into your decision-making, helping you contextualize price action within the rhythm of global trading sessions.
Simple MADSimple MAD is a lightweight and customizable indicator that calculates the Median Absolute Deviation (MAD) over a configurable period to measure market volatility. It dynamically displays Stop-Loss (SL) and Take-Profit (TP) levels based on MAD multipliers, both in absolute price and percentage terms.
The indicator includes a clean, watermark-style table with full layout controls — allowing you to adjust position, text size, alignment, and colors. It supports both manual entry price and automatic use of the latest close, making it ideal for traders who want to manage risk with precision and clarity.
Perfect for swing traders, volatility-based strategies, and anyone looking to integrate MAD into their decision-making.
XAUUSD Lot Size Calculator + RSI (Yoothobbiz)This indicator is designed for Gold traders on the 5-minute timeframe (M5) who want a clear and editable lot size, stop loss, and take profit calculator directly on their chart.
✨ Features:
📌 Dynamic Lot Size Calculation – based on account capital, chosen risk %, and stop loss distance.
⚖️ Risk/Reward Management – automatically displays TP level using a customizable risk/reward ratio (e.g., 1:2, 1:3, etc.).
🛑 Stop Loss in Points & Price – calculates SL from recent M5 highs/lows, including spread.
🎯 Take Profit in Price & Points – automatically adjusted to your risk/reward ratio.
💵 Risk in USD – instantly shows how much capital is at risk per trade.
🕒 Custom Time Zone Support – displays the real trading time (default UTC-4 for New York), fully editable for any user.
⏱ Timeframe Label – clearly shows the working timeframe (M5 by default).
🎨 Fully Editable Display Panel:
Position (6 corners available).
Font family, size, style (bold/italic).
Text and background colors.
Adjustable spacing between lines.
🔑 How to Use:
Set your capital and risk % in the settings.
Adjust spread (in points) if needed.
Choose your risk/reward ratio.
The panel will display:
Recommended lot size for XAUUSD
Stop loss (price + points)
Take profit (price + ratio)
Risk in $
Timeframe & real-time clock
📍 Notes:
Optimized for XAUUSD (Gold) and the 5M timeframe.
Works on any asset/timeframe, but SL logic is based on M5 candle highs/lows.
Ideal for traders who want a fast and disciplined risk management tool right on their chart.
Volume & RVOL TableVolume & RVOL Dynamic Table
Clean table displaying current volume, current RVOL%, and last RVOL% with dynamic color coding based on customizable percentage thresholds.
Features:
Color-coded RVOL cells change automatically based on volume activity levels
Vertical or horizontal layout options
Fully customizable colors, position, and text sizing
Adjustable RVOL period (default: 50 candles)
Perfect for quick volume analysis without chart clutter. Works on all timeframes.
High Minus LowThis indicator is a simple yet powerful tool for technical analysis. It measures the range of each candlestick by calculating the difference between its high and low, providing a direct visualization of market volatility.
Key Features:
Volatility at a Glance: The plot's height in the separate panel directly corresponds to the candle's trading range, allowing you to easily spot periods of high or low volatility.
Customizable Color: Easily change the line color to match your chart's theme and personal preferences.
Actionable Insights: Use this indicator to confirm periods of market consolidation before a breakout or to gauge the strength of a trend based on the expansion of candle ranges.
KPL with ATRThis is not my own formula. Just published in Team viewer. its the combination KPL and ATR
ADX with Custom Limit LineSimple ADX with Custom Threshold
A clean, educational ADX indicator that allows traders to set their own trend strength threshold.
Features:
- Customizable limit line for personalized trend analysis
- Color-coded ADX line based on trend strength
- Educational reference lines (15, 25, 40, 50)
- Background highlighting when above custom threshold
- Comprehensive alerts for trend changes
Perfect for traders who want a simple but effective tool to assess trend strength without complexity.
This indicator helps understand:
- When trends are strong enough to trade
- How to interpret ADX readings
- Optimal entry/exit timing based on trend strength
Educational and straightforward - ideal for both beginners and experienced traders.
⚠️ RISK DISCLAIMER:
This indicator is for educational purposes only and does not constitute financial advice.
Trading involves significant risk of loss. Always do your own research and consider
consulting with a qualified financial advisor before making trading decisions.
VXN Choch Pattern LevelsThis indicator is based on other open source scripts. It identifies and visualizes Change of Character (ChoCh) patterns on Nasdaq futures (NQ and MNQ) charts, using pivot points and the CBOE VXN index (Nasdaq-100 Volatility Index) to detect potential trend reversals.
It plots bullish and bearish ChoCh patterns with triangles, horizontal lines, and volume delta information.
The indicator uses VXN EMA and SMA to set a background color (green for bullish, red for bearish) to contextualize market sentiment.
Key features include:
- Detection of pivot highs and lows to identify ChoCh patterns.
- Visualization of patterns with polylines, labels, and horizontal lines.
- Optional display of volume delta for each pattern.
- Management of pattern zones to limit the number of displayed patterns and remove invalidated ones.
- Bullish/bearish triangle signals triggered by VXN EMA/SMA crossovers for confirmation.
Multi Timeframe EMA14 (CHANUT)เป็นการใช้ อินดิเคเตอร์ ในการดู แนวโน้มตลาดเช่น ทองคำ
It is the use of indicators to look at market trends such as gold.
(Fixed-Range) Anchored VWAPThis "Fixed-Range Anchored VWAP" indicator allows traders full control over where the VWAP calculation begins and ends. VWAP combines both price and volume to reflect the true average price paid, often serving as a benchmark for gauging value, sentiment, and trend strength.
With this tool, traders can anchor VWAP to any candle, optionally define an end point, or keep it running forward with a single toggle. Up to three bands can be added around VWAP, either as standard deviations or percentage offsets.
How to Use
The indicator is particularly useful for analyzing VWAP around significant events, like earnings announcements or sharp price swings, to identify support, resistance, and mean-reversion opportunities.
Add the indicator and select a candle to set the Anchor.
Choose an End point or enable Cancel End for an open-ended VWAP.
Pick Std Dev or Percent for band mode.
Turn on up to three bands, adjust multipliers, and set fill colors.
Use VWAP and its bands to evaluate extensions, trend context, and fair value zones.
ICT ob by AyushThis indicator marks **order blocks** by detecting the first opposite candle of any pullback run and drawing a line from its **open** to the confirming candle’s close.
It works on **any timeframe (or HTF projection)**, stays clean, and only shows **solid, body-confirmed OBs**.
Eureka & Phoenix Thrust — NYSE (90% Breadth Days)🚀Eureka & Phoenix Thrust Indicator (NYSE Breadth)
Overview
This free indicator highlights rare but powerful breadth thrust days on the NYSE that can mark important turning points in the market.
It automatically detects both:
📈 Eureka Thrust (90% Up Day)
– At least 90% of NYSE issues advance and at least 90% of NYSE volume is advancing.
– Often signals broad-based institutional buying and strong market demand.
📉 Phoenix Thrust (90% Down Day)
– At least 90% of NYSE issues decline and at least 90% of NYSE volume is declining.
– Reflects broad institutional selling or panic, sometimes marking capitulation lows.
Both signal types were popularized by Lowry’s Research and O’Neil/IBD market models.
Notes
Eureka Thrusts are bullish confirmation signals, especially when clustered.
Phoenix Thrusts often mark panic selling — bearish in the short term, but can precede market bottoms if followed by Eurekas.
These events are rare. You may need to scroll back in history (e.g., March 2020, 2008, 1987) to see them in action.
Disclaimer
This tool is for educational and informational purposes only.
It is not financial advice. Always do your own research and risk management before making trading or investment decisions.
RSI Value Display (Corner)RSI in the right corner (red when is above 70 and below 30 - Green for the rest)
Balanced Big Wicks (50/50) HighlighterThis open-source indicator highlights candles with balanced long wicks (50/50 style)—that is, candles where both upper and lower shadows are each at least 30–60% of the full range and within ~8% of each other, while retaining a substantial body. This specific structure often reflects indecision or liquidity sweeps and can precede strong breakout moves.
How It Works (Inputs and Logic)
Min wick % (each side): 30–60% of candle range
Max body %: up to 60% of range (preserves strong body presence)
Equality tolerance: wicks within 8% of each other
ATR filter (multiples of ATR14): ensures only significant-range candles are flagged
When a “50/50” candle forms, it’s visually colored and labeled; audibly alertable.
How to Use It
Long setup: price closes above the wick-high → potential long entry (SL below wick-low, TP = 1:1).
Short setup: price closes below wick-low → potential short entry (SL above wick-high, TP = 1:1).
Especially effective on 5–15 minute scalping charts when aligned with high-volume sessions or HTF trend context.
Why This Indicator Is Unique
Unlike standard wick or doji voters, this script specifically filters for candles with a strong body and symmetrical wicks, paired with a range filter, reducing noise significantly.
Important Notes
No unrealistic claims: backtested setups indicate high occurrence of clean breakouts, though performance depends on market structure.
Script built responsibly: uses real-time calculations only, no future-data lookahead.
Visuals on the published chart reflect default input values exactly.
Premarket Breakout Painter (08:00-09:29 ET) — First Break Only**Pre-Market Breakout Indicator**
This indicator is designed to help traders identify and trade **pre-market breakout levels**. It automatically marks the pre-market high and low range, then extends those levels into the regular session so you can see when price breaks above or below them.
---
## 🔑 **How It Works**
1. **Pre-Market Range**
* During extended hours (before the 09:30 ET open), the indicator tracks the **highest high** and **lowest low**.
* These levels form the **pre-market range**.
2. **Breakout Levels**
* At the market open, the pre-market high and low are plotted as horizontal lines.
* When price breaks above the pre-market high → potential **bullish breakout**.
* When price breaks below the pre-market low → potential **bearish breakout**.
3. **Optional Midline / VWAP**
---
🎨 **Visuals**
* **Horizontal lines** marking pre-market high and low.
* Lines extend into the regular session for easy tracking.
* Colors can be customized for bullish/bearish clarity.
---
⚙️ **Inputs**
* **Session Times** (default: 04:00–09:30 ET for U.S. equities).
* **Show/Hide Midline** (optional).
* **Line Styles & Colors**.
* **Alerts** (optional, e.g., alert when price crosses pre-market high or low).
---
🚨 **Practical Use**
* Look for **high volume breakouts** through pre-market high/low after the bell.
* Use levels as **support/resistance** for pullback entries.
* Combine with EMA trend filters, VWAP, or market internals for confirmation.
---
✅ This indicator doesn’t give buy/sell signals on its own — it’s a **visual framework** to highlight where the market may make its first decisive move of the day.
Future Value ProjectionFuture Value Projection with Actual CAGR
This indicator calculates the future value (FV) of the current ticker’s price using its historical Compound Annual Growth Rate (CAGR). It measures how much the price has grown over a chosen lookback period, derives the average annual growth rate, and then projects the current price forward into the future.
Formulae:
CAGR:
CAGR = ( PV_now / PV_past )^(1 / t) - 1
Future Value:
FV = PV_now × ( 1 + CAGR / n )^( n × T )
Where:
PV_now = Current price
PV_past = Price t years ago
t = Lookback period (years)
CAGR = Compound Annual Growth Rate
n = Compounding periods per year (1=annual, 12=monthly, 252=daily, etc.)
T = Projection horizon (years forward)
How it works:
Select a lookback period (e.g., 3 years).
The script finds the price from that time and computes the CAGR.
It then projects the current price forward by T years using the CAGR.
The chart shows:
Current price (blue)
Projected FV target (green)
A table with CAGR and projection details
Use case:
Helps investors and traders visualize long-term growth projections if the ticker continues growing at its historical pace.
Auto S/R 1H - Stable Simplethat is a script to find out the support and resistance as trendlines for stocks in one hour timeframe for swing trading.
Elite Pivot Points - 3 time frameElite Pivot Points — Multi-timeframe pivots (A/B/C)
Overview
Elite Pivot Points plots up to three pivot frameworks at once on the same chart. Choose the calculation type (Traditional, Fibonacci, Woodie, Classic, Camarilla), pick an independent timeframe for each set (Auto, Daily → Decennially), and set separate colors/visibility for P, S1–S5, and R1–R5. Labels can include prices and the resolved timeframe name (e.g., “Weekly”, “Quarterly”, or “Auto Monthly”).
What’s new in this edition
Adds the ability to display three selectable pivot timeframes simultaneously.
Each timeframe has its own color controls for all levels.
Labels show the chosen timeframe name for clarity.
The original pivot logic/structure remains unchanged.
How it works
Levels are computed using standard formulas for the selected type.
While a higher-timeframe period is open, the current period’s levels can update until that candle closes; historical periods are fixed after close.
Auto picks a source timeframe based on your chart (intraday → Daily/Weekly; weekly/monthly → Yearly by design).
Use Daily-based Values (optional) calculates from the exchange’s daily OHLC on intraday charts (if extended hours are shown, they’re included). Turning it off uses intraday data directly—results can differ by instrument.
Key inputs
Type: Traditional, Fibonacci, Woodie, Classic, Camarilla.
Timeframe A/B/C: Auto, Daily, Weekly, Biweekly, Monthly, Bimonthly, Quarterly, Biquarterly, Yearly, Biyearly, Triyearly, Quinquennially, Decennially.
Show Timeframe A/B/C: Toggle each set on/off.
Number of Pivots Back (per set): How many historical pivot periods to draw.
Use Daily-based Values (per set): Daily OHLC vs. intraday source.
Labels: Show/hide labels and/or prices; choose left/right placement.
Colors & Widths: Independent colors for P, S1–S5, R1–R5 per set; shared line width.
What it draws
Central pivot (P) plus up to five support (S1–S5) and five resistance (R1–R5) levels per selected timeframe.
Label text shows the level and the timeframe name (e.g., R2 (Quarterly)).
Notes & limitations
This is a charting tool, not a signal service; it does not generate trade recommendations.
Current-period levels on higher timeframes may shift until the source period closes.
On symbols where intraday vs. daily OHLC differ (common for stocks), enabling/disabling Use Daily-based Values will intentionally produce different levels.
Best practices
Combine three distinct horizons (e.g., Weekly + Monthly + Quarterly) for multi-frame confluence.
If the chart gets crowded, hide S4/S5 and R4/R5 or reduce Pivots Back.
Align your chart’s session/extended-hours settings with how you compute pivots.
Credits & permission
Original indicator by @TboneKrypto (closed-source). This edition is published with the author’s permission. It expands display options to three independent pivot timeframes with per-set colors while keeping the original logic intact. No affiliation or endorsement implied.
Disclaimer
For educational purposes only. This is not financial advice or a solicitation to buy or sell any asset. Trading involves risk. Always do your own research and manage risk appropriately.
3Signal Strategy+// This source code is subject to the terms of the Mozilla Public License 2.0 at mozilla.org
// Script combining Support Resistance Strategy and Buy/Sell Filter with 3 Moving Averages 3Signal Strategy+ by InteliCryptos
//@version=6
indicator("3Signal Strategy+", overlay=true, max_lines_count=500)
// ====== Inputs Section ======
// HHLL Strategy Inputs
lb = input.int(3, title="Support HL", minval=1)
rb = input.int(4, title="Resistance LH", minval=1)
showsupres = input.bool(true, title="Support/Resistance", inline="srcol")
supcol = input.color(color.red, title="", inline="srcol")
rescol = input.color(color.lime, title="", inline="srcol")
srlinestyle = input.string("solid", title="Line Style", options= , inline="style")
srlinewidth = input.int(1, title="Line Width", minval=1, maxval=5, inline="style")
changebarcol = input.bool(true, title="Change Bar Color", inline="bcol")
bcolup = input.color(color.yellow, title="", inline="bcol")
bcoldn = input.color(color.black, title="", inline="bcol")
// Twin Range Filter Inputs
source = input(close, title="Source")
per1 = input.int(27, minval=1, title="Fast Period")
mult1 = input.float(1.6, minval=0.1, title="Fast Range")
per2 = input.int(55, minval=1, title="Slow Period")
mult2 = input.float(2, minval=0.1, title="Slow Range")
// Moving Average Inputs
ma_type1 = input.string("EMA", "MA 1 Type (Fast)", options= , group="Moving Averages")
ma_length1 = input.int(12, "MA 1 Length", minval=1, group="Moving Averages")
ma_color1 = input.color(color.blue, "MA 1 Color", group="Moving Averages")
ma_type2 = input.string("EMA", "MA 2 Type (Medium)", options= , group="Moving Averages")
ma_length2 = input.int(50, "MA 2 Length", minval=1, group="Moving Averages")
ma_color2 = input.color(color.yellow, "MA 2 Color", group="Moving Averages")
ma_type3 = input.string("EMA", "MA 3 Type (Slow)", options= , group="Moving Averages")
ma_length3 = input.int(200, "MA 3 Length", minval=1, group="Moving Averages")
ma_color3 = input.color(color.purple, "MA 3 Color", group="Moving Averages")
ma_timeframe = input.string("", "MA Timeframe (e.g., 1m, 5m, 1H, D)", group="Moving Averages")
// ====== HHLL Strategy Logic ======
ph = ta.pivothigh(lb, rb)
pl = ta.pivotlow(lb, rb)
hl = not na(ph) ? 1 : not na(pl) ? -1 : na
zz = not na(ph) ? ph : not na(pl) ? pl : na
// Boolean conditions for ta.valuewhen
is_hl_minus1 = hl == -1
is_hl_plus1 = hl == 1
is_zz_valid = not na(zz)
prev_hl = ta.valuewhen(is_hl_minus1 or is_hl_plus1, hl, 1)
prev_zz = ta.valuewhen(is_zz_valid, zz, 1)
zz := not na(pl) and hl == -1 and prev_hl == -1 and pl > prev_zz ? na : zz
zz := not na(ph) and hl == 1 and prev_hl == 1 and ph < prev_zz ? na : zz
hl := hl == -1 and prev_hl == 1 and zz > prev_zz ? na : hl
hl := hl == 1 and prev_hl == -1 and zz < prev_zz ? na : hl
zz := na(hl) ? na : zz
findprevious() =>
ehl = hl == 1 ? -1 : 1
loc1 = 0.0, loc2 = 0.0, loc3 = 0.0, loc4 = 0.0
xx = 0
for x = 1 to 1000
if hl == ehl and not na(zz )
loc1 := zz
xx := x + 1
break
ehl := hl
for x = xx to 1000
if hl == ehl and not na(zz )
loc2 := zz
xx := x + 1
break
ehl := hl == 1 ? -1 : 1
for x = xx to 1000
if hl == ehl and not na(zz )
loc3 := zz
xx := x + 1
break
ehl := hl
for x = xx to 1000
if hl == ehl and not na(zz )
loc4 := zz
break
// Calling findprevious on each bar
= findprevious()
var float a = na
var float b = na
var float c = na
var float d = na
var float e = na
if not na(hl)
a := zz
b := loc1
c := loc2
d := loc3
e := loc4
// ====== Twin Range Filter Logic ======
smoothrng(x, t, m) =>
wper = t * 2 - 1
avrng = ta.ema(math.abs(x - x ), t)
smoothrng = ta.ema(avrng, wper) * m
smoothrng
smrng1 = smoothrng(source, per1, mult1)
smrng2 = smoothrng(source, per2, mult2)
smrng = (smrng1 + smrng2) / 2
rngfilt(x, r) =>
var float rngfilt = x
rngfilt := x > nz(rngfilt ) ? (x - r < nz(rngfilt ) ? nz(rngfilt ) : x - r) :
(x + r > nz(rngfilt ) ? nz(rngfilt ) : x + r)
rngfilt
filt = rngfilt(source, smrng)
var float upward = 0.0
var float downward = 0.0
upward := filt > filt ? nz(upward ) + 1 : filt < filt ? 0 : nz(upward )
downward := filt < filt ? nz(downward ) + 1 : filt > filt ? 0 : nz(downward )
// ====== Moving Average Logic ======
ma_source = ma_timeframe == "" ? close : request.security(syminfo.tickerid, ma_timeframe, close, lookahead=barmerge.lookahead_on)
ma1 = ma_type1 == "EMA" ? ta.ema(ma_source, ma_length1) :
ma_type1 == "SMA" ? ta.sma(ma_source, ma_length1) :
ta.wma(ma_source, ma_length1)
ma2 = ma_type2 == "EMA" ? ta.ema(ma_source, ma_length2) :
ma_type2 == "SMA" ? ta.sma(ma_source, ma_length2) :
ta.wma(ma_source, ma_length2)
ma3 = ma_type3 == "EMA" ? ta.ema(ma_source, ma_length3) :
ma_type3 == "SMA" ? ta.sma(ma_source, ma_length3) :
ta.wma(ma_source, ma_length3)
// ====== Combined Strategy Conditions ======
_hh = not na(zz) and (a > b and a > c and c > b and c > d)
_ll = not na(zz) and (a < b and a < c and c < b and c < d)
_hl = not na(zz) and ((a >= c and (b > c and b > d and d > c and d > e)) or (a < b and a > c and b < d))
_lh = not na(zz) and ((a <= c and (b < c and b < d and d < c and d < e)) or (a > b and a < c and b > d))
hband = filt + smrng
lband = filt - smrng
longCond = source > filt and source > source and upward > 0 or source > filt and source < source and upward > 0
shortCond = source < filt and source < source and downward > 0 or source < filt and source > source and downward > 0
var int CondIni = 0
CondIni := longCond ? 1 : shortCond ? -1 : nz(CondIni )
long = longCond and CondIni == -1
short = shortCond and CondIni == 1
// ====== Plotting Section ======
var float res = na
var float sup = na
res := _lh ? zz : res
sup := _hl ? zz : sup
var int trend = na
trend := close > res ? 1 : close < sup ? -1 : nz(trend )
res := (trend == 1 and _hh) or (trend == -1 and _lh) ? zz : res
sup := (trend == 1 and _hl) or (trend == -1 and _ll) ? zz : sup
rechange = res != res
suchange = sup != sup
var line resline = na
var line supline = na
if showsupres
if rechange
line.set_x2(resline, bar_index)
line.set_extend(id=resline, extend=extend.none)
resline := line.new(bar_index - rb, res, bar_index, res, color=rescol, extend=extend.right, style=srlinestyle == "solid" ? line.style_solid : srlinestyle == "dashed" ? line.style_dashed : line.style_dotted, width=srlinewidth)
if suchange
line.set_x2(supline, bar_index)
line.set_extend(id=supline, extend=extend.none)
supline := line.new(bar_index - rb, sup, bar_index, sup, color=supcol, extend=extend.right, style=srlinestyle == "solid" ? line.style_solid : srlinestyle == "dashed" ? line.style_dashed : line.style_dotted, width=srlinewidth)
// Plot HHLL signals
plotshape(_hl, text="HL", title="Higher Low", style=shape.labelup, color=color.lime, textcolor=color.black, location=location.belowbar, offset=-rb)
plotshape(_hh, text="HH", title="Higher High", style=shape.labeldown, color=color.lime, textcolor=color.black, location=location.abovebar, offset=-rb)
plotshape(_ll, text="LL", title="Lower Low", style=shape.labelup, color=color.red, textcolor=color.white, location=location.belowbar, offset=-rb)
plotshape(_lh, text="LH", title="Lower High", style=shape.labeldown, color=color.red, textcolor=color.white, location=location.abovebar, offset=-rb)
// Plot Range Filter signals
plotshape(long, title="Long", text="Long", style=shape.labelup, textcolor=color.black, size=size.tiny, location=location.belowbar, color=color.new(color.lime, 0))
plotshape(short, title="Short", text="Short", style=shape.labeldown, textcolor=color.white, size=size.tiny, location=location.abovebar, color=color.new(color.red, 0))
// Plot Moving Averages
plot(ma1, title="MA Fast (12)", color=ma_color1, linewidth=2)
plot(ma2, title="MA Medium (50)", color=ma_color2, linewidth=2)
plot(ma3, title="MA Slow (200)", color=ma_color3, linewidth=2)
barcolor(changebarcol ? (trend == 1 ? bcolup : bcoldn) : na)
// ====== Alerts Section ======
alertcondition(long, title="Long", message="Long")
alertcondition(short, title="Short", message="Short")