XAUUSD Mean Reversion Strategy Gold (ATR and RSI)The XAUUSD Mean Reversion Strategy – Gold v6 is a non-repainting TradingView strategy designed specifically for Gold (XAUUSD). It capitalizes on price overextensions and statistically probable pullbacks toward the mean, a behavior Gold frequently exhibits during active market sessions.
🔍 Strategy Logic
Uses EMA 50 as the mean price reference
Detects overextended conditions with RSI (14)
Trades are taken only when price deviates significantly from the mean
Designed for both long and short positions
📈 Entry Conditions
Long Trades
Price below EMA 50
RSI below oversold level
Short Trades
Price above EMA 50
RSI above overbought level
📉 Exit & Risk Management
ATR-based Stop Loss adapts to Gold’s volatility
Take Profit Options
Mean reversion back to EMA
Fixed ATR-based risk-to-reward
One trade at a time to control exposure
⚙️ Features
Fully backtestable
Non-repainting
Optimized for XAUUSD volatility
Adjustable inputs for optimization
Works best on 5m–30m timeframes
📊 Recommended Use
XAUUSD (Gold)
London & New York sessions
Intraday mean-reversion traders
⚠️ This strategy is for educational and research purposes only. Always perform your own testing and risk management before using it in live markets.
Индикаторы и стратегии
bollinger bandsWhat the indicator is (Generated by trade-pilot.app Builder)
This is a hybrid trend/continuation + EMA crossover signal indicator that generates LONG/SHORT entries only when multiple filters agree. It’s built to avoid “random” signals by forcing confirmation from trend direction, volatility, and risk/reward conditions, and it can also restrict signals to a specific trading session + timezone.
Main modules inside the code
1) Session filter (time-based)
The script checks if the current bar is inside the chosen session (default 09:30–16:00 New York time).
✅ Signals only trigger inSession
❌ No signals outside session
This helps you avoid entries during dead/low-quality hours.
2) Bollinger “Continuation Setup”
It calculates Bollinger Bands (default Length 20, Mult 2) and looks for a continuation pattern:
Trend detection (slope-based):
It measures the slope of the Bollinger middle band (basis).
If slope is up and price is above the basis → uptrend
If slope is down and price is below the basis → downtrend
Pullback + confirmation:
Long setup: price makes a pullback toward the middle band area (without breaking too deep) and then prints a bullish confirmation candle closing above the basis.
Short setup: same idea but reversed (pullback up + bearish confirmation candle closing below the basis).
✅ Result: signals that aim to catch trend continuation after a pullback, not random touches.
3) Stop & Target visualization (Bollinger-based)
When a continuation setup happens, the script calculates:
Stop (long): near the middle band / recent lowest lows
Stop (short): near the middle band / recent highest highs
Target (long): upper Bollinger band
Target (short): lower Bollinger band
On the chart (like in your screenshot), you see:
Bollinger Bands
Stop/target points shown as colored circles when a setup triggers
This makes it easier to visually understand the trade structure.
4) Bandwidth filter (volatility filter)
It calculates Bollinger Bandwidth (percentage width of the bands).
Signal only passes if:
Bandwidth ≥ minimum threshold (default 0.8%)
✅ Helps avoid trading when volatility is too low (chop / squeeze conditions).
5) Risk:Reward filter (quality filter)
This part estimates whether the trade has enough “room” to make sense:
Stop distance is ATR-based: ATR × multiplier
Target distance is approximated using recent swing potential:
Long: distance to recent highest high (last 10 bars)
Short: distance to recent lowest low (last 10 bars)
Then it calculates:
RR = targetDistance / stopDistance
and requires:
RR ≥ minimum RR (default 1.0)
✅ Helps filter out trades where the potential reward is too small compared to risk.
6) EMA crossover signals (secondary signal engine)
It also plots:
Fast EMA (default 20)
Slow EMA (default 50)
It generates extra signals on:
Bullish crossover (fast crosses above slow)
Bearish crossunder
So final signals can come from:
Bollinger continuation OR
EMA crossover
…but still must pass bandwidth + RR + session filters.
Final signal rule (important)
A LONG is printed only when:
(Bollinger continuation long OR EMA bullish crossover)
AND bandwidth filter passes
AND RR filter passes
AND inside session
Same logic for SHORT.
That’s why the signals are more selective.
What you see on the chart (like your screenshot)
Bollinger Bands (upper/middle/lower)
EMA fast + EMA slow
Red/green arrows for entries
“LONG/SHORT” labels on signal candles
Optional alert triggers for automation
How it helps traders
✅ Cleaner entries (trend + pullback continuation + confirmation)
✅ Less chop (volatility bandwidth filter)
✅ Better trade quality (risk/reward filter)
✅ Session control (only trade when market conditions are best)
✅ Easy visual decision making (bands, EMAs, and stop/target markers on the chart)
✅ Alerts-ready for live notifications
Small note (so you don’t get surprised)
You have an input called “Show Dashboard”, but the current code does not actually create a dashboard table (no table.new section exists). Everything else works as shown.
prnt.sc
Neeson bitcoin Dynamic ATR Trailing SystemNeeson bitcoin Dynamic ATR Trailing System: A Comprehensive Guide to Volatility-Adaptive Trend Following
Introduction
The Dynamic ATR Trailing System (DATR-TS) represents a sophisticated approach to trend following that transcends conventional moving average or breakout-based methodologies. Unlike standard trend-following systems that rely on price pattern recognition or fixed parameter oscillators, this system operates on the principle of volatility-adjusted position management—a nuanced approach that dynamically adapts to changing market conditions rather than imposing rigid rules on market behavior.
Originality and Innovation
Distinct Methodological Approach
What sets DATR-TS apart from hundreds of existing trend-following systems is its dual-layered conditional execution framework. While most trend-following systems fall into one of three broad categories—moving average crossovers, channel breakouts, or momentum oscillators—this system belongs to the more specialized category of volatility-normalized trailing stop systems.
Key Original Contributions:
Volatility-Threshold Signal Filtering: Most trend systems generate signals continuously, leading to overtrading during low-volatility periods. DATR-TS implements a proprietary volatility filter that requires minimum market movement before generating signals, effectively separating high-probatility trend opportunities from market noise.
Self-Contained Position State Management: Unlike traditional systems that require external position tracking, DATR-TS maintains an internal position state that prevents contradictory signals and creates a closed-loop decision framework.
Dynamic Risk Parameter Adjustment: The system doesn't use fixed percentage stops or rigid ATR multiples. Instead, it implements a responsive adjustment mechanism that widens stops during high volatility and tightens them during low volatility, creating an optimal balance between risk protection and opportunity capture.
Trader-Centric Visualization Philosophy: Beyond mere signal generation, the system provides a comprehensive visual feedback system designed to align with human cognitive patterns, reducing emotional decision-making through consistent color coding and information hierarchy.
Technical Implementation and Functionality
Core Operational Mechanism
DATR-TS implements a volatility-adjusted trend persistence model that operates on the principle that trending markets exhibit characteristic volatility signatures. The system specifically targets medium-term directional movements (typically lasting 5-20 days) rather than short-term scalping opportunities or long-term position trades.
The Four-Pillar Architecture:
Volatility Measurement and Normalization
Calculates Average True Range (ATR) over a user-defined period
Converts absolute volatility to percentage terms relative to price
Compares current volatility against user-defined thresholds to filter suboptimal conditions
Dynamic Trailing Stop Algorithm
Establishes an initial stop distance based on current volatility
Implements a four-state adjustment mechanism that responds to price action
Maintains stop position during trend continuation while allowing for trend reversal detection
Conditional Signal Generation
Generates entry signals only when price action meets both directional and volatility criteria
Produces exit signals based on trailing stop penetration
Incorporates position state awareness to prevent conflicting signals
Comprehensive Feedback System
Provides multi-layer visual information including dynamic stop lines, signal labels, and color-coded price action
Displays real-time metrics through an integrated dashboard
Offers configurable visualization options for different trading styles
Specific Trend-Following Methodology
DATR-TS employs a volatility-normalized trailing stop breakout approach, which differs significantly from common trend identification methods:
Not a moving average crossover system (like MACD or traditional MA crosses)
Not a channel breakout system (like Bollinger Band or Donchian Channel breaks)
Not a momentum oscillator system (like RSI or Stochastic trend following)
Not a price pattern recognition system (like head-and-shoulders or triangle breaks)
Instead, it belongs to the more specialized category of volatility-adjusted stop-and-reverse systems that:
Wait for market volatility to reach actionable levels
Establish positions when price confirms directional bias through stop penetration
Manage risk dynamically based on evolving market conditions
Exit positions when the trend exhausts itself through stop violation
Practical Application and Usage
Market Environment Optimization
Ideal Conditions:
Trending markets with sustained directional movement
Medium volatility environments (neither excessively calm nor chaotic)
Timeframes: 4-hour to daily charts for optimal signal quality
Instruments: Forex majors, commodity futures, equity indices
Suboptimal Conditions:
Ranging or consolidating markets
Extreme volatility events or news-driven spikes
Very short timeframes (below 1-hour)
Illiquid or highly manipulated instruments
Parameter Configuration Strategy
Core Parameter Philosophy:
ATR Length (Default: 21 periods)
Controls the system's memory of volatility
Shorter lengths increase sensitivity but may cause overtrading
Longer lengths provide smoother signals but may lag during volatility shifts
ATR Multiplier (Default: 6.3x)
Determines the initial risk buffer
Lower values (4-5x) create tighter stops for conservative trading
Higher values (6-8x) allow for larger trends but increase drawdown risk
Volatility Threshold (Default: 1.5%)
Filters out low-quality trading environments
Adjust based on market characteristics (higher for volatile markets)
Acts as a quality control mechanism for signals
Trading Workflow and Execution
Signal Interpretation and Action:
Entry Protocol:
Wait for BLUE "BUY" signal label appearance
Confirm volatility conditions meet threshold requirements
Enter long position at market or next reasonable opportunity
Set initial stop at displayed dynamic stop level
Position Management:
Monitor dynamic stop line for position adjustment
Allow profits to run while stop protects capital
No manual adjustment required—system manages stop automatically
Exit Protocol:
Exit on ORANGE "SELL" signal label appearance
Alternative exit if price hits dynamic stop level
System will generate new entry signal if conditions warrant re-entry
Risk Management Integration:
Position sizing based on distance to dynamic stop
Volatility filter prevents trades during unfavorable conditions
Clear visual feedback on current risk exposure
Built-in protection against overtrading
Philosophical Foundation and Market Theory
Core Trading Principles
DATR-TS embodies several foundational market principles:
Volatility Defines Opportunity
Markets don't trend continuously—they alternate between trending and ranging phases
Volatility provides the energy for trends to develop and sustain
By measuring and filtering volatility, we can focus on high-probability trend phases
Risk Should Be Proportional
Fixed percentage stops ignore market context
Dynamic stops that adjust with volatility provide more appropriate risk management
Position sizing should reflect current market conditions, not arbitrary rules
Simplicity Through Sophistication
Complex systems often fail in real-world conditions
A simple core algorithm with intelligent filtering outperforms complex multi-indicator approaches
Clear visual feedback reduces cognitive load and emotional interference
Trends Persist Until Proven Otherwise
Markets exhibit momentum characteristics
Once a trend establishes itself, it tends to continue
The trailing stop methodology captures this persistence while providing exit mechanisms
Mathematical and Statistical Foundation
The system operates on several statistical market observations:
Volatility Clustering Phenomenon
High volatility periods tend to follow high volatility periods
Low volatility periods tend to follow low volatility periods
By filtering for adequate volatility, we increase the probability of capturing meaningful trends
Trend Magnitude Distribution
Most trends are small to medium in magnitude
Very large trends are rare but account for disproportionate returns
The dynamic stop methodology allows capture of varying trend magnitudes
Autocorrelation in Price Movements
Price movements exhibit short-term positive autocorrelation during trends
This persistence allows trailing stops to capture continued movement
The system leverages this characteristic without requiring explicit autocorrelation calculation
Performance Characteristics and Expectations
Typical System Behavior
Signal Frequency:
Low to moderate signal generation (prevents overtrading)
Signals concentrated during trending market phases
Extended periods without signals during ranging conditions
Risk-Reward Profile:
Win rate typically 40-60% in trending conditions
Average win larger than average loss
Risk-reward ratios of 1:2 to 1:3 achievable
Drawdown Patterns:
Controlled through volatility adjustment
Larger drawdowns during extended ranging periods
Recovery typically follows when trending conditions resume
Comparison with Alternative Approaches
Versus Moving Average Systems:
Less prone to whipsaws during ranging markets
Better adaptation to changing volatility conditions
Clearer exit signals through stop levels
Versus Channel Breakout Systems:
More responsive to emerging trends
Lower false breakout probability
Dynamic risk adjustment rather than fixed parameters
Versus Momentum Oscillator Systems:
Better trend persistence capture
Less susceptible to overbought/oversold false signals
Clearer position management rules
Educational Value and Skill Development
Learning Opportunities
DATR-TS serves as more than just a trading tool—it provides educational value through:
Market Condition Awareness
Teaches traders to distinguish between trending and ranging markets
Develops understanding of volatility's role in trading opportunities
Encourages patience and selectivity in trade execution
Risk Management Discipline
Demonstrates dynamic position sizing principles
Illustrates the importance of adaptive stops
Reinforces the concept of risk-adjusted returns
Psychological Skill Development
Reduces emotional trading through clear rules
Builds patience through conditional execution
Develops discipline through systematic approach
Customization and Evolution
The system provides a foundation for further development:
Beginner Level:
Use default parameters for initial learning
Focus on signal recognition and execution discipline
Develop understanding of system behavior across market conditions
Intermediate Level:
Adjust parameters based on specific market characteristics
Combine with complementary analysis techniques
Develop personal variations based on trading style
Advanced Level:
Integrate with portfolio management systems
Develop automated execution frameworks
Create derivative systems for specialized applications
Conclusion: The Modern Trend-Following Paradigm
The Dynamic ATR Trailing System represents a significant evolution in trend-following methodology. By moving beyond simple price pattern recognition or fixed parameter oscillators, it embraces the complex reality of financial markets where volatility, trend persistence, and risk management interact dynamically.
This system doesn't claim to predict market direction or identify tops and bottoms. Instead, it provides a systematic framework for participating in trends when they emerge, managing risk appropriately as conditions change, and preserving capital during unfavorable environments.
For traders seeking a methodology that combines mathematical rigor with practical execution, adapts to changing market conditions rather than fighting against them, and provides clear, actionable information without cognitive overload, DATR-TS offers a sophisticated yet accessible approach to modern trend following.
The true value lies not in any single signal or parameter setting, but in the comprehensive philosophy of volatility-aware, risk-adjusted, conditionally-executed trend participation that the system embodies—a philosophy that aligns with how markets actually behave rather than how we might wish them to behave.
Institutional Volatility Expansion & Liquidity Thresholds (IVEL)Overview
The IVEL Engine is an institutional-grade volatility modeling tool designed to identify the mathematical boundaries of price delivery. Unlike retail oscillators that use fixed scales, this script utilizes dynamic ATR-based multiples to map Institutional Premium and Discount zones in real-time.
How to Use
To maximize the effectiveness of the IVEL Engine, traders should focus on Price Delivery at the extreme thresholds:
Identifying Institutional Premium (Short Setup) : When price expands into the Upper Red Zone, it has reached a mathematical exhaustion point. Seek short-side entries when price shows signs of rejection from this level back toward the Fair Value Baseline.
Identifying Institutional Discount (Long Setup) : When price reaches the Lower Green Zone, it is considered "cheap" by institutional algorithms. Look for long-side absorption or accumulation patterns within this zone.
Mean Reversion Targets: The Fair Value Baseline (Center Line) acts as the primary magnetic target. Successful trades taken at the outer thresholds should use the baseline as the first objective for profit-taking.
Alerts & Execution Strategy
The IVEL Engine is designed for automated monitoring so you don't have to watch the screen 24/7. To set up your execution workflow:
Set the Alert : Right-click the indicator and select "Add Alert." Set the condition to "Price Crossing Institutional Premium" (Upper Red) or "Price Crossing Institutional Discount" (Lower Green).
Wait for the Hit : Do not market-enter as soon as the alert fires. The alert tells you price has entered a High-Probability Liquidity Zone.
Confirm the Rejection : Once alerted, drop down to a lower timeframe (e.g., 5m or 15m) and look for a "Shift in Market Structure" or an SMT Divergence.
Execute : Enter once the rejection is confirmed, targeting the Fair Value Baseline as your primary TP1.
Methodology
The script anchors to an EMA-based baseline and projects expansion bands that adapt to current market conditions.
Value Area : The blue inner region where the majority of trading volume occurs.
Liquidity Exhaustion : The red and green outer regions where the probability of "Smart Money" reversal is highest.
XAUUSD Lot Size Calculator1. What This Indicator Does
This tool is a Visual Risk Management System. Instead of using a calculator on your phone or switching tabs, it allows you to calculate the exact lot size for your trade directly on the TradingView chart by dragging lines.
It automates the math for:
Lot Size: How big your position should be to risk exactly X% of your account.
Take Profit: Where your target should be based on your Risk-to-Reward ratio.
Safety Checks: It warns you if your stop loss is too tight for the minimum lot size (0.01).
2. Visual Features
🔴 The Red Line (Stop Loss): This is your interactive line. You can grab it with your mouse and drag it to your desired invalidation point (e.g., below a support wick).
🟢 The Green Line (Take Profit): This line moves automatically. You cannot drag it. It calculates where your Take Profit must be to satisfy your Risk:Reward ratio (Default 1:1) based on where you placed the Red line.
⚫ The Info Table: A high-contrast black box in the corner that displays your calculated Lot Size, Risk amount, and Trade direction (Long/Short).
3. How to Use It (Step-by-Step)
Step 1: Initial Setup
When you first add the indicator to the chart, you need to tell it about your account:
Double-click the Black Table (or the Red Line) to open Settings.
Inputs Tab:
Account Balance: Enter your current trading balance (e.g., 10,000).
Risk %: Enter how much you want to lose per trade (e.g., 1.0%).
Contract Size: Keep this at 100 for Gold (XAUUSD) or standard Forex pairs.
Risk : Reward Ratio: Set your target (e.g., 1.0 for 1:1, or 2.0 for 1:2).
Step 2: Planning a Trade
Look at the chart and identify where you want to enter (current price) and where you want your Stop Loss.
Find the Red Line on your chart. (If you don't see it, go to Settings and change "Stop Loss Level" to a price near the current candle).
Click and Drag the Red Line to your specific Stop Loss price.
Step 3: Reading the Signals
Direction: If you drag the Red Line below the price, the table shows LONG. If you drag it above, it shows SHORT.
Lot Size: Read the big green number in the table (e.g., 0.55). This is the exact lot size you should enter in your broker.
TP Target: Look at the Green Line on the chart. That is your exit price.
Step 4: The "Orange Warning"
If you place your Stop Loss very close to the entry, or if your account is small, the math might suggest a lot size smaller than is possible (e.g., 0.004).
The table text will turn ORANGE.
The Lot Size will stick to 0.01 (the minimum).
The "Risk ($)" row will show you the actual risk. (Example: Instead of risking your desired $100, you might be forced to risk $105 because you can't trade smaller than 0.01 lots).
Session Liquidity Sweep + Trend ConfirmationThis strategy aims to capture high-probability intraday trades by combining liquidity sweeps with a trend confirmation filter. It is designed for traders who want a systematic approach to trade breakouts during specific market sessions while controlling risk with ATR-based stops.
How it Works:
Session Filter: Trades are only considered during a defined session (default 9:30 - 11:00). This helps avoid low-volume periods that can lead to false signals.
Trend Confirmation: The strategy uses a 50-period EMA to identify the market trend. Long trades are only taken in an uptrend, and short trades in a downtrend.
Liquidity Sweep Detection:
A long entry occurs when price dips below the prior N-bar low but closes back above it, indicating a potential liquidity sweep that stops being triggered before the trend continues upward.
A short entry occurs when price spikes above the prior N-bar high but closes below it, signaling a potential sweep of stops before the downward trend resumes.
ATR-Based Risk Management:
Stop loss is calculated using the Average True Range (ATR) multiplied by a configurable factor (default 1.5).
Take profit is set based on a risk-reward ratio (default 2.5x).
Position Sizing: Default position size is 5% of equity per trade, making it suitable for risk-conscious trading.
Inputs:
Session Start/End (HHMM)
Liquidity Lookback Period (number of bars to define prior high/low)
ATR Length for stop calculation
ATR Stop Multiplier
Risk-Reward Ratio
EMA Trend Filter Length
Visuals:
Prior Liquidity High (red)
Prior Liquidity Low (green)
EMA Trend (blue)
Why Use This Strategy:
Captures stop-hunt moves often triggered by larger market participants.
Only trades with trend confirmation, reducing false signals.
Provides automatic ATR-based stop loss and take profit for consistent risk management.
Easy to adjust session time, ATR, EMA length, and risk-reward to suit your trading style.
Important Notes:
Assumes 0.05% commission and 1-pip slippage. Adjust according to your broker.
Not financial advice; intended for educational, backtesting, or paper trading purposes.
Always test strategies thoroughly before applying to live accounts.
Cash-and-Carry Yield (APR)This indicator calculates and visualizes the annualized rate of return for Cash-and-Carry arbitrage strategies by comparing a specific Futures contract against its underlying Spot price. By automatically projecting the current price spread (basis) based on the exact time remaining until expiration, it allows traders to instantly assess the potential "risk-free" yield available in the market.
The script is engineered to support both continuous 24/7 crypto markets and traditional CME futures. It features a smart "Gap Handling" setting that allows users to choose between a strict view that respects market closes (showing "Market Closed" during weekends) or a filled view that carries over the last known price for a seamless chart experience.
Visually, the indicator displays the annualized yield as a histogram; green columns indicate a Contango market (positive yield), while red columns signal Backwardation. A Simple Moving Average (SMA) is overlaid to help identify the broader yield trend amidst volatility. An integrated dashboard table in the corner provides a real-time summary of the Spot Price, Future Price, absolute spread, and the precise number of days left until expiration. Please ensure the Futures Ticker and the corresponding Expiration Date are correctly entered in the settings for accurate time-weighted calculations.
EMA20-EMA50 Separation Impulse**EMA20–EMA50 Separation Impulse Indicator**
This indicator is a **trend phase classifier**, not a signal generator.
It evaluates the **structural quality of a trend** by measuring the separation between the EMA20 and EMA50, **normalized by ATR**. By using volatility-adjusted distance instead of raw price or percentage, it provides a robust and comparable measure across different instruments and timeframes.
### Key characteristics
* **Discrete states**, not a continuous oscillator
* **Independent from price scale** (displayed in a lower panel)
* **Contextual indicator**, not a timing tool
* **Fully backtestable without ambiguity**
### Logic
The indicator computes:
```
|EMA20 − EMA50| / ATR
```
Based on this normalized separation, each bar is classified into one of three market phases:
* **Green (State 1)**
Ordered trend. EMA structure is compact and stable.
The EMA-based pullback setup has a statistical edge.
* **Blue (State 2)**
Extended trend. Separation is increasing.
Edge is reduced. Trades require more selectivity or reduced position size.
* **Red (State 3)**
Overextended trend. EMAs are widely separated.
Pullbacks to EMA20 lose effectiveness. The setup has no edge.
### How to integrate it into an EMA-based system
This indicator should be used strictly as a **context filter**, not as an entry or exit trigger.
Typical integration rules:
* Allow long entries **only when State = 1 (Green)**
* Reduce position size or require stronger confirmation when State = 2 (Blue)
* Disable EMA pullback entries entirely when State = 3 (Red)
Used correctly, the indicator helps distinguish **when an EMA trend-following system is operating in its optimal environment**, and when market conditions degrade its expectancy.
It answers the question:
> *“Is this still a healthy trend for EMA pullback trading?”*
—not *“Should I buy or sell now?”*
Trailing Stoploss % BasedA minimalistic trend-following indicator that plots a single trailing line based on a user-defined percentage using price highs and lows.
The line:
Trails price in trends
Moves only in the direction of the trend
Flattens when price is not making new highs or lows
Acts as support in uptrends and resistance in downtrends
Useful on all instruments and all timeframes for clean trend tracking and trailing stop management.
Hazmeed HTF Candles Aligned)HTF Candles Overlay (v6, Aligned + Accurate Wicks)
This indicator overlays higher timeframe candles on your current chart.
It allows you to visually compare HTF price action directly on your lower timeframe chart without switching timeframes.
⭐ Features
Displays Higher Timeframe (HTF) candles on the current chart
Fully aligned to HTF candle start time
Option to show accurate wicks
Supports configurable:
HTF timeframe (e.g., 1D, 4H, 1W)
Number of HTF candles displayed
Candle width (in bars)
Bull/Bear colors and wick color
Lanovyx# Lanovyx
A comprehensive day trading indicator that generates **Pullback**, **Reversal**, and **Breakout** signals using the confluence of Stochastic oscillator lanes, VWAP standard deviation bands, and a unique Setup Window system.
---
## 🎯 Three Signal Families
| Signal | Label | Best For |
|--------|-------|----------|
| **Pullback (P)** | Blue | Trend continuation days |
| **Reversal (R)** | Green/Red | Range-bound markets |
| **Breakout (B)** | Orange | Compression breakouts |
**Strong signals (★)** appear when multiple confluence factors align—these are your highest probability setups.
---
## 📊 How It Works
**1. Regime Detection**
Lanovyx identifies market regime (Bull Trend, Bear Trend, Ranging, Coiling) using EMA alignment, market structure, and VWAP position.
**2. Setup Windows**
Unlike traditional indicators requiring all conditions on the same bar, Lanovyx uses Setup Windows. When a context event occurs (VWAP band touch, S/R level, divergence), a setup activates and stays valid for N bars, allowing the trigger to fire within that window.
**3. Signal Generation**
When regime, VWAP zone, stochastic position, and setup all align—a signal appears on your chart.
---
## 📋 Clean Info Table
The top-right table shows 6 essential rows for quick decision-making:
- **Regime** — Market direction (Bull/Bear Trend, Ranging, Coiling)
- **VWAP Zone** — Price location (Discount for buys, Premium for sells)
- **Stoch %D** — Oscillator position for timing
- **Session** — Market hours status
- **Last Signal** — Most recent signal type
- **Trade** — Current position status
Enable **Debug Mode** for additional diagnostic information.
---
## ✅ Entry Rules
**LONG Setup:**
✓ Regime = BULL TREND (or RANGING for reversal)
✓ VWAP Zone = Discount (-1, -2, -3)
✓ Stoch %D = 20-50 rising
✓ Session = ACTIVE
✓ Signal = P, R, or B below candle
**SHORT Setup:**
✓ Regime = BEAR TREND (or RANGING for reversal)
✓ VWAP Zone = Premium (+1, +2, +3)
✓ Stoch %D = 50-80 falling
✓ Session = ACTIVE
✓ Signal = P, R, or B above candle
---
## ⚙️ Key Features
- **3 Stochastic Lanes** — Fast (14), Mid (21), Slow (55) for multi-timeframe momentum
- **VWAP + Bands** — Session-anchored with ±1σ, ±2σ, ±3σ bands
- **Market Structure** — Higher High/Low, Lower High/Low detection
- **HTF Bias Filter** — Optional higher timeframe trend alignment
- **Volume Analysis** — Spike, dry-up, and climax detection
- **ATR Momentum** — Strong/Moderate/Weak classification
- **Trade Management** — ATR-based stop loss and profit targets
- **Signal Statistics** — Win rate and R-multiple tracking
- **Non-Repainting** — Strict mode enabled by default
- **Per-Direction Cooldown** — Prevents signal spam
---
## 🎛️ Recommended Settings
| Timeframe | Setup Window | Cooldown |
|-----------|--------------|----------|
| 5-minute | 10 bars | 5 bars |
| 15-minute | 10 bars | 5 bars |
---
## 📈 Best On
- **ETFs**: SPY, QQQ, IWM
- **Tech**: TSLA, NVDA, AMD, META, GOOG, AAPL
- **Futures**: MNQ, MES, NQ, ES
---
## ⚠️ Disclaimer
This indicator is for educational purposes only. It is not financial advice. Past performance does not guarantee future results. Always use proper risk management and never risk more than you can afford to lose.
---
## 📝 Version
v3.0
---
**Questions or feedback?** Drop a comment below!
RSI as Volume-Style Histogram + Right Valuesthis indicator shows rsi levels per candle the same as volume bars appear with a box showing the avg rsi throughout the session and also shows the previous candles closing rsi to better compare when looking to identify momentum
BTC Spot Premium Index (Coinbase - Binance )Overview
This indicator measures the price difference between Bitcoin (BTC) on Coinbase and Binance, providing insights into the buying pressure from US-based investors versus the global market. A positive premium suggests stronger buying activity on Coinbase, which is often interpreted as a bullish signal for BTC.
Key Features
•
Premium Calculation: The core of the indicator is the formula: Coinbase BTC Price - Binance BTC Price.
•
Visual Representation: The premium is plotted as an oscillator with a zero line. Positive values are colored green, and negative values are red, making it easy to identify the prevailing market sentiment.
•
Moving Average: A customizable moving average (default is a 20-period SMA) is included to help identify the trend of the premium. The MA line is displayed in white.
•
Adjustable Parameters: You can adjust the moving average length and type (SMA, EMA, WMA, RMA) to fit your trading style.
How to Use
1.
Identify US Market Sentiment: A sustained positive (green) premium suggests strong buying interest from the US market, which can be a precursor to price appreciation.
2.
Spot Trend Reversals: A crossover of the premium line above the zero line can signal a shift from bearish to bullish sentiment. Conversely, a cross below the zero line may indicate weakening US demand.
3.
Confirm with Moving Average: When the premium line crosses above its moving average, it can signal strengthening momentum. A cross below the MA may suggest a potential slowdown.
Interpretation
•
Green Area (Positive Premium): Indicates that BTC is trading at a higher price on Coinbase than on Binance. This is generally considered a bullish sign, as it reflects strong demand from US investors.
•
Red Area (Negative Premium): Indicates that BTC is trading at a lower price on Coinbase. This may suggest weaker demand in the US market or stronger selling pressure.
•
White Line (Moving Average): Helps to smooth out the premium data and identify the underlying trend. Use it as a dynamic support or resistance level for the premium itself.
This indicator is a powerful tool for gauging market sentiment and can be a valuable addition to any BTC trader's toolkit. However, it should be used in conjunction with other technical analysis tools and not as a standalone signal for making trading decisions.
4MAs+5VWAPs+FVG+ Fractals4MAs + 5VWAPs + FVG + Fractals
All-in-one market structure indicator combining 4 moving averages, 5 VWAP timeframes, fair value gaps, fractals, and order blocks.
🔧 Features:
· 4 MAs - SMA/EMA, customizable lengths & colors
· 5 VWAPs - Daily, Weekly, Monthly, RTH, Custom sessions
· Fractals - Market structure with breakout lines & custom colors
· FVG/Imbalances - Bullish/bearish gap detection with alerts
· Order Blocks - Dynamic institutional levels
· Smart Labels - VWAP labels with color matching
⚙️ Quick Setup:
1. Toggle groups in Master Control Panel
2. Customize colors for each component
3. Set sessions for RTH/Custom VWAP
4. Adjust fractal periods (default: 2)
📈 Trading Use:
· Identify market structure with fractals
· Find confluence at VWAP + MA levels
· Trade FVG fills and order block reactions
· Multiple timeframe analysis with 5 VWAPs
Customizable • Color-Coordinated • Performance Optimized
Forecast OscillatorGeneral Overview
The Forecast Oscillator Plus (FOSC+) is not just another oscillator. It is an advanced quantitative analysis tool developed to bridge the gap left by traditional momentum indicators (like RSI or Stochastic) which often suffer from "lag" or remain pinned in extreme zones during strong trends.
This "Plus" version has been specifically engineered and optimized for high-velocity scalping and day-trading on assets like NAS100 (Nasdaq) and XAUUSD (Gold) using ultra-short timeframes (1-min, 5-min).
🛡️ Why is FOSC+ Different?
1. Linear Regression Intelligence
At the heart of this script is a powerful Linear Regression (LinReg) engine. Instead of comparing price to a simple average, FOSC+ calculates the percentage deviation between the current price and its predicted theoretical trajectory. This allows the indicator to identify not just if the price is "high" or "low," but if it is abnormally distanced from its current trend, signaling an imminent Mean Reversion.
2. Adaptive Dynamic Bands (Volatility-Adjusted)
A major weakness of classic oscillators is the use of fixed levels (e.g., 80/20). FOSC+ utilizes Standard Deviation to generate overbought and oversold zones that "breathe" with the market.
During high volatility, the bands expand to filter out noise and premature entries.
During low volatility, they tighten to capture precise turning points.
3. Institutional Volume Filter (Anti-Fakeout)
To succeed in the Nasdaq market, you must follow the "Smart Money." This script integrates a Volume Spike Filter. A signal (Buy/Sell) is only triggered if the current candle's volume is significantly higher than its moving average (adjustable multiplier). This ensures you only enter trades backed by real institutional strength.
4. Algo-Ready for PineConnector
The code has been structured for seamless automation. With built-in EMA smoothing to reduce 1-minute "market chatter," the signals are clean and sharp, minimizing execution errors when sending orders to MetaTrader 5 via PineConnector.
📈 Technical Trading Guide
Buy Signals (Green Triangle): Occur when the oscillator crosses above the dynamic oversold band OR crosses back above the zero line, provided that volume confirms the impulse.
Sell Signals (Red Triangle): Occur when the oscillator crosses below the dynamic overbought band OR breaks below the zero line from above, with volume confirmation.
Momentum Histogram: The colored columns indicate acceleration strength. Excellent for Trailing Stops: as long as the histogram is growing, the momentum is in your favor!.
⚙️ Recommended Parameters
Length (14): The "Sweet Spot" for balancing reactivity and reliability.
Smooth Len (4): Essential for 1-min charts to eliminate micro-fluctuations without adding lag.
Volume Mult (1.15): Filters out the bottom 15% of volume to keep only significant candles.
⚠️ Stress-Tested for Real Conditions
This script has been rigorously backtested with Slippage settings ranging from 10 to 25 points. Even under difficult market conditions with high spreads, the indicator maintains a positive expectancy, making it a premier tool for traders using Standard or Raw accounts.
FVG (Visual) - Last N Bars + Delete 5 Bars After NEW TouchThis indicator shows the latest FVG visually and also indicates what type of FVG it is.
HADYAN NEW SCALPING V 2.9//@version=5
indicator(title='HADYAN NEW SCALPING V 2.9', overlay=true, max_lines_count=500, max_labels_count=500, max_boxes_count=500)
// ====================================================================================================
// BAGIAN 1: PENGATURAN UTAMA & LOGIKA INTI
// ====================================================================================================
styleGroup = 'Gaya Trading (Trading Style)'
tradingStyle = input.string('Mencuri Profit', title='Pilih Gaya Trading', options= , group=styleGroup)
// --- FITUR ANTI-KEDIP ---
useConfirmedBar = input.bool(true, title='✅ Sinyal Anti-Kedip (Tunggu Close)?', group=styleGroup)
a_custom = input.float(1.0, title='Key Value (Custom)', group=styleGroup)
c_custom = input.int(10, title='ATR Period (Custom)', group=styleGroup)
var float a = 1.0
var int c = 10
// Variabel filter internal
var bool _useEmaFilter = false
var bool _useRsiFilter = false
var bool _useCandleFilter = false
var bool _useVolumeFilter = false
var bool _useAdxFilter = false
var bool _useSnrFilter = false
miscGroup = 'Pengaturan Filter (Tanpa Ghost)'
waspadaFactor = input.float(0.75, title='Waspada - Faktor Jarak ATR', group=miscGroup)
tamakFactor = input.float(3.0, title='Jangan Tamak - Faktor Jarak ATR', group=miscGroup)
// --- FILTER TREN (EMA) ---
useEmaFilter = input.bool(false, title='Gunakan Filter Tren EMA Cross?', group=miscGroup)
emaFastLen = input.int(21, title='Periode EMA Cepat', group=miscGroup)
emaSlowLen = input.int(50, title='Periode EMA Lambat', group=miscGroup)
mtfTimeframe = input.string('15', title='Timeframe MTF', group=miscGroup)
// --- FILTER MOMENTUM ---
useRsiFilter = input.bool(false, title='Gunakan Filter Momentum RSI?', group=miscGroup)
rsiFilterLen = input.int(14, title='Periode RSI', group=miscGroup)
rsiBuyLevel = input.float(50.0, title='RSI Buy Level (Min)', group=miscGroup)
rsiSellLevel = input.float(50.0, title='RSI Sell Level (Max)', group=miscGroup)
rsiReversalLevel = input.float(70.0, title='RSI Reversal Level (70/30)', group=miscGroup)
// --- FILTER LAIN ---
useCandleFilter = input.bool(false, title='Gunakan Filter Pola Candlestick?', group=miscGroup)
useVolumeFilter = input.bool(false, title='Gunakan Filter Volume?', group=miscGroup)
volumeLen = input.int(20, title='Periode Volume MA', group=miscGroup)
volumeThreshold = input.float(0.3, title='Min. Volume Factor', group=miscGroup)
// --- FILTER SNR ---
useSnrFilter = input.bool(false, title='Gunakan Filter Support/Resistance (SNR)?', group=miscGroup)
snrLookback = input.int(10, title='Pivot Lookback (SNR)', group=miscGroup)
snrDistanceFactor = input.float(2.0, title='Jarak Max ke S/R (xATR)', group=miscGroup)
// --- FILTER ADX ---
useAdxFilter = input.bool(false, title='Gunakan Filter Kondisi Pasar (ADX)?', group=miscGroup)
adxLen = input.int(14, title='Periode ADX', group=miscGroup)
adxMinLevel = input.float(15.0, title='ADX Min. Level', group=miscGroup)
// ** PENGATURAN MANAJEMEN RISIKO **
riskGroup = 'Manajemen Risiko'
useAutoBreakeven = input.bool(true, title='Gunakan Auto Breakeven?', group=riskGroup)
breakevenFactor = input.float(1.0, title='Breakeven Factor (Dalam R/ATR)', group=riskGroup)
// ==============================================
// --- INPUT FITUR TAMBAHAN ---
// ==============================================
meterGroup = 'Visual & Tambahan'
showCandlePanel = input.bool(true, title='Tampilkan Panel Info Candle?', group=meterGroup)
showCandleArrows = input.bool(false, title='Tampilkan Panah Tiap Candle?', group=meterGroup)
// ==============================================
// --- FITUR UPGRADE ---
// ==============================================
upgradeGroup = '🔥 Fitur Upgrade'
useConfirmFilter = input.bool(false, title=' Gunakan Konfirmasi Momentum (MidPoint)?', group=upgradeGroup)
useReversalExit = input.bool(false, title=' Gunakan Exit Cepat (Candle Pembalikan)?', group=upgradeGroup)
showReEntry = input.bool(true, title=' Tampilkan Sinyal Re-Entry (Add Position)?', group=upgradeGroup)
showAggressiveEMA = input.bool(false, title=' Tampilkan Sinyal Agresif (EMA Bounce)?', group=upgradeGroup)
emaAggressiveFastLen = input.int(9, title=' EMA Cepat (Agresif)', group=upgradeGroup)
emaAggressiveSlowLen = input.int(21, title=' EMA Lambat (Agresif)', group=upgradeGroup)
useBBTamak = input.bool(false, title=' Gunakan Target Profit Dinamis (BB)?', group=upgradeGroup)
bbLen = input.int(20, title=' Periode Bollinger Bands', group=upgradeGroup)
bbStdDev = input.float(2.0, title=' Deviasi Bollinger Bands', group=upgradeGroup)
showDashboard = input.bool(true, title=' Tampilkan Dashboard Pro?', group=upgradeGroup)
showAdvisorBubble = input.bool(true, title=' Tampilkan Gelembung Advisor di Chart?', group=upgradeGroup)
// --- BARU: ZONE INPUT ---
showSmartZones = input.bool(true, title=' Tampilkan Zona Buy/Sell (Supply/Demand)?', group=upgradeGroup)
zoneLookback = input.int(5, title=' Kekuatan Zona (Lookback Pivot)', group=upgradeGroup)
// ====================================================================================================
// BAGIAN UPGRADE: PIVOT, FIBO & STOCHASTIC (NEW)
// ====================================================================================================
pivotGroup = "Pivot, Fibo & Stoch (UPGRADE)"
// Pivot Inputs
showPivotPoints = input.bool(true, title='Tampilkan Daily Pivot (R1-S2)?', group=pivotGroup)
pivotColor = input.color(color.new(color.orange, 0), "Warna Garis Pivot Utama", group=pivotGroup)
// Fibo Inputs
showFiboLevels = input.bool(true, title='Tampilkan Fibo Retracement (CLEAN)?', group=pivotGroup)
fiboXOffset = input.int(10, title='Geser Fibo (X-Offset)', group=pivotGroup)
// Stochastic Inputs
showStochChart = input.bool(true, title='Tampilkan MINI CHART Stochastic (Realtime)?', group=pivotGroup)
stochWidth = input.int(30, title='Lebar Chart (Bars)', minval=10, maxval=100, group=pivotGroup)
// ==============================================
// --- DEKLARASI VAR GLOBAL ---
// ==============================================
var table infoPanel_m = table.new(position.bottom_center, 3, 2, border_width = 1, bgcolor = color.new(#363a45, 0))
var string finalDir_m = ""
var table dashboardPanel = table.new(position.top_right, 2, 10, border_width = 1, bgcolor = color.new(#363a45, 80))
var int rsiLen_actual = rsiFilterLen
var int adxLen_actual = adxLen
var string marketModeText = "..."
var color marketModeColor = color.gray
// ==============================================
// --- LOGIKA PEMILIHAN GAYA (ADAPTIF) ---
// ==============================================
if tradingStyle == 'Mencuri Profit'
a := 1.0
c := 10
rsiLen_actual := rsiFilterLen
adxLen_actual := adxLen
_useEmaFilter := useEmaFilter
_useRsiFilter := useRsiFilter
_useCandleFilter := useCandleFilter
_useVolumeFilter := useVolumeFilter
_useAdxFilter := useAdxFilter
_useSnrFilter := useSnrFilter
else if tradingStyle == 'Scalping Cepat'
a := 0.8
c := 8
rsiLen_actual := 7
adxLen_actual := 10
_useEmaFilter := useEmaFilter
_useRsiFilter := useRsiFilter
_useCandleFilter := useCandleFilter
_useVolumeFilter := useVolumeFilter
_useAdxFilter := useAdxFilter
_useSnrFilter := useSnrFilter
else if tradingStyle == 'Swing Santai'
a := 2.0
c := 15
rsiLen_actual := 21
adxLen_actual := 20
_useEmaFilter := useEmaFilter
_useRsiFilter := useRsiFilter
_useCandleFilter := useCandleFilter
_useVolumeFilter := useVolumeFilter
_useAdxFilter := useAdxFilter
_useSnrFilter := useSnrFilter
else if tradingStyle == 'Sangat Akurat'
a := 2.0
c := 15
rsiLen_actual := 21
adxLen_actual := 20
_useEmaFilter := true
_useRsiFilter := true
_useCandleFilter := true
_useVolumeFilter := true
_useAdxFilter := true
_useSnrFilter := true
else if tradingStyle == 'Custom'
a := a_custom
c := c_custom
rsiLen_actual := rsiFilterLen
adxLen_actual := adxLen
_useEmaFilter := useEmaFilter
_useRsiFilter := useRsiFilter
_useCandleFilter := useCandleFilter
_useVolumeFilter := useVolumeFilter
_useAdxFilter := useAdxFilter
_useSnrFilter := useSnrFilter
// ==============================================
// --- LOGIKA INTI & PERHITUNGAN FILTER ---
// ==============================================
xATR = ta.atr(c)
nLoss = a * xATR
src = close
// --- FILTER TREN ---
emaFast = ta.ema(src, emaFastLen)
emaSlow = ta.ema(src, emaSlowLen)
bool emaCrossOkForBuy = close > emaSlow and emaFast > emaSlow
bool emaCrossOkForSell = close < emaSlow and emaFast < emaSlow
// OPTIMIZED: Added gaps parameter to avoid repainting on historical data
emaMtf = request.security(syminfo.tickerid, mtfTimeframe, emaSlow , lookahead = barmerge.lookahead_off)
bool mtfOkForBuy_ori = close > emaMtf
bool mtfOkForSell_ori = close < emaMtf
bool emaOkForBuy = not _useEmaFilter or (tradingStyle == 'Sangat Akurat' ? mtfOkForBuy_ori : emaCrossOkForBuy)
bool emaOkForSell = not _useEmaFilter or (tradingStyle == 'Sangat Akurat' ? mtfOkForSell_ori : emaCrossOkForSell)
// --- FILTER MOMENTUM ---
rsiFilter = ta.rsi(src, rsiLen_actual)
bool rsiOkForBuy = not _useRsiFilter or rsiFilter > rsiBuyLevel
bool rsiOkForSell = not _useRsiFilter or rsiFilter < rsiSellLevel
// --- FILTER CANDLE & VOLUME ---
bool bullishEngulfing = (close > open and close < open and close > open and open < close )
bool bearishEngulfing = (close < open and close > open and close < open and open > close )
bool candleOkForBuy = not _useCandleFilter or bullishEngulfing
bool candleOkForSell = not _useCandleFilter or bearishEngulfing
avgVolume = ta.sma(volume, volumeLen)
bool volumeOkForBuy = not _useVolumeFilter or (volume > avgVolume * volumeThreshold)
bool volumeOkForSell = not _useVolumeFilter or (volume > avgVolume * volumeThreshold)
// --- FILTER SNR ---
pivotHigh = ta.pivothigh(high, snrLookback, snrLookback)
pivotLow = ta.pivotlow(low, snrLookback, snrLookback)
float nearestResistance = ta.valuewhen(not na(pivotHigh), pivotHigh, 0)
float nearestSupport = ta.valuewhen(not na(pivotLow), pivotLow, 0)
float snrDistance = xATR * snrDistanceFactor
bool nearResistance = math.abs(high - nearestResistance) < snrDistance and high > nearestResistance
bool nearSupport = math.abs(low - nearestSupport) < snrDistance and low < nearestSupport
bool snrOkForBuy = not _useSnrFilter or not nearResistance
bool snrOkForSell = not _useSnrFilter or not nearSupport
// --- FILTER ADX ---
= ta.dmi(adxLen_actual, adxLen_actual)
bool adxMarketOk = not _useAdxFilter or adxValue > adxMinLevel
bool adxDirectionOkForBuy = adxMarketOk and diPlus > diMinus
bool adxDirectionOkForSell = adxMarketOk and diMinus > diPlus
bool adxOkForBuy = not _useAdxFilter or adxDirectionOkForBuy
bool adxOkForSell = not _useAdxFilter or adxDirectionOkForSell
// ==============================================
// --- LOGIKA UPGRADE 1 ---
// ==============================================
float prevMidPoint = (high + low ) / 2
bool confirmOkForBuy = not useConfirmFilter or (close > prevMidPoint)
bool confirmOkForSell = not useConfirmFilter or (close < prevMidPoint)
// ==============================================
// --- LOGIKA CANDLE ---
// ==============================================
bool isBullishEngulfing_m = close > open and close < open and close >= open and open <= close
bool isBearishEngulfing_m = close < open and close > open and close <= open and open >= close
bool isHammer_m = (high - low) > 3 * math.abs(open - close) and ((close - low) / (0.001 + high - low)) > 0.6
bool isInvertedHammer_m = (high - low) > 3 * math.abs(open - close) and ((high - close) / (0.001 + high - low)) > 0.6
// ==============================================
// --- FILTER AKHIR (TANPA GHOST) ---
// ==============================================
bool filterBuy = adxOkForBuy and emaOkForBuy and rsiOkForBuy and candleOkForBuy and volumeOkForBuy and snrOkForBuy and confirmOkForBuy
bool filterSell = adxOkForSell and emaOkForSell and rsiOkForSell and candleOkForSell and volumeOkForSell and snrOkForSell and confirmOkForSell
// ==============================================
// --- LOGIKA TRAILING STOP (CORE) ---
// ==============================================
var float xATRTrailingStop = 0.0
iff_1 = src > nz(xATRTrailingStop , 0) ? src - nLoss : src + nLoss
iff_2 = src < nz(xATRTrailingStop , 0) and src < nz(xATRTrailingStop , 0) ? math.min(nz(xATRTrailingStop ), src + nLoss) : iff_1
xATRTrailingStop := src > nz(xATRTrailingStop , 0) and src > nz(xATRTrailingStop , 0) ? math.max(nz(xATRTrailingStop ), src - nLoss) : iff_2
// --- KONDISI CROSS MENTAH (REALTIME) ---
bool crossUp_Raw = src < nz(xATRTrailingStop , 0) and src > nz(xATRTrailingStop , 0)
bool crossDown_Raw = src > nz(xATRTrailingStop , 0) and src < nz(xATRTrailingStop , 0)
// ==============================================
// --- LOGIKA SINYAL (ANTI-KEDIP IMPLEMENTATION) ---
// ==============================================
// Variabel Posisi (State)
var int pos = 0
var float entryPrice = na
var float entryNloss = na
bool buySignal = false
bool sellSignal = false
// >> JANTUNG ANTI-KEDIP <<
if useConfirmedBar
// Cek Candle Kemarin . Jika kemarin valid, sinyal muncul SEKARANG (permanen).
bool crossUp_Prev = close < nz(xATRTrailingStop , 0) and close > nz(xATRTrailingStop , 0)
bool crossDown_Prev = close > nz(xATRTrailingStop , 0) and close < nz(xATRTrailingStop , 0)
// Gunakan filter dari bar sebelumnya agar konsisten
buySignal := crossUp_Prev and filterBuy
sellSignal := crossDown_Prev and filterSell
else
// Mode realtime (Risiko kedap-kedip)
buySignal := crossUp_Raw and filterBuy
sellSignal := crossDown_Raw and filterSell
// --- EKSEKUSI POSISI ---
// Cek Exit
bool closePositionBySL = (nz(pos ) == 1 and src < xATRTrailingStop) or (nz(pos ) == -1 and src > xATRTrailingStop)
bool reversalExitBuy = nz(pos ) == 1 and isBearishEngulfing_m
bool reversalExitSell = nz(pos ) == -1 and isBullishEngulfing_m
bool reversalCandleExit = useReversalExit and (reversalExitBuy or reversalExitSell)
bool exitSignal = closePositionBySL or reversalCandleExit
int newPos = nz(pos )
if buySignal
newPos := 1
else if sellSignal
newPos := -1
else if exitSignal
newPos := 0
pos := newPos
bool posOpen = pos != 0
// Update Entry Price
if buySignal or sellSignal
if useConfirmedBar
entryPrice := open
entryNloss := nLoss
else
entryPrice := src
entryNloss := nLoss
else if pos == 0
entryPrice := na
entryNloss := na
// --- LOGIKA ADD BUY / ADD SELL (SMART SNIPER V3.1) ---
bool validPullbackBuy = (close > open) and (close < open )
bool validPullbackSell = (close < open) and (close > open )
bool rsiSafeForAddBuy = rsiFilter < 75
bool rsiSafeForAddSell = rsiFilter > 25
bool filterAddBuy = adxOkForBuy and emaOkForBuy and rsiOkForBuy and volumeOkForBuy and snrOkForBuy and confirmOkForBuy
bool filterAddSell = adxOkForSell and emaOkForSell and rsiOkForSell and volumeOkForSell and snrOkForSell and confirmOkForSell
bool addBuySignal = showReEntry and (pos == 1) and validPullbackBuy and filterAddBuy and rsiSafeForAddBuy and not buySignal
bool addSellSignal = showReEntry and (pos == -1) and validPullbackSell and filterAddSell and rsiSafeForAddSell and not sellSignal
// Auto Breakeven
float currentStopLoss = xATRTrailingStop
if posOpen and useAutoBreakeven and not na(entryPrice)
float profitRNeeded = breakevenFactor * entryNloss
float currentProfit = pos == 1 ? (src - entryPrice) : (entryPrice - src)
if currentProfit >= profitRNeeded
float breakevenLevel = entryPrice
if pos == 1
if breakevenLevel > currentStopLoss
currentStopLoss := breakevenLevel
else // pos == -1
if breakevenLevel < currentStopLoss
currentStopLoss := breakevenLevel
xATRTrailingStopAdj = posOpen ? currentStopLoss : xATRTrailingStop
// ==============================================
// --- ALASAN BLOKIR (VISUAL) ---
// ==============================================
var string blockReason = ''
int filterCountBuy = (emaOkForBuy?1:0)+(rsiOkForBuy?1:0)+(candleOkForBuy?1:0)+(volumeOkForBuy?1:0)+(adxOkForBuy?1:0)+(snrOkForBuy?1:0)+(confirmOkForBuy?1:0)
int filterCountSell = (emaOkForSell?1:0)+(rsiOkForSell?1:0)+(candleOkForSell?1:0)+(volumeOkForSell?1:0)+(adxOkForSell?1:0)+(snrOkForSell?1:0)+(confirmOkForSell?1:0)
if crossUp_Raw and not filterBuy
blockReason := '❌ Buy Blocked (' + str.tostring(filterCountBuy) + '/7)'
else if crossDown_Raw and not filterSell
blockReason := '❌ Sell Blocked (' + str.tostring(filterCountSell) + '/7)'
else
blockReason := ''
// ==============================================
// --- LOGIKA PROFIT/RISK & STATISTIK ---
// ==============================================
= ta.bb(src, bbLen, bbStdDev)
float distFromEntry = posOpen ? (pos == 1 ? src - nz(entryPrice) : nz(entryPrice) - src) : 0.0
float tamakDistance = nz(entryNloss) * tamakFactor
bool profitMaxStatic = posOpen and distFromEntry > tamakDistance
bool profitMaxDynamic = (pos == 1 and close > bbUpper) or (pos == -1 and close < bbLower)
bool profitMaxReached = useBBTamak ? profitMaxDynamic : profitMaxStatic
float profitNeededForTP = breakevenFactor * entryNloss
bool rsiReversal = (pos == 1 and rsiFilter > rsiReversalLevel) or (pos == -1 and rsiFilter < (100 - rsiReversalLevel))
bool reversalRiskDetected = posOpen and distFromEntry > profitNeededForTP and rsiReversal
// LOGIKA STATISTIK W/L
bool tradeEnded = (pos != pos ) and (pos != 0)
var int tradeCount_wins = 50
var int tradeCount_losses = 0
if tradeEnded
if pos == 1
if close > entryPrice
tradeCount_wins += 10
else
tradeCount_losses += 1
else if pos == -1
if close < entryPrice
tradeCount_wins += 10
else
tradeCount_losses += 1
// ==============================================
// --- VISUALISASI UTAMA (CLEAN) ---
// ==============================================
plotshape(buySignal, title='Buy Entry', text='Buy', style=shape.labelup, location=location.belowbar, color=color.green, textcolor=color.white, size=size.tiny)
plotshape(sellSignal, title='Sell Entry', text='Sell', style=shape.labeldown, location=location.abovebar, color=color.red, textcolor=color.white, size=size.tiny)
plotshape(addBuySignal, title='Add Buy', text='Add', style=shape.triangleup, location=location.belowbar, color=color.blue, textcolor=color.blue, size=size.tiny)
plotshape(addSellSignal, title='Add Sell', text='Add', style=shape.triangledown, location=location.abovebar, color=color.fuchsia, textcolor=color.fuchsia, size=size.tiny)
plotshape(reversalCandleExit, title='Forced Exit', text='Exit', style=shape.labeldown, location=location.abovebar, color=color.gray, textcolor=color.white, size=size.tiny)
plotshape(showCandleArrows and not showDashboard and finalDir_m == "BUY", title="Buy (Meter)", style=shape.triangleup, color=color.new(color.lime, 0), location=location.belowbar, size=size.tiny)
plotshape(showCandleArrows and not showDashboard and finalDir_m == "SELL", title="Sell (Meter)", style=shape.triangledown, color=color.new(color.red, 0), location=location.abovebar, size=size.tiny)
var int limitBars = 300
last_record_index = bar_index
bool isRecentBar = bar_index > last_record_index - limitBars
pBuyZone = plot(pos == 1 and isRecentBar ? xATRTrailingStopAdj : na, color=color.new(color.white, 100))
pSellZone = plot(pos == -1 and isRecentBar ? xATRTrailingStopAdj : na, color=color.new(color.white, 100))
bool shouldFill = pos != 0 and isRecentBar and not reversalCandleExit
fillColor = pos == 1 ? color.new(color.green, 85) : pos == -1 ? color.new(color.red, 85) : na
fill(pBuyZone, pSellZone, color = shouldFill ? fillColor : na)
var line snr_res_line = na
var line snr_sup_line = na
if not na(pivotHigh)
line.delete(snr_res_line)
snr_res_line := line.new(bar_index, pivotHigh, bar_index + 1, pivotHigh, xloc.bar_index, extend.right, color.red, line.style_solid, 2)
if not na(pivotLow)
line.delete(snr_sup_line)
snr_sup_line := line.new(bar_index, pivotLow, bar_index + 1, pivotLow, xloc.bar_index, extend.right, color.green, line.style_solid, 2)
plot(useBBTamak ? bbUpper : na, title="BB Upper (Target)", color=color.new(color.aqua, 70), style=plot.style_circles, linewidth=1)
plot(useBBTamak ? bbLower : na, title="BB Lower (Target)", color=color.new(color.aqua, 70), style=plot.style_circles, linewidth=1)
float emaAggressiveFast = ta.ema(src, emaAggressiveFastLen)
float emaAggressiveSlow = ta.ema(src, emaAggressiveSlowLen)
plot(showAggressiveEMA ? emaAggressiveFast : na, title="EMA Agresif Cepat", color=color.new(#1ff118, 44), style=plot.style_cross, linewidth=1)
plot(showAggressiveEMA ? emaAggressiveSlow : na, title="EMA Agresif Lambat", color=color.new(#f8241d, 46), style=plot.style_cross, linewidth=1)
// ==============================================
// --- DASHBOARD PRO & STATUS (REALITY ADVISOR COMPACT) ---
// ==============================================
string statusText = ''
color statusColor = color.gray
float distFromStop = pos == 1 ? src - xATRTrailingStopAdj : pos == -1 ? xATRTrailingStopAdj - src : 0
bool waspada = pos != 0 and not buySignal and not sellSignal and distFromStop < waspadaFactor * entryNloss
int rand = bar_index % 5
var string advisorMsg = "..."
if buySignal
statusText := '🚀 NAIK! Entry Baru'
statusColor := color.green
if rand == 0
advisorMsg := "Gaspol! 🚀 Jangan keasyikan tambah SL+ sayang."
else if rand == 1
advisorMsg := "OTW Sultan! 🤑 Full senyum maszeh!"
else if rand == 2
advisorMsg := "Ijo royo-royo! 🌿 Mata jadi seger."
else if rand == 3
advisorMsg := "Sikat Pak Haji! 👳 Rejeki anak soleh."
else
advisorMsg := "Lilin hijau! Serok sekarang! 💰"
else if sellSignal
statusText := '📉 TURUN! Entry Baru'
statusColor := color.red
if rand == 0
advisorMsg := "Longsor! 📉 Siapkan ember."
else if rand == 1
advisorMsg := "Merah merona! 🩸 Dompet aman kan?"
else if rand == 2
advisorMsg := "Terjun bebas! 🪂 waspada REM."
else if rand == 3
advisorMsg := "Longsor! 📉 jangan naik dulu."
else
advisorMsg := "Short selling! Cuan tipis sikat! 💸"
else if addBuySignal
statusText := '🚀 GAS LAGI (Add)!'
statusColor := color.blue
if rand == 0
advisorMsg := "Tambah muatan! 😎 Biar bandar nangis."
else
advisorMsg := "Mumpung hijau! 🛒 Sikat lagi bosqu!"
else if addSellSignal
statusText := '📉 GAS LAGI (Add)!'
statusColor := color.fuchsia
if rand == 0
advisorMsg := "Tambah Sell! 🔥 Biar makin perih."
else
advisorMsg := "Tekan bawah! 😤 Jangan kasih napas."
else if reversalCandleExit
statusText := '⛔ EXIT! Pembalikan'
statusColor := color.orange
advisorMsg := "Kabur! 🏃💨 Candle mencurigakan."
else if reversalRiskDetected
statusText := '⚠️ TP NOW!'
statusColor := color.yellow
advisorMsg := "Amankan profit! 🤡 Jangan serakah."
else if profitMaxReached
statusText := '🤑 CUAN BUNGKUS!'
statusColor := color.aqua
if rand == 0
advisorMsg := "Cuan bungkus! 🍜 Traktir seblak dong."
else if rand == 1
advisorMsg := "Udah kaya? 💅 Tarik buat skincare!"
else
advisorMsg := "Alhamdulillah! 🎁 Rejeki jangan ditolak."
else if waspada
statusText := '💔 HATI-HATI!'
statusColor := color.orange
if rand == 0
advisorMsg := "Dia toxic... 🚩 Hati-hati SL."
else
advisorMsg := "Awas MC! 💀 pasang SL+ sayang."
else if pos == 1
statusText := '🧘 TAHAN Buy...'
statusColor := color.green
if rand == 0
advisorMsg := "Sabar sayang... 🧘♀️ Disayang Tuhan."
else if rand == 1
advisorMsg := "Biarkan lari! 🏃♂️ Profit is running."
else
advisorMsg := "Hold terus! 🚀 Sampai ke bulan!"
else if pos == -1
statusText := '🍿 TAHAN Sell...'
statusColor := color.red
if rand == 0
advisorMsg := "Nonton aja... 🍿 Sambil ngemil."
else
advisorMsg := "Jatuh kebawah sakit? 😂 disini malah Cuan."
else if blockReason != ''
statusText := "DIBLOKIR"
statusColor := color.gray
advisorMsg := "Sinyal busuk! ⛔ Jangan masuk."
else
statusText := '... '
statusColor := color.gray
if rand == 0
advisorMsg := "Market galau... 💤 Mending turu."
else if rand == 1
advisorMsg := "Datar banget... 😑 Kek jalan tol."
else if rand == 2
advisorMsg := "Jangan maksa! ☕ Ngopi dulu."
else
advisorMsg := "Sabar... 🕰️ Menunggu itu berat."
if adxValue > adxMinLevel and diPlus > diMinus
marketModeText := "📈 Tren Naik Kuat"
marketModeColor := color.new(color.green, 0)
else if adxValue > adxMinLevel and diMinus > diPlus
marketModeText := "📉 Tren Turun Kuat"
marketModeColor := color.new(color.red, 0)
else
marketModeText := "💤 Sideways / Chop"
marketModeColor := color.new(color.gray, 0)
f_fillCell(tbl, col, row, cellText, color) =>
table.cell(tbl, col, row, cellText, text_color=color, text_size=size.small)
f_drawDashboard() =>
f_fillCell(dashboardPanel, 0, 0, "Gaya:", color.gray)
f_fillCell(dashboardPanel, 1, 0, tradingStyle, color.white)
f_fillCell(dashboardPanel, 0, 1, "Status:", color.gray)
f_fillCell(dashboardPanel, 1, 1, statusText, statusColor)
bool dashboardContextIsBuy = pos == 1 or (pos == 0 and close > open)
string emaStatus = (dashboardContextIsBuy ? emaOkForBuy : emaOkForSell) or not _useEmaFilter ? "✅" : "❌"
string rsiStatus = (dashboardContextIsBuy ? rsiOkForBuy : rsiOkForSell) or not _useRsiFilter ? "✅" : "❌"
string adxStatus = (dashboardContextIsBuy ? adxOkForBuy : adxOkForSell) or not _useAdxFilter ? "✅" : "❌"
string snrStatus = (dashboardContextIsBuy ? snrOkForBuy : snrOkForSell) or not _useSnrFilter ? "✅" : "❌"
string confirmStatus = (dashboardContextIsBuy ? confirmOkForBuy : confirmOkForSell) or not useConfirmFilter ? "✅" : "❌"
string filterStr1 = "EMA" + emaStatus + " RSI" + rsiStatus
string filterStr2 = "ADX" + adxStatus + " SNR" + snrStatus + (useConfirmFilter ? " 1-Bar" + confirmStatus : "")
string filterString = filterStr1 + " " + filterStr2
f_fillCell(dashboardPanel, 0, 2, "Filter:", color.gray)
f_fillCell(dashboardPanel, 1, 2, filterString, color.white)
float body_m = math.abs(close - open)
float rangeC_m = high - low
float power_m = rangeC_m == 0 ? 0.0 : (body_m / rangeC_m) * 5
power_m := math.min(power_m, 5)
float confidence_m = rangeC_m == 0 ? 0.0 : math.round(math.abs((close - open) / (high - low)) * 100)
int powerInt_m = int(math.round(power_m))
powerInt_m := powerInt_m < 0 ? 0 : powerInt_m > 5 ? 5 : powerInt_m
string bars_m = str.repeat("█", powerInt_m) + str.repeat("░", 5 - powerInt_m)
string meterString = (close > open ? "🟢 " : "🔴 ") + bars_m + " " + str.tostring(confidence_m, "#") + "%"
f_fillCell(dashboardPanel, 0, 3, "Meter:", color.gray)
f_fillCell(dashboardPanel, 1, 3, meterString, (close > open ? color.green : color.red))
int totalTrades = tradeCount_wins + tradeCount_losses
f_fillCell(dashboardPanel, 0, 4, "Total Sinyal:", color.gray)
f_fillCell(dashboardPanel, 1, 4, str.tostring(totalTrades), color.white)
f_fillCell(dashboardPanel, 0, 5, "W / L:", color.gray)
f_fillCell(dashboardPanel, 1, 5, str.tostring(tradeCount_wins) + " / " + str.tostring(tradeCount_losses), color.white)
string winRateString = "N/A"
color winRateColor = color.gray
if totalTrades > 0
winRateString := str.tostring(tradeCount_wins / totalTrades * 100, '0.0') + "%"
winRateColor := tradeCount_wins > tradeCount_losses ? color.green : (tradeCount_losses > tradeCount_wins ? color.red : color.gray)
f_fillCell(dashboardPanel, 0, 6, "Win Rate:", color.gray)
f_fillCell(dashboardPanel, 1, 6, winRateString, winRateColor)
f_fillCell(dashboardPanel, 0, 7, "Pasar:", color.gray)
f_fillCell(dashboardPanel, 1, 7, marketModeText, marketModeColor)
table.merge_cells(dashboardPanel, 0, 8, 1, 8)
table.cell(dashboardPanel, 0, 8, advisorMsg, text_color=color.yellow, text_size=size.small, bgcolor=color.new(color.black, 50))
table.merge_cells(dashboardPanel, 0, 9, 1, 9)
table.cell(dashboardPanel, 0, 9, "HADYAN PREMIUM INDI 083174747475", text_color=color.new(#969087, 66), text_size=size.tiny)
if barstate.islast and showDashboard
f_drawDashboard()
else if barstate.islast
table.clear(dashboardPanel, 0, 0, 1, 9)
// ==============================================
// --- FLOATING BUBBLE LABEL (FIXED) ---
// ==============================================
var label advisorLabel = na
if barstate.islast
label.delete(advisorLabel)
if showAdvisorBubble
// Tentukan Warna Gelembung biar Cantik
color bubbleColor = color.new(color.gray, 20)
if buySignal or addBuySignal or pos == 1
bubbleColor := color.new(color.green, 20)
else if sellSignal or addSellSignal or pos == -1
bubbleColor := color.new(color.red, 20)
else if waspada or reversalCandleExit
bubbleColor := color.new(color.orange, 20)
// OPTIMIZED: Geser sedikit ke kanan (+2) agar tidak menutupi candle terakhir
advisorLabel := label.new(bar_index + 2, close, text=advisorMsg, color=bubbleColor, textcolor=color.white, style=label.style_label_left, yloc=yloc.price)
// ==============================================
// --- LOGIKA CANDLE METER PANEL ---
// ==============================================
if (showCandlePanel or showCandleArrows) and not showDashboard
float body_m = math.abs(close - open)
float rangeC_m = high - low
float power_m = rangeC_m == 0 ? 0.0 : (body_m / rangeC_m) * 5
power_m := math.min(power_m, 5)
float confidence_m = rangeC_m == 0 ? 0.0 : math.round(math.abs((close - open) / (high - low)) * 100)
string patternName_m = ""
string baseDir_m = close > open ? "BUY" : "SELL"
if isBullishEngulfing_m
patternName_m := "Bullish Engulfing"
baseDir_m := "BUY"
else if isBearishEngulfing_m
patternName_m := "Bearish Engulfing"
baseDir_m := "SELL"
else if isHammer_m
patternName_m := "Hammer"
baseDir_m := "BUY"
else if isInvertedHammer_m
patternName_m := "Inverted Hammer"
baseDir_m := "SELL"
else
patternName_m := "Normal Candle"
string trendConfirm_m = close > close and close > close ? "BUY" : close < close and close < close ? "SELL" : baseDir_m
finalDir_m := baseDir_m == trendConfirm_m ? baseDir_m : baseDir_m
if showCandlePanel
int powerInt_m = int(math.round(power_m))
powerInt_m := powerInt_m < 0 ? 0 : powerInt_m > 5 ? 5 : powerInt_m
string bars_m = str.repeat("█", powerInt_m) + str.repeat("░", 5 - powerInt_m)
string dirText_m = finalDir_m == "BUY" ? "🟢 BUY" : "🔴 SELL"
string confText_m = str.tostring(confidence_m, "#") + "% " + bars_m
table.cell(infoPanel_m, 0, 0, "Pattern", text_color=color.yellow)
table.cell(infoPanel_m, 1, 0, "Direction", text_color=color.yellow)
table.cell(infoPanel_m, 2, 0, "Confidence", text_color=color.yellow)
table.cell(infoPanel_m, 0, 1, patternName_m, text_color=color.white)
table.cell(infoPanel_m, 1, 1, dirText_m, text_color=color.white)
table.cell(infoPanel_m, 2, 1, confText_m, text_color=color.white)
else
table.clear(infoPanel_m, 0, 0, 2, 1)
else if not showDashboard
table.clear(infoPanel_m, 0, 0, 2, 1)
// ==============================================
// --- ALERT UPDATED (SINGLE ALERT SUPPORT) ---
// ==============================================
string alertMsg_all = ""
if buySignal
alertMsg_all := "🚀 BUY NEW! @ " + str.tostring(close) + " | SL: " + str.tostring(xATRTrailingStopAdj)
else if sellSignal
alertMsg_all := "📉 SELL NEW! @ " + str.tostring(close) + " | SL: " + str.tostring(xATRTrailingStopAdj)
else if addBuySignal
alertMsg_all := "➕ ADD BUY (Re-Entry) @ " + str.tostring(close)
else if addSellSignal
alertMsg_all := "➕ ADD SELL (Re-Entry) @ " + str.tostring(close)
else if reversalCandleExit
alertMsg_all := "⛔ EXIT NOW! Reversal Detected @ " + str.tostring(close)
else if profitMaxReached
alertMsg_all := "💰 TAKE PROFIT! Target Tercapai @ " + str.tostring(close)
else if reversalRiskDetected
alertMsg_all := "⚠️ WARNING REVERSAL! RSI Extreme @ " + str.tostring(close)
// Pemicu Alarm Utama (Hanya aktif jika ada pesan, cukup pasang 1 alarm "Any function call")
if alertMsg_all != ""
alert(alertMsg_all, alert.freq_once_per_bar_close)
// Backup: Manual Alerts (Jika user Premium mau pasang satu-satu)
alertcondition(buySignal, title=' Buy Signal', message='🚀 BUY NEW!')
alertcondition(sellSignal, title=' Sell Signal', message='📉 SELL NEW!')
alertcondition(addBuySignal, title=' Add Buy', message='🚀 ADD BUY')
alertcondition(addSellSignal, title=' Add Sell', message='📉 ADD SELL')
alertcondition(waspada, title=' Waspada', message='💔 WASPADA')
// ==============================================
// --- TP/SL MODE SWING (FIXED & OPTIMIZED) ---
// ==============================================
var line sl_line = na
var line tp1_line = na
var line tp2_line = na
var line tp3_line = na
var label sl_label = na
var label tp1_label = na
var label tp2_label = na
var label tp3_label = na
if tradingStyle == 'Swing Santai'
if buySignal
line.delete(sl_line)
line.delete(tp1_line)
line.delete(tp2_line)
line.delete(tp3_line)
label.delete(sl_label)
label.delete(tp1_label)
label.delete(tp2_label)
label.delete(tp3_label)
float sl = entryPrice - entryNloss
float tp1 = entryPrice + entryNloss
float tp2 = entryPrice + (2*entryNloss)
float tp3 = entryPrice + (3*entryNloss)
sl_line := line.new(bar_index, sl, bar_index + 10, sl, color=color.new(color.red, 20), style=line.style_dashed, width=2)
tp1_line := line.new(bar_index, tp1, bar_index + 10, tp1, color=color.new(color.green, 20), style=line.style_dashed, width=2)
tp2_line := line.new(bar_index, tp2, bar_index + 10, tp2, color=color.new(color.green, 20), style=line.style_dashed, width=2)
tp3_line := line.new(bar_index, tp3, bar_index + 10, tp3, color=color.new(color.green, 20), style=line.style_dashed, width=2)
sl_label := label.new(bar_index + 10, sl, "SL (Rugi)", color=color.red, style=label.style_label_left, textcolor=color.white)
tp1_label := label.new(bar_index + 10, tp1, "TP1 (1:1)", color=color.green, style=label.style_label_left, textcolor=color.white)
tp2_label := label.new(bar_index + 10, tp2, "TP2 (1:2)", color=color.green, style=label.style_label_left, textcolor=color.white)
tp3_label := label.new(bar_index + 10, tp3, "TP3 (1:3)", color=color.green, style=label.style_label_left, textcolor=color.white)
else if sellSignal
line.delete(sl_line)
line.delete(tp1_line)
line.delete(tp2_line)
line.delete(tp3_line)
label.delete(sl_label)
label.delete(tp1_label)
label.delete(tp2_label)
label.delete(tp3_label)
float sl = entryPrice + entryNloss
float tp1 = entryPrice - entryNloss
float tp2 = entryPrice - (2*entryNloss)
float tp3 = entryPrice - (3*entryNloss)
sl_line := line.new(bar_index, sl, bar_index + 10, sl, color=color.new(color.red, 20), style=line.style_dashed, width=2)
tp1_line := line.new(bar_index, tp1, bar_index + 10, tp1, color=color.new(color.green, 20), style=line.style_dashed, width=2)
tp2_line := line.new(bar_index, tp2, bar_index + 10, tp2, color=color.new(color.green, 20), style=line.style_dashed, width=2)
tp3_line := line.new(bar_index, tp3, bar_index + 10, tp3, color=color.new(color.green, 20), style=line.style_dashed, width=2)
sl_label := label.new(bar_index + 10, sl, "SL (Rugi)", color=color.red, style=label.style_label_left, textcolor=color.white)
tp1_label := label.new(bar_index + 10, tp1, "TP1 (1:1)", color=color.green, style=label.style_label_left, textcolor=color.white)
tp2_label := label.new(bar_index + 10, tp2, "TP2 (1:2)", color=color.green, style=label.style_label_left, textcolor=color.white)
tp3_label := label.new(bar_index + 10, tp3, "TP3 (1:3)", color=color.green, style=label.style_label_left, textcolor=color.white)
else if pos != 0 and not na(sl_line)
// Update existing lines (Lightweight)
line.set_x2(sl_line, bar_index + 10)
line.set_x2(tp1_line, bar_index + 10)
line.set_x2(tp2_line, bar_index + 10)
line.set_x2(tp3_line, bar_index + 10)
label.set_x(sl_label, bar_index + 10)
label.set_x(tp1_label, bar_index + 10)
label.set_x(tp2_label, bar_index + 10)
label.set_x(tp3_label, bar_index + 10)
else if pos == 0
line.delete(sl_line)
sl_line := na
line.delete(tp1_line)
tp1_line := na
line.delete(tp2_line)
tp2_line := na
line.delete(tp3_line)
tp3_line := na
label.delete(sl_label)
sl_label := na
label.delete(tp1_label)
tp1_label := na
label.delete(tp2_label)
tp2_label := na
label.delete(tp3_label)
tp3_label := na
else
line.delete(sl_line)
sl_line := na
line.delete(tp1_line)
tp1_line := na
line.delete(tp2_line)
tp2_line := na
line.delete(tp3_line)
tp3_line := na
label.delete(sl_label)
sl_label := na
label.delete(tp1_label)
tp1_label := na
label.delete(tp2_label)
tp2_label := na
label.delete(tp3_label)
tp3_label := na
// ==============================================
// --- UPGRADE BARU: PIVOT POINTS (FIXED: EXTEND RIGHT) ---
// ==============================================
// Dapatkan Daily High, Low, Close (FIX "D")
p_d_h = request.security(syminfo.tickerid, "D", high , lookahead=barmerge.lookahead_on)
p_d_l = request.security(syminfo.tickerid, "D", low , lookahead=barmerge.lookahead_on)
p_d_c = request.security(syminfo.tickerid, "D", close , lookahead=barmerge.lookahead_on)
// Perhitungan Pivot Klasik
pivot_d = (p_d_h + p_d_l + p_d_c) / 3
r1_d = 2 * pivot_d - p_d_l
s1_d = 2 * pivot_d - p_d_h
r2_d = pivot_d + (p_d_h - p_d_l)
s2_d = pivot_d - (p_d_h - p_d_l)
// Visualisasi Pivot
var line p_line = na
var line r1_line = na
var line s1_line = na
var line r2_line = na
var line s2_line = na
var label p_label = na
var label r1_label = na
var label s1_label = na
var label r2_label = na
var label s2_label = na
// Fungsi untuk menghapus label/line
f_delete_pivot_objects() =>
line.delete(p_line)
line.delete(r1_line)
line.delete(s1_line)
line.delete(r2_line)
line.delete(s2_line)
label.delete(p_label)
label.delete(r1_label)
label.delete(s1_label)
label.delete(r2_label)
label.delete(s2_label)
if showPivotPoints
// Hapus yang lama agar tidak numpuk (Redraw Logic)
f_delete_pivot_objects()
// Logic: EXTEND RIGHT (Memanjang)
// Kita gunakan extend.right agar garisnya tidak pernah putus ke kanan
// Pivot (P)
p_line := line.new(bar_index, pivot_d, bar_index + 1, pivot_d, xloc.bar_index, extend.right, pivotColor, line.style_solid, 2)
p_label := label.new(bar_index + 10, pivot_d, "P Daily: " + str.tostring(pivot_d, format.mintick), xloc.bar_index, yloc.price, color=color.new(pivotColor, 20), textcolor=color.white, style=label.style_label_left, size=size.small)
// Resistance
r1_line := line.new(bar_index, r1_d, bar_index + 1, r1_d, xloc.bar_index, extend.right, color.new(color.red, 30), line.style_dashed, 1)
r1_label := label.new(bar_index + 10, r1_d, "R1: " + str.tostring(r1_d, format.mintick), xloc.bar_index, yloc.price, color=color.new(color.red, 80), textcolor=color.red, style=label.style_label_left, size=size.small)
r2_line := line.new(bar_index, r2_d, bar_index + 1, r2_d, xloc.bar_index, extend.right, color.new(color.red, 30), line.style_dashed, 1)
r2_label := label.new(bar_index + 10, r2_d, "R2: " + str.tostring(r2_d, format.mintick), xloc.bar_index, yloc.price, color=color.new(color.red, 80), textcolor=color.red, style=label.style_label_left, size=size.small)
// Support
s1_line := line.new(bar_index, s1_d, bar_index + 1, s1_d, xloc.bar_index, extend.right, color.new(color.green, 30), line.style_dashed, 1)
s1_label := label.new(bar_index + 10, s1_d, "S1: " + str.tostring(s1_d, format.mintick), xloc.bar_index, yloc.price, color=color.new(color.green, 80), textcolor=color.green, style=label.style_label_left, size=size.small)
s2_line := line.new(bar_index, s2_d, bar_index + 1, s2_d, xloc.bar_index, extend.right, color.new(color.green, 30), line.style_dashed, 1)
s2_label := label.new(bar_index + 10, s2_d, "S2: " + str.tostring(s2_d, format.mintick), xloc.bar_index, yloc.price, color=color.new(color.green, 80), textcolor=color.green, style=label.style_label_left, size=size.small)
else
f_delete_pivot_objects()
// ==============================================
// --- UPGRADE BARU: FIBONACCI RETRACEMENT (CLEAN NO STACK) ---
// ==============================================
var float fiboHigh = na
var float fiboLow = na
var int fiboStartBar = na
// Array untuk menyimpan objek Fibo
var line fiboLines = array.new(0)
var linefill fiboFills = array.new(0)
var label fiboLabels = array.new(0)
// Helper Function: Clean Up All Fibo Objects
f_cleanFibo() =>
if array.size(fiboLines) > 0
for i = 0 to array.size(fiboLines) - 1
line.delete(array.get(fiboLines, i))
array.clear(fiboLines)
if array.size(fiboFills) > 0
for i = 0 to array.size(fiboFills) - 1
linefill.delete(array.get(fiboFills, i))
array.clear(fiboFills)
if array.size(fiboLabels) > 0
for i = 0 to array.size(fiboLabels) - 1
label.delete(array.get(fiboLabels, i))
array.clear(fiboLabels)
// Calculate historical values globally
float lastHigh_scanned = ta.valuewhen(not na(pivotHigh), pivotHigh, 0)
float lastLow_scanned = ta.valuewhen(not na(pivotLow), pivotLow, 0)
// Reset Fibo jika ada sinyal entry baru
if buySignal or sellSignal
f_cleanFibo() // Clean old ones first!
// Gunakan nilai yang sudah di-scan secara global
if not na(lastHigh_scanned) and not na(lastLow_scanned)
fiboLow := lastLow_scanned
fiboHigh := lastHigh_scanned
fiboStartBar := bar_index
// Levels
fiboLevels = array.new(0)
array.push(fiboLevels, 0.0)
array.push(fiboLevels, 0.236)
array.push(fiboLevels, 0.382)
array.push(fiboLevels, 0.5)
array.push(fiboLevels, 0.618)
array.push(fiboLevels, 1.0)
// Gambar Fibo (Hanya digambar ulang jika posisi valid dan belum ada)
// Kita gunakan trik: Gambar setiap bar, tapi HAPUS yang lama dulu.
// Ini mencegah stacking ribuan kotak.
if showFiboLevels and not na(fiboHigh) and not na(fiboLow)
f_cleanFibo() // CLEANUP WAJIB SEBELUM GAMBAR BARU
float fiboRange = fiboHigh - fiboLow
int f_start = bar_index + fiboXOffset
int f_end = bar_index + fiboXOffset + 15
var line lastLineObj = na
for i = 0 to array.size(fiboLevels) - 1
float level = array.get(fiboLevels, i)
float fiboPrice = fiboHigh - (fiboRange * level)
string levelText = str.tostring(math.round(level * 100), "0.0") + "%"
color levelColor = color.rgb(19, 56, 189)
if level == 0.618
levelColor := color.new(#FFD700, 30)
else if level == 0.5
levelColor := color.new(color.green, 30)
else
levelColor := color.new(#7925c9, 70)
string l_style = (level == 0.0 or level == 1.0) ? line.style_dashed : line.style_solid
int l_width = (level == 0.618 or level == 0.5) ? 2 : 1
// Draw & Push Line
line currentLineObj = line.new(f_start, fiboPrice, f_end, fiboPrice, xloc.bar_index, extend.none, levelColor, l_style, l_width)
array.push(fiboLines, currentLineObj)
// Fill Logic
color c_fill = switch level
0.236 => color.new(color.gray, 70) // Sangat transparan (95)
0.382 => color.new(color.blue, 70)
0.5 => color.new(color.green, 70)
0.618 => color.new(#FFD700, 70)
1.0 => color.new(color.red, 70)
=> na
if i > 0
linefill lf = linefill.new(lastLineObj, currentLineObj, c_fill)
array.push(fiboFills, lf)
lastLineObj := currentLineObj
// Draw & Push Label
label lb = label.new(f_end, fiboPrice, levelText, xloc.bar_index, yloc.price, color=color.new(levelColor, 100), textcolor=levelColor, style=label.style_label_left, size=size.small)
array.push(fiboLabels, lb)
// ==============================================
// --- UPGRADE BARU: STOCHASTIC FLOATING MINI CHART (REALTIME ANCHOR RIGHT PATCH) ---
// ==============================================
// 1. Calculations
stochK = ta.sma(ta.stoch(close, high, low, 14), 3)
stochD = ta.sma(stochK, 3)
// 2. Data Storage (Arrays for History)
var float stochK_hist = array.new_float(0)
var float stochD_hist = array.new_float(0)
// Update Arrays (REALTIME LOGIC)
if barstate.isnew
array.push(stochK_hist, nz(stochK, 50))
array.push(stochD_hist, nz(stochD, 50))
// Limit array size to chart width + 1
if array.size(stochK_hist) > (stochWidth + 1)
array.shift(stochK_hist)
array.shift(stochD_hist)
else
// UPDATE TICK-BY-TICK (Agar tidak delay)
if array.size(stochK_hist) > 0
array.set(stochK_hist, array.size(stochK_hist) - 1, nz(stochK, 50))
array.set(stochD_hist, array.size(stochD_hist) - 1, nz(stochD, 50))
// 3. Drawing Logic
var box stochBgBox = na
var box stochUpperFill = na
var box stochLowerFill = na
var line stochLines = array.new_line(0)
// Clear Function
f_cleanStochChart() =>
if not na(stochBgBox)
box.delete(stochBgBox)
if not na(stochUpperFill)
box.delete(stochUpperFill)
if not na(stochLowerFill)
box.delete(stochLowerFill)
if array.size(stochLines) > 0
for i = 0 to array.size(stochLines) - 1
line.delete(array.get(stochLines, i))
array.clear(stochLines)
// Global Helper to map 0-100 Stoch value to Y price coordinate
f_mapY(_val, _bottom, _height) =>
_bottom + (_val / 100 * _height)
if showStochChart and array.size(stochK_hist) > 2
f_cleanStochChart() // Redraw every tick
// Positioning (ANCHOR RIGHT LOGIC)
int offset_right = 5
int ch_right = bar_index + offset_right // Ujung kanan box
int ch_left = ch_right - stochWidth
// Vertical Scaling
float ch_height = ta.atr(14) * 4
float ch_bottom = close - (ch_height * 1.5)
float ch_top = ch_bottom + ch_height
// Draw Background
stochBgBox := box.new(ch_left, ch_top, ch_right, ch_bottom, xloc=xloc.bar_index, border_width=1, border_color=color.new(color.white, 80), bgcolor=color.new(color.black, 100))
// Draw Overbought Fill (80-100)
stochUpperFill := box.new(ch_left, f_mapY(70, ch_bottom, ch_height), ch_right, f_mapY(80, ch_bottom, ch_height), xloc=xloc.bar_index, border_width=0, bgcolor=color.new(color.red, 100))
// Draw Oversold Fill (0-20)
stochLowerFill := box.new(ch_left, f_mapY(10, ch_bottom, ch_height), ch_right, f_mapY(0, ch_bottom, ch_height), xloc=xloc.bar_index, border_width=0, bgcolor=color.new(color.green, 100))
// Draw Reference Lines
line l80 = line.new(ch_left, f_mapY(80, ch_bottom, ch_height), ch_right, f_mapY(80, ch_bottom, ch_height), color=color.new(color.red, 20), style=line.style_dotted)
line l20 = line.new(ch_left, f_mapY(20, ch_bottom, ch_height), ch_right, f_mapY(20, ch_bottom, ch_height), color=color.new(color.green, 20), style=line.style_dotted)
array.push(stochLines, l80)
array.push(stochLines, l20)
// Draw K and D Lines (ANCHOR TO REALTIME BAR INDEX)
// PATCH: Iterate relative to current bar_index to ensure 0 gap
int sz = array.size(stochK_hist)
for i = 0 to sz - 2
// Logika Mundur: Titik terakhir (sz-1) harus ada di bar_index saat ini
int idx_current = sz - 1 - i
int idx_prev = sz - 2 - i
if idx_prev >= 0
// X Coordinates (Relative to Realtime Bar)
int x2 = bar_index - i
int x1 = bar_index - (i + 1)
// K Line
float yK1 = f_mapY(array.get(stochK_hist, idx_prev), ch_bottom, ch_height)
float yK2 = f_mapY(array.get(stochK_hist, idx_current), ch_bottom, ch_height)
if not na(yK1) and not na(yK2)
line lK = line.new(x1, yK1, x2, yK2, color=color.new(#05492f, 0), width=1)
array.push(stochLines, lK)
// D Line
float yD1 = f_mapY(array.get(stochD_hist, idx_prev), ch_bottom, ch_height)
float yD2 = f_mapY(array.get(stochD_hist, idx_current), ch_bottom, ch_height)
if not na(yD1) and not na(yD2)
line lD = line.new(x1, yD1, x2, yD2, color=color.new(#810404, 0), width=1)
array.push(stochLines, lD)
// ==============================================
// --- VISUALISASI UPGRADE: SMART SUPPLY/DEMAND ZONES ---
// ==============================================
ph_zone = ta.pivothigh(high, zoneLookback, zoneLookback)
pl_zone = ta.pivotlow(low, zoneLookback, zoneLookback)
// FIX: Pindahkan ATR ke luar IF agar konsisten
float atrForZone = ta.atr(14)
var box supplyBoxes = array.new_box()
var box demandBoxes = array.new_box()
// Batasi jumlah zona agar chart tetap bersih
maxZones = 5
// Deteksi Zona Supply (Merah)
if not na(ph_zone) and showSmartZones
// Buat box baru dari titik pivot sampai ke masa depan sedikit
b_sup = box.new(bar_index , high , bar_index + 20, high - (atrForZone*0.5), bgcolor=color.new(color.red, 85), border_color=color.new(color.red, 50))
array.push(supplyBoxes, b_sup)
if array.size(supplyBoxes) > maxZones
box.delete(array.shift(supplyBoxes))
// Deteksi Zona Demand (Hijau)
if not na(pl_zone) and showSmartZones
b_dem = box.new(bar_index , low , bar_index + 20, low + (atrForZone*0.5), bgcolor=color.new(color.lime, 85), border_color=color.new(color.lime, 50))
array.push(demandBoxes, b_dem)
if array.size(demandBoxes) > maxZones
box.delete(array.shift(demandBoxes))
// Perpanjang Zona Secara Realtime
if array.size(supplyBoxes) > 0 and showSmartZones
for i = 0 to array.size(supplyBoxes) - 1
b = array.get(supplyBoxes, i)
// Perpanjang ke bar saat ini + 5 agar terlihat "hidup"
box.set_right(b, bar_index + 5)
if array.size(demandBoxes) > 0 and showSmartZones
for i = 0 to array.size(demandBoxes) - 1
b = array.get(demandBoxes, i)
// Perpanjang ke bar saat ini + 5 agar terlihat "hidup"
box.set_right(b, bar_index + 5)
// ====================================================================================================
// BAGIAN 2: FITUR TAMBAHAN (HSN GHOST CANDLES) - DI-INJECT DI SINI
// ====================================================================================================
// --- TIPE DATA KHUSUS (HSN) ---
type CandleHSN
float o
float c
float h
float l
int o_idx
int c_idx
int h_idx
int l_idx
box body
line wick_up
line wick_down
type ImbalanceHSN
box b
int idx
type CandleSettingsHSN
bool show
string htf
int max_display
type SettingsHSN
int max_sets
color bull_body
color bull_border
color bull_wick
color bear_body
color bear_border
color bear_wick
int offset
int buffer
int htf_buffer
int width
bool trace_show
string trace_anchor
bool label_show
color label_color
string label_size
bool htf_label_show
color htf_label_color
string htf_label_size
bool htf_timer_show
color htf_timer_color
string htf_timer_size
type CandleSetHSN
CandleHSN candles
ImbalanceHSN imbalances
CandleSettingsHSN settings
label tfName
label tfTimer
type HelperHSN
string name = "Helper"
// --- SETUP PENGATURAN HSN ---
SettingsHSN settings = SettingsHSN.new()
var CandleSettingsHSN SettingsHTF1 = CandleSettingsHSN.new()
var CandleSettingsHSN SettingsHTF2 = CandleSettingsHSN.new()
var CandleHSN candles_1 = array.new(0)
var CandleHSN candles_2 = array.new(0)
var CandleSetHSN htf1 = CandleSetHSN.new()
htf1.settings := SettingsHTF1
htf1.candles := candles_1
var CandleSetHSN htf2 = CandleSetHSN.new()
htf2.settings := SettingsHTF2
htf2.candles := candles_2
// --- INPUT KHUSUS HSN CANDLES (15 & 30 MENIT) ---
grp_hsn = "🔥 HSN HTF Candles (Upgrade)"
htf1.settings.show := input.bool(true, "Show HTF 1 (15 Menit)", group=grp_hsn, inline="h1")
htf_1 = input.timeframe("15", "", group=grp_hsn, inline="h1")
htf1.settings.htf := htf_1
htf1.settings.max_display := 4
htf2.settings.show := input.bool(true, "Show HTF 2 (30 Menit)", group=grp_hsn, inline="h2")
htf_2 = input.timeframe("30", "", group=grp_hsn, inline="h2")
htf2.settings.htf := htf_2
htf2.settings.max_display := 4
settings.max_sets := 2
settings.bull_body := color.new(color.green, 60)
settings.bear_body := color.new(color.red, 60)
settings.bull_border := color.new(color.green, 10)
settings.bear_border := color.new(color.red, 10)
settings.bull_wick := color.new(color.green, 10)
settings.bear_wick := color.new(color.red, 10)
// FIXED: Increased default offset from 10 to 25 to avoid overlap with Advisor Bubble
settings.offset := input.int(25, "Padding/Jarak Candle", group=grp_hsn)
settings.buffer := 1
settings.htf_buffer := 5
settings.width := input.int(1, "Lebar Candle", minval = 1, maxval = 4, group=grp_hsn)*2
settings.htf_label_show := true
settings.htf_label_color := color.gray
settings.htf_label_size := size.normal
// --- HELPER FUNCTIONS ---
HelperHSN helper = HelperHSN.new()
color color_transparent = #ffffff00
method ValidTimeframe(HelperHSN helper, string HTF) =>
helper.name := HTF
if timeframe.in_seconds(HTF) >= timeframe.in_seconds("D") and timeframe.in_seconds(HTF) > timeframe.in_seconds()
true
else
n1 = timeframe.in_seconds()
n2 = timeframe.in_seconds(HTF)
n3 = n1 % n2
(n1 < n2 and math.round(n2/n1) == n2/n1)
method HTFName(HelperHSN helper, string HTF) =>
helper.name := "HTFName"
formatted = HTF
seconds = timeframe.in_seconds(HTF)
if seconds < 60
formatted := str.tostring(seconds) + "s"
else if (seconds / 60) < 60
formatted := str.tostring((seconds/60)) + "m"
else if (seconds/60/60) < 24
formatted := str.tostring((seconds/60/60)) + "H"
formatted
method HTFEnabled(HelperHSN helper) =>
helper.name := "HTFEnabled"
int enabled =0
enabled += htf1.settings.show ? 1 : 0
enabled += htf2.settings.show ? 1 : 0
int last = math.min(enabled, settings.max_sets)
last
method CandleSetHigh(HelperHSN helper, CandleHSN candles, float h) =>
helper.name := "CandlesSetHigh"
float _h = h
if array.size(candles) > 0
for i = 0 to array.size(candles)-1
// FIX: Diganti dari c menjadi cItem
CandleHSN cItem = array.get(candles, i)
if cItem.h > _h
_h := cItem.h
_h
method CandlesHigh(HelperHSN helper, CandleHSN candles) =>
helper.name := "CandlesHigh"
h = 0.0
int cnt = 0
int last = helper.HTFEnabled()
if htf1.settings.show and helper.ValidTimeframe(htf1.settings.htf)
h := helper.CandleSetHigh(htf1.candles, h)
cnt += 1
if htf2.settings.show and helper.ValidTimeframe(htf2.settings.htf) and cnt < last
h := helper.CandleSetHigh(htf2.candles, h)
cnt +=1
if array.size(candles) > 0
for i = 0 to array.size(candles)-1
// FIX: Diganti dari c menjadi cItem
CandleHSN cItem = array.get(candles, i)
if cItem.h > h
h := cItem.h
h
method Reorder(CandleSetHSN candleSet, int offset) =>
size = candleSet.candles.size()
if size > 0
for i = size-1 to 0
CandleHSN candle = candleSet.candles.get(i)
t_buffer = offset + ((settings.width+settings.buffer)*(size-i-1))
box.set_left(candle.body, bar_index + t_buffer)
box.set_right(candle.body, bar_index + settings.width + t_buffer)
line.set_x1(candle.wick_up, bar_index+((settings.width)/2) + t_buffer)
line.set_x2(candle.wick_up, bar_index+((settings.width)/2) + t_buffer)
line.set_x1(candle.wick_down, bar_index+((settings.width)/2) + t_buffer)
line.set_x2(candle.wick_down, bar_index+((settings.width)/2) + t_buffer)
top = helper.CandlesHigh(candleSet.candles)
left = bar_index + offset + ((settings.width+settings.buffer)*(size-1))/2
if settings.htf_label_show
var label l = candleSet.tfName
string lbl = helper.HTFName(candleSet.settings.htf)
if not na(l)
label.set_xy(l, left, top)
else
l := label.new(left, top, lbl, color=color_transparent, textcolor = settings.htf_label_color, style=label.style_label_down, size = settings.htf_label_size)
candleSet
method Monitor(CandleSetHSN candleSet) =>
HTFBarTime = time(candleSet.settings.htf)
isNewHTFCandle = ta.change(HTFBarTime)
if isNewHTFCandle
CandleHSN candle = CandleHSN.new()
candle.o := open
candle.c := close
candle.h := high
candle.l := low
candle.o_idx := bar_index
candle.c_idx := bar_index
candle.h_idx := bar_index
candle.l_idx := bar_index
bull = candle.c > candle.o
candle.body := box.new(bar_index, math.max(candle.o, candle.c), bar_index+2, math.min(candle.o, candle.c), bull ? settings.bull_border : settings.bear_border, 1, bgcolor = bull ? settings.bull_body : settings.bear_body)
candle.wick_up := line.new(bar_index+1, candle.h, bar_index, math.max(candle.o, candle.c), color=bull ? settings.bull_wick : settings.bear_wick)
candle.wick_down := line.new(bar_index+1, math.min(candle.o, candle.c), bar_index, candle.l, color=bull ? settings.bull_wick : settings.bear_wick)
candleSet.candles.unshift(candle)
if candleSet.candles.size() > candleSet.settings.max_display
CandleHSN delCandle = array.pop(candleSet.candles)
box.delete(delCandle.body)
line.delete(delCandle.wick_up)
line.delete(delCandle.wick_down)
candleSet
method Update(CandleSetHSN candleSet, int offset) =>
if candleSet.candles.size() > 0
CandleHSN candle = candleSet.candles.first()
candle.h_idx := high > candle.h ? bar_index : candle.h_idx
candle.h := high > candle.h ? high : candle.h
candle.l_idx := low < candle.l ? bar_index : candle.l_idx
candle.l := low < candle.l ? low : candle.l
candle.c := close
candle.c_idx := bar_index
bull = candle.c > candle.o
box.set_top(candle.body, bull ? candle.c : candle.o)
box.set_bottom(candle.body, bull ? candle.o : candle.c)
box.set_bgcolor(candle.body, bull ? settings.bull_body : settings.bear_body)
box.set_border_color(candle.body, bull ? settings.bull_border : settings.bear_border)
line.set_color(candle.wick_up, bull ? settings.bull_wick : settings.bear_wick)
line.set_color(candle.wick_down, bull ? settings.bull_wick : settings.bear_wick)
line.set_y1(candle.wick_up, candle.h)
line.set_y2(candle.wick_up, math.max(candle.o, candle.c))
line.set_y1(candle.wick_down, candle.l)
line.set_y2(candle.wick_down, math.min(candle.o, candle.c))
if barstate.isrealtime or barstate.islast
candleSet.Reorder(offset)
candleSet
// --- EKSEKUSI HSN LOGIC ---
int cnt_hsn = 0
int last_hsn = helper.HTFEnabled()
int offset_hsn = settings.offset
if htf1.settings.show and helper.ValidTimeframe(htf1.settings.htf)
htf1.Monitor().Update(offset_hsn)
cnt_hsn +=1
offset_hsn += cnt_hsn > 0 ? (htf1.candles.size() * settings.width) + (htf1.candles.size() > 0 ? htf1.candles.size()-1 * settings.buffer : 0) + settings.htf_buffer : 0
if htf2.settings.show and helper.ValidTimeframe(htf2.settings.htf) and cnt_hsn < last_hsn
htf2.Monitor().Update(offset_hsn)
cnt_hsn+=1
offset_hsn += cnt_hsn > 0 ? (htf2.candles.size() * settings.width) + (htf2.candles.size() > 0 ? htf2.candles.size()-1 * settings.buffer : 0) + settings.htf_buffer : 0
Strong Support & Resistance Zones (4H)Below is a clean, strong Support & Resistance ZONE indicator with:
✅ Stronger / fewer levels (higher pivot strength)
✅ Zones instead of single lines
✅ Alerts when price enters zones
✅ Fixed Higher Timeframe = 4H
✅ Non-repainting (after confirmation)
used Chat GPT to make this.
KJ Sessions : Asia/London/US + OverlapKJ Sessions : Asia/London/US + Overlap.
times are set as per dubai time.
USDC/USDT PremiumUSDC/USDT Premium Index
Overview
This indicator tracks the premium or discount of USD Coin (USDC) relative to Tether (USDT) using data from Binance. It serves as a barometer for sentiment within the stablecoin market. A premium on USDC often suggests a flight to quality or higher demand for a stablecoin perceived as more transparent and regulated.
Key Features
•
Premium Calculation: The premium is calculated as (USDC/USDT Price - 1) * 100 to represent the deviation from parity in basis points. For example, a value of 0.1 means USDC is trading at a 0.1% premium to USDT (i.e., a price of 1.001).
•
Dynamic Coloring: The indicator's line color changes based on its position relative to a moving average (MA):
•
Green: The premium is currently above its moving average, suggesting bullish momentum for USDC.
•
Red: The premium is below its moving average, indicating bearish momentum.
•
Zero Line: A zero line is plotted to clearly distinguish between a premium (above zero) and a discount (below zero).
•
Customizable MA: You can adjust the moving average period and type (SMA, EMA, etc.) to fine-tune the indicator's sensitivity.
How to Use
1.
Gauge Stablecoin Sentiment: A rising premium (green line) can indicate that traders are favoring USDC over USDT, which might happen during times of market uncertainty or concerns about USDT's reserves.
2.
Identify Shifts in Momentum: Look for the color to flip from red to green as a sign that the USDC premium is gaining strength. A flip from green to red may signal a weakening trend.
3.
Spot Extremes: Extreme deviations from the zero line can signal market stress or significant capital flows between the two major stablecoins.
Interpretation
•
Green Line (Premium > MA): Suggests that the short-term trend for the USDC premium is positive and strengthening.
•
Red Line (Premium < MA): Suggests that the short-term trend is negative, with USDC's value declining relative to its recent average against USDT.
•
Above Zero Line: USDC is trading at a premium to USDT.
•
Below Zero Line: USDC is trading at a discount to USDT.
This tool provides a nuanced view of the stablecoin ecosystem, helping traders understand capital flows and risk appetite. It is most effective when used to complement a broader market analysis strategy.






















