HaP RobotWhat is the HaP Robot?
This code is for the "HaP Robot," an advanced automated trading (algo-trading) signal generator and scanner that runs on TradingView. Its primary purpose is to scan predefined lists of stocks (in groups) based on a specific strategy and, when buy or sell conditions are met, to generate alert messages in a special format to be sent to a specific brokerage's API.
In other words, this is not just an indicator but the "brain" of an automated trading infrastructure.
Core Components and Functions:
To better understand how the code works, we can break it down into its main sections:
1. User Inputs
This section allows the user to customize the strategy and settings.
tutar (Amount): Determines the monetary amount for each trade (e.g., 10,000 TRY).
APIKEY and TOKEN: These are the credentials provided by the brokerage for automated trading. This information is included in the generated alert message.
grupSec (Group Selection): Used to select the list of stocks to be scanned. It offers 14 different groups and a "CUSTOM LIST" option. This allows the code to scan nearly 40 stocks simultaneously.
per (Period): Allows you to select the timeframe for the scans (e.g., 1h, 4h, 1D).
2. Technical Indicators and Calculations
These are the mathematical calculations that form the basis of the strategy.
V5 Critical Threshold: This is the strategy's main indicator. Unlike standard moving averages, it involves mathematical calculations that adjust its speed based on increases or decreases in market volatility. It reacts faster during high volatility and slower during low volatility. The code calculates three different V5 Critical Thresholds:
current_V5: The V5 for the current period open on the chart.
v5_daily: The V5 on the daily period. This is used as a reference point to understand the overall trend.
lower_v5: The V5 from one timeframe lower than the current period. For instance, if you are on a 1-hour chart, it calculates the 30-minute V5. This is used to catch signals earlier.
EMA (Exponential Moving Average): A simple 5-period exponential moving average used to track short-term price movements.
Blue Arrow Signal: A volatility-based trailing stop loss indicator. It generates a "Buy" signal when the price crosses above this line and a "Sell" signal when it crosses below.
3. Trading Strategy (Criteria)
Data from the indicators are combined to generate BUY and SELL signals. It executes trades using strategies compatible with the HaP system.
4. Position Management
The code includes a position tracking mechanism to prevent consecutive buys or sells on the same stock.
5. Multi-Symbol Scanning and Automated Alert System
This is the code's most critical and powerful feature.
Symbol Groups: Variables like a01, a02... a35 contain BIST stocks based on the group selected by the user. If "CUSTOM LIST" is chosen, the symbols entered manually by the user are scanned.
alertTrigger Function: This function runs the strategy for each stock individually.
It uses the request.security() command to pull the price and signal data (the Sinyal variable) for each stock in the list.
It tracks the position status for each stock separately. This allows it to manage the positions of 40 different stocks without confusion.
When a BUY signal occurs for a stock and there is no existing position for it:
It calculates how many lots/shares to buy based on the specified tutar (amount).
It creates an alert text containing information like the APIKEY, TOKEN, symbol name, buy price, and quantity.
It triggers this special text using the alert() command. This alert can be sent to the brokerage's system via TradingView's "Webhook URL" feature to execute the trade automatically.
When a SELL signal occurs for a stock and there is an existing position, it creates a sell alert in the same manner to close the position.
In Summary, What Does It Do?
This script continuously scans a stock group you've selected (e.g., Group 1, consisting of 40 stocks) on your chosen period (e.g., 4-hour). When it identifies a buying or selling opportunity based on its internal volatility-sensitive V5 and Blue Arrow strategy, it automatically prepares the order command to be sent to your brokerage (e.g., "BUY 10,000 TRY worth of THYAO at market price") and triggers it as an alert. By connecting these alerts to a webhook, you can run a fully automated trading robot.
Moving Averages
Srujan Multi-Timeframe Triple EMAThis is a normal moving average indicator, and can be combined with various other indicator.
Settings available such as, multi time frame changes, to view an overall aspect of the market dirtection
Srujan Naidu Strict EMA Exaggerated Touch-Free SignalGet Market Lows and Highs using this indicator
Use this Indicator by combining with the other indicators for accuracy
Médias Tasso📊 Tasso Moving Averages — Professional trend-reading setup
Combines EMA 9, MA 21, MA 50, MA 80 and MA 200 in a clean layout with automatic labels at the end of each line.
✅ Customizable thickness and colors (in the “Inputs” tab)
✅ Transparent background and professional visualization
✅ Perfect for identifying trend direction, pullbacks and reversals
Médias Lorenz📊 Lorenz Moving Averages — Professional trend-reading setup
Combines EMA 9, MA 21, MA 50, MA 80 and MA 200 in a clean layout with automatic labels at the end of each line.
✅ Customizable thickness and colors (in the “Inputs” tab)
✅ Transparent background and professional visualization
✅ Perfect for identifying trend direction, pullbacks and reversals
Designed by Lorenz — clear, accurate and visually refined.
TraderDemircan (Triz Global) EMA Dynamic Crossover v1.1TraderDemircan (Triz Global) EMA Dynamic Crossover v1.1
HaP OtoDinamikFİBO+EMA1. Automatic Dynamic Fibonacci Levels
This is the first and primary feature of the indicator. Instead of manually drawing the Fibonacci tool, this section automates the entire process.
Zigzag Algorithm: It automatically detects significant high and low points (swings) on the chart. While making these detections, it adjusts its own period based on the chart's timeframe (e.g., weekly, daily, 4-hour).
Automatic Fibo Drawing: It automatically draws Fibonacci retracement and extension levels between the last two significant high and low points it has detected.
Dynamic Updates: When a new and more significant low or high is formed in the market, it automatically updates the Fibonacci levels to reflect this new structure. As Fibonacci levels are breached, the next relevant levels are automatically displayed.
Customization: Users can toggle the visibility of the Fibonacci lines, adjust their thickness and colors (e.g., different colors for levels between 0-1 and for levels above 1), and choose whether the price labels appear on the right or left side of the chart.
2. Dynamic EMA (Exponential Moving Average) Support/Resistance Zones
Instead of cluttering the chart with dozens of moving averages, this feature is an intelligent system that displays only the most relevant ones at any given time.
Multi-Timeframe Analysis: It calculates numerous popular EMA values (e.g., 5, 8, 13, 21, ..., 1000) in the background on both the Daily (D) and Weekly (W) timeframes. This allows you to see where the daily and weekly EMAs are located, even when you are viewing a 1-hour chart.
Displaying the Closest Levels: Based on the current price location, it finds the nearest EMA above it (resistance) and the nearest EMA below it (support), and displays only these two on the chart.
Informative Labels: It adds labels to these EMA lines, indicating their timeframe (D/W) and period (e.g., D EMA 55), their price value, and their percentage distance from the current price.
Special Condition Handling: If the price moves above all calculated EMAs or drops below all of them (indicating a strong trend), it will only show the 5-period EMA to keep the chart clean.
Comprehensive Settings: Users can toggle the visibility of all EMAs, the price line, and labels. They can fully customize the colors, thickness, and style of the lines, as well as the size, color, and position of the labels according to their preferences.
Summary
In summary, this indicator is a powerful and flexible tool designed to help traders with the following:
Identifying potential support, resistance, and target levels through automatic and effortless Fibonacci analysis.
Instantly viewing the most critical dynamic support and resistance zones for the current price by utilizing EMAs from multiple timeframes.
Simplifying the analysis process by keeping the chart clean and understandable.
OrderVibe HF indicator (Invite-Only)What it is
OrderVibe HF is a closed-source analytical tool designed to visualize short-term directional bias and volatility structure in real time.
It does not execute or manage trades.
It highlights directional shifts, adaptive baseline transitions, and ATR-based setups for educational analysis and strategy development.
How it works — technical overview
* Adaptive Directional Core.
The script computes a multi-bar comparative score between recent prices and a dynamically smoothed baseline.
This allows detection of directional shifts with minimal response delay while preserving consistency across fast timeframes.
* Volatility Model (adaptive).
ATR-plus-percentile framework measures short-term volatility relative to recent candle bodies, stabilizing responses during both quiet and high-velocity phases.
* Quality Filters.
ATR-normalized body and session filters remove low-quality candles and suppress setups when price movement becomes erratic or too compressed.
* HTF Trend Confirmation (optional).
A higher-timeframe directional filter can confirm lower-timeframe bias for additional confluence.
* Cooldown Logic.
After any directional update, a cooldown timer (bars or minutes) prevents redundant signals and maintains clarity.
* Delayed Confirmation (optional).
Allows setups to require a defined number of bars before confirmation, minimizing premature bias flips.
* Reverse-on-Adverse-Move (risk awareness).
Built-in reversal condition can flip directional state if price exceeds a user-defined adverse threshold (points, ticks, or ATR×).
* ATR-Based Setup Projection.
On each validated event, the tool visualizes multi-target structures (TP1–TP5) and protective SL, all derived from ATR.
Highlighted entry zones are for visual context only — not for execution.
* Alerts (optional).
Event-based alerts for new directional setups and bias reversals, with selectable confirmation behavior.
Why it’s not a simple moving-average signal
* Directional logic based on comparative scoring, not raw MA slope.
* ATR-normalized volatility adjustment for consistent behavior across assets.
* Integrated reversal framework with multiple measurement modes.
* Unified design combining bias detection, volatility modeling, and multi-target setup mapping.
* Provides analytical structure and situational awareness — not mechanical entries.
How to use
* Works on any instrument; defaults are tuned for M1 gold (XAUUSD).
* The indicator performs best with default settings on the XAUUSD (OANDA) chart, 1-minute timeframe, and Heiken Ashi candles .
* Use as a directional and volatility visualizer, not a signal generator.
* ATR-based setups assist in measuring potential risk/reward structure.
* Optional modules (confirmation, cooldown, reversal) can be toggled as needed.
* Forward-test before integrating into any live decision process.
Disclaimer
Analytical tool for research and educational purposes only.
This is not financial advice.
No performance guarantees — users must apply independent judgment and risk management.
Access
Access is invite-only and granted manually on TradingView.
For contact or collaboration, see Signature.
TENOMAX V15 OSC (by 3dots)A simple scalping tool ...
By using crsi and moving average and calculated divergences using rsi and macd and a powerful vwap calculation , now it is easy to decide where we can enter a trade.
Phase Coherence Index (PCI) — Hilbert Prototype v0.1Phase Coherence Index (PCI) — Hilbert Prototype v0.1
✨ Concept:
The Phase Coherence Index (PCI) measures the degree of phase alignment among multiple trend components derived from band-filtered price signals.
In simpler terms, PCI quantifies how “in-sync” short, mid, and long-term market oscillations are.
A high PCI (values near 100) means the market’s cyclical components are moving together — a state of phase alignment that typically accompanies sustained, directional trends.
A low PCI (values near 0) indicates phase disorder or divergence between timeframes — often seen during transitions, chop, or volatility compression phases.
✨ How it works:
1. Multi-Band Extraction
The price series is decomposed into three frequency bands using a simple EMA-difference
bandpass filter:
Short-term band
Mid-term band
Long-term band
2. Hilbert Quadrature Approximation
For each band, a Hilbert-style quadrature signal (Q) is estimated using an Ehlers-inspired FIR kernel with coefficients h0=0.0962 and h1=0.5769.
The original bandpass (I) and its quadrature (Q) form a complex phasor that carries instantaneous phase information.
3. Phase Extraction
The arctangent of Q/I gives the phase angle (−π to π).
Each band’s phase represents the “timing” of its oscillation relative to price movement.
4. Coherence Calculation
All three band phases are converted to unit phasors (cos φ, sin φ).
The average of these phasors is taken, and the magnitude of the resulting vector defines the PCI value:
PCI = |mean_phasor| × 100
PCI = 100 → perfect phase alignment
PCI = 0 → complete phase randomness
5. Smoothing and Regime Coloring
The raw PCI is lightly smoothed by EMA to stabilize readings.
A simple SuperTrend regime filter (ATR length 5, factor 6) colors the PCI line:
Green: uptrend regime
Red: downtrend regime
Gray: low-coherence or neutral zone
✨ How to interpret PCI
High PCI (≥70):
Indicates strong phase coherence — multi-timeframe alignment, stable directional energy.
Often coincides with trend persistence or mature momentum phases.
Low PCI (≤30):
Suggests phase dispersion or regime transition — signals are desynchronized across bands.
Common near reversals, volatility compressions, or sideways congestion.
Cross-phase Transitions:
Rapid drops in PCI often precede periods of uncertainty or trend fatigue.
Rising PCI after a contraction suggests emerging order or trend formation.
✨ Visualization
PCI Line:
Displays phase coherence magnitude (0–100).
Color changes dynamically with SuperTrend regime.
Dotted Reference Levels:
70 (high coherence), 30 (low coherence), 50 (midline).
Optional Label:
When PCI is high, a text label appears indicating whether the average phase bias leans bullish or bearish.
✨ Practical Use
Combine PCI with momentum or volatility tools (e.g., RSI, ATR, DFI) to detect when multiple timeframes become synchronized.
Use PCI drops (<30) as early warnings for possible trend exhaustion or market disorder.
Use PCI rises (>70) as confirmation of trend continuation or emerging coherence.
✨ Limitations
PCI measures phase alignment, not directional bias. It should be combined with a directional filter (e.g., SuperTrend, slope, or moving average).
The Hilbert approximation is not a true analytic signal, but a real-time proxy optimized for stability.
PCI is best interpreted as a structural context indicator rather than a direct entry signal.
✨ Educational intent
This script is designed for quantitative study and visualization of phase alignment, not for direct trading advice.
It demonstrates how Hilbert-style phasors and vector averaging can reveal coherence across timescales — a foundational concept for spectral, cyclical, and structural analysis.
✨ Disclaimer
This script is provided for educational purposes only.
It does not constitute financial advice.
Trading involves risk; use at your own discretion.
© 2025 Trading Playground Labs — “Phase Coherence Index (Hilbert Prototype v0.1)
───────────────────────────────
📘 한국어 설명 (Korean translation below)
───────────────────────────────
Phase Coherence Index (PCI) — Hilbert Prototype v0.1 (한국어 설명)
✨ 개념
Phase Coherence Index (PCI) 는 여러 주기의 추세 구성 요소들 간에 위상의 정합 정도를 측정하는 지표입니다.
쉽게 말하면, 시장의 단기·중기·장기 진동(사이클)들이 서로 얼마나 “같은 박자”로 움직이는지를 수치화한 것입니다.
PCI 값이 100에 가까울수록 시장의 주기적 구성 요소들이 함께 움직이고 있다는 뜻이며,
이는 일반적으로 지속적인 방향성 추세(trend persistence) 상태를 의미합니다.
반대로 PCI 값이 0에 가까울수록 각 주기의 움직임이 서로 엇박자 상태로 흐르며,
이는 전환기(chop), 혼돈(chaos), 혹은 압축(squeeze) 상태를 반영합니다.
✨ 작동 원리
1. 다중 밴드 추출
가격 데이터를 3개의 주파수 대역으로 분리합니다.
단기 (short-term band)
중기 (mid-term band)
장기 (long-term band)
각 대역은 빠른 EMA와 느린 EMA의 차이(EMA difference)로 얻은 단순한 밴드패스로 계산됩니다.
2. Hilbert 직교 성분 근사
각 밴드에 대해 Ehlers 계열 FIR 필터를 이용한 Hilbert 근사 신호(Q)를 계산합니다.
원본 밴드패스 신호(I)와 Q를 결합하면 복소 위상(phasor) 를 구성할 수 있고,
이를 통해 각 대역의 순간 위상(instantaneous phase) 을 추정합니다.
3. 위상 계산
Q/I의 아크탄젠트 값을 구하면 위상각 φ(−π ~ π)가 도출됩니다.
이 위상은 해당 주기의 진동 타이밍을 나타냅니다.
4. 위상 정합(Phase Coherence) 계산
각 밴드의 위상을 단위 페이저 벡터 (cos φ, sin φ)로 변환합니다.
세 벡터의 평균을 구하고, 그 평균 벡터의 크기를 0~100 스케일로 변환한 값이 PCI입니다.
PCI = |평균 페이저| × 100
PCI = 100 → 완전한 위상 일치
PCI = 0 → 완전한 위상 무질서
5. 스무딩 및 추세 컬러링
계산된 PCI는 EMA로 약간 평활화되어 안정적으로 표시됩니다.
또한, SuperTrend 레짐 필터(ATR=5, Factor=6) 로 추세 방향에 따라 색이 바뀝니다:
초록색: 상승 추세
빨간색: 하락 추세
회색: 저정합 / 중립 구간
✨ 해석 방법
PCI ≥ 70 (높은 정합)
여러 타임프레임이 같은 방향으로 동기화되어 있는 상태입니다.
이는 추세 지속성, 모멘텀 유지, 구조적 안정 상태를 의미합니다.
PCI ≤ 30 (낮은 정합)
각 주기 간 위상 불일치가 심해지며, 시장이 방향을 잃거나 변곡점에 근접한 상황입니다.
보통 조정기, 변동성 축소, 횡보 국면에서 자주 나타납니다.
급격한 변동 (Phase Transition)
PCI가 급격히 하락하는 구간은 추세 피로(trend fatigue) 또는 혼돈 국면 진입의 신호일 수 있으며,
이후 PCI가 상승하기 시작하면 새로운 질서(추세 형성) 가 시작될 가능성을 의미합니다.
✨ 시각화 구성
PCI 라인:
위상 정합도의 크기(0~100)를 표시합니다.
SuperTrend 방향에 따라 색이 동적으로 변합니다.
점선 기준선:
70(높은 정합), 50(중간), 30(낮은 정합) 기준으로 시각화됩니다.
평균 위상 라벨:
PCI가 높을 때, 평균 위상의 방향이 상승(bullish) 인지 하락(bearish) 인지를 라벨로 표시합니다.
✨ 활용 방법
RSI, ATR, DFI 등 다른 모멘텀/변동성 지표와 함께 사용하면, 복수 타임프레임 동기화 구간을 탐지할 수 있습니다.
PCI 하락(30 이하)은 추세 피로 또는 혼돈 진입의 신호로, PCI 상승(70 이상)은 질서 회복 또는 추세 지속의 신호로 해석할 수 있습니다.
추세 전환, 조정, 또는 모멘텀 재편성 구간을 감지하는 데 유용합니다.
✨ 한계점
PCI는 방향성(Direction)을 직접 측정하지 않고, 구조적 정합(Alignment) 만 측정합니다. 따라서 반드시 방향 필터(SuperTrend, MA 기울기 등)와 함께 해석해야 합니다.
Hilbert 근사는 완전한 복소 해석 신호가 아니라, 실시간 안정성을 중시한 근사 모델입니다.
PCI는 진입 시그널용보다는 시장 구조 인식용 보조 지표로 적합합니다.
✨ 교육적 목적
이 스크립트는 위상 정합(phase coherence) 개념의 시각화와 정량적 연구를 위한 목적으로 설계되었습니다.
힐버트 변환 기반 위상 벡터(phasor) 와 벡터 평균화(vector averaging) 의 개념을 통해
시장의 다중 시간 구조 간 일관성(coherence)을 탐색할 수 있습니다.
✨면책
이 지표는 교육 목적으로만 제공됩니다.
투자 조언이 아니며, 모든 트레이딩 결정의 책임은 사용자에게 있습니다.
© 2025 Trading Playground Labs — Phase Coherence Index (Hilbert Prototype v0.1)
Developed for structural & spectral analysis of market phase alignment.
4H SMA+CCI Signal Map - J&COverview
This TradingView indicator identifies high-timeframe (HTF) trend-confirmation entry signals based on the relationship between two Simple Moving Averages (SMAs) and the Commodity Channel Index (CCI). It provides visual cues (arrows, labels, and background shading) when a new 4-hour bar confirms a long or short setup, even if applied to lower-timeframe charts (like 1H or 15m).
Core Concept
The script monitors higher-timeframe (default: 4H) trend conditions:
Fast SMA (default 20) and Slow SMA (default 40) determine the trend direction.
CCI (default 5-period) acts as a momentum filter.
Signals are generated only when a new 4H candle opens, ensuring cleaner higher-timeframe alignment and avoiding lower-timeframe noise.
SuperBulls - Heiken Ashi StrategyA streamlined, trade-ready strategy from the SuperBulls universe that turns noisy charts into clear decisions. It combines a smoothed price view, adaptive momentum gating, and a dynamic support/resistance overlay so you can spot high-probability turns without overthinking every candle. Entries and exits are signalled visually and designed to work with simple position sizing — perfect for discretionary traders and systematic setups alike.
Why traders like it
Clean visual signals reduce analysis paralysis and speed up decision-making.
Built-in momentum filter helps avoid chop and chase only the stronger moves.
Dynamic S/R zones provide objective areas for targets and stop placement.
Works with simple risk rules — position sizing and pyramiding kept conservative by default.
Who it’s for
Traders who want a reliable, low-friction strategy to trade intraday or swing setups without rebuilding indicators from scratch. Minimal tuning required; plug in your size and let the SuperBulls logic do the heavy lifting.
Use it, don’t overfit it, and try not to blame the indicator when you ignore risk management.
MTF 20 SMA Table - DXY**MTF 20 SMA Table - Multi-Timeframe Trend Analysis Dashboard**
**Overview:**
This indicator provides a comprehensive multi-timeframe analysis dashboard that displays the relationship between price and the 20-period Simple Moving Average (SMA) across four key timeframes: 15-minute, 1-hour, 4-hour, and Daily. It's designed to help traders quickly identify trend alignment and potential trading opportunities across multiple timeframes at a glance. It's definitely not perfect but has helped me speed up my backtesting efforts as it's worked well for me eliminating flipping back and forth between timeframes excpet when I have confluence on the table, then I check the HTF.
**How It Works:**
The indicator creates a table overlay on your chart showing three critical metrics for each timeframe:
1. **Price vs SMA (Row 1):** Shows whether price is currently above (bullish) or below (bearish) the 20 SMA
- Green = Price Above SMA
- Red = Price Below SMA
2. **SMA Direction (Row 2):** Indicates the trend direction of the SMA itself over a lookback period
- Green (↗ Rising) = Uptrend
- Red (↘ Falling) = Downtrend
- Gray (→ Flat) = Ranging/Consolidation
3. **Strength (Row 3):** Displays the distance between current price and the SMA in pips
- Purple background = Strong move (>50 pips away)
- Orange background = Moderate move (20-50 pips)
- Gray background = Weak/consolidating (<20 pips)
- Text color: Green for positive distance, Red for negative
**Key Features:**
- **Customizable Table Position:** Place the table anywhere on your chart (9 position options)
- **Adjustable SMA Lengths:** Modify the SMA period for each timeframe independently (default: 20)
- **Direction Lookback Settings:** Fine-tune how far back the indicator looks to determine SMA direction for each timeframe
- **Flat Threshold:** Set the pip threshold for determining when an SMA is "flat" vs trending (default: 5 pips)
- **DXY Optimized:** Calculations are calibrated for the US Dollar Index (1 pip = 0.01)
**Best Use Cases:**
1. **Trend Alignment:** Identify when multiple timeframes align in the same direction for higher probability trades
2. **Divergence Spotting:** Detect when lower timeframes diverge from higher timeframes (potential reversals)
3. **Entry Timing:** Use lower timeframe signals while higher timeframes confirm overall trend
4. **Strength Assessment:** Gauge how extended price is from the mean (SMA) to avoid overextended entries
**Settings Guide:**
- **SMA Settings Group:** Adjust the SMA period for each timeframe (15M, 1H, 4H, Daily)
- **SMA Direction Group:** Control lookback periods to determine trend direction
- 15M: Default 5 candles
- 1H: Default 10 candles
- 4H: Default 15 candles
- Daily: Default 20 candles
- **Flat Threshold:** Set sensitivity for "flat" detection (lower = more sensitive to ranging markets)
**Trading Strategy Examples:**
1. **Trend Following:** Look for all timeframes showing the same direction (all green or all red)
2. **Pullback Trading:** When Daily/4H are green but 15M/1H show red, wait for lower timeframes to flip green for entry
3. **Ranging Markets:** When multiple SMAs show "flat", consider range-bound strategies
**Important Notes:**
- This is a reference tool only, not a standalone trading system
- Always use proper risk management and combine with other analysis methods
- Best suited for trending instruments like indices and major forex pairs
- Calculations are optimized for DXY but can be used on other instruments (pip calculations may need adjustment)
**Credits:**
Feel free to modify and improve this code! Suggestions for enhancements are welcome in the comments.
---
**Installation Instructions:**
1. Add the indicator to your TradingView chart
2. Adjust the table position via settings to avoid overlap with price action
3. Customize SMA lengths and lookback periods to match your trading style
4. Monitor the table for timeframe alignment and trend confirmation
---
This indicator is published as open source for the community to learn from and improve upon. Happy trading! 📈
True Average PriceTrue Average Price
Overview
The indicator plots a single line representing the cumulative average closing price of any symbol you choose. It lets you project a long-term mean onto your active chart, which is useful when your favourite symbol offers limited history but you still want context from an index or data-rich feed.
How It Works
The script retrieves all available historical bars from the selected symbol, sums their closes, counts the bars, and divides the totals to compute the lifetime average. That value is projected onto the chart you are viewing so you can compare current price action to the broader historical mean.
Inputs
Use Symbol : Toggle on to select an alternate symbol; leave off to default to the current chart.
Symbol : Pick the data source used for the average when the toggle is enabled.
Line Color : Choose the display color of the average line.
Line Width : Adjust the thickness of the plotted line.
Usage Tips
Apply the indicator to exchanges with shallow history while sourcing the average from a complete index (e.g., INDEX:BTCUSD for crypto pairs).
Experiment with different symbols to understand how alternative data feeds influence the baseline level.
Disclaimer
This indicator is designed as a technical analysis tool and should be used in conjunction with other forms of analysis and proper risk management.
Past performance does not guarantee future results, and traders should thoroughly test any strategy before implementing it with real capital.
Price Action Brooks ProPrice Action Brooks Pro (PABP) - Professional Trading Indicator
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
📊 OVERVIEW
Price Action Brooks Pro (PABP) is a professional-grade TradingView indicator developed based on Al Brooks' Price Action trading methodology. It integrates decades of Al Brooks' trading experience and price action analysis techniques into a comprehensive technical analysis tool, helping traders accurately interpret market structure and identify trading opportunities.
• Applicable Markets: Stocks, Futures, Forex, Cryptocurrencies
• Timeframes: 1-minute to Daily (5-minute chart recommended)
• Theoretical Foundation: Al Brooks Price Action Trading Method
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
🎯 CORE FEATURES
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
1️⃣ INTELLIGENT GAP DETECTION SYSTEM
Automatically identifies and marks three critical types of gaps in the market.
TRADITIONAL GAP
• Detects complete price gaps between bars
• Upward gap: Current bar's low > Previous bar's high
• Downward gap: Current bar's high < Previous bar's low
• Hollow border design - doesn't obscure price action
• Color coding: Upward gaps (light green), Downward gaps (light pink)
• Adjustable border: 1-5 pixel width options
TAIL GAP
• Detects price gaps between bar wicks/shadows
• Analyzes across 3 bars for precision
• Identifies hidden market structure
BODY GAP
• Focuses only on gaps between bar bodies (open/close)
• Filters out wick noise
• Disabled by default, enable as needed
Trading Significance:
• Gaps signal strong momentum
• Gap fills provide trading opportunities
• Consecutive gaps indicate trend continuation
✓ Independent alert system for all gap types
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
2️⃣ RTH BAR COUNT (Trading Session Counter)
Intelligent counting system designed for US stock intraday trading.
FEATURES
• RTH Only Display: Regular Trading Hours (09:30-15:00 EST)
• 5-Minute Chart Optimized: Displays every 3 bars (15-minute intervals)
• Daily Auto-Reset: Counting starts from 1 each trading day
SMART COLOR CODING
• 🔴 Red (Bars 18 & 48): Critical turning moments (1.5h & 4h)
• 🔵 Sky Blue (Multiples of 12): Hourly markers (12, 24, 36...)
• 🟢 Light Green (Bar 6): Half-hour marker (30 minutes)
• ⚫ Gray (Others): Regular 15-minute interval markers
Al Brooks Time Theory:
• Bar 18 (90 min): First 90 minutes determine daily trend
• Bar 48 (4 hours): Important afternoon turning point
• Hourly markers: Track institutional trading rhythm
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
3️⃣ FOUR-LINE EMA SYSTEM
Professional-grade configurable moving average system.
DEFAULT CONFIGURATION
• EMA 20: Short-term trend (Al Brooks' most important MA)
• EMA 50: Medium-short term reference
• EMA 100: Medium-long term confirmation
• EMA 200: Long-term trend and bull/bear dividing line
FLEXIBLE CUSTOMIZATION
Each EMA can be independently configured:
• On/Off toggle
• Data source selection (close/high/low/open, etc.)
• Custom period length
• Offset adjustment
• Color and transparency
COLOR SCHEME
• EMA 20: Dark brown, opaque (most important)
• EMA 50/100/200: Blue-purple gradient, 70% transparent
TRADING APPLICATIONS
• Bullish Alignment: Price > 20 > 50 > 100 > 200
• Bearish Alignment: 200 > 100 > 50 > 20 > Price
• EMA Confluence: All within <1% = major move precursor
Al Brooks Quote:
"The EMA 20 is the most important moving average. Almost all trading decisions should reference it."
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
4️⃣ PREVIOUS VALUES (Key Prior Price Levels)
Automatically marks important price levels that often act as support/resistance.
THREE INDEPENDENT CONFIGURATIONS
Each group configurable for:
• Timeframe (1D/60min/15min, etc.)
• Price source (close/high/low/open/CurrentOpen, etc.)
• Line style and color
• Display duration (Today/TimeFrame/All)
SMART OPEN PRICE LABELS ⭐
• Auto-displays "Open" label when CurrentOpen selected
• Label color matches line color
• Customizable label size
TYPICAL SETUP
• 1st Line: Previous close (Support/Resistance)
• 2nd Line: Previous high (Breakout target)
• 3rd Line: Previous low (Support level)
Al Brooks Magnet Price Theory:
• Previous open: Price frequently tests opening price
• Previous high/low: Strongest support/resistance
• Breakout confirmation: Breaking prior levels = trend continuation
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
5️⃣ INSIDE & OUTSIDE BAR PATTERN RECOGNITION
Automatically detects core candlestick patterns from Al Brooks' theory.
ii PATTERN (Consecutive Inside Bars)
• Current bar contained within previous bar
• Two or more consecutive
• Labels: ii, iii, iiii (auto-accumulates)
• High-probability breakout setup
• Stop loss: Outside both bars
Trading Significance:
"Inside bars are one of the most reliable breakout setups, especially three or more consecutive inside bars." - Al Brooks
OO PATTERN (Consecutive Outside Bars)
• Current bar engulfs previous bar
• Two or more consecutive
• Labels: oo, ooo (auto-accumulates)
• Indicates indecision or volatility increase
ioi PATTERN (Inside-Outside-Inside)
• Three-bar combination: Inside → Outside → Inside
• Auto-detected and labeled
• Tug-of-war pattern
• Breakout direction often very strong
SMART LABEL SYSTEM
• Auto-accumulation counting
• Dynamic label updates
• Customizable size and color
• Positioned above bars
✓ Independent alerts for all patterns
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
💡 USE CASES
INTRADAY TRADING
✓ Bar Count (timing rhythm)
✓ Traditional Gap (strong signals)
✓ EMA 20 + 50 (quick trend)
✓ ii/ioi Patterns (breakout points)
SWING TRADING
✓ Previous Values (key levels)
✓ EMA 20 + 50 + 100 (trend analysis)
✓ Gaps (trend confirmation)
✓ iii Patterns (entry timing)
TREND FOLLOWING
✓ All four EMAs (alignment analysis)
✓ Gaps (continuation signals)
✓ Previous Values (targets)
BREAKOUT TRADING
✓ iii Pattern (high-reliability setup)
✓ Previous Values (targets)
✓ EMA 20 (trend direction)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
🎨 DESIGN FEATURES
PROFESSIONAL COLOR SCHEME
• Gaps: Hollow borders + light colors
• Bar Count: Smart multi-color coding
• EMAs: Gradient colors + transparency hierarchy
• Previous Values: Customizable + smart labels
CLEAR VISUAL HIERARCHY
• Important elements: Opaque (EMA 20, bar count)
• Reference elements: Semi-transparent (other EMAs, gaps)
• Hollow design: Doesn't obscure price action
USER-FRIENDLY INTERFACE
• Clear functional grouping
• Inline layout saves space
• All colors and sizes customizable
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
📚 AL BROOKS THEORY CORE
READING PRICE ACTION
"Don't try to predict the market, read what the market is telling you."
PABP converts core concepts into visual tools:
• Trend Assessment: EMA system
• Time Rhythm: Bar Count
• Market Structure: Gap analysis
• Trade Setups: Inside/Outside Bars
• Support/Resistance: Previous Values
PROBABILITY THINKING
• ii pattern: Medium probability
• iii pattern: High probability
• iii + EMA 20 support: Very high probability
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
⚙️ TECHNICAL SPECIFICATIONS
• Pine Script Version: v6
• Maximum Objects: 500 lines, 500 labels, 500 boxes
• Alert Functions: 8 independent alerts
• Supported Timeframes: All (5-min recommended for Bar Count)
• Compatibility: All TradingView plans, Mobile & Desktop
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
🚀 RECOMMENDED INITIAL SETTINGS
GAPS
• Traditional Gap: ✓
• Tail Gap: ✓
• Border Width: 2
BAR COUNT
• Use Bar Count: ✓
• Label Size: Normal
EMA
• EMA 20: ✓
• EMA 50: ✓
• EMA 100: ✓
• EMA 200: ✓
PREVIOUS VALUES
• 1st: close (Previous close)
• 2nd: high (Previous high)
• 3rd: low (Previous low)
INSIDE & OUTSIDE BAR
• All patterns: ✓
• Label Size: Large
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
🌟 WHY CHOOSE PABP?
✅ Solid Theoretical Foundation
Based on Al Brooks' decades of trading experience
✅ Complete Professional Features
Systematizes complex price action analysis
✅ Highly Customizable
Every feature adjustable to personal style
✅ Excellent Performance
Optimized code ensures smooth experience
✅ Continuous Updates
Constantly improving based on feedback
✅ Suitable for All Levels
Benefits beginners to professionals
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
📖 RECOMMENDED LEARNING
Al Brooks Books:
• "Trading Price Action Trends"
• "Trading Price Action Trading Ranges"
• "Trading Price Action Reversals"
Learning Path:
1. Understand basic candlestick patterns
2. Learn EMA applications
3. Master market structure analysis
4. Develop trading system
5. Continuous practice and optimization
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
⚠️ RISK DISCLOSURE
IMPORTANT NOTICE:
• For educational and informational purposes only
• Does not constitute investment advice
• Past performance doesn't guarantee future results
• Trading involves risk and may result in capital loss
• Trade according to your risk tolerance
• Test thoroughly in demo account first
RESPONSIBLE TRADING:
• Always use stop losses
• Control position sizes reasonably
• Don't overtrade
• Continuous learning and improvement
• Keep trading journal
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
📜 COPYRIGHT
Price Action Brooks Pro (PABP)
Author: © JimmC98
License: Mozilla Public License 2.0
Pine Script Version: v6
Acknowledgments:
Thanks to Dr. Al Brooks for his contributions to price action trading. This indicator is developed based on his theories.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Experience professional-grade price action analysis now!
"The best traders read price action, not indicators. But when indicators help you read price action better, use them." - Al Brooks
Smart Buy & SellThis is a tool that is widely used
Especially for Overbought and Oversold systems, but I have made some changes in this indicator,
How to use it...
I have set it as the default setting
- RSI Length: 6 (<10 for scalping - 5m-15m)
- Overbought: 70
- Oversold: 30
What is unique about this tool?
we can see 3 conditions:
1) RSI Overbought / Oversold with Bullish Engulfing / Bearish Engulfing
2) RSI Overbought / Oversold with Hammer and Shooting Star
3) RSI Overbought / Oversold with 2 Bullish Bars / 2 Bearish Bars
4) RSI Overbought / Oversold with All Patterns at the same time
When the RSI reaches its Oversold line, the code will wait for Bullish Engulfing pattren, when oversold and Bullish engulfing matched, This indicator will generate a buy signal when the condition is met,
and same as for Bear market, When the RSI reaches its Overbought line, the code will wait for Bearish Engulfing pattren, This indicator will generate a sell/exit signal when the condition is met,
2nd condition is that a Hammer candle will be waited for when RSI touches the Overbought line, for Bullish Move
and Shooting Star candle will be waited for when RSI touches the Overbought line, for Bullish Move, for Bearish Move
3rd Condition is also the same as Condition 1 and Condition 2,
When the RSI reaches its Oversold line, the code will wait for 2 Bullish Bars, when oversold and 2 Bullish Bars matched then this indicator will generate a buy signal, and same as for Bear market,
When the RSI reaches its Overbought line, the code will wait for 2 Bearish Bars, when overbought and 2 Bearish Bars matched then this indicator will generate a Sell signal,
4th Condition is that we can use All Conditions at the same time,
- Bullish Engulfing / Bearish Engulfing
- Hammer and Shooting Star
- 2 Bullish Bars / 2 Bearish Bars
Multi-Anchor VWAP Deviation Dashboard Overview
Multi-Anchor VWAP Deviation Dashboard (Optimized Global) is an overlay indicator that computes up to five user-defined Anchored Volume Weighted Average Prices (AVWAPs) from custom timestamps, plotting their lines and displaying real-time percentage deviations from the current close. It enables precise analysis of price positioning relative to key events (e.g., earnings, news) or periods (e.g., weekly opens), with a compact dashboard for quick scans. Optimized for performance, it uses manual iterative calculations to handle dynamic anchor changes without repainting.
Core Mechanics
The indicator focuses on efficient AVWAP computation and deviation tracking:
Anchor Configuration: Five independent anchors, each with a name, UTC timestamp (e.g., "01 Oct 2025 00:00" for monthly open), show toggle, and color. Timestamps define the calculation start—e.g., AVWAP1 from "20 Oct 2025" onward.
AVWAP Calculation: For each enabled anchor, it identifies the first bar at/after the timestamp as the reset point, then iteratively accumulates (price * volume) / total volume from there. Uses HLC3 source (customizable); handles input changes by resetting sums on new anchors.
Deviation Metric: For each AVWAP, computes % deviation = ((close - AVWAP) / AVWAP) * 100—positive = above (potential resistance), negative = below (support).
Visuals: Plots lines (linewidth 1–2, user colors); dashboard (2 columns, 6 rows) shows names (anchor-colored if enabled) and deviations (green >0%, red <0%, gray N/A), positioned user-selectable with text sizing. Updates on last bar for efficiency.
This setup scales deviations across volatilities, aiding multi-period bias assessment.
Why This Adds Value & Originality
Standard VWAPs limit to session anchors (daily/weekly); deviation tools often lack multiples. This isn't a simple mashup: Manual iterative AVWAP (no built-in ta.vwap reliance) ensures dynamic resets on timestamp tweaks—e.g., shift "Event" to FOMC date without recalc lag. The 5-anchor flexibility (arbitrary UTC times) + centralized dashboard (colored deviations at a glance) creates a "global timeline scanner" unique to event-driven trading, unlike rigid multi-VWAP scripts. It streamlines what requires 5 separate indicators, with % normalization for cross-asset comparison (e.g., SPY vs. BTC).
How to Use
Setup: Overlay on chart. Configure anchors (e.g., Anchor1: "Weekly Open" at next Monday 00:00 UTC; enable/show 2–3 for focus). Set source (HLC3 default), position (Top Right), text size (Small).
Interpret Dashboard:
Left Column: Anchor names (e.g., "Monthly Open" in orange).
Right Column: Deviations (e.g., "+1.25%" green = above, bullish exhaustion?).
Scan for confluence (e.g., all >+2% = overbought).
Trading:
Lines: Price near AVWAP = mean reversion; breaks = momentum.
Example: -0.8% below "Event" anchor post-earnings → potential bounce buy.
Use on 1H–D; adjust timestamps via calendar.
Tips: Enable 1–3 anchors to avoid clutter; test on historical events.
Limitations & Disclaimer
AVWAPs reset on anchor bars, potentially lagging mid-period; deviations are % only (add ATR for absolute). Table updates on close (no intrabar). Timestamps must be UTC/future-proof. No alerts/exits—integrate manually. Not advice; backtest deviations on your assets. Past ≠ future. Comments for ideas.
Enhanced Trend & EMA Screener
Overview
Enhanced Trend & ML Screener is a multi-ticker overlay indicator that scans up to 8 symbols (e.g., SPY, QQQ, major tech stocks) across user-defined timeframes for trend signals via EMA crossovers, Ichimoku cloud positioning, ADX directionality, ATR volatility regimes, and linear regression slope (as a simple ML proxy for momentum). It generates a real-time dashboard summarizing bullish/bearish/neutral sentiments per metric, plus a debug table for raw values. Crossover labels and alerts highlight actionable events, making it a streamlined tool for portfolio monitoring and confluence hunting without manual chart-switching.
Core Mechanics
The screener processes each ticker in parallel, fetching data via secure requests (no lookahead bias):
EMA Crossovers: Monitors price crosses over/under EMAs (10, 21, 50, 89 periods)—e.g., close > EMA10 flags bullish momentum.
Ichimoku Sentiment: Scores cloud position (above both spans = Bullish 8/10; below = Bearish 2/10; inside = Neutral 5/10).
ADX Direction: Compares +DI/-DI for Bullish (up > down), Bearish (down > up), or Neutral.
ATR Regime: Normalizes ATR% vs. close; percentile ranks over lookback classify as Rising (high + increasing = Bullish), Falling (low + decreasing = Bearish), or Stable (Neutral).
ML Slope (Linear Regression): Computes 21-bar slope % (threshold 0% default); >0% = Bullish, <0% = Bearish, near-zero = Neutral.
MTF Trend: Pulls weekly ML slope for higher-timeframe bias. Data aggregates into a main dashboard (7 columns: Symbol, ML Trend, MTF, Ichimoku, ADX, ATR, Crossover) with color-coded cells (green/red for Bull/Bear, gray Neutral). A debug table lists prices, EMAs, and slopes. Plots include EMAs and LinReg line on the chart; labels mark crossovers (e.g., "AAPL ↑ EMA10").
Why This Adds Value & Originality
Basic screeners track one metric; multi-indicator ones overload. This fuses EMAs (momentum), Ichimoku (structure), ADX (strength), ATR (volatility), and LinReg (ML-like slope) into a unified sentiment matrix per ticker—e.g., AAPL showing Bullish across 5/6 metrics signals strong confluence. The MTF weekly overlay adds depth without extra charts, while percentile-based ATR avoids raw-value bias across assets. It's original for its compact, color-coded aggregation (no similar public script scans 8 tickers with this blend + debug view), reducing noise via thresholded LinReg and enabling quick "at-a-glance" portfolio scans.
How to Use
Setup: Add to any chart (overlay=true). Customize tickers (e.g., replace GOOGL with NVDA), timeframe (D default), periods (EMA 89 for long-term). Set LinReg threshold (0% for sensitive).
Interpret Dashboard:
Rows: Per-ticker sentiments (e.g., "Bullish" green for ML Trend if slope >0%).
Crossover Column: "↑ 50" for price > EMA50; "--" if none.
Scan for confluence (e.g., 4+ Bullish = long bias).
Debug Table: Raw values (e.g., EMA10=150.25) for verification.
Trading:
Labels/alerts on crossovers (e.g., "TSLA ↓ EMA21" warns downside).
Use MTF for bias (Weekly Bullish = favor longs).
Example: SPY all Bullish + ↑ EMA10 = portfolio buy signal.
Best For: Daily/weekly scans on indices/stocks; 1H–D timeframes.
Limitations & Disclaimer
Data lags by TF resolution; crossovers confirm on close (no repaint, but delayed). Sentiments are directional filters—not entries (pair with volume/SR). LinReg "ML" is basic regression, not trained model. Alerts once/bar close. No risk tools—use stops <1% risk. Not advice; backtest on your symbols. Feedback in comments.
The Bardan Bias IndicatorThis Bardan Bias Indicator analyzes pure daily chart momentum agnostically across any asset by employing a weighted scoring system based on three universal components: EMA alignment (20, 50, 100 periods), price position relative to these EMAs, and momentum indicators (RSI and MACD). The system objectively awards points for bullish configurations like stacked EMA alignment, price trading above key EMAs, and positive momentum readings, while deducting points for bearish setups, completely independent of the specific instrument. The total score normalizes to a 0-100 scale and classifies into five clear bias categories, providing a single, universal overlay that reveals the underlying daily trend direction for any tradable asset—from cryptocurrencies to stocks to forex—while effectively filtering out minor pullbacks and market noise.
Triangular Moving Average (TRIMA)The Triangular Moving Average (TRIMA) is a technical indicator that applies a triangular weighting scheme to price data, providing enhanced smoothing compared to simpler moving averages. Originating in the early 1970s as technical analysts sought more effective noise filtering methods, the TRIMA was first popularized through the work of market technician Arthur Merrill. Its formal mathematical properties were established in the 1980s, and the indicator gained widespread adoption in the 1990s as computerized charting became standard. TRIMA effectively filters out market noise while maintaining important trends through its unique center-weighted calculation method.
## Core Concepts
* **Double-smoothing process:** TRIMA can be viewed as applying a simple moving average twice, creating more effective noise filtering
* **Triangular weighting:** Uses a symmetrical weight distribution that emphasizes central data points and reduces emphasis toward both ends
* **Constant-time implementation:** Two $O(1)$ SMA passes with circular buffers preserve exact triangular weights while keeping update cost constant per bar
* **Market application:** Particularly effective for identifying the underlying trend in noisy market conditions where standard moving averages generate too many false signals
* **Timeframe flexibility:** Works across multiple timeframes, with longer periods providing cleaner trend signals in higher timeframes
The core innovation of TRIMA is its unique triangular weighting scheme, which can be viewed either as a specialized weight distribution or as a twice-applied simple moving average with adjusted period. This creates more effective noise filtering without the excessive lag penalty typically associated with longer-period averages. The symmetrical nature of the weight distribution ensures zero phase distortion, preserving the timing of important market turning points.
## Common Settings and Parameters
| Parameter | Default | Function | When to Adjust |
|-----------|---------|----------|---------------|
| Length | 14 | Controls the lookback period | Increase for smoother signals in volatile markets, decrease for responsiveness |
| Source | close | Price data used for calculation | Consider using hlc3 for a more balanced price representation |
**Pro Tip:** For a good balance between smoothing and responsiveness, try using a TRIMA with period N instead of an SMA with period 2N - you'll get similar smoothing characteristics but with less lag.
## Calculation and Mathematical Foundation
**Simplified explanation:**
TRIMA calculates a weighted average of prices where the weights form a triangle shape. The middle prices get the most weight, and weights gradually decrease toward both the recent and older ends. This creates a smooth filter that effectively removes random price fluctuations while preserving the underlying trend.
**Technical formula:**
TRIMA = Σ(Price × Weight ) / Σ(Weight )
Where the triangular weights form a symmetric pattern:
- Weight = min(i, n-1-i) + 1
- Example for n=5: weights =
- Example for n=4: weights =
Alternatively, TRIMA can be calculated as:
TRIMA(source, p) = SMA(SMA(source, (p+1)/2), (p+1)/2)
> 🔍 **Technical Note:** The double application of SMA explains why TRIMA provides better smoothing than a single SMA or WMA. This approach effectively applies smoothing twice with optimal period adjustment, creating a -18dB/octave roll-off in the frequency domain compared to -6dB/octave for a simple moving average, and the current implementation achieves $O(1)$ complexity through circular buffers and NA-safe warmup compensation.
## Interpretation Details
TRIMA can be used in various trading strategies:
* **Trend identification:** The direction of TRIMA indicates the prevailing trend
* **Signal generation:** Crossovers between price and TRIMA generate trade signals with fewer false alarms than SMA
* **Support/resistance levels:** TRIMA can act as dynamic support during uptrends and resistance during downtrends
* **Trend strength assessment:** Distance between price and TRIMA can indicate trend strength
* **Multiple timeframe analysis:** Using TRIMAs with different periods can confirm trends across different timeframes
## Limitations and Considerations
* **Market conditions:** Like all moving averages, less effective in choppy, sideways markets
* **Lag factor:** More lag than WMA or EMA due to center-weighted emphasis
* **Limited adaptability:** Fixed weighting scheme cannot adapt to changing market volatility
* **Response time:** Takes longer to reflect sudden price changes than directionally-weighted averages
* **Complementary tools:** Best used with momentum oscillators or volume indicators for confirmation
## References
* Ehlers, John F. "Cycle Analytics for Traders." Wiley, 2013
* Kaufman, Perry J. "Trading Systems and Methods." Wiley, 2013
* Colby, Robert W. "The Encyclopedia of Technical Market Indicators." McGraw-Hill, 2002
Savitzky-Golay Filter (SGF)The Savitzky-Golay Filter (SGF) is a digital filter that performs local polynomial regression on a series of values to determine the smoothed value for each point. Developed by Abraham Savitzky and Marcel Golay in 1964, it is particularly effective at preserving higher moments of the data while reducing noise. This implementation provides a practical adaptation for financial time series, offering superior preservation of peaks, valleys, and other important market structures that might be distorted by simpler moving averages.
## Core Concepts
* **Local polynomial fitting:** Fits a polynomial of specified order to a sliding window of data points
* **Moment preservation:** Maintains higher statistical moments (peaks, valleys, inflection points)
* **Optimized coefficients:** Uses pre-computed coefficients for common polynomial orders
* **Adaptive weighting:** Weight distribution varies based on polynomial order and window size
* **Market application:** Particularly effective for preserving significant price movements while filtering noise
The core innovation of the Savitzky-Golay filter is its ability to smooth data while preserving important features that are often flattened by other filtering methods. This makes it especially valuable for technical analysis where maintaining the shape of price patterns is crucial.
## Common Settings and Parameters
| Parameter | Default | Function | When to Adjust |
|-----------|---------|----------|---------------|
| Window Size | 11 | Number of points used in local fitting (must be odd) | Increase for smoother output, decrease for better feature preservation |
| Polynomial Order | 2 | Order of fitting polynomial (2 or 4) | Use 2 for general smoothing, 4 for better peak preservation |
| Source | close | Price data used for calculation | Consider using hlc3 for more stable fitting |
**Pro Tip:** A window size of 11 with polynomial order 2 provides a good balance between smoothing and feature preservation. For sharper peaks and valleys, use order 4 with a smaller window size.
## Calculation and Mathematical Foundation
**Simplified explanation:**
The filter fits a polynomial of specified order to a moving window of price data. The smoothed value at each point is computed from this local fit, effectively removing noise while preserving the underlying shape of the data.
**Technical formula:**
For a window of size N and polynomial order M, the filtered value is:
y = Σ(c_i × x )
Where:
- c_i are the pre-computed filter coefficients
- x are the input values in the window
- Coefficients depend on window size N and polynomial order M
> 🔍 **Technical Note:** The implementation uses optimized coefficient calculations for orders 2 and 4, which cover most practical applications while maintaining computational efficiency.
## Interpretation Details
The Savitzky-Golay filter can be used in various trading strategies:
* **Pattern recognition:** Preserves chart patterns while removing noise
* **Peak detection:** Maintains amplitude and width of significant peaks
* **Trend analysis:** Smooths price movement without distorting important transitions
* **Divergence trading:** Better preservation of local maxima and minima
* **Volatility analysis:** Accurate representation of price movement dynamics
## Limitations and Considerations
* **Computational complexity:** More intensive than simple moving averages
* **Edge effects:** First and last few points may show end effects
* **Parameter sensitivity:** Performance depends on appropriate window size and order selection
* **Data requirements:** Needs sufficient points for polynomial fitting
* **Complementary tools:** Best used with volume analysis and momentum indicators
## References
* Savitzky, A., Golay, M.J.E. "Smoothing and Differentiation of Data by Simplified Least Squares Procedures," Analytical Chemistry, 1964
* Press, W.H. et al. "Numerical Recipes: The Art of Scientific Computing," Chapter 14
* Schafer, R.W. "What Is a Savitzky-Golay Filter?" IEEE Signal Processing Magazine, 2011
Bilateral Filter (BILATERAL)The Bilateral Filter is an edge-preserving smoothing technique that combines spatial filtering with intensity filtering to achieve noise reduction while maintaining significant price structure. Originally developed in computer vision for image processing, this adaptive filter has been adapted for financial time series analysis to provide superior smoothing that preserves important market transitions. The filter intelligently reduces noise in stable price regions while preserving sharp transitions like breakouts, reversals, and other significant market structures that would be blurred by conventional filters.
## Core Concepts
* **Dual-domain filtering:** Combines traditional time-based (spatial) filtering with value-based (range) filtering for adaptive smoothing
* **Edge preservation:** Maintains important price transitions while aggressively smoothing areas of minor fluctuation
* **Adaptive processing:** Automatically adjusts filtering strength based on local price characteristics
The core innovation of the Bilateral Filter is its ability to distinguish between random noise and significant price movements. Unlike conventional filters that smooth everything equally, Bilateral filtering preserves major price transitions by reducing the influence of price points that differ significantly from the current price, effectively preserving market structure while still eliminating noise.
## Common Settings and Parameters
| Parameter | Default | Function | When to Adjust |
|-----------|---------|----------|---------------|
| Length | 14 | Controls the lookback window size | Increase for more context in filtering decisions, decrease for quicker response |
| Sigma_S_Ratio | 0.3 | Controls spatial (time) weighting | Lower values emphasize recent bars, higher values distribute influence more evenly |
| Sigma_R_Mult | 2.0 | Controls range (price) sensitivity | Lower values increase edge preservation, higher values increase smoothing |
| Source | close | Price data used for calculation | Consider using hlc3 for a more balanced price representation |
**Pro Tip:** For breakout trading strategies, try reducing Sigma_R_Mult to 1.0-1.5 to make the filter more sensitive to significant price moves, allowing it to preserve breakout signals while still filtering noise.
## Calculation and Mathematical Foundation
**Simplified explanation:**
The Bilateral Filter calculates a weighted average of nearby prices, where the weights depend on two factors: how far away in time the price point is (spatial weight) and how different the price value is (range weight). Points that are close in time AND similar in value get the highest weight. This means stable price regions get smoothed while significant changes are preserved.
**Technical formula:**
BF = (1 / Wp) × Σ_{q ∈ S} G_s(||p - q||) × G_r(|I - I |) × I
Where:
- G_s is the spatial Gaussian kernel: exp(-||p - q||² / (2 × σ_s²))
- G_r is the range Gaussian kernel: exp(-|I - I |² / (2 × σ_r²))
- Wp is the normalization factor (sum of all weights)
> 🔍 **Technical Note:** The sigma_r parameter is typically calculated dynamically based on local price volatility (standard deviation) to provide adaptive filtering - this automatically adjusts filtering strength based on market conditions.
## Interpretation Details
The Bilateral Filter can be applied in various trading contexts:
* **Trend identification:** Reveals cleaner underlying price direction by removing noise while preserving trend changes
* **Support/resistance identification:** Provides clearer price levels by preserving significant turning points
* **Pattern recognition:** Maintains critical chart patterns while eliminating distracting minor fluctuations
* **Breakout trading:** Preserves sharp price transitions for more reliable breakout signals
* **Pre-processing:** Can be used as an initial filter before applying other technical indicators to reduce false signals
## Limitations and Considerations
* **Computational complexity:** More intensive calculations than traditional linear filters
* **Parameter sensitivity:** Performance highly dependent on proper parameter selection
* **Non-linearity:** Non-linear behavior may produce unexpected results in certain market conditions
* **Interpretation adjustment:** Requires different interpretation than conventional moving averages
* **Complementary tools:** Best used alongside volume analysis and traditional indicators for confirmation
## References
* Tomasi, C. and Manduchi, R. "Bilateral Filtering for Gray and Color Images," Proceedings of IEEE ICCV, 1998
* Paris, S. et al. "A Gentle Introduction to Bilateral Filtering and its Applications," ACM SIGGRAPH, 2008






















