ENTRY CONFIRMATION V2An indicator from candle man. Helps determine whether supply and demand zone are truly supply or demand.
Cari skrip untuk "entry"
Entry Percent: EssamThis Pine Script code is designed to perform the task of computing and showcasing the profit percentage, profit value, and the duration for which a specific asset is held, all in real-time. The script effectively leverages the built-in resources to provide a seamless and robust experience, as it presents the calculated figures in an easily readable format on the chart, without causing any lag or disruptions to the chart.
MA_Script- Entry Point : base on MA20, MA50, MA100, MA200.
- Exit Point : base on stop loss, MA and trailing stop.
sa-strategy with HTF-TSLEntry- based on HA close above HMA confirmation done with ST and HTF ATR
Exit- based on close below ATR which works as trailing SL
[MV] %B with SMA + Volume Based Colored Bars
Entry Signal when %B Crosses with SMA and this is more meaningful if it supports colored bars.
Black Bar when prices go down and volume is bigger than 150% of its average, that indicates us price action is supported by a strong bearish volume
Blue Bar when prices go up and volume bigger than 150% of its average, that indicates us price action is supported by a strong bullish volume
VBC author @KIVANCfr3762
FX Sniper: T3-CCI Strategy - With 100 IndicatorsEntry signal when moving above -100, sell signal when going below 100
Amazing Crossover SystemEntry Rules
BUY when the 5 EMA crosses above the 10 EMA from underneath and the RSI crosses above the 50.0 mark from the bottom.
SELL when the 5 EMA crosses below the 10 EMA from the top and the RSI crosses below the 50.0 mark from the top.
Make sure that the RSI did cross 50.0 from the top or bottom and not just ranging tightly around the level.
How to setup Alert:
1) Add the Amazing Crossover System to your chart via Indicators
2) Find your currency pair
3) Set the timeframe on the chart to 1 hour
4) Press 'Alt + A' (create alert shortcut)
5) Set the following criteria for the alert:
Condition = 'Amazing Crossover System', Plot, ' BUY Signal'
The rest of the alert can be customized to your preferences
5) Repeat steps 1 - 4, but set the Condition = 'Amazing Crossover System', Plot, ' SELL Signal'
Volume Profile DeltaMap [MHA Finverse]Volume Profile DeltaMap with Session Analysis
SHORT DESCRIPTION (for listing)
Advanced Volume Profile indicator with Delta Analysis, Value Area, Volume Nodes, Imbalance Zones, and Multi-Session Profiles. Professional tool for institutional-style volume analysis and market structure understanding.
---
DETAILED DESCRIPTION
📊 OVERVIEW
The Volume Profile DeltaMap is a comprehensive institutional-grade indicator that visualizes volume distribution across price levels, revealing where the most significant trading activity occurred. Unlike traditional indicators that plot data over time, Volume Profile analyzes price levels to identify key support/resistance zones, equilibrium areas, and buyer/seller dominance.
This indicator combines multiple advanced features:
- Volume Profile Analysis with customizable bins
- Delta Heat Map showing buyer vs seller pressure
- Value Area (VAH/VAL) calculations
- High/Low Volume Node Detection
- Imbalance Zone Identification
- Multi-Session Profile Separation (Tokyo, London, NY, Sydney)
- Point of Control (POC) highlighting
---
🎯 KEY FEATURES
1. Volume Profile Core
- Divides price range into customizable bins (10-100 levels)
- Accumulates volume at each price level over a lookback period
- Displays volume distribution horizontally on the chart
- Configurable lookback period (default: 200 bars)
2. Delta Analysis & Heat Map
- Delta (Δ) : Measures the difference between buying and selling pressure
- Color-coded visualization :
- Green/Teal = Buyer dominance
- Red/Pink = Seller dominance
- Heat map intensity : Shows volume concentration with gradient colors
- Percentage labels : Displays exact buyer/seller ratios at each level
3. Point of Control (POC)
- Automatically identifies the price level with maximum volume
- Marked with cyan border and volume label
- Acts as a strong magnetic level where price tends to return
- Often serves as major support/resistance
4. Value Area (VAH/VAL)
- Value Area : Price range containing 70% of total volume (configurable 50-90%)
- VAH (Value Area High) : Upper boundary - resistance level
- VAL (Value Area Low) : Lower boundary - support level
- Displayed with dashed lines and labels
- Represents fair value zone where institutional traders are most active
5. Volume Nodes
- HVN (High Volume Nodes) : Areas with ≥80% of maximum volume
- Highlighted in yellow/amber
- Strong support/resistance zones
- Price tends to consolidate here
- LVN (Low Volume Nodes) : Areas with ≤30% of maximum volume
- Highlighted in orange
- Low liquidity gaps
- Price moves quickly through these zones
- Potential breakout areas
6. Imbalance Zones
- Identifies areas with extreme directional bias (≥70% threshold)
- Buy Imbalance : Green overlay - exhaustion of buying pressure
- Sell Imbalance : Red overlay - exhaustion of selling pressure
- Indicates potential reversal or continuation zones
7. Session-Based Analysis
- Session Background Overlay : Color-codes current trading session
- Separate Session Profiles : Creates individual volume profiles for:
- 🇯🇵 Tokyo Session (00:00-09:00)
- 🇬🇧 London Session (07:00-16:00)
- 🇺🇸 New York Session (13:00-22:00)
- 🇦🇺 Sydney Session (21:00-06:00)
- Compare volume patterns across different market sessions
- Identify session-specific support/resistance levels
---
⚙️ CONFIGURATION SETTINGS
Basic Settings
- LookBack : Number of bars to analyze (50-500 recommended)
- Bins : Number of price levels (10-100, default: 30)
- Horizontal Offset : Adjust profile position on chart
#### Features Toggle
- Delta Heat Map
- Delta Labels
- Volume Bars (Buy/Sell split)
- POC Line
- Custom colors for positive/negative volume
Advanced Features
- Value Area calculation with adjustable percentage
- Volume Nodes (HVN/LVN) with custom thresholds
- Imbalance Zones with adjustable sensitivity
- Session backgrounds and separate profiles
- Profile spacing for multi-session view
---
📈 HOW TO USE THIS INDICATOR
Installation & Setup
1. Add to Chart :
- Search for "Volume Profile DeltaMap"
- Click "Add to favorites" ⭐
- Apply to your chart
2. Recommended Timeframes :
- Scalping : 1-5 minute charts
- Day Trading : 5-15 minute charts
- Swing Trading : 1-4 hour charts
- Position Trading : Daily charts
3. Initial Settings :
- Start with default settings
- For intraday: Set LookBack to 200-400 bars
- For higher timeframes: Use 100-200 bars
4. Enable Session Profiles (Optional):
- Go to Settings → Advanced Features
- Enable "Separate Profiles Per Session"
- Adjust "Profile Spacing" for better visibility
---
🔍 READING THE INDICATOR
Understanding the Display
Main Profile Elements:
- Horizontal bars : Length represents volume at that price
- Color gradient : Shows delta (buyer vs seller dominance)
- Bright cyan line : Point of Control (POC) - highest volume
- Green dashed line : Value Area High (VAH)
- Red dashed line : Value Area Low (VAL)
- Yellow highlights : High Volume Nodes (HVN)
- Orange highlights : Low Volume Nodes (LVN)
Volume Bars (if enabled):
- Top half (Red) : Selling volume percentage
- Bottom half (Teal) : Buying volume percentage
Delta Labels:
- Shows Δ percentage
- Positive = More buyers
- Negative = More sellers
---
📊 MARKET ANALYSIS & TRADING STRATEGIES
1. Support & Resistance Trading
POC as Key Level:
- Price tends to return to POC (magnetic effect)
- Strategy :
- When price is above POC → Look for pullbacks to POC for long entries
- When price is below POC → Look for rallies to POC for short entries
- POC acts as dynamic support/resistance
Value Area Trading:
- Inside Value Area (between VAH & VAL):
- Market is in balance/equilibrium
- Range-bound trading strategies
- Look for mean reversion
- Outside Value Area :
- Price accepted above VAH = Bullish breakout
- Price accepted below VAL = Bearish breakdown
- Trend-following strategies
Example Setup:
Price above VAH + Strong buying delta = Bullish trend
→ Wait for pullback to VAH
→ Enter long with stop below VAH
→ Target: Next HVN or previous session high
2. Volume Node Trading
High Volume Nodes (HVN):
- Characteristics : Strong support/resistance, consolidation zones
- Trading Strategy :
- Price approaching HVN from above → Potential support
- Price approaching HVN from below → Potential resistance
- Breakout from HVN → Strong momentum move
- Setup : Place limit orders at HVN boundaries
Low Volume Nodes (LVN):
- Characteristics : Low liquidity, fast price movement
- Trading Strategy :
- Price in LVN = Don't chase, wait for next HVN
- LVN breakout = Rapid moves, use wider stops
- Price rejection from LVN = Quick return to HVN
- Setup : Avoid placing stops in LVN zones
Example:
Price consolidating at HVN (yellow) near $50,000
→ Breakout above with volume
→ Fast move through LVN (orange) gap
→ Next target: Upper HVN at $51,500
3. Delta Analysis for Entry Timing
Strong Buying Delta (Green zones):
- Δ > +20% = Buyers in control
- Bullish Signal : Accumulation zone
- Strategy : Look for long entries on pullbacks
- Confirmation : Rising price + positive delta
Strong Selling Delta (Red zones):
- Δ < -20% = Sellers in control
- Bearish Signal : Distribution zone
- Strategy : Look for short entries on rallies
- Confirmation : Falling price + negative delta
Delta Divergence (Advanced):
- Bullish Divergence : Price making lower lows, but delta improving (less negative)
- Indicates selling pressure weakening
- Potential reversal signal
- Bearish Divergence : Price making higher highs, but delta weakening (less positive)
- Indicates buying pressure exhausting
- Potential reversal signal
4. Imbalance Zone Trading
Buy Imbalance (Bright Green):
- 70%+ buying pressure
- Interpretation :
- Potential exhaustion of buyers
- Smart money distribution
- Strategy :
- Look for reversal signals (bearish candles, resistance)
- Take profits on long positions
- Consider short entries with confirmation
Sell Imbalance (Bright Red):
- 70%+ selling pressure
- Interpretation :
- Potential exhaustion of sellers
- Smart money accumulation
- Strategy :
- Look for reversal signals (bullish candles, support)
- Take profits on short positions
- Consider long entries with confirmation
Example:
```
Price at VAH with 80% sell imbalance
→ Selling exhaustion likely
→ Wait for bullish reversal candle
→ Enter long with stop below VAL
```
5. Multi-Session Analysis
When "Separate Profiles Per Session" is enabled:
Session-Specific Levels:
- Each session creates its own POC and value area
- Compare sessions to identify:
- Where institutions accumulated/distributed
- Which levels each session respected
- Unfinished business from previous sessions
Trading Strategies:
A. Session POC Confluence
London POC: $49,500
NY POC: $49,550
→ Strong support zone at $49,500-$49,550
→ High probability long setup on pullback
B. Value Area Overlap
London VAH: $50,000
NY VAL: $49,800
→ Overlap creates strong consolidation zone
→ Breakout strategy: Enter on break above $50,000
C. Unfinished Business
London session rejected $51,000 (sell imbalance)
NY session hasn't tested this level yet
→ Watch for NY session to revisit $51,000
→ Potential reversal zone
D. Session Handoff
Tokyo session: Sideways, low volume
London session: Strong buying delta, break above VAH
NY session: Continuation or reversal?
→ Monitor NY open for direction confirmation
6. Market Profile Analysis
Profile Shape Interpretation:
A. P-Shape (Peak at Top)
- High volume at top of range
- Interpretation : Distribution, potential reversal down
- Strategy : Look for shorts at resistance
B. b-Shape (Peak at Bottom)
- High volume at bottom of range
- Interpretation : Accumulation, potential reversal up
- Strategy : Look for longs at support
C. D-Shape (Peak in Middle)
- Balanced profile, POC in center
- Interpretation : Equilibrium, neutral market
- Strategy : Range trading between VAH/VAL
D. Thin Profile (LVN Gap)
- Low volume throughout
- Interpretation : Trending market, little acceptance
- Strategy : Trend following, avoid counter-trend trades
---
🎯 COMPLETE TRADING WORKFLOW
Step 1: Market Structure Analysis
1. Identify overall profile shape
2. Locate POC, VAH, VAL
3. Note HVN and LVN zones
4. Check current price position relative to value area
Step 2: Delta & Imbalance Check
1. Review delta distribution (where are buyers/sellers?)
2. Identify imbalance zones
3. Look for delta divergences
4. Note any exhaustion signals
Step 3: Session Analysis (if enabled)
1. Compare current session vs previous sessions
2. Identify key levels each session created
3. Look for level confluences or gaps
4. Note unfinished business
Step 4: Trade Setup
1. Define your bias (long/short/neutral)
2. Identify entry zone (HVN, VAH/VAL, POC)
3. Set stop loss (below/above key level or opposite LVN)
4. Set target (next HVN, VAH/VAL, or session high/low)
Step 5: Execution & Management
1. Wait for price to reach entry zone
2. Confirm with price action (candlestick patterns)
3. Enter trade with defined risk
4. Move stop to breakeven at first target
5. Trail stop or take profits at resistance/support
---
📋 EXAMPLE TRADE SCENARIOS
Scenario 1: Long Setup at VAL
Setup:
- Price pulled back to VAL ($49,200)
- VAL coincides with HVN (yellow zone)
- Delta showing +15% buying (green)
- London session POC also at $49,200
Entry:
- Buy at $49,200 (VAL/HVN confluence)
- Stop loss: $49,000 (below VAL, in LVN)
- Target 1: $49,800 (POC)
- Target 2: $50,200 (VAH)
Management:
- Move stop to breakeven when Target 1 reached
- Trail stop below recent swing lows
- Exit 50% at VAH, let remainder run
Risk:Reward : 200 points risk / 1000 points potential = 1:5 R:R
---
Scenario 2: Short Setup at Sell Imbalance
Setup:
- Price at VAH ($50,500)
- Sell imbalance zone (85% sellers, bright red)
- Bearish divergence (higher high, weaker delta)
- Previous session rejected this level
Entry:
- Short at $50,500 after bearish engulfing candle
- Stop loss: $50,750 (above VAH + imbalance zone)
- Target 1: $50,000 (POC)
- Target 2: $49,600 (VAL)
Management:
- Take 50% profit at POC
- Trail stop above recent swing highs
- Exit remainder at VAL or if delta turns positive
Risk:Reward : 250 points risk / 900 points potential = 1:3.6 R:R
---
Scenario 3: Range Trading Inside Value Area
Setup:
- Market consolidating between VAH ($50,200) and VAL ($49,600)
- POC at $49,900
- Multiple HVNs creating range boundaries
- Delta oscillating between +/-10%
Long Trade:
- Entry: $49,650 (near VAL)
- Stop: $49,500 (below VAL)
- Target: $50,150 (near VAH)
- Risk:Reward: 150/500 = 1:3.3
Short Trade:
- Entry: $50,150 (near VAH)
- Stop: $50,300 (above VAH)
- Target: $49,700 (near VAL)
- Risk:Reward: 150/450 = 1:3
Management:
- Reduce position size in range trading
- Take profits at opposite boundary
- Exit if breakout occurs (stop hunt possible)
---
Scenario 4: Session Breakout Trade
Setup:
- London session: Range-bound $49,500-$50,000
- London VAH at $50,000 (resistance)
- NY session opens: Strong buying delta (+35%)
- Price breaks above $50,000 with momentum
Entry:
- Buy on breakout above $50,000
- Or buy on retest of $50,000 (old resistance = new support)
- Stop loss: $49,700 (below breakout level + buffer)
- Target 1: $50,500 (next HVN from previous day)
- Target 2: $51,000 (measured move)
Management:
- Enter 50% position on breakout
- Add remaining 50% on successful retest
- Move stop to breakeven when price +$300
- Trail stop below 20 EMA or recent higher lows
Risk:Reward : 300 points risk / 1000 points potential = 1:3.3 R:R
---
⚠️ BEST PRACTICES & RISK MANAGEMENT
Do's:
✅ Use on liquid markets (major crypto, forex, indices)
✅ Combine with price action and candlestick patterns
✅ Wait for confirmation before entering trades
✅ Always use stop losses based on volume structure
✅ Take partial profits at key levels (HVN, VAH/VAL)
✅ Adjust lookback period based on timeframe
✅ Use higher timeframe profiles for context
✅ Compare current profile with previous day/session
✅ Consider volume trends (increasing/decreasing)
✅ Backtest strategies on your specific market
Don'ts:
❌ Don't trade solely based on this indicator
❌ Don't ignore price action and market context
❌ Don't place stops in LVN zones (prone to spikes)
❌ Don't chase price in low volume areas
❌ Don't overtrade - wait for quality setups
❌ Don't use on extremely low volume/illiquid assets
❌ Don't forget to adjust for different market conditions
❌ Don't ignore fundamental news events
❌ Don't use excessive leverage even with good setups
❌ Don't force trades - patience is key
Risk Management Rules:
1. Risk per trade : Never risk more than 1-2% of capital
2. Position sizing : Based on stop loss distance
3. Stop placement : Always below/above key volume levels
4. Profit taking : Scale out at multiple targets
5. Drawdown limits : Stop trading after 3 consecutive losses
6. Win rate expectation : 50-60% is realistic
7. Risk:Reward minimum : Aim for 1:2 or better
8. Correlation : Don't take correlated positions
---
🔧 TROUBLESHOOTING & OPTIMIZATION
If profiles look too compressed:
- Increase "Bins" to 40-50
- Reduce "LookBack" period
- Adjust "Horizontal Offset"
If too cluttered:
- Disable "Delta Labels"
- Disable "Volume Bars"
- Keep only POC and Value Area
- Use "Session Background Overlay" instead of separate profiles
For scalping (1-5 min):
- LookBack: 300-500 bars
- Bins: 20-30
- Enable separate session profiles
- Focus on imbalance zones
For swing trading (1H-4H):
- LookBack: 100-200 bars
- Bins: 25-35
- Focus on VAH/VAL and HVN
- Disable session features
For position trading (Daily):
- LookBack: 50-100 bars
- Bins: 30-40
- Focus on weekly/monthly POC
- Compare with previous week profiles
---
📚 ADVANCED CONCEPTS
1. Composite Profiles
- Build profiles across multiple days
- Increase LookBack to 500+ bars on 15-min chart
- Identifies major support/resistance from weeks of data
- Use for swing trading key levels
2. Profile Migration
- Track how POC moves day over day
- Uptrend : POC migrating higher
- Downtrend : POC migrating lower
- Range : POC oscillating in same area
3. Failed Auctions
- Price briefly leaves value area but quickly returns
- Failed auction high : Bearish signal
- Failed auction low : Bullish signal
- Indicates rejection of new price levels
4. Overnight Inventory
- Compare previous day's close to value area
- Close above VAH : Bullish bias for next day
- Close below VAL : Bearish bias for next day
- Close in value area : Neutral, range expected
5. Volume Delta Momentum
- Track cumulative delta across time
- Rising cumulative delta + rising price : Strong trend
- Falling cumulative delta + rising price : Weak/topping
- Rising cumulative delta + falling price : Potential reversal
---
📊 INTEGRATION WITH OTHER INDICATORS
Complementary Indicators:
1. Moving Averages (20/50/200 EMA)
- Use with POC and VAH/VAL
- Confluence with EMAs = stronger levels
2. RSI/Stochastic
- Overbought at resistance (VAH/HVN) = strong short
- Oversold at support (VAL/HVN) = strong long
3. VWAP
- POC often aligns with VWAP
- Deviation from VWAP + Volume Profile = trade setup
4. Order Flow/Footprint Charts
- Confirm delta analysis
- Detailed buyer/seller pressure
5. Market Profile (TPO)
- Similar concept, different visualization
- Use together for complete picture
Example Multi-Indicator Setup:
Price at VAL ✓
+ 200 EMA support ✓
+ RSI oversold (30) ✓
+ Positive delta zone ✓
+ Bullish engulfing candle ✓
= High probability long entry
---
🎓 LEARNING CURVE & PRACTICE
Week 1-2: Understanding
- Study each feature individually
- Identify POC, VAH, VAL on historical charts
- Note HVN and LVN patterns
- Observe how price reacts to these levels
Week 3-4: Pattern Recognition
- Track different profile shapes
- Identify session-specific patterns
- Note delta distribution patterns
- Document imbalance zone outcomes
Week 5-6: Paper Trading
- Take simulated trades based on setups
- Record entry/exit reasoning
- Track win rate and R:R
- Refine strategy based on results
Week 7-8: Live Trading (Small Size)
- Start with minimal position sizes
- Focus on execution and discipline
- Build confidence with real money
- Gradually increase size as proficiency grows
Ongoing:
- Review trades weekly
- Keep trading journal
- Adapt to changing market conditions
- Continuously refine strategy
---
💡 KEY TAKEAWAYS
1. Volume Profile shows WHERE the market is most active (POC, HVN)
2. Delta shows WHO is in control (buyers vs sellers)
3. Value Area shows FAIR VALUE (equilibrium zone)
4. Volume Nodes show STRUCTURE (support/resistance)
5. Imbalances show EXHAUSTION (potential reversals)
6. Sessions show PARTICIPATION (institutional activity)
The indicator is a MAP, not a SIGNAL:
- It shows you the battlefield terrain
- You still need to decide when/how to engage
- Combine with price action for best results
- Risk management is always paramount
---
⚖️ DISCLAIMER
This indicator is for educational and informational purposes only.
- Not financial advice
- Past performance does not guarantee future results
- Trading involves substantial risk of loss
- Only trade with capital you can afford to lose
- Always do your own research and due diligence
- Test strategies thoroughly before risking real money
- Consider consulting a licensed financial advisor
The creator is not responsible for any trading losses incurred while using this indicator.
---
Happy Trading! 📈🚀
MACD Forecast Colorful [DiFlip]MACD Forecast Colorful
The Future of Predictive MACD — is one of the most advanced and customizable MACD indicators ever published on TradingView. Built on the classic MACD foundation, this upgraded version integrates statistical forecasting through linear regression to anticipate future movements — not just react to the past.
With a total of 22 fully configurable long and short entry conditions, visual enhancements, and full automation support, this indicator is designed for serious traders seeking an analytical edge.
⯁ Real-Time MACD Forecasting
For the first time, a public MACD script combines the classic structure of MACD with predictive analytics powered by linear regression. Instead of simply responding to current values, this tool projects the MACD line, signal line, and histogram n bars into the future, allowing you to trade with foresight rather than hindsight.
⯁ Fully Customizable
This indicator is built for flexibility. It includes 22 entry conditions, all of which are fully configurable. Each condition can be turned on/off, chained using AND/OR logic, and adapted to your trading model.
Whether you're building a rules-based quant system, automating alerts, or refining discretionary signals, MACD Forecast Colorful gives you full control over how signals are generated, displayed, and triggered.
⯁ With MACD Forecast Colorful, you can:
• Detect MACD crossovers before they happen.
• Anticipate trend reversals with greater precision.
• React earlier than traditional indicators.
• Gain a powerful edge in both discretionary and automated strategies.
• This isn’t just smarter MACD — it’s predictive momentum intelligence.
⯁ Scientifically Powered by Linear Regression
MACD Forecast Colorful is the first public MACD indicator to apply least-squares predictive modeling to MACD behavior — effectively introducing machine learning logic into a time-tested tool.
It uses statistical regression to analyze historical behavior of the MACD and project future trajectories. The result is a forward-shifted MACD forecast that can detect upcoming crossovers and divergences before they appear on the chart.
⯁ Linear Regression: Technical Foundation
Linear regression is a statistical method that models the relationship between a dependent variable (y) and one or more independent variables (x). The basic formula for simple linear regression is:
y = β₀ + β₁x + ε
Where:
y = predicted variable (e.g., future MACD value)
x = independent variable (e.g., bar index)
β₀ = intercept
β₁ = slope
ε = random error (residual)
The regression model calculates β₀ and β₁ using the least squares method, minimizing the sum of squared prediction errors to produce the best-fit line through historical values. This line is then extended forward, generating a forecast based on recent price momentum.
⯁ Least Squares Estimation
The regression coefficients are computed with the following formulas:
β₁ = Σ((xᵢ - x̄)(yᵢ - ȳ)) / Σ((xᵢ - x̄)²)
β₀ = ȳ - β₁x̄
Where:
Σ denotes summation; x̄ and ȳ are the means of x and y; and i ranges from 1 to n (number of observations). These equations produce the best linear unbiased estimator under the Gauss–Markov assumptions — constant variance (homoscedasticity) and a linear relationship between variables.
⯁ Regression in Machine Learning
Linear regression is a foundational model in supervised learning. Its ability to provide precise, explainable, and fast forecasts makes it critical in AI systems and quantitative analysis.
Applying linear regression to MACD forecasting is the equivalent of injecting artificial intelligence into one of the most widely used momentum tools in trading.
⯁ Visual Interpretation
Picture the MACD values over time like this:
Time →
MACD →
A regression line is fitted to recent MACD values, then projected forward n periods. The result is a predictive trajectory that can cross over the real MACD or signal line — offering an early-warning system for trend shifts and momentum changes.
The indicator plots both current MACD and forecasted MACD, allowing you to visually compare short-term future behavior against historical movement.
⯁ Scientific Concepts Used
Linear Regression: models the relationship between variables using a straight line.
Least Squares Method: minimizes squared prediction errors for best-fit.
Time-Series Forecasting: projects future data based on past patterns.
Supervised Learning: predictive modeling using labeled inputs.
Statistical Smoothing: filters noise to highlight trends.
⯁ Why This Indicator Is Revolutionary
First open-source MACD with real-time predictive modeling.
Scientifically grounded with linear regression logic.
Automatable through TradingView alerts and bots.
Smart signal generation using forecasted crossovers.
Highly customizable with 22 buy/sell conditions.
Enhanced visuals with background (bgcolor) and area fill (fill) support.
This isn’t just an update — it’s the next evolution of MACD forecasting.
⯁ Example of simple linear regression with one independent variable
This example demonstrates how a basic linear regression works when there is only one independent variable influencing the dependent variable. This type of model is used to identify a direct relationship between two variables.
⯁ In linear regression, observations (red) are considered the result of random deviations (green) from an underlying relationship (blue) between a dependent variable (y) and an independent variable (x)
This concept illustrates that sampled data points rarely align perfectly with the true trend line. Instead, each observed point represents the combination of the true underlying relationship and a random error component.
⯁ Visualizing heteroscedasticity in a scatterplot with 100 random fitted values using Matlab
Heteroscedasticity occurs when the variance of the errors is not constant across the range of fitted values. This visualization highlights how the spread of data can change unpredictably, which is an important factor in evaluating the validity of regression models.
⯁ The datasets in Anscombe’s quartet were designed to have nearly the same linear regression line (as well as nearly identical means, standard deviations, and correlations) but look very different when plotted
This classic example shows that summary statistics alone can be misleading. Even with identical numerical metrics, the datasets display completely different patterns, emphasizing the importance of visual inspection when interpreting a model.
⯁ Result of fitting a set of data points with a quadratic function
This example illustrates how a second-degree polynomial model can better fit certain datasets that do not follow a linear trend. The resulting curve reflects the true shape of the data more accurately than a straight line.
⯁ What is the MACD?
The Moving Average Convergence Divergence (MACD) is a technical analysis indicator developed by Gerald Appel. It measures the relationship between two moving averages of a security’s price to identify changes in momentum, direction, and strength of a trend. The MACD is composed of three components: the MACD line, the signal line, and the histogram.
⯁ How to use the MACD?
The MACD is calculated by subtracting the 26-period Exponential Moving Average (EMA) from the 12-period EMA. A 9-period EMA of the MACD line, called the signal line, is then plotted on top of the MACD line. The MACD histogram represents the difference between the MACD line and the signal line.
Here are the primary signals generated by the MACD:
• Bullish Crossover: When the MACD line crosses above the signal line, indicating a potential buy signal.
• Bearish Crossover: When the MACD line crosses below the signal line, indicating a potential sell signal.
• Divergence: When the price of the security diverges from the MACD, suggesting a potential reversal.
• Overbought/Oversold Conditions: Indicated by the MACD line moving far away from the signal line, though this is less common than in oscillators like the RSI.
⯁ How to use MACD forecast?
The MACD Forecast is built on the same foundation as the classic MACD, but with predictive capabilities.
Step 1 — Spot Predicted Crossovers:
Watch for forecasted bullish or bearish crossovers. These signals anticipate when the MACD line will cross the signal line in the future, letting you prepare trades before the move.
Step 2 — Confirm with Histogram Projection:
Use the projected histogram to validate momentum direction. A rising histogram signals strengthening bullish momentum, while a falling projection points to weakening or bearish conditions.
Step 3 — Combine with Multi-Timeframe Analysis:
Use forecasts across multiple timeframes to confirm signal strength (e.g., a 1h forecast aligned with a 4h forecast).
Step 4 — Set Entry Conditions & Automation:
Customize your buy/sell rules with the 20 forecast-based conditions and enable automation for bots or alerts.
Step 5 — Trade Ahead of the Market:
By preparing for future momentum shifts instead of reacting to the past, you’ll always stay one step ahead of lagging traders.
📈 BUY
🍟 Signal Validity: The signal will remain valid for X bars.
🍟 Signal Sequence: Configurable as AND or OR.
🍟 MACD > Signal Smoothing
🍟 MACD < Signal Smoothing
🍟 Histogram > 0
🍟 Histogram < 0
🍟 Histogram Positive
🍟 Histogram Negative
🍟 MACD > 0
🍟 MACD < 0
🍟 Signal > 0
🍟 Signal < 0
🍟 MACD > Histogram
🍟 MACD < Histogram
🍟 Signal > Histogram
🍟 Signal < Histogram
🍟 MACD (Crossover) Signal
🍟 MACD (Crossunder) Signal
🍟 MACD (Crossover) 0
🍟 MACD (Crossunder) 0
🍟 Signal (Crossover) 0
🍟 Signal (Crossunder) 0
🔮 MACD (Crossover) Signal Forecast
🔮 MACD (Crossunder) Signal Forecast
📉 SELL
🍟 Signal Validity: The signal will remain valid for X bars.
🍟 Signal Sequence: Configurable as AND or OR.
🍟 MACD > Signal Smoothing
🍟 MACD < Signal Smoothing
🍟 Histogram > 0
🍟 Histogram < 0
🍟 Histogram Positive
🍟 Histogram Negative
🍟 MACD > 0
🍟 MACD < 0
🍟 Signal > 0
🍟 Signal < 0
🍟 MACD > Histogram
🍟 MACD < Histogram
🍟 Signal > Histogram
🍟 Signal < Histogram
🍟 MACD (Crossover) Signal
🍟 MACD (Crossunder) Signal
🍟 MACD (Crossover) 0
🍟 MACD (Crossunder) 0
🍟 Signal (Crossover) 0
🍟 Signal (Crossunder) 0
🔮 MACD (Crossover) Signal Forecast
🔮 MACD (Crossunder) Signal Forecast
🤖 Automation
All BUY and SELL conditions can be automated using TradingView alerts. Every configurable condition can trigger alerts suitable for fully automated or semi-automated strategies.
⯁ Unique Features
Linear Regression: (Forecast)
Signal Validity: The signal will remain valid for X bars
Signal Sequence: Configurable as AND/OR
Table of Conditions: BUY/SELL
Conditions Label: BUY/SELL
Plot Labels in the graph above: BUY/SELL
Automate & Monitor Signals/Alerts: BUY/SELL
Background Colors: "bgcolor"
Background Colors: "fill"
Linear Regression (Forecast)
Signal Validity: The signal will remain valid for X bars
Signal Sequence: Configurable as AND/OR
Table of Conditions: BUY/SELL
Conditions Label: BUY/SELL
Plot Labels in the graph above: BUY/SELL
Automate & Monitor Signals/Alerts: BUY/SELL
Background Colors: "bgcolor"
Background Colors: "fill"
PinkSlips Sauce IndicatorChecklist v4PinkSlips’ personal checklist assistant for catching clean trend moves.
It stacks EMAs (20/50/200), checks RSI strength, filters chop with ATR, then prints a simple YES/NO checklist so you know when the sauce is actually there.
What it does
EMA trend filter (bullish / bearish structure)
RSI confirmation for high-probability longs & shorts
ATR chop filter so you avoid dead zones
On-chart checklist box: trend up/down, ATR OK, long/short ready, last signal
Optional LONG/SHORT labels on the candles for execution
Use this as your pre–entry checklist so you stop forcing trades and only take the clean PinkSlips setups.
PST Bread Checklist v4Uses 50/200 EMA for higher-timeframe trend
Uses RSI zones + cross for entry
Adds volatility filter (ATR vs its own average)
Optional session filter (RTH 09:30–16:00)
Has a cooldown so you don’t get 10 labels in a row
Shows a checklist box + last signal
Third eye • StrategyThird eye • Strategy – User Guide
1. Idea & Concept
Third eye • Strategy combines three things into one system:
Ichimoku Cloud – to define market regime and support/resistance.
Moving Average (trend filter) – to trade only in the dominant direction.
CCI (Commodity Channel Index) – to generate precise entry signals on momentum breakouts.
The script is a strategy, not an indicator: it can backtest entries, exits, SL, TP and BreakEven logic automatically.
2. Indicators Used
2.1 Ichimoku
Standard Ichimoku settings (by default 9/26/52/26) are used:
Conversion Line (Tenkan-sen)
Base Line (Kijun-sen)
Leading Span A & B (Kumo Cloud)
Lagging Span is calculated but hidden from the chart (for visual simplicity).
From the cloud we derive:
kumoTop – top of the cloud under current price.
kumoBottom – bottom of the cloud under current price.
Flags:
is_above_kumo – price above the cloud.
is_below_kumo – price below the cloud.
is_in_kumo – price inside the cloud.
These conditions are used as trend / regime filters and for stop-loss & trailing stops.
2.2 Moving Average
You can optionally display and use a trend MA:
Types: SMA, EMA, DEMA, WMA
Length: configurable (default 200)
Source: default close
Filter idea:
If MA Direction Filter is ON:
When Close > MA → strategy allows only Long signals.
When Close < MA → strategy allows only Short signals.
The MA is plotted on the chart (if enabled).
2.3 CCI & Panel
The CCI (Commodity Channel Index) is used for entry timing:
CCI length and source are configurable (default length 20, source hlc3).
Two thresholds:
CCI Upper Threshold (Long) – default +100
CCI Lower Threshold (Short) – default –100
Signals:
Long signal:
CCI crosses up through the upper threshold
cci_val < upper_threshold and cci_val > upper_threshold
Short signal:
CCI crosses down through the lower threshold
cci_val > lower_threshold and cci_val < lower_threshold
There is a panel (table) in the bottom-right corner:
Shows current CCI value.
Shows filter status as colored dots:
Green = filter enabled and passed.
Red = filter enabled and blocking trades.
Gray = filter is disabled.
Filters shown in the panel:
Ichimoku Cloud filter (Long/Short)
Ichimoku Lines filter (Conversion/Base vs Cloud)
MA Direction filter
3. Filters & Trade Direction
All filters can be turned ON/OFF independently.
3.1 Ichimoku Cloud Filter
Purpose: trade only when price is clearly above or below the Kumo.
Long Cloud Filter (Use Ichimoku Cloud Filter) – when enabled:
Long trades only if close > cloud top.
Short Cloud Filter – when enabled:
Short trades only if close < cloud bottom.
If the cloud filter is disabled, this condition is ignored.
3.2 Ichimoku Lines Above/Below Cloud
Purpose: stronger trend confirmation: Ichimoku lines should also be on the “correct” side of the cloud.
Long Lines Filter:
Long allowed only if Conversion Line and Base Line are both above the cloud.
Short Lines Filter:
Short allowed only if both lines are below the cloud.
If this filter is OFF, the conditions are not checked.
3.3 MA Direction Filter
As described above:
When ON:
Close > MA → only Longs.
Close < MA → only Shorts.
4. Anti-Re-Entry Logic (Cloud Touch Reset)
The strategy uses internal flags to avoid continuous re-entries in the same direction without a reset.
Two flags:
allowLong
allowShort
After a Long entry, allowLong is set to false, allowShort to true.
After a Short entry, allowShort is set to false, allowLong to true.
Flags are reset when price touches the Kumo:
If Low goes into the cloud → allowLong = true
If High goes into the cloud → allowShort = true
If Close is inside the cloud → both allowLong and allowShort are set to true
There is a key option:
Wait Position Close Before Flag Reset
If ON: cloud touch will reset flags only when there is no open position.
If OFF: flags can be reset even while a trade is open.
This gives a kind of regime-based re-entry control: after a trend leg, you wait for a “cloud interaction” to allow new signals.
5. Risk Management
All risk management is handled inside the strategy.
5.1 Position Sizing
Order Size % of Equity – default 10%
The strategy calculates:
position_value = equity * (Order Size % / 100)
position_qty = position_value / close
So position size automatically adapts to your current equity.
5.2 Take Profit Modes
You can choose one of two TP modes:
Percent
Fibonacci
5.2.1 Percent Mode
Single Take Profit at X% from entry (default 2%).
For Long:
TP = entry_price * (1 + tp_pct / 100)
For Short:
TP = entry_price * (1 - tp_pct / 100)
One strategy.exit per side is used: "Long TP/SL" and "Short TP/SL".
5.2.2 Fibonacci Mode (2 partial TPs)
In this mode, TP levels are based on a virtual Fib-style extension between entry and stop-loss.
Inputs:
Fib TP1 Level (default 1.618)
Fib TP2 Level (default 2.5)
TP1 Share % (Fib) (default 50%)
TP2 share is automatically 100% - TP1 share.
Process for Long:
Compute a reference Stop (see SL section below) → sl_for_fib.
Compute distance: dist = entry_price - sl_for_fib.
TP levels:
TP1 = entry_price + dist * (Fib TP1 Level - 1)
TP2 = entry_price + dist * (Fib TP2 Level - 1)
For Short, the logic is mirrored.
Two exits are used:
TP1 – closes TP1 share % of position.
TP2 – closes remaining TP2 share %.
Same stop is used for both partial exits.
5.3 Stop-Loss Modes
You can choose one of three Stop Loss modes:
Stable – fixed % from entry.
Ichimoku – fixed level derived from the Kumo.
Ichimoku Trailing – dynamic SL following the cloud.
5.3.1 Stable SL
For Long:
SL = entry_price * (1 - Stable SL % / 100)
For Short:
SL = entry_price * (1 + Stable SL % / 100)
Used both for Percent TP mode and as reference for Fib TP if Kumo is not available.
5.3.2 Ichimoku SL (fixed, non-trailing)
At the time of a new trade:
For Long:
Base SL = cloud bottom minus small offset (%)
For Short:
Base SL = cloud top plus small offset (%)
The offset is configurable: Ichimoku SL Offset %.
Once computed, that SL level is fixed for this trade.
5.3.3 Ichimoku Trailing SL
Similar to Ichimoku SL, but recomputed each bar:
For Long:
SL = cloud bottom – offset
For Short:
SL = cloud top + offset
A red trailing SL line is drawn on the chart to visualize current stop level.
This trailing SL is also used as reference for BreakEven and for Fib TP distance.
6. BreakEven Logic (with BE Lines)
BreakEven is optional and supports two modes:
Percent
Fibonacci
Inputs:
Percent mode:
BE Trigger % (from entry) – move SL to BE when price goes this % in profit.
BE Offset % from entry – SL will be set to entry ± this offset.
Fibonacci mode:
BE Fib Level – Fib level at which BE will be activated (default 1.618, same style as TP).
BE Offset % from entry – how far from entry to place BE stop.
The logic:
Before BE is triggered, SL follows its normal mode (Stable/Ichimoku/Ichimoku Trailing).
When BE triggers:
For Long:
New SL = max(current SL, BE SL).
For Short:
New SL = min(current SL, BE SL).
This means BE will never loosen the stop – only tighten it.
When BE is activated, the strategy draws a violet horizontal line at the BreakEven level (once per trade).
BE state is cleared when the position is closed or when a new position is opened.
7. Entry & Exit Logic (Summary)
7.1 Long Entry
Conditions for a Long:
CCI signal:
CCI crosses up through the upper threshold.
Ichimoku Cloud Filter (optional):
If enabled → price must be above the Kumo.
Ichimoku Lines Filter (optional):
If enabled → Conversion Line and Base Line must be above the Kumo.
MA Direction Filter (optional):
If enabled → Close must be above the chosen MA.
Anti-re-entry flag:
allowLong must be true (cloud-based reset).
Position check:
Long entries are allowed when current position size ≤ 0 (so it can also reverse from short to long).
If all these conditions are true, the strategy sends:
strategy.entry("Long", strategy.long, qty = calculated_qty)
After entry:
allowLong = false
allowShort = true
7.2 Short Entry
Same structure, mirrored:
CCI signal:
CCI crosses down through the lower threshold.
Cloud filter: price must be below cloud (if enabled).
Lines filter: conversion & base must be below cloud (if enabled).
MA filter: Close must be below MA (if enabled).
allowShort must be true.
Position check: position size ≥ 0 (allows reversal from long to short).
Then:
strategy.entry("Short", strategy.short, qty = calculated_qty)
Flags update:
allowShort = false
allowLong = true
7.3 Exits
While in a position:
The strategy continuously recalculates SL (depending on chosen mode) and, in Percent mode, TP.
In Fib mode, fixed TP levels are computed at entry.
BreakEven may raise/tighten the SL if its conditions are met.
Exits are executed via strategy.exit:
Percent mode: one TP+SL exit per side.
Fib mode: two partial exits (TP1 and TP2) sharing the same SL.
At position open, the script also draws visual lines:
White line — entry price.
Green line(s) — TP level(s).
Red line — SL (if not using Ichimoku Trailing; with trailing, the red line is updated dynamically).
Maximum of 30 lines are kept to avoid clutter.
8. How to Use the Strategy
Choose market & timeframe
Works well on trending instruments. Try crypto, FX or indices on H1–H4, or intraday if you prefer more trades.
Adjust Ichimoku settings
Keep defaults (9/26/52/26) or adapt to your timeframe.
Configure Moving Average
Typical: EMA 200 as a trend filter.
Turn MA Direction Filter ON if you want to trade only with the main trend.
Set CCI thresholds
Default ±100 is classic.
Lower thresholds → more signals, higher noise.
Higher thresholds → fewer but stronger signals.
Enable/disable filters
Turn on Ichimoku Cloud and Ichimoku Lines if you want only “clean” trend trades.
Use Wait Position Close Before Flag Reset to control how often re-entries are allowed.
Choose TP & SL mode
Percent mode is simpler and easier to understand.
Fibonacci mode is more advanced: it aligns TP levels with the distance to stop, giving asymmetric RR setups (two partial TPs).
Choose Stable SL for fixed-risk trades, or Ichimoku / Ichimoku Trailing to tie stops to the cloud structure.
Set BreakEven
Enable BE if you want to lock in risk-free trades after a certain move.
Percent mode is straightforward; Fib mode keeps BreakEven in harmony with your Fib TP setup.
Run Backtest & Optimize
Press “Add to chart” → go to Strategy Tester.
Adjust parameters to your market and timeframe.
Look at equity curve, PF, drawdown, average trade, etc.
Live / Paper Trading
After you’re satisfied with backtest results, use the strategy to generate signals.
You can mirror entries/exits manually or connect them to alerts (if you build an alert-based execution layer).
BAY_PIVOT S/R(4 Full Lines + ALL Labels)//@version=5
indicator("BAY_PIVOT S/R(4 Full Lines + ALL Labels)", overlay=true, max_labels_count=500, max_lines_count=500)
// ────────────────────── TOGGLES ──────────────────────
showPivot = input.bool(true, "Show Pivot (Full Line + Label)")
showTarget = input.bool(true, "Show Target (Full Line + Label)")
showLast = input.bool(true, "Show Last Close (Full Line + Label)")
showPrevClose = input.bool(true, "Show Previous Close (Full Line + Label)")
useBarchartLast = input.bool(true, "Use Barchart 'Last' (Settlement Price)")
showR1R2R3 = input.bool(true, "Show R1 • R2 • R3")
showS1S2S3 = input.bool(true, "Show S1 • S2 • S3")
showStdDev = input.bool(true, "Show ±1σ ±2σ ±3σ")
showFib4W = input.bool(true, "Show 4-Week Fibs")
showFib13W = input.bool(true, "Show 13-Week Fibs")
showMonthHL = input.bool(true, "Show 1M High / Low")
showEntry1 = input.bool(false, "Show Manual Entry 1")
showEntry2 = input.bool(false, "Show Manual Entry 2")
entry1 = input.float(0.0, "Manual Entry 1", step=0.25)
entry2 = input.float(0.0, "Manual Entry 2", step=0.25)
stdLen = input.int(20, "StdDev Length", minval=1)
fib4wBars = input.int(20, "4W Fib Lookback")
fib13wBars = input.int(65, "13W Fib Lookback")
// ────────────────────── DAILY CALCULATIONS ──────────────────────
high_y = request.security(syminfo.tickerid, "D", high , lookahead=barmerge.lookahead_on)
low_y = request.security(syminfo.tickerid, "D", low , lookahead=barmerge.lookahead_on)
close_y = request.security(syminfo.tickerid, "D", close , lookahead=barmerge.lookahead_on)
pivot = (high_y + low_y + close_y) / 3
r1 = pivot + 0.382 * (high_y - low_y)
r2 = pivot + 0.618 * (high_y - low_y)
r3 = pivot + (high_y - low_y)
s1 = pivot - 0.382 * (high_y - low_y)
s2 = pivot - 0.618 * (high_y - low_y)
s3 = pivot - (high_y - low_y)
prevClose = close_y
last = useBarchartLast ? request.security(syminfo.tickerid, "D", close , lookahead=barmerge.lookahead_off) : close
target = pivot + (pivot - prevClose)
// StdDev + Fibs + Monthly (unchanged)
basis = ta.sma(close, stdLen)
dev = ta.stdev(close, stdLen)
stdRes1 = basis + dev
stdRes2 = basis + dev*2
stdRes3 = basis + dev*3
stdSup1 = basis - dev
stdSup2 = basis - dev*2
stdSup3 = basis - dev*3
high4w = ta.highest(high, fib4wBars)
low4w = ta.lowest(low, fib4wBars)
fib382_4w = high4w - (high4w - low4w) * 0.382
fib50_4w = high4w - (high4w - low4w) * 0.500
high13w = ta.highest(high, fib13wBars)
low13w = ta.lowest(low, fib13wBars)
fib382_13w_high = high13w - (high13w - low13w) * 0.382
fib50_13w = high13w - (high13w - low13w) * 0.500
fib382_13w_low = low13w + (high13w - low13w) * 0.382
monthHigh = ta.highest(high, 30)
monthLow = ta.lowest(low, 30)
// ────────────────────── COLORS ──────────────────────
colRed = color.rgb(255,0,0)
colLime = color.rgb(0,255,0)
colYellow = color.rgb(255,255,0)
colOrange = color.rgb(255,165,0)
colWhite = color.rgb(255,255,255)
colGray = color.rgb(128,128,128)
colMagenta = color.rgb(255,0,255)
colPink = color.rgb(233,30,99)
colCyan = color.rgb(0,188,212)
colBlue = color.rgb(0,122,255)
colPurple = color.rgb(128,0,128)
colRed50 = color.new(colRed,50)
colGreen50 = color.new(colLime,50)
// ────────────────────── 4 KEY FULL LINES ──────────────────────
plot(showPivot ? pivot : na, title="PIVOT", color=colYellow, linewidth=3, style=plot.style_linebr)
plot(showTarget ? target : na, title="TARGET", color=colOrange, linewidth=2, style=plot.style_linebr)
plot(showLast ? last : na, title="LAST", color=colWhite, linewidth=2, style=plot.style_linebr)
plot(showPrevClose ? prevClose : na, title="PREV CLOSE",color=colGray, linewidth=1, style=plot.style_linebr)
// ────────────────────── LABELS FOR ALL 4 KEY LEVELS (SAME STYLE AS OTHERS) ──────────────────────
f_label(price, txt, bgColor, txtColor) =>
if barstate.islast and not na(price)
label.new(bar_index, price, txt, style=label.style_label_left, color=bgColor, textcolor=txtColor, size=size.small)
if barstate.islast
showPivot ? f_label(pivot, "PIVOT\n" + str.tostring(pivot, "#.##"), colYellow, color.black) : na
showTarget ? f_label(target, "TARGET\n" + str.tostring(target, "#.##"), colOrange, color.white) : na
showLast ? f_label(last, "LAST\n" + str.tostring(last, "#.##"), colWhite, color.black) : na
showPrevClose ? f_label(prevClose, "PREV CLOSE\n"+ str.tostring(prevClose, "#.##"), colGray, color.white) : na
// ────────────────────── OTHER LEVELS – line stops at label ──────────────────────
f_level(p, txt, tc, lc, w=1) =>
if barstate.islast and not na(p)
lbl = label.new(bar_index, p, txt, style=label.style_label_left, color=lc, textcolor=tc, size=size.small)
line.new(bar_index-400, p, label.get_x(lbl), p, extend=extend.none, color=lc, width=w)
if barstate.islast
if showR1R2R3
f_level(r1, "R1\n" + str.tostring(r1, "#.##"), color.white, colRed)
f_level(r2, "R2\n" + str.tostring(r2, "#.##"), color.white, colRed)
f_level(r3, "R3\n" + str.tostring(r3, "#.##"), color.white, colRed, 2)
if showS1S2S3
f_level(s1, "S1\n" + str.tostring(s1, "#.##"), color.black, colLime)
f_level(s2, "S2\n" + str.tostring(s2, "#.##"), color.black, colLime)
f_level(s3, "S3\n" + str.tostring(s3, "#.##"), color.black, colLime, 2)
if showStdDev
f_level(stdRes1, "+1σ\n" + str.tostring(stdRes1, "#.##"), color.white, colPink)
f_level(stdRes2, "+2σ\n" + str.tostring(stdRes2, "#.##"), color.white, colPink)
f_level(stdRes3, "+3σ\n" + str.tostring(stdRes3, "#.##"), color.white, colPink, 2)
f_level(stdSup1, "-1σ\n" + str.tostring(stdSup1, "#.##"), color.white, colCyan)
f_level(stdSup2, "-2σ\n" + str.tostring(stdSup2, "#.##"), color.white, colCyan)
f_level(stdSup3, "-3σ\n" + str.tostring(stdSup3, "#.##"), color.white, colCyan, 2)
if showFib4W
f_level(fib382_4w, "38.2% 4W\n" + str.tostring(fib382_4w, "#.##"), color.white, colMagenta)
f_level(fib50_4w, "50% 4W\n" + str.tostring(fib50_4w, "#.##"), color.white, colMagenta)
if showFib13W
f_level(fib382_13w_high, "38.2% 13W High\n" + str.tostring(fib382_13w_high, "#.##"), color.white, colMagenta)
f_level(fib50_13w, "50% 13W\n" + str.tostring(fib50_13w, "#.##"), color.white, colMagenta)
f_level(fib382_13w_low, "38.2% 13W Low\n" + str.tostring(fib382_13w_low, "#.##"), color.white, colMagenta)
if showMonthHL
f_level(monthHigh, "1M HIGH\n" + str.tostring(monthHigh, "#.##"), color.white, colRed50, 2)
f_level(monthLow, "1M LOW\n" + str.tostring(monthLow, "#.##"), color.white, colGreen50, 2)
// Manual entries
plot(showEntry1 and entry1 > 0 ? entry1 : na, "Entry 1", color=colBlue, linewidth=2, style=plot.style_linebr)
plot(showEntry2 and entry2 > 0 ? entry2 : na, "Entry 2", color=colPurple, linewidth=2, style=plot.style_linebr)
// Background
bgcolor(close > pivot ? color.new(color.blue, 95) : color.new(color.red, 95))
Big Candle Identifier with RSI Divergence and Advanced Stops1. Strategy Objective
The main goal of this strategy is to:
Identify significant price momentum (big candles).
Enter trades at opportune moments based on market signals (candlestick patterns and RSI divergence).
Limit initial risk through a fixed stop loss.
Maximize profits by using a trailing stop that activates only after the trade moves a specified distance in the profitable direction.
2. Components of the Strategy
A. Big Candle Identification
The strategy identifies big candles as indicators of strong momentum.
A big candle is defined as:
The body (absolute difference between close and open) of the current candle (body0) is larger than the bodies of the last five candles.
The candle is:
Bullish Big Candle: If close > open.
Bearish Big Candle: If open > close.
Purpose: Big candles signal potential continuation or reversal of trends, serving as the primary entry trigger.
B. RSI Divergence
Relative Strength Index (RSI): A momentum oscillator used to detect overbought/oversold conditions and divergence.
Fast RSI: A 5-period RSI, which is more sensitive to short-term price movements.
Slow RSI: A 14-period RSI, which smoothens fluctuations over a longer timeframe.
Divergence: The difference between the fast and slow RSIs.
Positive divergence (divergence > 0): Bullish momentum.
Negative divergence (divergence < 0): Bearish momentum.
Visualization: The divergence is plotted on the chart, helping traders confirm momentum shifts.
C. Stop Loss
Initial Stop Loss:
When entering a trade, an immediate stop loss of 200 points is applied.
This stop loss ensures the maximum risk is capped at a predefined level.
Implementation:
Long Trades: Stop loss is set below the entry price at low - 200 points.
Short Trades: Stop loss is set above the entry price at high + 200 points.
Purpose:
Prevents significant losses if the price moves against the trade immediately after entry.
D. Trailing Stop
The trailing stop is a dynamic risk management tool that adjusts with price movements to lock in profits. Here’s how it works:
Activation Condition:
The trailing stop only starts trailing when the trade moves 200 ticks (profit) in the right direction:
Long Position: close - entry_price >= 200 ticks.
Short Position: entry_price - close >= 200 ticks.
Trailing Logic:
Once activated, the trailing stop:
For Long Positions: Trails behind the price by 150 ticks (trail_stop = close - 150 ticks).
For Short Positions: Trails above the price by 150 ticks (trail_stop = close + 150 ticks).
Exit Condition:
The trade exits automatically if the price touches the trailing stop level.
Purpose:
Ensures profits are locked in as the trade progresses while still allowing room for price fluctuations.
E. Trade Entry Logic
Long Entry:
Triggered when a bullish big candle is identified.
Stop loss is set at low - 200 points.
Short Entry:
Triggered when a bearish big candle is identified.
Stop loss is set at high + 200 points.
F. Trade Exit Logic
Trailing Stop: Automatically exits the trade if the price touches the trailing stop level.
Fixed Stop Loss: Exits the trade if the price hits the predefined stop loss level.
G. 21 EMA
The strategy includes a 21-period Exponential Moving Average (EMA), which acts as a trend filter.
EMA helps visualize the overall market direction:
Price above EMA: Indicates an uptrend.
Price below EMA: Indicates a downtrend.
H. Visualization
Big Candle Identification:
The open and close prices of big candles are plotted for easy reference.
Trailing Stop:
Plotted on the chart to visualize its progression during the trade.
Green Line: Indicates the trailing stop for long positions.
Red Line: Indicates the trailing stop for short positions.
RSI Divergence:
Positive divergence is shown in green.
Negative divergence is shown in red.
3. Key Parameters
trail_start_ticks: The number of ticks required before the trailing stop activates (default: 200 ticks).
trail_distance_ticks: The distance between the trailing stop and price once the trailing stop starts (default: 150 ticks).
initial_stop_loss_points: The fixed stop loss in points applied at entry (default: 200 points).
tick_size: Automatically calculates the minimum tick size for the trading instrument.
4. Workflow of the Strategy
Step 1: Entry Signal
The strategy identifies a big candle (bullish or bearish).
If conditions are met, a trade is entered with a fixed stop loss.
Step 2: Initial Risk Management
The trade starts with an initial stop loss of 200 points.
Step 3: Trailing Stop Activation
If the trade moves 200 ticks in the profitable direction:
The trailing stop is activated and follows the price at a distance of 150 ticks.
Step 4: Exit the Trade
The trade is exited if:
The price hits the trailing stop.
The price hits the initial stop loss.
5. Advantages of the Strategy
Risk Management:
The fixed stop loss ensures that losses are capped.
The trailing stop locks in profits after the trade becomes profitable.
Momentum-Based Entries:
The strategy uses big candles as entry triggers, which often indicate strong price momentum.
Divergence Confirmation:
RSI divergence helps validate momentum and avoid false signals.
Dynamic Profit Protection:
The trailing stop adjusts dynamically, allowing the trade to capture larger moves while protecting gains.
6. Ideal Market Conditions
This strategy performs best in:
Trending Markets:
Big candles and momentum signals are more effective in capturing directional moves.
High Volatility:
Larger price swings improve the probability of reaching the trailing stop activation level (200 ticks).
Nef33 Forex & Crypto Trading Signals PRO
1. Understanding the Indicator's Context
The indicator generates signals based on confluence (trend, volume, key zones, etc.), but it does not include predefined SL or TP levels. To establish them, we must:
Use dynamic or static support/resistance levels already present in the script.
Incorporate volatility (such as ATR) to adjust the levels based on market conditions.
Define a risk/reward ratio (e.g., 1:2).
2. Options for Determining SL and TP
Below, I provide several ideas based on the tools available in the script:
Stop Loss (SL)
The SL should protect you from adverse movements. You can base it on:
ATR (Volatility): Use the smoothed ATR (atr_smooth) multiplied by a factor (e.g., 1.5 or 2) to set a dynamic SL.
Buy: SL = Entry Price - (atr_smooth * atr_mult).
Sell: SL = Entry Price + (atr_smooth * atr_mult).
Key Zones: Place the SL below a support (for buys) or above a resistance (for sells), using Order Blocks, Fair Value Gaps, or Liquidity Zones.
Buy: SL below the nearest ob_lows or fvg_lows.
Sell: SL above the nearest ob_highs or fvg_highs.
VWAP: Use the daily VWAP (vwap_day) as a critical level.
Buy: SL below vwap_day.
Sell: SL above vwap_day.
Take Profit (TP)
The TP should maximize profits. You can base it on:
Risk/Reward Ratio: Multiply the SL distance by a factor (e.g., 2 or 3).
Buy: TP = Entry Price + (SL Distance * 2).
Sell: TP = Entry Price - (SL Distance * 2).
Key Zones: Target the next resistance (for buys) or support (for sells).
Buy: TP at the next ob_highs, fvg_highs, or liq_zone_high.
Sell: TP at the next ob_lows, fvg_lows, or liq_zone_low.
Ichimoku: Use the cloud levels (Senkou Span A/B) as targets.
Buy: TP at senkou_span_a or senkou_span_b (whichever is higher).
Sell: TP at senkou_span_a or senkou_span_b (whichever is lower).
3. Practical Implementation
Since the script does not automatically draw SL/TP, you can:
Calculate them manually: Observe the chart and use the levels mentioned.
Modify the code: Add SL/TP as labels (label.new) at the moment of the signal.
Here’s an example of how to modify the code to display SL and TP based on ATR with a 1:2 risk/reward ratio:
Modified Code (Signals Section)
Find the lines where the signals (trade_buy and trade_sell) are generated and add the following:
pinescript
// Calculate SL and TP based on ATR
atr_sl_mult = 1.5 // Multiplier for SL
atr_tp_mult = 3.0 // Multiplier for TP (1:2 ratio)
sl_distance = atr_smooth * atr_sl_mult
tp_distance = atr_smooth * atr_tp_mult
if trade_buy
entry_price = close
sl_price = entry_price - sl_distance
tp_price = entry_price + tp_distance
label.new(bar_index, low, "Buy: " + str.tostring(math.round(bull_conditions, 1)), color=color.green, textcolor=color.white, style=label.style_label_up, size=size.tiny)
label.new(bar_index, sl_price, "SL: " + str.tostring(math.round(sl_price, 2)), color=color.red, textcolor=color.white, style=label.style_label_down, size=size.tiny)
label.new(bar_index, tp_price, "TP: " + str.tostring(math.round(tp_price, 2)), color=color.blue, textcolor=color.white, style=label.style_label_up, size=size.tiny)
if trade_sell
entry_price = close
sl_price = entry_price + sl_distance
tp_price = entry_price - tp_distance
label.new(bar_index, high, "Sell: " + str.tostring(math.round(bear_conditions, 1)), color=color.red, textcolor=color.white, style=label.style_label_down, size=size.tiny)
label.new(bar_index, sl_price, "SL: " + str.tostring(math.round(sl_price, 2)), color=color.red, textcolor=color.white, style=label.style_label_up, size=size.tiny)
label.new(bar_index, tp_price, "TP: " + str.tostring(math.round(tp_price, 2)), color=color.blue, textcolor=color.white, style=label.style_label_down, size=size.tiny)
Code Explanation
SL: Calculated by subtracting/adding sl_distance to the entry price (close) depending on whether it’s a buy or sell.
TP: Calculated with a double distance (tp_distance) for a 1:2 risk/reward ratio.
Visualization: Labels are added to the chart to display SL (red) and TP (blue).
4. Practical Strategy Without Modifying the Code
If you don’t want to modify the script, follow these steps manually:
Entry: Take the trade_buy or trade_sell signal.
SL: Check the smoothed ATR (atr_smooth) on the chart or calculate a fixed level (e.g., 1.5 times the ATR). Also, review nearby key zones (OB, FVG, VWAP).
TP: Define a target based on the next key zone or multiply the SL distance by 2 or 3.
Example:
Buy at 100, ATR = 2.
SL = 100 - (2 * 1.5) = 97.
TP = 100 + (2 * 3) = 106.
5. Recommendations
Test in Demo: Apply this logic in a demo account to adjust the multipliers (atr_sl_mult, atr_tp_mult) based on the market (forex or crypto).
Combine with Zones: If the ATR-based SL is too wide, use the nearest OB or FVG as a reference.
Risk/Reward Ratio: Adjust the TP based on your tolerance (1:1, 1:2, 1:3)
Risk & Position DashboardRisk & Position Dashboard
Overview
The Risk & Position Dashboard is a comprehensive trading tool designed to help traders calculate optimal position sizes, manage risk, and visualize potential profit/loss scenarios before entering trades. This indicator provides real-time calculations for position sizing based on account size, risk percentage, and stop-loss levels, while displaying multiple take-profit targets with customizable risk-reward ratios.
Key Features
Position Sizing & Risk Management:
Automatic position size calculation based on account size and risk percentage
Support for leveraged trading with maximum leverage limits
Fractional shares support for brokers that allow partial share trading
Real-time fee calculation including entry, stop-loss, and take-profit fees
Break-even price calculation including trading fees
Multi-Target Profit Management:
Support for up to 3 take-profit levels with individual portion allocations
Customizable risk-reward ratios for each take-profit target
Visual profit/loss zones displayed as colored boxes on the chart
Individual profit calculations for each take-profit level
Visual Dashboard:
Clean, customizable table display showing all key metrics
Configurable label positioning and styling options
Real-time tracking of whether stop-loss or take-profit levels have been reached
Color-coded visual zones for easy identification of risk and reward areas
Advanced Configuration:
Comprehensive input validation and error handling
Support for different chart timeframes and symbols
Customizable colors, fonts, and display options
Hide/show individual data fields for personalized dashboard views
How to Use
Set Account Parameters: Configure your account size, maximum risk percentage per trade, and trading fees in the "Account Settings" section.
Define Trade Setup: Use the "Entry" time picker to select your entry point on the chart, then input your entry price and stop-loss level.
Configure Take Profits: Set your desired risk-reward ratios and portion allocations for each take-profit level. The script supports 1-3 take-profit targets.
Analyze Results: The dashboard will automatically calculate and display position size, number of shares, potential profits/losses, fees, and break-even levels.
Visual Confirmation: Colored boxes on the chart show profit zones (green) and loss zones (red), with lines extending to current price levels.
Reset Entry and SL:
You can easily reset the entry and stop-loss by clicking the "Reset points..." button from the script's "More" menu.
This is useful if you want to quickly clear your current trade setup and start fresh without manually adjusting the points on the chart.
Calculations
The script performs sophisticated calculations including:
Position size based on risk amount and price difference between entry and stop-loss
Leverage requirements and position amount calculations
Fee-adjusted risk-reward ratios for realistic profit expectations
Break-even price including all trading costs
Individual profit calculations for partial position closures
Detailed Take-Profit Calculation Formula:
The take-profit prices are calculated using the following mathematical formula:
// Core variables:
// risk_amount = account_size * (risk_percentage / 100)
// total_risk_per_share = |entry_price - sl_price| + (entry_price * fee%) + (sl_price * fee%)
// shares = risk_amount / total_risk_per_share
// direction_factor = 1 for long positions, -1 for short positions
// Take-profit calculation:
net_win = total_risk_per_share * shares * RR_ratio
tp_price = (net_win + (direction_factor * entry_price * shares) + (entry_price * fee% * shares)) / (direction_factor * shares - fee% * shares)
Step-by-step example for a long position (based on screenshot):
Account Size: 2,000 USDT, Risk: 2% = 40 USDT
Entry: 102,062.9 USDT, Stop Loss: 102,178.4 USDT, Fee: 0.06%
Risk per share: |102,062.9 - 102,178.4| + (102,062.9 × 0.0006) + (102,178.4 × 0.0006) = 115.5 + 61.24 + 61.31 = 238.05 USDT
Shares: 40 ÷ 238.05 = 0.168 shares (rounded to 0.17 in display)
Position Size: 0.17 × 102,062.9 = 17,350.69 USDT
Position Amount (with 9x leverage): 17,350.69 ÷ 9 = 1,927.85 USDT
For 2:1 RR: Net win = 238.05 × 0.17 × 2 = 80.94 USDT
TP1 price = (80.94 + (1 × 102,062.9 × 0.17) + (102,062.9 × 0.0006 × 0.17)) ÷ (1 × 0.17 - 0.0006 × 0.17) = 101,464.7 USDT
For 3:1 RR: TP2 price = 101,226.7 USDT (following same formula with RR=3)
This ensures that after accounting for all fees, the actual risk-reward ratio matches the specified target ratio.
Risk Management Features
Maximum Trade Amount: Optional setting to limit position size regardless of account size
Leverage Limits: Built-in maximum leverage protection
Fee Integration: All calculations include realistic trading fees for accurate expectations
Validation: Automatic checking that take-profit portions sum to 100%
Historical Tracking: Visual indication when stop-loss or take-profit levels are reached (within last 5000 bars)
Understanding Max Trade Amount - Multiple Simultaneous Trades:
The "Max Trade Amount" feature is designed for traders who want to open multiple positions simultaneously while maintaining proper risk management. Here's how it works:
Key Concept:
- Risk percentage (2%) always applies to your full Account Size
- Max Trade Amount limits the capital allocated per individual trade
- This allows multiple trades with full risk on each trade
Example from Screenshot:
Account Size: 2,000 USDT
Max Trade Amount: 500 USDT
Risk per Trade: 2% × 2,000 = 40 USDT per trade
Stop Loss Distance: 0.11% from entry
Result: Position Size = 17,350.69 USDT with 35x leverage
Total Risk (including fees): 40.46 USDT
Multiple Trades Strategy:
With this setup, you can open:
Trade 1: 40 USDT risk, 495.73 USDT position amount (35x leverage)
Trade 2: 40 USDT risk, 495.73 USDT position amount (35x leverage)
Trade 3: 40 USDT risk, 495.73 USDT position amount (35x leverage)
Trade 4: 40 USDT risk, 495.73 USDT position amount (35x leverage)
Total Portfolio Exposure:
- 4 simultaneous trades = 4 × 495.73 = 1,982.92 USDT position amount
- Total risk exposure = 4 × 40 = 160 USDT (8% of account)
PivotBoss VWAP Bands (Auto TF) - FixedWhat this indicator shows (high level)
The indicator plots a VWAP line and three bands above (R1, R2, R3) and three bands below (S1, S2, S3).
Band spacing is computed from STD(abs(VWAP − price), N) and multiplied by 1, 2 and 3 to form R1–R3 / S1–S3. The script is timeframe-aware: on 30m/1H charts it uses Weekly VWAP and weekly bands; on Daily charts it uses Monthly VWAP and monthly bands; otherwise it uses the session/chart VWAP.
VWAP = the market’s volume-weighted average price (a measure of fair value). Bands = volatility-scaled zones around that fair value.
Trading idea — concept summary
VWAP = fair value. Price above VWAP implies bullish bias; below VWAP implies bearish bias.
Bands = graded overbought/oversold zones. R1/S1 are near-term limits, R2/S2 are stronger, R3/S3 are extreme.
Use trend alignment + price action + volume to choose higher-probability trades. VWAP bands give location and magnitude; confirmations reduce false signals.
Entry rules (multiple strategies with examples)
A. Momentum breakout (trend-following) — preferred on trending markets
Setup: Price consolidates near or below R1 and then closes above R1 with above-average volume. Chart: 30m/1H (Weekly VWAP) or Daily (Monthly VWAP) depending on your timeframe.
Entry: Enter long at the close of the breakout bar that closes above R1.
Stop-loss: Place initial stop below the higher of (VWAP or recent swing low). Example: if price broke R1 at ₹1,200 and VWAP = ₹1,150, set stop at ₹1,145 (5 rupee buffer below VWAP) or below the last swing low if that is wider.
Target: Partial target at R2, full target at R3. Trail stop to VWAP or to R1 after price reaches R2.
Example numeric: Weekly VWAP = ₹1,150, R1 = ₹1,200, R2 = ₹1,260. Buy at ₹1,205 (close above R1), stop ₹1,145, target1 ₹1,260 (R2), target2 ₹1,320 (R3).
B. Mean-reversion fade near bands — for range-bound markets
Setup: Market is not trending (VWAP flatish). Price rallies up to R2 or R3 and shows rejection (pin bar, bearish engulfing) on increasing or neutral volume.
Entry: Enter short after a confirmed rejection candle that fails to sustain above R2 or R3 (prefer confirmation: close back below R1 or below the rejection candle low).
Stop-loss: Just above the recent high (e.g., 1–2 ATR or a fixed buffer above R2/R3).
Target: First target VWAP, second target S1. Reduce size if taking R3 fade as it’s an extreme.
Example numeric: VWAP = ₹950, R2 = ₹1,020. Price spikes to ₹1,025 and forms a bearish engulfing candle. Enter short at ₹1,015 after the next close below ₹1,020. Stop at ₹1,035, target VWAP ₹950.
C. Pullback entries in trending markets — higher probability
Setup: Price is above VWAP and trending higher (higher highs and higher lows). Price pulls back toward VWAP or S1 with decreasing downside volume and a reversal candle forms.
Entry: Long when price forms a bullish reversal (hammer/inside-bar) with a close back above the pullback candle.
Stop-loss: Below the pullback low (or below S2 if a larger stop is justified).
Target: VWAP then R1; if momentum resumes, trail toward R2/R3.
Example numeric: Price trending above Weekly VWAP at ₹1,400; pullback to S1 at ₹1,360. Enter long at ₹1,370 when a bullish candle closes; stop at ₹1,350; first target VWAP ₹1,400, second target R1 ₹1,450.
Exit rules and money management
Basic exit hierarchy
Hard stop exit — when price hits initial stop-loss. Always use.
Target exit — take partial profits at R1/R2 (for longs) or S1/S2 (for shorts). Use trailing stops for the remainder.
VWAP invalidation — if you entered long above VWAP and price returns and closes significantly below VWAP, consider exiting (condition depends on timeframe and trade size).
Price action exit — reversal patterns (strong opposite candle, bearish/bullish engulfing) near targets or beyond signals to exit.
Trailing rules
After price reaches R2, move stop to breakeven + a small buffer or to VWAP.
After price reaches R3, trail by 1 ATR or lock a defined profit percentage.
Position sizing & risk
Risk per trade: commonly 0.5–2% of account equity.
Determine position size by RiskAmount ÷ (EntryPrice − StopPrice).
If the stop distance is large (e.g., trading R3 fades), reduce position size.
Filters & confirmation (to reduce false signals)
Volume filter: For breakouts, require volume above short-term average (e.g., >20-period average). Breakouts on low volume are suspect.
Trend filter: Only take breakouts in the direction of the higher-timeframe trend (for example, use Daily/Weekly trend when trading 30m/1H).
Candle confirmation: Prefer entries on close of the confirming candle (not intrabar noise).
Multiple confirmations: When R1 break happens but RSI/plotted momentum indicator does not confirm, treat signal as lower probability.
Special considerations for timeframe-aware logic
On 30m/1H the script uses Weekly VWAP/bands. That means band levels change only on weekly candles — they are strong, structural levels. Treat R1/R2/R3 as significant and expect fewer, stronger signals.
On Daily, the script uses Monthly VWAP/bands. These are wider; trades should allow larger stops and smaller position sizes (or be used for swing trades).
On other intraday charts you get session VWAP (useful for intraday scalps).
Example: If you trade 1H and the Weekly R1 is at ₹2,400 while session VWAP is ₹2,350, a close above Weekly R1 represents a weekly-level breakout — prefer that for swing entries rather than scalps.
Example trade walkthrough (step-by-step)
Context: 1H chart, auto-mapped → Weekly VWAP used.
Weekly VWAP = ₹3,000; R1 = ₹3,080; R2 = ₹3,150.
Price consolidates below R1. A large bullish candle closes at ₹3,085 with volume 40% above the 20-bar average.
Entry: Buy at close ₹3,085.
Stop: Place stop at ₹2,995 (just under Weekly VWAP). Risk = ₹90.
Position size: If risking ₹900 per trade → size = 900 ÷ 90 = 10 units.
Targets: Partial take-profit at R2 = ₹3,150; rest trailed with stop moved to breakeven after R2 is hit.
If price reverses and closes below VWAP within two bars, exit immediately to limit drawdown.
When to avoid trading these signals
High-impact news (earnings, macro announcements) that can gap through bands unpredictably.
Thin markets with low volume — VWAP loses significance when volumes are extremely low.
When weekly/monthly bands are flat but intraday price is volatile without clear structure — prefer session VWAP on smaller timeframes.
Alerts & automation suggestions
Alert on close above R1 / below S1 (use the built-in alertcondition the script adds). For higher-confidence alerts, require volume filter in the alert condition.
Automated order rules (if you automate): use limit entry at breakout close plus a small slippage buffer, immediate stop order, and OCO for TP and SL.
BackTestLibLibrary "BackTestLib"
Allows backtesting indicator performance. Tracks typical metrics such as won/loss, profit factor, draw down, etc. Trading View strategy library provides similar (and more comprehensive)
functionality but only works with strategies. This libary was created to address performance tracking within indicators.
Two primary outputs are generated:
1. Summary Table: Displays overall performance metrics for the indicator over the chart's loaded timeframe and history
2. Details Table: Displays a table of individual trade entries and exits. This table can grow larger than the available chart space. It does have a max number of rows supported. I haven't
found a way to add scroll bars or scroll bar equivalents yet.
f_init(data, _defaultStopLoss, _defaultTakeProfit, _useTrailingStop, _useTraingStopToBreakEven, _trailingStopActivation, _trailingStopOffset)
f_init Initialize the backtest data type. Called prior to using the backtester functions
Parameters:
data (backtesterData) : backtesterData to initialize
_defaultStopLoss (float) : Default trade stop loss to apply
_defaultTakeProfit (float) : Default trade take profit to apply
_useTrailingStop (bool) : Trailing stop enabled
_useTraingStopToBreakEven (bool) : When trailing stop active, trailing stop will increase no further than the entry price
_trailingStopActivation (int) : When trailing stop active, trailing will begin once price exceeds base stop loss by this number of points
_trailingStopOffset (int) : When trailing stop active, it will trail the max price achieved by this number of points
Returns: Initialized data set
f_buildResultStr(_resultType, _price, _resultPoints, _numWins, _pointsWon, _numLoss, _pointsLost)
f_buildResultStr Helper function to construct a string of resutling data for exit tooltip labels
Parameters:
_resultType (string)
_price (float)
_resultPoints (float)
_numWins (int)
_pointsWon (float)
_numLoss (int)
_pointsLost (float)
f_buildResultLabel(data, labelVertical, labelOffset, long)
f_buildResultLabel Helper function to construct an Exit label for display on the chart
Parameters:
data (backtesterData)
labelVertical (bool)
labelOffset (int)
long (bool)
f_updateTrailingStop(_entryPrice, _curPrice, _sl, _tp, trailingStopActivationInput, trailingStopOffsetInput, useTrailingStopToBreakEven)
f_updateTrailingStop Helper function to advance the trailing stop as price action dictates
Parameters:
_entryPrice (float)
_curPrice (float)
_sl (float)
_tp (float)
trailingStopActivationInput (float)
trailingStopOffsetInput (float)
useTrailingStopToBreakEven (bool)
Returns: Updated stop loss for current price action
f_enterShort(data, entryPrice, fixedStopLoss)
f_enterShort Helper function to enter a short and collect data necessary for tracking the trade entry
Parameters:
data (backtesterData)
entryPrice (float)
fixedStopLoss (float)
Returns: Updated backtest data
f_enterLong(data, entryPrice, fixedStopLoss)
f_enterLong Helper function to enter a long and collect data necessary for tracking the trade entry
Parameters:
data (backtesterData)
entryPrice (float)
fixedStopLoss (float)
Returns: Updated backtest data
f_exitTrade(data)
f_enterLong Helper function to exit a trade and update/reset tracking data
Parameters:
data (backtesterData)
Returns: Updated backtest data
f_checkTradeConditionForExit(data, condition, curPrice, enableRealTime)
f_checkTradeConditionForExit Helper function to determine if provided condition indicates an exit
Parameters:
data (backtesterData)
condition (bool) : When true trade will exit
curPrice (float)
enableRealTime (bool) : When true trade will evaluate if barstate is relatime or barstate is confirmed; otherwise just checks on is confirmed
Returns: Updated backtest data
f_checkTrade(data, curPrice, curLow, curHigh, enableRealTime)
f_checkTrade Helper function to determine if current price action dictates stop loss or take profit exit
Parameters:
data (backtesterData)
curPrice (float)
curLow (float)
curHigh (float)
enableRealTime (bool) : When true trade will evaluate if barstate is relatime or barstate is confirmed; otherwise just checks on is confirmed
Returns: Updated backtest data
f_fillCell(_table, _column, _row, _title, _value, _bgcolor, _txtcolor, _text_size)
f_fillCell Helper function to construct result table cells
Parameters:
_table (table)
_column (int)
_row (int)
_title (string)
_value (string)
_bgcolor (color)
_txtcolor (color)
_text_size (string)
Returns: Table cell
f_prepareStatsTable(data, drawTesterSummary, drawTesterDetails, summaryTableTextSize, detailsTableTextSize, displayRowZero, summaryTableLocation, detailsTableLocation)
f_fillCell Helper function to populate result table
Parameters:
data (backtesterData)
drawTesterSummary (bool)
drawTesterDetails (bool)
summaryTableTextSize (string)
detailsTableTextSize (string)
displayRowZero (bool)
summaryTableLocation (string)
detailsTableLocation (string)
Returns: Updated backtest data
backtesterData
backtesterData - container for backtest performance metrics
Fields:
tradesArray (array) : Array of strings with entries for each individual trade and its results
pointsBalance (series float) : Running sum of backtest points won/loss results
drawDown (series float) : Running sum of backtest total draw down points
maxDrawDown (series float) : Running sum of backtest total draw down points
maxRunup (series float) : Running sum of max points won over the backtest
numWins (series int) : Number of wins of current backtes set
numLoss (series int) : Number of losses of current backtes set
pointsWon (series float) : Running sum of points won to date
pointsLost (series float) : Running sum of points lost to date
entrySide (series string) : Current entry long/short
tradeActive (series bool) : Indicates if a trade is currently active
tradeComplete (series bool) : Indicates if a trade just exited (due to stop loss or take profit)
entryPrice (series float) : Current trade entry price
entryTime (series int) : Current trade entry time
sl (series float) : Current trade stop loss
tp (series float) : Current trade take profit
defaultStopLoss (series float) : Default trade stop loss to apply
defaultTakeProfit (series float) : Default trade take profit to apply
useTrailingStop (series bool) : Trailing stop enabled
useTrailingStopToBreakEven (series bool) : When trailing stop active, trailing stop will increase no further than the entry price
trailingStopActivation (series int) : When trailing stop active, trailing will begin once price exceeds base stop loss by this number of points
trailingStopOffset (series int) : When trailing stop active, it will trail the max price achieved by this number of points
resultType (series string) : Current trade won/lost
exitPrice (series float) : Current trade exit price
resultPoints (series float) : Current trade points won/lost
summaryTable (series table) : Table to deisplay summary info
tradesTable (series table) : Table to display per trade info
position_toolLibrary "position_tool"
Trying to turn TradingView's position tool into a library from which you can draw position tools for your strategies on the chart. Not sure if this is going to work
calcBaseUnit()
Calculates the chart symbol's base unit of change in asset prices.
Returns: (float) A ticks or pips value of base units of change.
calcOrderPipsOrTicks(orderSize, unit)
Converts the `orderSize` to ticks.
Parameters:
orderSize (float) : (series float) The order size to convert to ticks.
unit (simple float) : (simple float) The basic units of change in asset prices.
Returns: (int) A tick value based on a given order size.
calcProfitLossSize(price, entryPrice, isLongPosition)
Calculates a difference between a `price` and the `entryPrice` in absolute terms.
Parameters:
price (float) : (series float) The price to calculate the difference from.
entryPrice (float) : (series float) The price of entry for the position.
isLongPosition (bool)
Returns: (float) The absolute price displacement of a price from an entry price.
calcRiskRewardRatio(profitSize, lossSize)
Calculates a risk to reward ratio given the size of profit and loss.
Parameters:
profitSize (float) : (series float) The size of the profit in absolute terms.
lossSize (float) : (series float) The size of the loss in absolute terms.
Returns: (float) The ratio between the `profitSize` to the `lossSize`
createPosition(entryPrice, entryTime, tpPrice, slPrice, entryColor, tpColor, slColor, textColor, showExtendRight)
Main function to create a position visualization with entry, TP, and SL
Parameters:
entryPrice (float) : (float) The entry price of the position
entryTime (int) : (int) The entry time of the position in bar_time format
tpPrice (float) : (float) The take profit price
slPrice (float) : (float) The stop loss price
entryColor (color) : (color) Color for entry line
tpColor (color) : (color) Color for take profit zone
slColor (color) : (color) Color for stop loss zone
textColor (color) : (color) Color for text labels
showExtendRight (bool) : (bool) Whether to extend lines to the right
Returns: (bool) Returns true when position is closed
CalculatePercentageSlTpLibrary "CalculatePercentageSlTp"
This Library calculate the sl and tp amount in percentage
sl_percentage(entry_price, sl_price)
this function calculates the sl value in percentage
Parameters:
entry_price : indicates the entry level
sl_price : indicates the stop loss level
Returns: stop loss in percentage
tp_percentage(entry_price, tp_price)
this function calculates the tp value in percentage
Parameters:
entry_price : indicates the entry level
tp_price : indicates the take profit level
Returns: take profit in percentage
sl_level(entry_price, sl_percentage)
this function calculates the sl level price
Parameters:
entry_price : indicates the entry level
sl_percentage : indicates the stop loss percentage
Returns: stop loss price in $
tp_level(entry_price, tp_percentage)
this function calculates the tp level price
Parameters:
entry_price : indicates the entry level
tp_percentage : indicates the take profit percentage
Returns: take profit price in $
ApicodeLibrary "Apicode"
percentToTicks(percent, from)
Converts a percentage of the average entry price or a specified price to ticks when the
strategy has an open position.
Parameters:
percent (float) : (series int/float) The percentage of the `from` price to express in ticks, e.g.,
a value of 50 represents 50% (half) of the price.
from (float) : (series int/float) Optional. The price from which to calculate a percentage and convert
to ticks. The default is `strategy.position_avg_price`.
Returns: (float) The number of ticks within the specified percentage of the `from` price if
the strategy has an open position. Otherwise, it returns `na`.
percentToPrice(percent, from)
Calculates the price value that is a specific percentage distance away from the average
entry price or a specified price when the strategy has an open position.
Parameters:
percent (float) : (series int/float) The percentage of the `from` price to use as the distance. If the value
is positive, the calculated price is above the `from` price. If negative, the result is
below the `from` price. For example, a value of 10 calculates the price 10% higher than
the `from` price.
from (float) : (series int/float) Optional. The price from which to calculate a percentage distance.
The default is `strategy.position_avg_price`.
Returns: (float) The price value at the specified `percentage` distance away from the `from` price
if the strategy has an open position. Otherwise, it returns `na`.
percentToCurrency(price, percent)
Parameters:
price (float) : (series int/float) The price from which to calculate the percentage.
percent (float) : (series int/float) The percentage of the `price` to calculate.
Returns: (float) The amount of the symbol's currency represented by the percentage of the specified
`price`.
percentProfit(exitPrice)
Calculates the expected profit/loss of the open position if it were to close at the
specified `exitPrice`, expressed as a percentage of the average entry price.
NOTE: This function may not return precise values for positions with multiple open trades
because it only uses the average entry price.
Parameters:
exitPrice (float) : (series int/float) The position's hypothetical closing price.
Returns: (float) The expected profit percentage from exiting the position at the `exitPrice`. If
there is no open position, it returns `na`.
priceToTicks(price)
Converts a price value to ticks.
Parameters:
price (float) : (series int/float) The price to convert.
Returns: (float) The value of the `price`, expressed in ticks.
ticksToPrice(ticks, from)
Calculates the price value at the specified number of ticks away from the average entry
price or a specified price when the strategy has an open position.
Parameters:
ticks (float) : (series int/float) The number of ticks away from the `from` price. If the value is positive,
the calculated price is above the `from` price. If negative, the result is below the `from`
price.
from (float) : (series int/float) Optional. The price to evaluate the tick distance from. The default is
`strategy.position_avg_price`.
Returns: (float) The price value at the specified number of ticks away from the `from` price if
the strategy has an open position. Otherwise, it returns `na`.
ticksToCurrency(ticks)
Converts a specified number of ticks to an amount of the symbol's currency.
Parameters:
ticks (float) : (series int/float) The number of ticks to convert.
Returns: (float) The amount of the symbol's currency represented by the tick distance.
ticksToStopLevel(ticks)
Calculates a stop-loss level using a specified tick distance from the position's average
entry price. A script can plot the returned value and use it as the `stop` argument in a
`strategy.exit()` call.
Parameters:
ticks (float) : (series int/float) The number of ticks from the position's average entry price to the
stop-loss level. If the position is long, the value represents the number of ticks *below*
the average entry price. If short, it represents the number of ticks *above* the price.
Returns: (float) The calculated stop-loss value for the open position. If there is no open position,
it returns `na`.
ticksToTpLevel(ticks)
Calculates a take-profit level using a specified tick distance from the position's average
entry price. A script can plot the returned value and use it as the `limit` argument in a
`strategy.exit()` call.
Parameters:
ticks (float) : (series int/float) The number of ticks from the position's average entry price to the
take-profit level. If the position is long, the value represents the number of ticks *above*
the average entry price. If short, it represents the number of ticks *below* the price.
Returns: (float) The calculated take-profit value for the open position. If there is no open
position, it returns `na`.
calcPositionSizeByStopLossTicks(stopLossTicks, riskPercent)
Calculates the entry quantity required to risk a specified percentage of the strategy's
current equity at a tick-based stop-loss level.
Parameters:
stopLossTicks (float) : (series int/float) The number of ticks in the stop-loss distance.
riskPercent (float) : (series int/float) The percentage of the strategy's equity to risk if a trade moves
`stopLossTicks` away from the entry price in the unfavorable direction.
Returns: (int) The number of contracts/shares/lots/units to use as the entry quantity to risk the
specified percentage of equity at the stop-loss level.
calcPositionSizeByStopLossPercent(stopLossPercent, riskPercent, entryPrice)
Calculates the entry quantity required to risk a specified percentage of the strategy's
current equity at a percent-based stop-loss level.
Parameters:
stopLossPercent (float) : (series int/float) The percentage of the `entryPrice` to use as the stop-loss distance.
riskPercent (float) : (series int/float) The percentage of the strategy's equity to risk if a trade moves
`stopLossPercent` of the `entryPrice` in the unfavorable direction.
entryPrice (float) : (series int/float) Optional. The entry price to use in the calculation. The default is
`close`.
Returns: (int) The number of contracts/shares/lots/units to use as the entry quantity to risk the
specified percentage of equity at the stop-loss level.
exitPercent(id, lossPercent, profitPercent, qty, qtyPercent, comment, alertMessage)
A wrapper for the `strategy.exit()` function designed for creating stop-loss and
take-profit orders at percentage distances away from the position's average entry price.
NOTE: This function calls `strategy.exit()` without a `from_entry` ID, so it creates exit
orders for *every* entry in an open position until the position closes. Therefore, using
this function when the strategy has a pyramiding value greater than 1 can lead to
unexpected results. See the "Exits for multiple entries" section of our User Manual's
"Strategies" page to learn more about this behavior.
Parameters:
id (string) : (series string) Optional. The identifier of the stop-loss/take-profit orders, which
corresponds to an exit ID in the strategy's trades after an order fills. The default is
`"Exit"`.
lossPercent (float) : (series int/float) The percentage of the position's average entry price to use as the
stop-loss distance. The function does not create a stop-loss order if the value is `na`.
profitPercent (float) : (series int/float) The percentage of the position's average entry price to use as the
take-profit distance. The function does not create a take-profit order if the value is `na`.
qty (float) : (series int/float) Optional. The number of contracts/lots/shares/units to close when an
exit order fills. If specified, the call uses this value instead of `qtyPercent` to
determine the order size. The exit orders reserve this quantity from the position, meaning
other orders from `strategy.exit()` cannot close this portion until the strategy fills or
cancels those orders. The default is `na`, which means the order size depends on the
`qtyPercent` value.
qtyPercent (float) : (series int/float) Optional. A value between 0 and 100 representing the percentage of the
open trade quantity to close when an exit order fills. The exit orders reserve this
percentage from the open trades, meaning other calls to this command cannot close this
portion until the strategy fills or cancels those orders. The percentage calculation
depends on the total size of the applicable open trades without considering the reserved
amount from other `strategy.exit()` calls. The call ignores this parameter if the `qty`
value is not `na`. The default is 100.
comment (string) : (series string) Optional. Additional notes on the filled order. If the value is specified
and not an empty "string", the Strategy Tester and the chart show this text for the order
instead of the specified `id`. The default is `na`.
alertMessage (string) : (series string) Optional. Custom text for the alert that fires when an order fills. If the
value is specified and not an empty "string", and the "Message" field of the "Create Alert"
dialog box contains the `{{strategy.order.alert_message}}` placeholder, the alert message
replaces the placeholder with this text. The default is `na`.
Returns: (void) The function does not return a usable value.
closeAllAtEndOfSession(comment, alertMessage)
A wrapper for the `strategy.close_all()` function designed to close all open trades with a
market order when the last bar in the current day's session closes. It uses the command's
`immediately` parameter to exit all trades at the last bar's `close` instead of the `open`
of the next session's first bar.
Parameters:
comment (string) : (series string) Optional. Additional notes on the filled order. If the value is specified
and not an empty "string", the Strategy Tester and the chart show this text for the order
instead of the automatically generated exit identifier. The default is `na`.
alertMessage (string) : (series string) Optional. Custom text for the alert that fires when an order fills. If the
value is specified and not an empty "string", and the "Message" field of the "Create Alert"
dialog box contains the `{{strategy.order.alert_message}}` placeholder, the alert message
replaces the placeholder with this text. The default is `na`.
Returns: (void) The function does not return a usable value.
closeAtEndOfSession(entryId, comment, alertMessage)
A wrapper for the `strategy.close()` function designed to close specific open trades with a
market order when the last bar in the current day's session closes. It uses the command's
`immediately` parameter to exit the trades at the last bar's `close` instead of the `open`
of the next session's first bar.
Parameters:
entryId (string)
comment (string) : (series string) Optional. Additional notes on the filled order. If the value is specified
and not an empty "string", the Strategy Tester and the chart show this text for the order
instead of the automatically generated exit identifier. The default is `na`.
alertMessage (string) : (series string) Optional. Custom text for the alert that fires when an order fills. If the
value is specified and not an empty "string", and the "Message" field of the "Create Alert"
dialog box contains the `{{strategy.order.alert_message}}` placeholder, the alert message
replaces the placeholder with this text. The default is `na`.
Returns: (void) The function does not return a usable value.
sortinoRatio(interestRate, forceCalc)
Calculates the Sortino ratio of the strategy based on realized monthly returns.
Parameters:
interestRate (simple float) : (simple int/float) Optional. The *annual* "risk-free" return percentage to compare against
strategy returns. The default is 2, meaning it uses an annual benchmark of 2%.
forceCalc (bool) : (series bool) Optional. A value of `true` forces the function to calculate the ratio on the
current bar. If the value is `false`, the function calculates the ratio only on the latest
available bar for efficiency. The default is `false`.
Returns: (float) The Sortino ratio, which estimates the strategy's excess return per unit of
downside volatility.
sharpeRatio(interestRate, forceCalc)
Calculates the Sharpe ratio of the strategy based on realized monthly returns.
Parameters:
interestRate (simple float) : (simple int/float) Optional. The *annual* "risk-free" return percentage to compare against
strategy returns. The default is 2, meaning it uses an annual benchmark of 2%.
forceCalc (bool) : (series bool) Optional. A value of `true` forces the function to calculate the ratio on the
current bar. If the value is `false`, the function calculates the ratio only on the latest
available bar for efficiency. The default is `false`.
Returns: (float) The Sortino ratio, which estimates the strategy's excess return per unit of
total volatility.
Commission-aware Trade LabelsCommission-aware Trade Labels
Description:
This library provides an easy way to visualize take-profit and stop-loss levels on your chart, taking into account trading commissions. The library calculates and displays the net profit or loss, along with other useful information such as risk/reward ratio, shares, and position size.
Features:
Configurable take-profit and stop-loss prices or percentages.
Set entry amount or shares.
Calculates and displays the risk/reward ratio.
Shows net profit or loss, considering trading commissions.
Customizable label appearance.
Usage:
Add the script to your chart.
Create an Order object for take-profit and stop-loss with desired configurations.
Call target_label() and stop_label() methods for each order object.
Example:
target_order = Order.new(take_profit_price=27483, stop_loss_price=28000, shares=0.2)
stop_order = Order.new(stop_loss_price=29000, shares=1)
target_order.target_label()
stop_order.stop_label()
This script is a powerful tool for visualizing your trading strategy's performance and helps you make better-informed decisions by considering trading commissions in your profit and loss calculations.
Library "tradelabels"
entry_price(this)
Parameters:
this : Order object
@return entry_price
take_profit_price(this)
Parameters:
this : Order object
@return take_profit_price
stop_loss_price(this)
Parameters:
this : Order object
@return stop_loss_price
is_long(this)
Parameters:
this : Order object
@return entry_price
is_short(this)
Parameters:
this : Order object
@return entry_price
percent_to_target(this, target)
Parameters:
this : Order object
target : Target price
@return percent
risk_reward(this)
Parameters:
this : Order object
@return risk_reward_ratio
shares(this)
Parameters:
this : Order object
@return shares
position_size(this)
Parameters:
this : Order object
@return position_size
commission_cost(this, target_price)
Parameters:
this : Order object
@return commission_cost
target_price
net_result(this, target_price)
Parameters:
this : Order object
target_price : The target price to calculate net result for (either take_profit_price or stop_loss_price)
@return net_result
create_take_profit_label(this, prefix, size, offset_x, bg_color, text_color)
Parameters:
this
prefix
size
offset_x
bg_color
text_color
create_stop_loss_label(this, prefix, size, offset_x, bg_color, text_color)
Parameters:
this
prefix
size
offset_x
bg_color
text_color
create_entry_label(this, prefix, size, offset_x, bg_color, text_color)
Parameters:
this
prefix
size
offset_x
bg_color
text_color
create_line(this, target_price, line_color, offset_x, line_style, line_width, draw_entry_line)
Parameters:
this
target_price
line_color
offset_x
line_style
line_width
draw_entry_line
Order
Order
Fields:
entry_price : Entry price
stop_loss_price : Stop loss price
stop_loss_percent : Stop loss percent, default 2%
take_profit_price : Take profit price
take_profit_percent : Take profit percent, default 6%
entry_amount : Entry amount, default 5000$
shares : Shares
commission : Commission, default 0.04%






















