EMA Cross Strategy + Breakout Entry (Trend Filtered)A High-Probability Trading Strategy Using EMAs and Long-Term Trend Filters in Pine Script
In financial markets, successful trading often depends on identifying high-probability setups with consistent rules and clear confirmations. The Pine Script developed here combines the simplicity of exponential moving average (EMA) crossovers with the robustness of long-term trend filtering, enhancing entry timing and reducing exposure to false signals. This essay explains the strategy’s logic, technical components, strengths, and its potential effectiveness for active traders.
Introduction to the Strategy
This Pine Script trading strategy is built upon two foundational components:
1. EMA Crossovers: A well-established technique where a fast EMA (8-period) and a slower EMA (21-period) are used to detect short-term momentum shifts.
2. Trend Filtering Using SMA: A 100-period simple moving average (SMA) acts as a long-term trend indicator. Only trades in the direction of the dominant trend are considered valid.
These two elements are combined to create a high-probability, trend-following system that aims to capture meaningful price movements while avoiding low-quality entries that typically occur during sideways or choppy markets.
⸻
Core Entry Logic
The script defines two distinct entry conditions designed to complement each other:
1. Standard EMA Crossover Entry (Type A)
This is a classic momentum entry condition. When the 8 EMA crosses above the 21 EMA, it indicates a shift in short-term momentum. However, this signal alone is insufficient in many market conditions, especially when the broader trend is unclear or reversing. To mitigate this risk, the crossover is only accepted when the 100 SMA is in an uptrend, defined as the SMA currently being higher than its value on the previous bar. This ensures the strategy only takes long entries in bullish environments, aligning with the principle of trading with the trend.
2. Breakout Entry After Trend Reversal (Type B)
The second entry condition captures powerful “breakout” opportunities that often follow a fresh trend reversal. Specifically, when the 100 SMA transitions from a downtrend to an uptrend, the script starts a 15-bar lookback window. If, during that window, the price, 8 EMA, and 21 EMA all rise above the long-term SMA, it is considered a confirmation of trend strength and momentum alignment. A long entry is then signaled.
This condition is designed to capitalize on early participation in new uptrends, catching strong price expansions that typically follow a change in market direction.
⸻
Exit Logic
The exit logic is intentionally simple and tied to the same framework as entries. A position is exited when the 8 EMA crosses below the 21 EMA, and the 100 SMA remains in an uptrend. This ensures that exits are aligned with weakening momentum while the larger trend remains bullish. This avoids premature exits during minor pullbacks and focuses on retaining trades during sustained uptrends.
Notably, exits do not occur when the long-term trend has flipped bearish. This design choice prevents “reverse trend” noise from triggering exits too early and instead focuses purely on short-term weakness within a bullish macro backdrop.
⸻
Technical Components of the Script
The Pine Script is structured with clear and logical components:
1. Inputs: The user can customize the periods for the fast EMA, slow EMA, long-term SMA, and the trend-reversal lookback window (defaulted to 15 bars).
2. Trend Detection: The long-term trend is calculated using the slope of the 100 SMA. If the SMA is rising, the trend is marked as bullish and is visually plotted in green; otherwise, it is plotted in red.
3. State Management: The script tracks how many bars have passed since the long-term trend turned bullish. This is managed using a var integer variable that resets upon trend reversal and increments while the trend remains up.
4. Entry and Exit Signals: These are plotted as shape markers on the chart — green triangles for entry and red triangles for exit — providing visual clarity.
Each of these components works in harmony to ensure that trade signals are issued only in favorable environments with multiple confirmations.
⸻
Benefits of the Strategy
There are several key advantages to using this hybrid strategy:
1. Filters Out Choppy Markets
By requiring the long-term SMA to be in an uptrend for any entry or exit signal to be valid, the strategy avoids noisy, sideways price action where EMA crossovers are more likely to produce false signals.
2. Dual Entry Approach
The inclusion of two different entry types allows the strategy to both:
• Capture new trends as they emerge (Breakout Entry).
• Ride existing trends using EMA crossover logic (Standard Entry).
This dual approach balances early participation with trend confirmation, offering flexibility for different market conditions.
3. Clear Exit Criteria
By tying exits to a momentum weakening signal (EMA crossover down), traders are not left guessing when to exit. This supports consistent execution and reduces emotional decision-making.
4. Trend Alignment
Aligning both entry and exit decisions with the broader trend increases the probability that trades will move in the desired direction. This is a cornerstone of successful trend-following strategies.
5. Modular Design
The script’s modularity allows traders to easily expand it with backtesting functions, alerts, or additional filters like RSI, ATR, or volume-based conditions, depending on their individual trading needs.
⸻
Use Cases and Applications
This strategy is particularly well-suited for swing traders and position traders operating on the 4-hour or daily timeframes. It is also effective on trending assets like equity indices, major stocks, or cryptocurrencies with defined directional movement.
Additionally, this script can be used as a signal engine in a larger portfolio of strategies, where only trades with trend confirmation are allowed to proceed. It can also function as a discretionary trading aid, helping traders visually identify when technical conditions align favorably.
⸻
Conclusion
This enhanced EMA crossover strategy, powered by a long-term trend filter and a secondary breakout entry condition, offers a robust and disciplined approach to navigating financial markets. By focusing on trading in the direction of a confirmed uptrend and using both momentum and structural price behavior for entry confirmation, the strategy aims to minimize whipsaw trades and maximize participation in sustained bullish moves.
Its simple logic, visual clarity, and strong filtering mechanisms make it both practical for new traders and a valuable foundation for more advanced systems. Whether used as-is or further expanded with custom features, this Pine Script serves as an excellent tool for executing a structured, high-probability trading plan.
Corak carta
Doji Candle with Horizontal Lines Raja Saien🔰 Doji Candle with Horizontal Lines By Raja Saien
Created by: Wasif Samejo
Script Type: Visual Doji Identifier with Key Level Markers
Overlay: Yes
📌 Description:
This indicator helps you visually identify Doji candles and automatically plots horizontal key levels based on their high, low, and a defined price zone.
A Doji candle is a powerful signal in price action trading that shows indecision in the market, often leading to strong reversals or breakouts. This script is especially useful for traders who want to mark such candles and prepare for possible trade setups.
📈 Features:
✅ Automatic Doji Detection – Based on customizable body size (20.0% of the total range).
✅ Highlights Doji Candle – Visually changes the bar color to yellow when a Doji is found.
✅ High/Low Horizontal Lines – Marks the candle's actual high and low for better visual analysis.
✅ Zone Lines Above/Below – Draws outer levels to form a zone around the Doji, helpful for breakout setups.
Zone Line Color – Set the color for the upper and lower zone lines.
High/Low Line Color – Set the color for the high and low candle levels.
💡 Combine this indicator with trendlines, volume, or Fibonacci tools for better confirmation.
Same Date Last Year PatternThis tool is designed to help you analyze past price patterns from the same date last year to gain insights into potential market behavior today. It’s perfect for traders who want to spot recurring trends or directional cues (buy or sell signals) based on historical candle formations, rather than focusing on exact price levels. Here’s how it works and how to use it:
How It Works
Historical Lookback: The script examines the price action from the same calendar date last year (e.g., May 26, 2024, for today, May 26, 2025). Since markets may be closed on weekends or holidays (like Memorial Day), it automatically finds the nearest trading day with available data.
Pattern Detection: Instead of showing raw prices (which may not match today’s higher or lower price range), it analyzes the candle’s shape and direction. It tells you if the past candle was bullish (closing higher, suggesting a potential buy) or bearish (closing lower, suggesting a potential sell), along with details like wick size and the trend leading up to it.
Contextual Insight: It checks the trend from the previous few days (uptrend, downtrend, or sideways) to give you a sense of the market’s mood back then. This helps you decide if the pattern might repeat.
Prediction Suggestion: Based on last year’s candle direction, it offers a simple guess for the next candle’s potential move (e.g., bullish or bearish), though this is for reference only and not a guaranteed signal.
Key Features
Customizable Asset Type: You can set it for "Traditional" markets (e.g., stocks, forex) or "Crypto" (e.g., Bitcoin), adjusting how it searches for data based on whether the market runs 24/7.
Visual Cues: Labels appear on your chart showing the pattern and prediction, with colors (green for bullish, red for bearish, blue for prediction) to make it easy to read.
Range Consideration: This tool works best when the chart’s price range is around 1000 (e.g., stocks trading near $1000 or crypto pairs with similar values). Outside this range, the label positioning might not align perfectly due to scaling differences.
How to Use
Add to Chart: Load this script into TradeLocker’s indicator section on a daily chart for best results.
Select Asset Type: In the settings, choose "Traditional" for stocks or forex, or "Crypto" for 24/7 markets like Bitcoin.
Check Data: On the same date each year (e.g., May 26), it will display the pattern from last year’s nearest trading day. Ensure your chart has at least 455 days of historical data loaded to cover the search range.
Interpret Results: Look at the label to see the pattern (e.g., "Bullish Candle, Potential Buy"), trend context, and prediction. Use this to inform your trading decisions, but combine it with other tools for confirmation.
Important Notes
Limitations: It may show "No Data Found" if historical data isn’t available within its search window (up to 90 days around the target date for traditional markets). This is more likely for weekends or holidays. For best results, test it on assets trading around the 1000 price range.
Not a Guarantee: The prediction is based solely on last year’s candle and trend, not a definitive signal. Use it as a guide alongside your strategy and market analysis.
Customization: If you need it to work outside the 1000 range or add more pattern details (e.g., specific candlestick types), let the community know, and we can refine it!
This tool was crafted to help traders explore historical patterns in a user-friendly way. Share your feedback or suggestions in the TradeLocker community to make it even better!
EMA 9/21 Cross + Volume FilterThis indicator plots fast (9-period) and slow (21-period) EMAs and highlights bullish or bearish crossovers only when volume exceeds its 20-period average, filtering out low-participation whipsaws. It places “UP”/“DN” triangles on qualifying crosses and includes built-in alertcondition() triggers plus a single alert() call, so one “Any alert() function call” alert delivers real-time push, e-mail, or webhook notifications. Adjustable inputs: EMA lengths, volume-SMA length, and a toggle to show/hide signal labels. Ideal for trend-following scalps or swing entries on any timeframe and ticker.
Consolidation BoxesConsolidation Boxes — Indicator
Overview :
This indicator automatically detects and highlights periods of market consolidation, drawing shaded boxes around tight price ranges where the market is temporarily indecisive. It’s designed to help traders easily identify when price is moving sideways — a key phase that often precedes a breakout.
Key Features :
-Automatic Consolidation Detection: Recognizes when a series of candles close within a defined range and marks the area as a consolidation zone.
-Customizable Parameters: Set how many candles must consolidate before a box is drawn.
-Breakout Alerts: Notifies you when price breaks out above or below a consolidation box — a potential signal for trade entries.
-Clean Chart Management: Optional setting to automatically remove old zones when new consolidations form.
-Dynamic Box Extension: As long as price stays within the box, the zone will continue to extend until a breakout occurs.
Inputs :
- Minimum Consolidation Candles : Define how many candles must fit within a range to confirm a consolidation zone.
- Terminate Old Zones : Automatically delete the previous zone when a new one is formed (optional).
How to use :
1. Add the Indicator: Apply it to any chart — works across all timeframes and markets (e.g., crypto, stocks, forex).
2. Adjust Parameters: Choose how many candles must consolidate to form a valid box. Enable or disable zone termination to fit your preference.
3. Watch the Boxes: The indicator draws a shaded box once it detects a valid consolidation zone. The box will continue to extend as long as price stays within the range.
4. Look for Breakouts: When price breaks above or below the box, a breakout is confirmed and an alert (if enabled) will trigger — great for breakout trading strategies.
5. Use in Strategy: Combine with volume, momentum indicators, or price action to validate breakouts and filter false signals.
Ideal For :
Traders who want to visually identify consolidation areas and trade breakout setups with minimal manual analysis. Especially useful for scalpers, day traders, and swing traders looking to anticipate volatility after quiet periods.
Chaikin Momentum Scalper🎯 Overview
The Chaikin Momentum Scalper is a powerful trading strategy designed to identify momentum shifts in the market and ride the trend for maximum profits. This strategy is ideal for trading the USD/JPY currency pair on a 15-minute chart, making it perfect for high-frequency trading (HFT). Whether you’re starting with a small account of $1,000 or managing a larger portfolio, this strategy can scale to suit your needs.
________________________________________
🔑 How the Strategy Works
Here’s how the Chaikin Momentum Scalper identifies trade opportunities:
1️⃣ Momentum Detection
The core of this strategy is the Chaikin Oscillator, a tool that measures the flow of money into or out of a market. It helps us understand whether buyers (bulls) or sellers (bears) are in control.
• When the indicator crosses above zero, it signals that buying momentum is picking up – a buying opportunity.
• When the indicator crosses below zero, it signals that selling momentum is increasing – a selling opportunity.
2️⃣ Trend Confirmation
We don’t just jump into trades based on momentum alone. We also use a 200-period simple moving average (SMA) to confirm the overall trend.
• If the price is above the SMA, it confirms an uptrend, so we look for buy trades.
• If the price is below the SMA, it confirms a downtrend, so we look for sell trades.
This way, we align our trades with the broader market direction for higher success rates.
3️⃣ Volatility & Risk Management
We use a tool called the Average True Range (ATR) to measure market volatility. This helps us:
• Set a stop-loss (where we’ll exit the trade if the market moves against us) at a safe distance from our entry point.
• Set a take-profit (where we’ll lock in profits) at a target that’s larger than the stop-loss, ensuring a good reward-to-risk ratio.
This approach adapts to the market’s behavior, tightening stops in calmer conditions and widening them when volatility increases.
________________________________________
📈 Why This Strategy Works
✅ It combines momentum and trend-following principles, increasing the chances of trading in the right direction.
✅ It dynamically adjusts risk levels based on market volatility, keeping losses small and profits big.
✅ It’s scalable – perfect for both small accounts (like $1,000) and larger, corporate-sized portfolios.
✅ It has been deep-backtested on USD/JPY 15-minute charts, proving its consistency across different market conditions.
________________________________________
📝 Important Notes
📌 This strategy is best used for USD/JPY on a 15-minute chart, making it great for high-frequency trading while you continue to build and refine your trading system.
📌 It’s designed to work on both small ($1,000+) and large accounts, so it can grow with you as your capital increases.
📌 While it has passed deep backtesting on this pair and timeframe, remember that no strategy is perfect. It’s crucial to test it yourself, start with a demo account, and apply proper risk management before trading real money.
🌟 Final Thoughts
The Chaikin Momentum Scalper is a solid, adaptable trading approach combining momentum, trend direction, and volatility awareness. If you’re looking for a strategy to kick-start your trading journey—or to add to your existing system—it offers a strong foundation.
Triangle Asc/Descending Patterns [Drobode]█ DESCRIPTION
The script automatically tracks the descending or ascending triangle pattern. The script provides advanced settings, allowing you to adjust the pattern accuracy from high to low depending on your needs and technical analysis style. The main goal of the script is to facilitate the routine work of a trader in identifying certain trading situations (patterns). However, you should understand that the script is not a full-fledged self-sufficient strategy, in case of receiving a signal, it is recommended that you additionally conduct a comprehensive thorough analysis before taking trading actions. The script can be useful for traders of all levels, both beginners and experienced analysts. This variation of the script, in case of identifying a pattern, draws a contour triangle with the background color of the figure. The ascending triangle has a blue color, the descending triangle has a red color. The logic of the script provides that one of the legs (one side) of the triangle is always a horizontal line, simultaneously being a line of resistance or support, other variations of triangle patterns are not tracked. According to generally defined beliefs and observations of pattern formation, a descending and ascending triangle may indicate a possible breakdown of the conditional horizontal level to which the price of the instrument has approached, however, at the same time it is necessary to deeply analyze many other factors at this point, in particular, such as volumes, consolidation, volatility, and so on.
█ SCRIPT SETTINGS
By default, the script was pre-developed and tested on the M15 timeframe with the USDT.P crypto futures instruments.
Alert
The Alert function in the script is enabled by default, you just need to activate the Alert in the TradingView window and select the signal source - Triangle Asc/Descending Patterns .
The notification provides the following information (example):
Triangle_Ascending
Ticker- EGLDUSDT.P
Price-19.754
Timeframe- 15
Period length-160
Periods length
The script allows you to set the period length (number) of bars on which the calculation will be performed. Different periods make it possible to cover more timeframes (in particular, larger timeframes). The calculation is performed simultaneously on all periods, but you can turn off "Period length 3" and "Period length 4" by clicking on the check mark, this can speed up the script. The following period values are set by default: "Period length 1" – 80,
"Period length 2" – 160, "Period length 3" – 300, "Period length 4" – 681.
Percentage deviation of extremes
The next settings are the percentage deviation from the hypotenuse and horizontal leg, which creates the zone in which the extremes of the bars that will form the triangle shape should be. The smaller the deviation, the greater the accuracy and the closer to the hypotenuse and leg the bar extrema should be, however, in this case the number of pattern identifications will be smaller. By default, the deviation zone from the hypotenuse "Deflection zone of tangents to the hypotenuse" is - 0.4%, the deviation zone from the horizontal leg "Tangent deviation zone horizontal leg" is - 0.08%.
The presence of extrema at certain points on the sides of a triangle
The last block of settings are the conditions that increase the accuracy of the proportions of the pattern figure. These settings are aimed at confirming the presence of extrema in certain areas along the hypotenuse and horizontal leg. Thus, enabling "Extrema on the horizontal leg almost along the entire length" means that only those triangles will be tracked in which the horizontal leg zone has extrema almost along the entire length of this leg, this increases the accuracy but reduces the number of detected patterns. "Extremes present on second half of horizontal leg (more than 50%)" assumes that only those triangles will be tracked in which the extrema are present on the second half of the length of the given leg (more than 50%) in the zone of the horizontal leg. "Presence of an extrema in the middle region of the hypotenuse" assumes that only those triangles will be tracked in which the extrema are present on a certain segment of length in the central region of the hypotenuse.
[Stoxello] Linear Regression Chop Zone Indicator📊 Linear Regression Chop Zone Indicator – Description
The Stoxello Linear Regression Chop Zone Indicator is a custom-built, multi-functional visual tool for identifying market trend direction, strength, and potential entry/exit signals using a combination of linear regression, EMA slope angles, and volatility-adjusted smoothing.
🧠 Core Features:
🔶 1. Chop Zone Color Coding (Trend Strength via EMA Angle)
The script calculates the angle of a 34-period EMA, representing momentum and trend steepness.
This angle is then translated into color-coded bars on the chart to help traders visually identify chop zones and trend strength.
Turquoise / Dark Green / Pale Green = Increasing bullish trend.
Lime / Yellow = Neutral or low momentum (choppy zones).
Orange / Red / Dark Red = Increasing bearish trend.
🔶 2. Linear Regression Deviation Channels (Trend Path)
A custom linear regression line is drawn with +/- deviation bands above and below it.
These lines track the expected price path and visually define upper/lower zones, similar to regression channels.
The correlation (R) and determination (R²) values are displayed as labels on the chart, measuring the strength and reliability of the linear fit.
🔶 3. Linear Regression-Adjusted EMA (Smoothing with Volatility)
A novel volatility-adaptive EMA is computed by combining a traditional EMA with distance from a linear regression line.
The result is a dynamic EMA that becomes more reactive in volatile conditions and smoother in stable ones.
Two lines are plotted:
Primary EMA (Yellow)
Trigger Line (Lagged by 2 bars, Fuchsia)
The fill color between these two helps visualize short-term bullish or bearish pressure.
🔶 4. Buy/Sell Signal Logic with De-Duplication
Buy signals are triggered when:
The adjusted EMA crosses above its previous value (bullish inflection).
Or when the EMA angle exceeds +5° (strong trend detected).
Sell signals occur when:
The adjusted EMA crosses below its previous value.
Each signal is deduplicated by tracking the last signal using var string lastSignal:
No repeat buys after a buy, or sells after a sell.
Signals are marked on the chart using clean text labels:
Buy: "•Entry• = Price"
Sell: "•Exit• = Price"
🔶 5. Alerts
Two alertconditions are included for:
BUY signals (long_signal)
SELL signals (short_signal)
Can be used with webhooks, email, or app notifications to automate or monitor trades.
🔍 Ideal Use Cases:
Traders who want a clear visual aid for market chop vs. trend.
Swing or intraday traders looking for adaptive entry/exit points.
Anyone combining regression analysis and momentum tracking into one indicator.
cd_respect2_EQ_Cx🔹 Overview:
Many traders form a bias or look for trade setups by analyzing the high (H) and low (L) of previous higher timeframe candles. For example: a close above the previous daily high, a failure to close after breaking the high, or approaching the level without making a new high. As we’ve been taught to focus on these key levels, I wanted to draw attention to what's happening at the mid-levels (Equilibrium) of the current and higher timeframe candles.
We’ve all heard the phrase “Strong price reacts from equilibrium,” yet most of us wait at the extremes.
While working on equilibrium levels of both higher timeframes and the current timeframe, I noticed that when a current candle closes above/below the previous HTF candle's high/low, price often respects the part of the candle that caused the break — which I refer to as the Last Block. When respected, price tends to continue with momentum; when lost, a pullback or reversal often follows.
________________________________________
🔹 About the Indicator:
This tool analyzes four different higher timeframes and shows:
• Current candle equilibrium levels
• Previous candle equilibrium levels (2 display options):
1. On Box – classic display
2. On Candle – equilibrium is linked to the last candle that includes the level, making those candles more meaningful or "strengthened"
• Alerts (standard) and on-screen warnings when price approaches previous equilibrium levels
• High/Low levels of previous HTF candles
• High/Low levels of live HTF candles
• Last Block: the upper or lower part of the candle that caused the breakout when price closes above/below the previous HTF high/low
• Countdown timer until the close of selected HTFs
________________________________________
🔹 Menus & Usage:
🔸 Show/Hide Tab:
• Toggle Previous Equilibrium display (On Candle / On Box)
• Toggle Live Equilibrium levels, color selection, and left extension
• Toggle Current Candle Equilibrium and colors
• Alert on Chart: flashing on-screen visual alert
• Approach Limit: sets how close price must be to trigger alert
• Remaining Time (RT): toggle countdown display for selected timeframes
________________________________________
🔸 HTF H/L Levels Tab:
• Show previous and live HTF candle highs/lows
• Customize colors, starting points, and left extension options
________________________________________
🔸 Timeframes & Options Tab:
• Select which timeframes to display
• Choose level colors
• Enable price alerts
• Control visibility in the time chart
• Toggle Last Block display (close-to-high/low)
________________________________________
🔸 Look Back HTF Candles Tab:
• Delete filled levels: removes invalidated zones; only unmitigated remain
• Back Control: set how many candles to look back per timeframe (unlimited if not set)
________________________________________
🔸 HTF Boxes Tab:
• Display HTF candles in boxes
• Set colors (single color or per timeframe)
• Adjust font sizes across the chart
________________________________________
🔹 Usage & Last Blocks:
The core idea behind both equilibrium levels and last blocks is:
Price should “gain” and respect them to validate continuation.
Viewing multiple timeframes together strengthens bias.
Each level is treated as part of the candle it's associated with — defining the “area to be gained.”
“Did price respect the level because of that candle, or did the candle gain significance because it aligned with the level? That’s open for debate.”
(In my opinion, the candle gains significance because it aligns with the level.)
When respected, these levels/blocks act as support; when lost, they act as resistance.
In suitable timeframes, reclaiming previous equilibrium levels may be interpreted as CHoCH / CISD / IDM depending on the context.
________________________________________
🔹 Usage Example – Last Blocks:
I personally trade on 1-minute and use Daily / H4 / H1 / 15m as selected timeframes.
For example, if price reclaims the previous 15m level, I view it as a Change of Character. I then expect the next candle to show respect in that direction.
Choose timeframes based on your trading style.
Sometimes, HTF levels (past and live) cluster tightly — these areas are key watch zones for me.
That’s the reason I decided to share this indicator.
________________________________________
🔹 Chart Examples:
🔸 Example 1:
Price closes above both the 12:45 15m candle and the 12:00 H1 equilibrium levels.
Last Block forms. After retracing, price mitigates the block and respects live equilibrium levels (H4/H1/15m).
🔸 Example 2:
Explained on chart – Levels that pushed price down in the bearish trend later acted as support.
🔸 Example 3 – CHoCH/CISD/IDM Alternative:
Explained on chart – Replacing structural signals with equilibrium levels.
I see this pattern often — very effective.
🔸 Example 4:
Many levels are clustered in a narrow range; price shows respect across the board.
________________________________________
🔹 Final Note:
Hope you like the tool. I’d love to hear your thoughts and suggestions.
"Keep in mind, strong price reverses from equilibrium."
Happy trading!
Lorentzian Classification - Advanced Trading DashboardLorentzian Classification - Relativistic Market Analysis
A Journey from Theory to Trading Reality
What began as fascination with Einstein's relativity and Lorentzian geometry has evolved into a practical trading tool that bridges theoretical physics and market dynamics. This indicator represents months of wrestling with complex mathematical concepts, debugging intricate algorithms, and transforming abstract theory into actionable trading signals.
The Theoretical Foundation
Lorentzian Distance in Market Space
Traditional Euclidean distance treats all feature differences equally, but markets don't behave uniformly. Lorentzian distance, borrowed from spacetime geometry, provides a more nuanced similarity measure:
d(x,y) = Σ ln(1 + |xi - yi|)
This logarithmic formulation naturally handles:
Scale invariance: Large price moves don't overwhelm small but significant patterns
Outlier robustness: Extreme values are dampened rather than dominating
Non-linear relationships: Captures market behavior better than linear metrics
K-Nearest Neighbors with Relativistic Weighting
The algorithm searches historical market states for patterns similar to current conditions. Each neighbor receives weight inversely proportional to its Lorentzian distance:
w = 1 / (1 + distance)
This creates a "gravitational" effect where closer patterns have stronger influence on predictions.
The Implementation Challenge
Creating meaningful market features required extensive experimentation:
Price Features: Multi-timeframe momentum (1, 2, 3, 5, 8 bar lookbacks) Volume Features: Relative volume analysis against 20-period average
Volatility Features: ATR and Bollinger Band width normalization Momentum Features: RSI deviation from neutral and MACD/price ratio
Each feature undergoes min-max normalization to ensure equal weighting in distance calculations.
The Prediction Mechanism
For each current market state:
Feature Vector Construction: 12-dimensional representation of market conditions
Historical Search: Scan lookback period for similar patterns using Lorentzian distance
Neighbor Selection: Identify K nearest historical matches
Outcome Analysis: Examine what happened N bars after each match
Weighted Prediction: Combine outcomes using distance-based weights
Confidence Calculation: Measure agreement between neighbors
Technical Hurdles Overcome
Array Management: Complex indexing to prevent look-ahead bias
Distance Calculations: Optimizing nested loops for performance
Memory Constraints: Balancing lookback depth with computational limits
Signal Filtering: Preventing clustering of identical signals
Advanced Dashboard System
Main Control Panel
The primary dashboard provides real-time market intelligence:
Signal Status: Current prediction with confidence percentage
Neighbor Analysis: How many historical patterns match current conditions
Market Regime: Trend strength, volatility, and volume analysis
Temporal Context: Real-time updates with timestamp
Performance Analytics
Comprehensive tracking system monitors:
Win Rate: Percentage of successful predictions
Signal Count: Total predictions generated
Streak Analysis: Current winning/losing sequence
Drawdown Monitoring: Maximum equity decline
Sharpe Approximation: Risk-adjusted performance estimate
Risk Assessment Panel
Multi-dimensional risk analysis:
RSI Positioning: Overbought/oversold conditions
ATR Percentage: Current volatility relative to price
Bollinger Position: Price location within volatility bands
MACD Alignment: Momentum confirmation
Confidence Heatmap
Visual representation of prediction reliability:
Historical Confidence: Last 10 periods of prediction certainty
Strength Analysis: Magnitude of prediction values over time
Pattern Recognition: Color-coded confidence levels for quick assessment
Input Parameters Deep Dive
Core Algorithm Settings
K Nearest Neighbors (1-20): More neighbors create smoother but less responsive signals. Optimal range 5-8 for most markets.
Historical Lookback (50-500): Deeper history improves pattern recognition but reduces adaptability. 100-200 bars optimal for most timeframes.
Feature Window (5-30): Longer windows capture more context but reduce sensitivity. Match to your trading timeframe.
Feature Selection
Price Changes: Essential for momentum and reversal detection Volume Profile: Critical for institutional activity recognition Volatility Measures: Key for regime change detection Momentum Indicators: Vital for trend confirmation
Signal Generation
Prediction Horizon (1-20): How far ahead to predict. Shorter horizons for scalping, longer for swing trading.
Signal Threshold (0.5-0.9): Confidence required for signal generation. Higher values reduce false signals but may miss opportunities.
Smoothing (1-10): EMA applied to raw predictions. More smoothing reduces noise but increases lag.
Visual Design Philosophy
Color Themes
Professional: Corporate blue/red for institutional environments Neon: Cyberpunk cyan/magenta for modern aesthetics
Matrix: Green/red hacker-inspired palette Classic: Traditional trading colors
Information Hierarchy
The dashboard system prioritizes information by importance:
Primary Signals: Largest, most prominent display
Confidence Metrics: Secondary but clearly visible
Supporting Data: Detailed but unobtrusive
Historical Context: Available but not distracting
Trading Applications
Signal Interpretation
Long Signals: Prediction > threshold with high confidence
Look for volume confirmation
- Check trend alignment
- Verify support levels
Short Signals: Prediction < -threshold with high confidence
Confirm with resistance levels
- Check for distribution patterns
- Verify momentum divergence
- Market Regime Adaptation
Trending Markets: Higher confidence in directional signals
Ranging Markets: Focus on reversal signals at extremes
Volatile Markets: Require higher confidence thresholds
Low Volume: Reduce position sizes, increase caution
Risk Management Integration
Confidence-Based Sizing: Larger positions for higher confidence signals
Regime-Aware Stops: Wider stops in volatile regimes
Multi-Timeframe Confirmation: Align signals across timeframes
Volume Confirmation: Require volume support for major signals
Originality and Innovation
This indicator represents genuine innovation in several areas:
Mathematical Approach
First application of Lorentzian geometry to market pattern recognition. Unlike Euclidean-based systems, this naturally handles market non-linearities.
Feature Engineering
Sophisticated multi-dimensional feature space combining price, volume, volatility, and momentum in normalized form.
Visualization System
Professional-grade dashboard system providing comprehensive market intelligence in intuitive format.
Performance Tracking
Real-time performance analytics typically found only in institutional trading systems.
Development Journey
Creating this indicator involved overcoming numerous technical challenges:
Mathematical Complexity: Translating theoretical concepts into practical code
Performance Optimization: Balancing accuracy with computational efficiency
User Interface Design: Making complex data accessible and actionable
Signal Quality: Filtering noise while maintaining responsiveness
The result is a tool that brings institutional-grade analytics to individual traders while maintaining the theoretical rigor of its mathematical foundation.
Best Practices
- Parameter Optimization
- Start with default settings and adjust based on:
Market Characteristics: Volatile vs. stable
Trading Timeframe: Scalping vs. swing trading
Risk Tolerance: Conservative vs. aggressive
Signal Confirmation
Never trade on Lorentzian signals alone:
Price Action: Confirm with support/resistance
Volume: Verify with volume analysis
Multiple Timeframes: Check higher timeframe alignment
Market Context: Consider overall market conditions
Risk Management
Position Sizing: Scale with confidence levels
Stop Losses: Adapt to market volatility
Profit Targets: Based on historical performance
Maximum Risk: Never exceed 2-3% per trade
Disclaimer
This indicator is for educational and research purposes only. It does not constitute financial advice or guarantee profitable trading results. The Lorentzian classification system reveals market patterns but cannot predict future price movements with certainty. Always use proper risk management, conduct your own analysis, and never risk more than you can afford to lose.
Market dynamics are inherently uncertain, and past performance does not guarantee future results. This tool should be used as part of a comprehensive trading strategy, not as a standalone solution.
Bringing the elegance of relativistic geometry to market analysis through sophisticated pattern recognition and intuitive visualization.
Thank you for sharing the idea. You're more than a follower, you're a leader!
@vasanthgautham1221
Trade with precision. Trade with insight.
— Dskyz , for DAFE Trading Systems
Turbo Market Regime Detector [QuantAlgo]The Turbo Market Regime Detector is a market state classification system that combines volatility-adaptive filtering with slope analysis to identify and categorize market regimes. It helps traders and investors distinguish between trending and ranging market conditions across different timeframes and asset classes.
🟢 Technical Foundation
The Turbo Market Regime Detector employs a multi-layered analytical approach to market regime identification, incorporating:
Volatility-Adaptive Regime Filter (VARF) : Uses dynamic alpha calculation based on price volatility and range to create an adaptive filter that responds to changing market conditions
Slope Analysis : Calculates the absolute slope of the VARF curve and applies customizable moving average smoothing to determine trend strength and market regime classification
Normalized Histogram : Transforms raw slope data into percentage-based metrics (0-100%) for interpretation of market conditions
Multi-Threshold Classification System : Implements user-defined thresholds to categorize markets into Strong Trend, Weak Trend, and Ranging regimes
The indicator processes price data through mathematical operations including volatility adjustment, slope normalization, and statistical range analysis. This creates a regime detection system that adapts to market volatility while maintaining classification consistency across different timeframes and asset classes.
🟢 Key Features & Signals
1. Market Regime Classification
The indicator presents market conditions through a normalized histogram that distinguishes between three distinct market states:
1/ Strong Trend Regime: When the histogram exceeds the strong trend threshold (default 30%), indicating directional market movement with sustained momentum
2/ Weak Trend Regime: When the histogram falls between weak trend (default 10%) and strong trend thresholds, representing transitional market conditions with moderate directional bias
3/ Ranging Regime: When the histogram remains below the weak trend threshold, signaling consolidation periods with limited directional movement
This classification system provides insights into:
→ Current market state with percentage-based quantification
→ Regime transitions and their timing
→ Market momentum strength across different timeframes
2. Visual Feedback System
The indicator features multiple visualization options for market analysis:
Background Coloring: Optional chart background coloring that applies regime-based colors to both the indicator pane and main price chart for visual context
Bar Coloring: Price bar coloring based on current market regime, providing visual feedback on market conditions
Reference Lines: Horizontal reference lines at 25%, 50%, 75%, and 100% levels for percentage assessment and historical comparison
Information Table: Real-time status display showing current market state and trend strength percentage with customizable positioning and sizing options
3. Alert and Notification System
The indicator generates alerts for regime transitions:
State Change Alerts: Notifications triggered when the market transitions between regime states (Strong Trend ↔ Weak Trend ↔ Ranging)
Specific Regime Entry Alerts: Individual alert conditions for entering Strong Trend, Weak Trend, or Ranging regimes for targeted trading strategies
Customizable Alert Messages: Pre-formatted alert messages including exchange and ticker information for context and decision-making
🟢 Practical Usage Guidelines
→ Regime-Based Strategy Selection: Use the indicator to identify potential trading strategies - trend-following during Strong Trend regimes, mean-reversion during Ranging periods, and adjusted position sizing during Weak Trend transitions
→ Multi-Timeframe Analysis: Apply the indicator across different timeframes to understand market regime hierarchy and identify confluence between short-term and long-term market states
→ Threshold Optimization: Adjust regime thresholds based on market volatility and asset characteristics - lower thresholds for more sensitive regime detection, higher thresholds for more definitive regime changes
🟢 Configuration Tips
VARF settings optimization:
→ Lower thresholds (-0.3 to -0.5) for more responsive regime detection in volatile markets
→ Higher thresholds (-0.1 to 0.1) for smoother signals in stable market conditions
→ Enable adaptive VARF for automatic volatility adjustment across different market cycles
Slope analysis parameter tuning:
→ Shorter MA lengths (100-200) for faster regime transition signals
→ Longer MA lengths (300-500) for more stable regime identification
→ Adjust sensitivity multiplier based on desired responsiveness vs. stability balance
Regime interpretation framework:
→ Strong Trend regimes for momentum-based strategies and trend following
→ Ranging regimes for mean-reversion and support/resistance trading
→ Weak Trend periods for reduced position sizing and cautious market approach
Complementary analysis integration:
→ Volume analysis for regime change confirmation
→ Support/resistance levels for entry/exit timing within regime contexts
→ Price action patterns for validation of regime-based trading decisions
→ Economic calendar events that may influence regime transitions
ES OHLC BASED ON 9:301. RTH Price Levels
YC (Yesterday's Close): Previous day's RTH closing price at 4:00 PM ET
0DTE-O (Today's Open): Current day's RTH opening price at 9:30 AM ET
T-E-M (Today's Europe-Asia Midpoint): Midpoint of overnight session high/low
T-E-R (Today's Europe-Asia Resistance): Overnight session high
T-E-S (Today's Europe-Asia Support): Overnight session low
Y-T-M (Yesterday-Today Midpoint): Midpoint between YC and 0DTE-O
2. Previous Bar Percentage Levels
Displays 50% retracement level for all bars
Shows 70% level for bullish bars (close > open)
Shows 30% level for bearish bars (close < open)
Lines automatically update with each new bar
3. Custom Support/Resistance Lines
Up to 4 customizable horizontal levels (2 resistance, 2 support)
Useful for marking key psychological levels or pivot points
4. VIX-Based Options Strategy Suggestions
Real-time VIX value display
Time Zone Handling
The indicator is configured for Central Time (CT) as Pine Script's default:
RTH Open: 8:30 AM CT (9:30 AM ET)
RTH Close: 3:00 PM CT (4:00 PM ET)
Overnight session: 7:00 PM CT to 8:30 AM CT next day
Usage Notes
Chart Requirement: This indicator only works on 5-minute timeframe charts
Auto-refresh: All lines and labels automatically refresh at each new trading day's RTH open
24-hour Market: Designed for ES futures which trade nearly 24 hours
Visual Clarity: Different line styles and colors for easy identification
Ideal For
Day traders focusing on ES futures
0DTE options traders needing key reference levels
Traders using overnight gaps and previous day's levels
Those incorporating VIX-based strategies in their trading
Malama's Heikin CountMalama's Heikin Count is a Pine Script indicator designed to enhance price action analysis by combining Heikin Ashi candlestick calculations with a normalized measurement of upper and lower shadow sizes. The indicator overlays Heikin Ashi candles on the chart and displays the relative sizes of upper and lower shadows as numerical labels (scaled from 1 to 10) for candles within the last two days, starting from 9:00 AM each day. This tool aims to help traders identify the strength of price movements and potential reversals by quantifying the significance of candlestick shadows in the context of Heikin Ashi’s smoothed price data. It is particularly useful for day traders and swing traders who rely on candlestick patterns to gauge market sentiment and momentum.
The indicator solves the problem of interpreting raw candlestick data by providing a smoothed visualization through Heikin Ashi candles and a simplified, numerical representation of shadow sizes. This allows traders to quickly assess whether a candle’s upper or lower shadow indicates strong buying or selling pressure, aiding in decision-making for entries, exits, or reversals.
Originality and Usefulness
Originality: While Heikin Ashi candles are a well-known technique for smoothing price data and reducing noise, Malama's Heikin Count introduces a novel feature by calculating and normalizing the sizes of upper and lower shadows relative to the total candle height. Unlike standard Heikin Ashi implementations, which focus solely on candle body trends, this indicator quantifies shadow proportions and presents them on a standardized 1–10 scale. This normalization makes it easier for traders to compare shadow significance across different timeframes and assets without needing to manually interpret raw measurements. The restriction of shadow size labels to the last two days from 9:00 AM ensures relevance for active trading sessions, avoiding clutter from older data.
Usefulness: The indicator is particularly valuable for traders who combine candlestick pattern analysis with trend-following strategies. By integrating Heikin Ashi’s trend-smoothing capabilities with shadow size metrics, it provides a unique perspective on market dynamics. For example, large upper shadows (high normalized values) may indicate rejection at resistance levels, while large lower shadows may suggest support or buying pressure. Unlike other open-source Heikin Ashi indicators, which typically focus only on candle plotting, this script’s shadow size normalization and time-based filtering offer a distinctive tool for intraday and short-term trading strategies.
Detailed Methodology ("How It Works")
The core logic of Malama's Heikin Count revolves around three main components: Heikin Ashi candle calculations, shadow size analysis, and time-based filtering for label display. Below is a breakdown of how these components work together:
Heikin Ashi Candle Calculations:
The script calculates Heikin Ashi candles to smooth price data and reduce market noise, making trends easier to identify.
Formulas:
haClose = (open + high + low + close) / 4: The Heikin Ashi close is the average of the current bar’s open, high, low, and close prices.
haOpen = na(haOpen ) ? (open + close) / 2 : (haOpen + haClose ) / 2: The Heikin Ashi open is either the average of the current bar’s open and close (for the first bar) or the average of the previous Heikin Ashi open and close.
haHigh = max(high, max(haOpen, haClose)): The Heikin Ashi high is the maximum of the current bar’s high, Heikin Ashi open, and Heikin Ashi close.
haLow = min(low, min(haOpen, haClose)): The Heikin Ashi low is the minimum of the current bar’s low, Heikin Ashi open, and Heikin Ashi close.
These calculations produce smoothed candles that emphasize trend direction and reduce the impact of short-term price fluctuations.
Shadow Size Analysis:
The script calculates the upper and lower shadows of each Heikin Ashi candle to assess market sentiment.
Formulas:
upperShadow = haHigh - max(haClose, haOpen): Measures the length of the upper shadow (distance from the top of the candle body to the high).
lowerShadow = min(haClose, haOpen) - haLow: Measures the length of the lower shadow (distance from the bottom of the candle body to the low).
totalHeight = haHigh - haLow: Calculates the total height of the candle (from high to low).
upperShadowPercentage = (upperShadow / totalHeight) * 100: Converts the upper shadow length to a percentage of the total candle height.
lowerShadowPercentage = (lowerShadow / totalHeight) * 100: Converts the lower shadow length to a percentage of the total candle height.
Normalization: The normalizeShadowSize function scales the shadow percentages to a 1–10 range using math.round(value / 10). This ensures that shadow sizes are presented in an easily interpretable format, where 1 represents a very small shadow (less than 10% of the candle height) and 10 represents a very large shadow (90–100% of the candle height). The normalization caps values between 1 and 10 for consistency.
Time-Based Filtering:
The script only displays shadow size labels for candles within the last two days, starting from 9:00 AM each day. This is achieved by calculating a start timestamp using timestamp(year(timenow), month(timenow), dayofmonth(timenow) - daysBack, startHour, startMinute), where daysBack = 2, startHour = 9, and startMinute = 0.
The condition time >= startTime ensures that labels are only plotted for candles within this time window, keeping the chart relevant for recent trading activity and avoiding clutter from older data.
Signal Generation:
The script does not generate explicit buy or sell signals but provides visual cues through shadow size labels. Large upper shadow sizes (e.g., 8–10) may indicate selling pressure or resistance, while large lower shadow sizes may suggest buying pressure or support. Traders can use these metrics in conjunction with the Heikin Ashi candle colors (green for bullish, red for bearish) to make trading decisions.
Strategy Results and Risk Management
Backtesting: The script is an indicator and does not include built-in backtesting or strategy logic for generating buy/sell signals. As such, it does not assume specific commission, slippage, or account sizing parameters. Traders using this indicator should incorporate it into their existing strategies, applying their own risk management rules.
Risk Management Guidance:
Traders can use the shadow size labels to inform risk management decisions. For example, a large upper shadow (e.g., 8–10) at a resistance level may prompt a trader to set a tighter stop-loss above the candle’s high, anticipating a potential reversal. Conversely, a large lower shadow at a support level may suggest a wider stop-loss below the low to account for volatility.
Default settings (e.g., 2-day lookback, 9:00 AM start) are designed to focus on recent price action, which is suitable for intraday and short-term swing trading. Traders should combine the indicator with other tools (e.g., support/resistance levels, trendlines) to define risk limits, such as risking 5–10% of equity per trade.
The indicator does not enforce specific risk management settings, allowing traders to customize their approach based on their risk tolerance and trading style.
User Settings and Customization
The script includes the following user-customizable inputs:
Days Back (daysBack = 2):
Description: Controls the lookback period for displaying shadow size labels. The default value of 2 means labels are shown for candles within the last two days.
Impact: Increasing daysBack extends the time window for label display, which may be useful for longer-term analysis but could clutter the chart. Decreasing it focuses on more recent data, ideal for intraday trading.
Start Hour (startHour = 9) and Start Minute (startMinute = 0):
Description: Defines the start time of the trading day (default is 9:00 AM). Labels are only shown for candles after this time each day within the lookback period.
Impact: Traders can adjust these settings to align with their preferred trading session (e.g., 9:30 AM for U.S. market open). Changing the start time shifts the time window for label display, affecting which candles are analyzed.
These settings allow traders to tailor the indicator to their trading timeframe and session preferences, ensuring that the shadow size labels remain relevant to their analysis.
Visualizations and Chart Setup
The indicator plots the following elements on the chart:
Heikin Ashi Candles:
Plotted using plotcandle(haOpen, haClose, haHigh, haLow), these candles overlay the standard price chart.
Color Coding: Green candles indicate bullish momentum (Heikin Ashi close ≥ open), while red candles indicate bearish momentum (Heikin Ashi close < open).
These candles provide a smoothed view of price trends, making it easier to identify trend direction and continuations.
Shadow Size Labels:
Upper Shadow Labels: Displayed above each candle at the Heikin Ashi high, showing the normalized upper shadow size (1–10). These labels are green with white text and use the label.style_label_down style for clear visibility.
Lower Shadow Labels: Displayed below each candle at the Heikin Ashi low, showing the normalized lower shadow size (1–10). These labels are red with white text and use the label.style_label_up style.
Labels are only shown for candles within the last two days from 9:00 AM, ensuring that only recent and relevant data is visualized.
Debugging Labels (Optional):
A blue label at the bottom of the chart displays the text "Upper: Lower: " for each candle, showing both shadow sizes for debugging purposes. This can be removed or commented out if not needed, as it is primarily for development use.
The visualizations are designed to be minimal and focused, ensuring that traders can quickly interpret the Heikin Ashi trend and shadow size metrics without unnecessary clutter. The use of color-coded candles and labels enhances readability, while the time-based filtering keeps the chart clean and relevant.
Malama's Candle Sniper Malama's Candle Sniper
This Pine Script is an overlay indicator crafted for TradingView to detect and highlight a variety of bullish and bearish candlestick patterns directly on the price chart. Its primary goal is to assist traders in identifying potential reversal or continuation signals by marking these patterns with labeled visual cues. The indicator is versatile, applicable across different markets (e.g., stocks, forex, cryptocurrencies) and timeframes, making it a valuable tool for enhancing technical analysis and informing trading decisions.
Originality and Usefulness
While the candlestick patterns detected by this script are well-established in technical analysis, "Malama's Candle Sniper" stands out due to its comprehensive nature. It consolidates the detection of numerous patterns—ranging from engulfing patterns to doji variations and multi-candle formations—into a single, unified indicator. This eliminates the need for traders to apply multiple individual indicators, streamlining their charting process and saving time.
The indicator’s usefulness lies in its ability to:
Provide Visual Clarity: Labels are plotted on the chart when patterns are detected, offering immediate recognition of potential trading opportunities.
Broad Pattern Coverage: It identifies both bullish and bearish patterns, accommodating various market conditions and trading strategies.
This makes it an ideal tool for traders who incorporate candlestick analysis into their decision-making, whether for spotting trend reversals or confirming ongoing momentum.
How It Works
"Malama's Candle Sniper" operates by defining helper functions in Pine Script that evaluate whether specific candlestick pattern conditions are met for the current bar. Each function returns a boolean value (true/false) based on predefined criteria involving the open, high, low, and close prices of the candles. The script then checks for transitions from false to true (i.e., a pattern newly appearing) and plots a corresponding label on the chart.
Bullish Patterns Detected
The script identifies the following bullish patterns, which typically signal potential upward price movements:
Bullish Engulfing: A small bearish candle followed by a larger bullish candle that engulfs it.
Three White Soldiers: Three consecutive bullish candles with higher closes.
Bullish Three Line Strike: Three bullish candles followed by a bearish candle that doesn’t negate the prior uptrend.
Three Inside Up: A bearish candle, a smaller bullish candle within its range, and a strong bullish confirmation candle.
Dragonfly Doji: A doji with a long lower wick and little to no upper wick, opening and closing near the high.
Piercing Line: A bearish candle followed by a bullish candle that opens below the prior low and closes above the midpoint of the prior candle.
Bullish Marubozu: A strong bullish candle with no upper or lower wicks.
Bullish Abandoned Baby: A bearish candle, a doji gapped below it, and a bullish candle gapped above the doji.
Rising Window: A gap up between two candles, with the current low above the prior high.
Hammer: A candle with a small body and a long lower wick, indicating rejection of lower prices.
Morning Star: A three-candle pattern with a bearish candle, a small-bodied middle candle, and a strong bullish candle.
Bearish Patterns Detected
The script also detects these bearish patterns, which often indicate potential downward price movements:
Bearish Engulfing: A small bullish candle followed by a larger bearish candle that engulfs it.
Three Black Crows: Three consecutive bearish candles with lower closes.
Bearish Three Line Strike: Three bearish candles followed by a bullish candle that doesn’t reverse the downtrend.
Three Inside Down: A bullish candle, a smaller bearish candle within its range, and a strong bearish confirmation candle.
Gravestone Doji: A doji with a long upper wick and little to no lower wick, opening and closing near the low.
Dark Cloud Cover: A bullish candle followed by a bearish candle that opens above the prior high and closes below the midpoint of the prior candle.
Bearish Marubozu: A strong bearish candle with no upper or lower wicks.
Bearish Abandoned Baby: A bullish candle, a doji gapped above it, and a bearish candle gapped below the doji.
Falling Window: A gap down between two candles, with the current high below the prior low.
Hanging Man: A candle with a small body and a long lower wick after an uptrend, signaling potential reversal.
Label Plotting
When a pattern is detected (i.e., its condition transitions from false to true):
Bullish Patterns: A label is plotted at the high of the bar, using a green background with white text and a downward-pointing style (e.g., "Bull Engulf" for Bullish Engulfing).
Bearish Patterns: A label is plotted at the low of the bar, using a red background with white text and an upward-pointing style (e.g., "Bear Engulf" for Bearish Engulfing).
This visual distinction helps traders quickly differentiate between bullish and bearish signals and their precise locations on the chart.
Strategy and Risk Management
Backtesting: "Malama's Candle Sniper" is strictly an indicator and does not include backtesting capabilities or automated trading signals. It does not simulate trades or provide performance statistics such as win rates or profit/loss metrics.
Risk Management: As an informational tool, it lacks built-in risk management features. Traders must independently implement strategies like stop-loss orders, take-profit levels, or position sizing to manage risk when acting on the detected patterns. For example, a trader might place a stop-loss below a Hammer pattern’s low or above a Hanging Man’s high to limit potential losses.
User Settings and Customization
Inputs: The script does not offer user-configurable inputs. All pattern detection logic is hardcoded, meaning traders cannot adjust parameters such as lookback periods or pattern sensitivity through the interface.
Customization: Advanced users with Pine Script knowledge can modify the code directly to:
Add or remove patterns.
Adjust the conditions (e.g., tweak the wick-to-body ratio for a Hammer).
Change label styles or colors.
However, the default version is fixed and ready-to-use as is.
Visualizations and Chart Setup
Plotted Elements:
Bullish Labels: Appear at the candle’s high with a green background, white text, and a downward-pointing arrow (e.g., "Hammer").
Bearish Labels: Appear at the candle’s low with a red background, white text, and an upward-pointing arrow (e.g., "Hanging Man").
Chart Setup: The indicator is configured as an overlay (overlay=true), meaning it integrates seamlessly with the price chart. Labels are displayed directly on the candlesticks, eliminating the need for a separate pane and keeping the focus on price action.
Usage Example
To use "Malama's Candle Sniper":
Add the indicator to your TradingView chart via the Indicators menu.
Observe the price chart for green (bullish) or red (bearish) labels as they appear.
Analyze the context of each pattern (e.g., trend direction, support/resistance levels) to decide on potential trades.
Apply your own entry, exit, and risk management rules based on the signals.
For instance, spotting a "Morning Star" label during a downtrend near a support level might prompt a trader to consider a long position, while a "Dark Cloud Cover" at resistance could signal a short opportunity.
Inside 4+ Candles Box (Entry + Target + SMA Stop Logic)🔍 What This Script Does
This indicator detects price compression areas using 4 or more consecutive inside candles, then draws a breakout box to visually highlight the range.
Once price closes above the box, a long entry marker is plotted, along with:
🎯 Target line at 1x box size above the breakout.
❌ Stop-loss at the box low or at a dynamic SMA-based level if the box is too large.
🧠 Why It’s Unique
This script combines inside bar compression, breakout logic, risk control, and visual clarity — all in one tool.
It also cancels the setup entirely if price closes below the box low before breakout, avoiding late or false entries.
⚙️ Customizable Settings
Minimum inside candles (default = 4)
SMA length (used as stop if box is large)
Box size % threshold to activate smart stop
Entry, Target, and Stop marker colors
📌 Notes
For long setups only (no short signals).
Use on any asset or timeframe (ideal on 4H/1D).
This is not financial advice. Use with proper risk management.
Backtest thoroughly before live use.
Built with ❤️ by using Pine Script v6.
🇸🇦 وصف مختصر باللغة العربية:
هذا المؤشر يكتشف مناطق تماسك السعر من خلال 4 شموع داخلية أو أكثر، ثم يرسم مربعًا يحدد منطقة الاختراق المحتملة.
عند الإغلاق أعلى المربع، يتم عرض إشارة دخول وسطر هدف بنسبة 100% من حجم المربع.
كما يتم احتساب وقف الخسارة تلقائيًا إما عند قاع المربع أو عند متوسط متحرك ذكي (SMA) إذا كان حجم المربع كبيرًا.
الميزة الإضافية: إذا تم كسر قاع المربع قبل الاختراق، يتم إلغاء الصفقة تلقائيًا لتجنب الدخول المتأخر.
🧪 للاستفادة التعليمية والتحليل فقط. لا يُعتبر توصية مالية.
BALUM SWINGThis Pine Script instrument delineates pivotal market inflections by synthesizing multi-factorial Gann-inspired vectoral assessments. The core computational engine operates through a recursive analysis of bar-to-bar price-time harmonics, meticulously classifying each period's dynamic signature based on Gann's foundational quadrilateral typologies (Ascendant, Descendant, Interior, and Exterior resonant states).
Inflection points are not merely identified by trivial maxima or minima; rather, they are precipitated by a critical phase-shift in the dominant directional eigenstate. The algorithm quantifies the cumulative energetic potential of successive resonant states. A confirmed pivot materializes only when the established directional momentum vector undergoes a significant angular displacement, triggered by the emergence of a contra-harmonic bar signature that overcomes the prevailing energetic threshold.
Interior resonant states (Inside Bars) are integrated as periods of temporal consolidation, their energetic signature absorbed into the prevailing directional vector without initiating immediate phase-reversal. Exterior resonant states (Outside Bars) are dynamically resolved based on their closing equilibrium point relative to their intrinsic energetic mean, contributing their weighted vector to the ongoing market dynamic.
The plotted lines thus represent the consequential pathways forged by these harmonically validated points of equilibrium shift, tracing the market's cyclical progression through its various energetic phases. The terminal, ephemeral projection visualizes the nascent vector of the current, unresolved energetic sequence.
Failure Swing IndicatorIdentify Failure Swing nice and easy
J. Welles Wilder Jr. describes Failure Swings as specific chart patterns used in conjunction with the Relative Strength Index (RSI) to identify potential reversals in price trends.
These patterns signal weakening momentum and can indicate a shift in market direction
Wilder emphasized that these patterns are more reliable when confirmed by price action or other technical indicators.
EMA Pullback Indicator with Volume Confirmationvolume analysis that follows momentum and only enters on pullbacks. Exit at end of next candle
ORB 5M + VWAP + Braid Filter + TP 2R o Niveles PreviosORB 5-Minute Breakout Strategy Summary
Strategy Name:
ORB 5M + VWAP + Braid Filter + TP 2R or Previous Levels
Timeframe:
5-minute chart
Trading Window:
9:35 AM to 11:00 AM (New York time)
✅ Entry Conditions:
Opening Range: Defined from 9:30 to 9:35 AM (first 5-minute candle).
Breakout Entry:
Long trade: Price breaks above the opening range high.
Short trade: Price breaks below the opening range low.
Confirmation Filters (All must be met):
Strong candle (green for long, red for short).
VWAP in the direction of the trade.
Braid Filter by Mango2Juice supports the breakout direction (green for long, red for short).
📉 Stop Loss:
Placed at the opposite side of the opening range.
🎯 Take Profit (TP):
+2R (Risk-to-Reward Ratio of 2:1),
or
Closest of the following: previous day’s high/low or premarket levels.
⚙️ Additional Rules:
Only valid signals between 9:35 and 11:00 AM.
Only one trade per breakout direction per day.
Filter out "trap candles" (very small or indecisive candles).
Avoid trading after 11:00 AM.
📊 Performance Goals:
Maintain a high Profit Factor (above 3 ideally).
Focus on tickers with good historical performance under this strategy (e.g., AMZN, PLTR, CVNA).
FVG (Nephew sam remake)Hello i am making my own FVG script inspired by Nephew Sam as his fvg code is not open source. My goal is to replicate his Script and then add in alerts and more functions. Thus, i spent few days trying to code. There is bugs such as lower time frame not showing higher time frame FVG.
This script automatically detects and visualizes Fair Value Gaps (FVGs) — imbalances between demand and supply — across multiple timeframes (15-minute, 1-hour, and 4-hour).
15m chart shows:
15m FVGs (green/red boxes)
1H FVGs (lime/maroon)
4H FVGs (faded green/red with borders) (Bugged For now i only see 1H appearing)
1H chart shows:
1H FVGs
4H FVGs
4H chart shows:
4H FVGs only
There is the function to auto close FVG when a future candle fully disrespected it.
You're welcome to:
🔧 Customize the appearance: adjust box colors, transparency, border style
🧪 Add alerts: e.g., when price enters or fills a gap
📅 Expand to Daily/Weekly: just copy the logic and plug in "D" or "W" as new layers
📈 Build confluence logic: combine this with order blocks, liquidity zones, or ICT concepts
🧠 Experiment with entry signals: e.g., candle confirmation on return to FVG
🚀 Improve performance: if you find a lighter way to track gaps, feel free to optimize!
Dual Bollinger BandsIndicator Name:
Double Bollinger Bands (2-9 & 2-20)
Description:
This indicator plots two sets of Bollinger Bands on a single chart for enhanced volatility and trend analysis:
Fast Bands (2-9 Length) – Voilet
More responsive to short-term price movements.
Useful for spotting quick reversals or scalping opportunities.
Slow Bands (2-20 Length) – Black
Smoother, trend-following bands for longer-term context.
Helps confirm broader market direction.
Both bands use the standard settings (2 deviations, SMA basis) for consistency. The transparent fills improve visual clarity while keeping the chart uncluttered.
Use Cases:
Trend Confirmation: When both bands expand together, it signals strong momentum.
Squeeze Alerts: A tight overlap suggests low volatility before potential breakouts.
Multi-Timeframe Analysis: Compare short-term vs. long-term volatility in one view.
How to Adjust:
Modify lengths (2-9 and 2-20) in the settings.
Change colors or transparency as needed.
Why Use This Script?
No Repainting – Uses standard Pine Script functions for reliability.
Customizable – Easy to tweak for different trading styles.
Clear Visuals – Color-coded bands with background fills for better readability.
Ideal For:
Swing traders, day traders, and volatility scalpers.
Combining short-term and long-term Bollinger Band strategies.
Separators & Liquidity [K]Separators & Liquidity
This indicator offers a unified visual framework for institutional price behaviour, combining calendar-based levels, intraday session liquidity, and opening price anchors. It is specifically designed for ICT-inspired traders who rely on time-of-day context, prior high/low sweeps, and mitigation dynamics to structure their trading decisions.
Previous Day, Week, and Month Highs/Lows
These levels are dynamically updated and optionally stop projecting forward once mitigated. Mitigation is defined as a confirmed price interaction (touch or break), and labels visually adjust upon confirmation.
Intraday Session Liquidity Zones
Includes:
Asia Session (18:00–02:30 EST)
London Session (02:00–07:00 EST)
New York AM Session (07:00–11:30 EST)
New York Lunch Session (11:30–13:00 EST)
Each session tracks its own high/low with mitigation logic and duplicate filtering to avoid plotting overlapping levels when values are identical to previous session or daily levels.
Opening Price Anchors
Plots key opens:
Midnight (00:00 EST) (Customizable)
New York Open (09:30 EST) (Customizable)
PM Session Open (13:30 EST) (Customizable)
Weekly Open
Monthly Open
These levels serve as orientation for daily range expansion/contraction and premium/discount analysis.
Time Labels
Includes weekday markers and mid-month labels for better visual navigation on intraday and higher timeframes.
All components feature user-defined controls for visibility, line extension, color, label size, and plotting style. Filtering logic prevents redundant lines and maintains chart clarity.
Originality and Justification
While elements such as daily highs/lows and session ranges exist in other indicators, this script combines them under a fully mitigation-aware, duplicate-filtering, and session-synchronized logic model. Each level is tracked and managed independently, but drawn cooperatively using a shared visual and behavioral control system.
This script is not a mashup but an integrated tool designed to support precise execution timing, market structure analysis, and liquidity-based interpretation within ICT-style trading frameworks.
This version does not reuse any code from open-source scripts, and no built-in indicators are merged. The logic is independently constructed for real-time tracking and multi-session visualization.
Inspiration
This tool is inspired by core ICT concepts and time-based session structures commonly discussed in educational content and the broader ICT community.
It also draws conceptual influence from the TFO Killzones & Pivots script by tradeforopp, particularly in the spirit of time-based liquidity tracking and institutional session segmentation. This script was developed independently but aligns in purpose. Full credit is given to TFO as an inspiration source, especially for traders using similar timing models.
Intended Audience
Designed for traders studying or applying:
ICT’s core market structure principles
Power of Three (PO3) setups
Session bias models (e.g., AM reversals, London continuations)
Liquidity sweep and mitigation analysis
Time-of-day-based confluence planning
The script provides structural levels—not signals—and is intended for visual scaffolding around discretionary execution strategies.
Beta Tracker [theUltimator5]This script calculates the Pearson correlation coefficient between the charted symbol and a dynamic composite of up to four other user-defined tickers. The goal is to track how closely the current asset’s normalized price behavior aligns with, or diverges from, the selected group (or basket)
How can this indicator be valuable?
You can compare the correlation of your current symbol against a basket of other tickers to see if it is moving independently, or being pulled with the basket.... or is it moving against the basket.
It can be used to help identify 'swap' baskets of stocks or other tickers that tend to generally move together and visually show when your current ticker diverges from the basket.
It can be used to track beta (or negative beta) with the market or with a specific ticker.
This is best used as a supplement to other trading signals to give a more complete picture of the external forces potentially pulling or pushing the price action of the ticker.
🛠️ How It Works
The current symbol and each selected comparison ticker are normalized over a custom lookback window, allowing fair pattern-based comparison regardless of price scale.
The normalized values from 1 to 4 selected tickers are averaged into a composite, which represents the group’s collective movement.
A Pearson correlation coefficient is computed over a separate correlation lookback period, measuring the relationship between the current asset and the composite.
The result is plotted as a dynamic line, with color gradients:
Blue = strongly correlated (near +1)
Orange = strongly inverse correlation (near –1)
Intermediate values fade proportionally
A highlighted background appears when the correlation drops below a user-defined threshold (e.g. –0.7), helping identify strong negative beta periods visually.
A toggleable info table displays which tickers are currently being compared, along with customizable screen positioning.
⚙️ User Inputs
Ticker 1–4: Symbols to compare the current asset against (blank = ignored)
Normalization Lookback: Period to normalize each series
Correlation Lookback: Period over which correlation is calculated
Negative Correlation Highlight: Toggle for background alert and threshold level
Comparison Table: Toggle and position controls for an on-screen summary of selected tickers
imgur.com
⚠️ Notes
The script uses request.security() to pull data from external symbols; these must be available for the selected chart timeframe.
A minimum of one valid ticker must be provided for the script to calculate a composite and render correlation.