Cari dalam skrip untuk "北证50+股票+新浪财经"
UO_30-50-70Ultimate Oscillator with bands present at the 30, 50, and 70 pt levels.
Personally use this every time, created a script to hard code these lines so I wouldn't need to redraw them all the time.
Enjoy
The Lazy Trader - Index (ETF) Trend Following Robot50/150 moving average, index (ETF) trend following robot. Coded for people who cannot psychologically handle dollar-cost-averaging through bear markets and extreme drawdowns (although DCA can produce better results eventually), this robot helps you to avoid bear markets. Be a fair-weathered friend of Mr Market, and only take up his offer when the sun is shining! Designed for the lazy trader who really doesn't care...
Recommended Chart Settings:
Asset Class: ETF
Time Frame: Daily
Necessary ETF Macro Conditions:
a) Country must have healthy demographics, good ratio of young > old
b) Country population must be increasing
c) Country must be experiencing price-inflation
Default Robot Settings:
Slow Moving Average: 50 (integer) //adjust to suit your underlying index
Fast Moving Average: 150 (integer) //adjust to suit your underlying index
Bullish Slope Angle: 5 (degrees) //up angle of moving averages
Bearish Slope Angle: -5 (degrees) //down angle of moving averages
Average True Range: 14 (integer) //input for slope-angle formula
Risk: 100 (%) //100% risk means using all equity per trade
ETF Test Results (Default Settings):
SPY (1993 to 2020, 27 years), 332% profit, 20 trades, 6.4 profit factor, 7% drawdown
EWG (1996 to 2020, 24 years), 310% profit, 18 trades, 3.7 profit factor, 10% drawdown
EWH (1996 to 2020, 24 years), 4% loss, 26 trades, 0.9 profit factor, 36% drawdown
QQQ (1999 to 2020, 21 years), 232% profit, 17 trades, 3.6 profit factor, 2% drawdown
EEM (2003 to 2020, 17 years), 73% profit, 17 trades, 1.1 profit factor, 3% drawdown
GXC (2007 to 2020, 13 years), 18% profit, 14 trades, 1.3 profit factor, 26% drawdown
BKF (2009 to 2020, 11 years), 11% profit, 13 trades, 1.2 profit factor, 33% drawdown
A longer time in the markets is better, with the exception of EWH. 6 out of 7 tested ETFs were profitable, feel free to test on your favourite ETF (default settings) and comment below.
Risk Warning:
Not tested on commodities nor other financial products like currencies (code will not work), feel free to leave comments below.
Moving Average Slope Angle Formula:
Reproduced and modified from source:
50-Line Oscillator // (\_/)
// ( •.•)
// (")_(")
25-Line Oscillator
Description:
The 25-Line Oscillator is a sophisticated technical analysis tool designed to visualize market trends through the use of multiple Simple Moving Averages (SMAs). This indicator computes a series of 26 SMAs, incrementally increasing the base length, providing traders with a comprehensive view of price dynamics.
Features:
Customizable Base Length: Adjust the base length of the SMAs according to trading preferences, enhancing versatility for different market conditions.
Rainbow Effect: The indicator employs a visually appealing rainbow color scheme to differentiate between the various trend lines, making it easy to identify crossovers and momentum shifts.
Crossovers Detection: The script includes logic to detect crossover events between consecutive trend lines, which can serve as signals for potential entry or exit points in trading.
Clear Visualization: Suitable for both novice and seasoned traders, the plots enable quick interpretation of trends and market behavior.
How to Use:
Add the indicator to your chart and customize the base length as desired.
Observe the rainbow-colored lines for trend direction.
Look for crossover events between the SMAs as potential trading signals.
Application: This indicator is particularly useful for swing traders and trend followers who aim to capitalize on market momentum and identify reversals. By monitoring the behavior of multiple SMAs, traders can gain insights into the strength and direction of price movements over various time frames.
AK Simple Moving Average 50 days Simple Moving average suitable for Intraday on 1Hr,30Min.15Min Time frames
1. When candle crossing above SMA Line - Go for Long Entries
2. When candle crossing below SMA Line - Go for short Entries
50 SMA / 200 EMA / 128EMA Moving Average CrossFound success using 50SMA vs 200EMA.
128 EMA also charted for it's BTC relevance.
50/100/200 Moving Averages (Pine Script For Copy)by fresca
SCRIPT LANGUAGE
Copy script below and adjust based on your preferences.
-function (change function from "sma" to "ema", "wma" and more)
-length (25 Day, 150 Day or add more averages to the three in this script.)
-color, (red, yellow, etc. or use color hex codes i.e. #FEDA15, #FFAD8F, etc.)
-transparency (set to desired level 1-100)
Or add more options.
RESOURCES
Color hex codes site: www.canva.com
Trading View Pine Script Editor Reference Guide: www.tradingview.com
Taint's Multi Time Frame MA50-100-200 SMA with two 200 EMA's all with the ability choose a time frame for each.
Trade Life Balance Multi EMAThe Trade Life Balance EMA Indicator is a versatile and essential tool for technical analysts and traders. It combines five of the most commonly used Exponential Moving Averages (EMAs) into a single indicator, and additionally offers two optional EMAs for advanced analysis. This indicator helps to quickly identify trend direction, dynamic support and resistance levels, and potential entry and exit points.
Important Note:
Moving averages are lagging indicators, meaning they are based on past price data and do not predict future price movements. For a comprehensive market analysis, it is highly recommended to use the TLB EMA indicator in combination with other analytical tools such as volume, price action, and oscillators.
How the TLB EMA Indicator Works
The indicator plots multiple Exponential Moving Averages directly on the price chart. An EMA is a type of moving average that gives more weight and significance to the most recent price data, making it more responsive to price changes than a Simple Moving Average (SMA).
Default Configuration:
The indicator comes pre-configured with five core EMAs that play a crucial role in many trading strategies:
EMA 13 & 20: Often used as short-term trend indicators. Their slope and the distance to the price can indicate the strength of the current momentum.
EMA 50: Considered an important mid-term trend indicator. A price holding above the 50 EMA often suggests a healthy uptrend.
EMA 100: Serves as a mid- to long-term trend filter.
EMA 200: Widely regarded as the decisive line between a long-term bull and bear market.
The color scheme, ranging from light red (fastest EMA) to dark red (slowest EMA), facilitates quick visual identification.
Customization Options
The TLB EMA indicator is fully customizable to suit individual trading strategies and preferences:
EMA Lengths: All five standard EMAs, as well as the two optional ones, can be set to any desired length in the "Inputs" settings.
Optional EMAs: Two additional EMAs are disabled by default. They can be activated via a checkbox to supplement the analysis with other user-defined periods (e.g., for Fibonacci numbers or specific strategies).
Visual Style: In the "Style" tab of the indicator settings, the color, thickness, and visibility of each individual EMA line can be adjusted as desired.
Advantages of the TLB EMA Indicator
All-in-One Solution: Consolidates the most important EMAs into a single indicator, keeping the chart view clean and eliminating the need to add multiple individual indicators.
High Flexibility: With fully customizable lengths and two optional EMAs, the indicator can be configured for any strategy and any market (stocks, forex, crypto, etc.).
Visual Clarity: The pre-configured color coding allows for an intuitive and quick interpretation of the different trend speeds.
Efficiency: Saves time in chart setup and analysis.
Using the TLB EMA Indicator
The TLB EMA can be used in various ways in trading:
Trend Identification: The simplest application is to determine the overall trend. If the price is above the EMAs (especially the 200), it indicates an uptrend. If it is below, the trend is downward.
Dynamic Support and Resistance: In an uptrend, the EMAs often act as dynamic support zones where the price can bounce. In a downtrend, they serve as dynamic resistance zones.
Crossover Signals: The crossing of EMAs can generate trading signals. A "Golden Cross" (e.g., the 50 EMA crosses above the 200 EMA) is considered a bullish signal, while a "Death Cross" (50 EMA crosses below the 200 EMA) is considered a bearish signal.
Please note that the TLB EMA indicator is a tool for analysis and does not guarantee profitable trades. Always use it in conjunction with a solid risk management strategy.
svm tikole ADX rsi How this works:
ADX checks trend strength. (Above 25 = strong trend)
RSI confirms momentum (above 50 = bullish, below 50 = bearish).
Strong Buy = ADX strong + DI+ > DI– + RSI > 50.
Strong Sell = ADX strong + DI– > DI+ + RSI < 50.
Buy/Sell labels are plotted on chart.
RSI panel included as optional.
👉 This script is error-free and gives clear strong buy/sell signals.
Multi SMA + Golden/Death + Heatmap + BB**Multi SMA (50/100/200) + Golden/Death + Candle Heatmap + BB**
A practical trend toolkit that blends classic 50/100/200 SMAs with clear crossover labels, special 🚀 Golden / 💀 Death Cross markers, and a readable candle heatmap based on a dynamic regression midline and volatility bands. Optional Bollinger Bands are included for context.
* See trend direction at a glance with SMAs.
* Get minimal, de-cluttered labels on important crosses (50↔100, 50↔200, 100↔200).
* Highlight big regime shifts with special Golden/Death tags.
* Read momentum and volatility with the candle heatmap.
* Add Bollinger Bands if you want classic mean-reversion context.
Designed to be lightweight, non-repainting on confirmed bars, and flexible across timeframes.
# What This Indicator Does (plain English)
* **Tracks trend** using **SMA 50/100/200** and lets you optionally compute each SMA on a higher or different timeframe (HTF-safe, no lookahead).
* **Prints labels** when SMAs cross each other (up or down). You can force signals only after bar close to avoid repaint.
* **Marks Golden/Death Crosses** (50 over/under 200) with special labels so major regime changes stand out.
* **Colors candles** with a **heatmap** built from a regression midline and volatility bands—greenish above, reddish below, with a smooth gradient.
* **Optionally shows Bollinger Bands** (basis SMA + stdev bands) and fills the area between them.
* **Includes alert conditions** for Golden and Death Cross so you can automate notifications.
---
# Settings — Simple Explanations
## Source
* **Source**: Price source used to calculate SMAs and Bollinger basis. Default: `close`.
## SMA 50
* **Show 50**: Turn the SMA(50) line on/off.
* **Length 50**: How many bars to average. Lower = faster but noisier.
* **Color 50** / **Width 50**: Visual style.
* **Timeframe 50**: Optional alternate timeframe for SMA(50). Leave empty to use the chart timeframe.
## SMA 100
* **Show 100**: Turn the SMA(100) line on/off.
* **Length 100**: Bars used for the mid-term trend.
* **Color 100** / **Width 100**: Visual style.
* **Timeframe 100**: Optional alternate timeframe for SMA(100).
## SMA 200
* **Show 200**: Turn the SMA(200) line on/off.
* **Length 200**: Bars used for the long-term trend.
* **Color 200** / **Width 200**: Visual style.
* **Timeframe 200**: Optional alternate timeframe for SMA(200).
## Signals (crossover labels)
* **Show crossover signals**: Prints triangle labels on SMA crosses (50↔100, 50↔200, 100↔200).
* **Wait for bar close (confirmed)**: If ON, signals only appear after the candle closes (reduces repaint).
* **Min bars between same-pair signals**: Minimum spacing to avoid duplicate labels from the same SMA pair too often.
* **Trend filter (buy: 50>100>200, sell: 50<100<200)**: Only show bullish labels when SMAs are stacked bullish (50 above 100 above 200), and only show bearish labels when stacked bearish.
### Label Offset
* **Offset mode**: Choose how to push labels away from price:
* **Percent**: Offset is a % of price.
* **ATR x**: Offset is ATR(14) × multiplier.
* **Percent of price (%)**: Used when mode = Percent.
* **ATR multiplier (for ‘ATR x’)**: Used when mode = ATR x.
### Label Colors
* **Bull color** / **Bear color**: Background of triangle labels.
* **Bull label text color** / **Bear label text color**: Text color inside the triangles.
## Golden / Death Cross
* **Show 🚀 Golden Cross (50↑200)**: Show a special “Golden” label when SMA50 crosses above SMA200.
* **Golden label color** / **Golden text color**: Styling for Golden label.
* **Show 💀 Death Cross (50↓200)**: Show a special “Death” label when SMA50 crosses below SMA200.
* **Death label color** / **Death text color**: Styling for Death label.
## Candle Heatmap
* **Enable heatmap candle colors**: Turns the heatmap on/off.
* **Length**: Lookback for the regression midline and volatility measure.
* **Deviation Multiplier**: Band width around the midline (bigger = wider).
* **Volatility basis**:
* **RMA Range** (smoothed high-low range)
* **Stdev** (standard deviation of close)
* **Upper/Middle/Lower color**: Gradient colors for the heatmap.
* **Heatmap transparency (0..100)**: 0 = solid, 100 = invisible.
* **Force override base candles**: Repaint base candles so heatmap stays visible even if your chart has custom coloring.
## Bollinger Bands (optional)
* **Show Bollinger Bands**: Toggle the overlay on/off.
* **Length**: Basis SMA length.
* **StdDev Multiplier**: Distance of bands from the basis in standard deviations.
* **Basis color** / **Band color**: Line colors for basis and bands.
* **Bands fill transparency**: Opacity of the fill between upper/lower bands.
---
# Features & How It Works
## 1) HTF-Safe SMAs
Each SMA can be calculated on the chart timeframe or a higher/different timeframe you choose. The script pulls HTF values **without lookahead** (non-repainting on confirmed bars).
## 2) Crossover Labels (Three Pairs)
* **50↔100**, **50↔200**, **100↔200**:
* **Triangle Up** label when the first SMA crosses **above** the second.
* **Triangle Down** label when it crosses **below**.
* Optional **Trend Filter** ensures only signals aligned with the overall stack (50>100>200 for bullish, 50<100<200 for bearish).
* **Debounce** spacing avoids repeated labels for the same pair too close together.
## 3) Golden / Death Cross Highlights
* **🚀 Golden Cross**: SMA50 crosses **above** SMA200 (often a longer-term bullish regime shift).
* **💀 Death Cross**: SMA50 crosses **below** SMA200 (often a longer-term bearish regime shift).
* Separate styling so they stand out from regular cross labels.
## 4) Candle Heatmap
* Builds a **regression midline** with **volatility bands**; colors candles by their position inside that channel.
* Smooth gradient: lower side → reddish, mid → yellowish, upper side → greenish.
* Helps you see momentum and “where price sits” relative to a dynamic channel.
## 5) Bollinger Bands (Optional)
* Classic **basis SMA** ± **StdDev** bands.
* Light visual context for mean-reversion and volatility expansion.
## 6) Alerts
* **Golden Cross**: `🚀 GOLDEN CROSS: SMA 50 crossed ABOVE SMA 200`
* **Death Cross**: `💀 DEATH CROSS: SMA 50 crossed BELOW SMA 200`
Add these to your alerts to get notified automatically.
---
# Tips & Notes
* For fewer false positives, keep **“Wait for bar close”** ON, especially on lower timeframes.
* Use the **Trend Filter** to align signals with the broader stack and cut noise.
* For HTF context, set **Timeframe 50/100/200** to higher frames (e.g., H1/H4/D) while you trade on a lower frame.
* Heatmap “Length” and “Deviation Multiplier” control smoothness and channel width—tune for your asset’s volatility.
DTC Intra+DTC Intra+
Complete Indian Intraday Trading Indicator
What This Indicator Does:
DTC Intra+ is a comprehensive intraday trading indicator designed specifically for Indian markets. It provides real-time session analysis, volume profiling, and technical insights that work consistently across all timeframes.
Key Features:
Multi-Timeframe Data Consistency
Solves the common problem where indicators show different values on different timeframes
Gap percentage, ADR (Average Daily Range), and Burst values remain consistent whether viewing 1-minute or daily charts
Uses proprietary algorithms to fetch daily data and apply it accurately to intraday calculations
Intelligent Session Detection
Automatically detects and displays three Indian market sessions: Morning (9:15-11:00 AM), Mid-Day (11:00-1:30 PM), Afternoon (1:30-3:30 PM)
Creates visual session boxes that extend dynamically and finalize at session boundaries
Each session maintains distinct colors and labels for easy identification
Advanced Volume Analysis
Calculates Relative Volume (RVol) using 21-period moving average for volume strength assessment
Colors candles based on volume strength: high/moderate bullish and bearish volume patterns
Customizable volume thresholds (150% and 200% of average volume) for precise signal generation
Pattern Recognition System
Identifies mini-coil consolidation patterns with customizable styling options
Maintains visual persistence across timeframes and chart updates
Configurable lookback periods and pattern validation algorithms
Technical Analysis Tools
Four customizable Moving Averages (10, 20, 50, 200) with multiple calculation types (SMA, EMA, WMA, HMA)
VWAP integration with theme-adaptive styling
Gap analysis with customizable thresholds (1% and 2%+) and visual alerts
Theme-Adaptive Interface
Automatically detects and adapts to dark or light chart themes
Professional color schemes optimized for both theme types
Customizable transparency and styling for all visual elements
Information Dashboard
Dynamic information table displaying Gap %, RVol, ADR, Burst, Sector, Industry, Theme, and Session data
Real-time sector and industry classification from TradingView data
Burst Ranker with descriptive labels (GREAT, GOOD, LOW) based on historical performance analysis
How It Works:
Session Management:
The indicator uses time-based detection algorithms to identify Indian market sessions, creating visual boxes that extend dynamically and finalize at session boundaries. Each session maintains its own color scheme and label system.
Data Consistency Engine:
Proprietary cross-timeframe calculation system ensures that daily metrics display consistently across all timeframes by fetching daily data and applying it to intraday calculations.
Volume Profiling:
Custom volume analysis algorithms calculate relative volume strength and apply color coding to candles based on volume thresholds and price direction, providing immediate visual feedback on market activity.
Pattern Detection:
Advanced consolidation pattern recognition system that identifies mini-coil formations using customizable parameters and maintains visual persistence across chart updates.
How To Use:
Apply to any Indian stock chart (BSE, NSDL) on intraday timeframes
Session times are pre-configured for Indian markets but can be customized
Moving Averages can be adjusted to your preferred lengths and calculation types
Volume thresholds can be modified based on your trading strategy
Monitor the information panel for real-time market insights
Use session boxes to identify optimal trading windows
Who This Is For:
Indian intraday traders seeking comprehensive market analysis
Traders who need consistent data across multiple timeframes
Volume-based traders requiring real-time volume strength analysis
Technical analysts needing session-based market structure insights
Busy professionals who want market insights without constant chart monitoring
What Makes It Unique:
Unlike basic session indicators, DTC Intra+ provides cross-timeframe data consistency, advanced volume profiling, and comprehensive Indian market analysis in a single, theme-adaptive interface. The proprietary algorithms ensure accurate daily metrics on intraday charts, making it essential for serious Indian market traders who need reliable, consistent data across all timeframes.
The Bottom Line:
This indicator transforms how you view Indian intraday markets by providing consistent, reliable data across all timeframes while offering advanced session analysis, volume profiling, and pattern recognition. It's designed specifically for Indian market characteristics and trading patterns, giving you the tools to trade with confidence and precision.
PnL Bubble [%] | Fractalyst1. What's the indicator purpose?
The PnL Bubble indicator transforms your strategy's trade PnL percentages into an interactive bubble chart with professional-grade statistics and performance analytics. It helps traders quickly assess system profitability, understand win/loss distribution patterns, identify outliers, and make data-driven strategy improvements.
How does it work?
Think of this indicator as a visual report card for your trading performance. Here's what it does:
What You See
Colorful Bubbles: Each bubble represents one of your trades
Blue/Cyan bubbles = Winning trades (you made money)
Red bubbles = Losing trades (you lost money)
Bigger bubbles = Bigger wins or losses
Smaller bubbles = Smaller wins or losses
How It Organizes Your Trades:
Like a Photo Album: Instead of showing all your trades at once (which would be messy), it shows them in "pages" of 500 trades each:
Page 1: Your first 500 trades
Page 2: Trades 501-1000
Page 3: Trades 1001-1500, etc.
What the Numbers Tell You:
Average Win: How much money you typically make on winning trades
Average Loss: How much money you typically lose on losing trades
Expected Value (EV): Whether your trading system makes money over time
Positive EV = Your system is profitable long-term
Negative EV = Your system loses money long-term
Payoff Ratio (R): How your average win compares to your average loss
R > 1 = Your wins are bigger than your losses
R < 1 = Your losses are bigger than your wins
Why This Matters:
At a Glance: You can instantly see if you're a profitable trader or not
Pattern Recognition: Spot if you have more big wins than big losses
Performance Tracking: Watch how your trading improves over time
Realistic Expectations: Understand what "average" performance looks like for your system
The Cool Visual Effects:
Animation: The bubbles glow and shimmer to make the chart more engaging
Highlighting: Your biggest wins and losses get extra attention with special effects
Tooltips: hover any bubble to see details about that specific trade.
What are the underlying calculations?
The indicator processes trade PnL data using a dual-matrix architecture for optimal performance:
Dual-Matrix System:
• Display Matrix (display_matrix): Bounded to 500 trades for rendering performance
• Statistics Matrix (stats_matrix): Unbounded storage for complete statistical accuracy
Trade Classification & Aggregation:
// Separate wins, losses, and break-even trades
if val > 0.0
pos_sum += val // Sum winning trades
pos_count += 1 // Count winning trades
else if val < 0.0
neg_sum += val // Sum losing trades
neg_count += 1 // Count losing trades
else
zero_count += 1 // Count break-even trades
Statistical Averages:
avg_win = pos_count > 0 ? pos_sum / pos_count : na
avg_loss = neg_count > 0 ? math.abs(neg_sum) / neg_count : na
Win/Loss Rates:
total_obs = pos_count + neg_count + zero_count
win_rate = pos_count / total_obs
loss_rate = neg_count / total_obs
Expected Value (EV):
ev_value = (avg_win × win_rate) - (avg_loss × loss_rate)
Payoff Ratio (R):
R = avg_win ÷ |avg_loss|
Contribution Analysis:
ev_pos_contrib = avg_win × win_rate // Positive EV contribution
ev_neg_contrib = avg_loss × loss_rate // Negative EV contribution
How to integrate with any trading strategy?
Equity Change Tracking Method:
//@version=6
strategy("Your Strategy with Equity Change Export", overlay=true)
float prev_trade_equity = na
float equity_change_pct = na
if barstate.isconfirmed and na(prev_trade_equity)
prev_trade_equity := strategy.equity
trade_just_closed = strategy.closedtrades != strategy.closedtrades
if trade_just_closed and not na(prev_trade_equity)
current_equity = strategy.equity
equity_change_pct := ((current_equity - prev_trade_equity) / prev_trade_equity) * 100
prev_trade_equity := current_equity
else
equity_change_pct := na
plot(equity_change_pct, "Equity Change %", display=display.data_window)
Integration Steps:
1. Add equity tracking code to your strategy
2. Load both strategy and PnL Bubble indicator on the same chart
3. In bubble indicator settings, select your strategy's equity tracking output as data source
4. Configure visualization preferences (colors, effects, page navigation)
How does the pagination system work?
The indicator uses an intelligent pagination system to handle large trade datasets efficiently:
Page Organization:
• Page 1: Trades 1-500 (most recent)
• Page 2: Trades 501-1000
• Page 3: Trades 1001-1500
• Page N: Trades to
Example: With 1,500 trades total (3 pages available):
• User selects Page 1: Shows trades 1-500
• User selects Page 4: Automatically falls back to Page 3 (trades 1001-1500)
5. Understanding the Visual Elements
Bubble Visualization:
• Color Coding: Cyan/blue gradients for wins, red gradients for losses
• Size Mapping: Bubble size proportional to trade magnitude (larger = bigger P&L)
• Priority Rendering: Largest trades displayed first to ensure visibility
• Gradient Effects: Color intensity increases with trade magnitude within each category
Interactive Tooltips:
Each bubble displays quantitative trade information:
tooltip_text = outcome + " | PnL: " + pnl_str +
"\nDate: " + date_str + " " + time_str +
"\nTrade #" + str.tostring(trade_number) + " (Page " + str.tostring(active_page) + ")" +
"\nRank: " + str.tostring(rank) + " of " + str.tostring(n_display_rows) +
"\nPercentile: " + str.tostring(percentile, "#.#") + "%" +
"\nMagnitude: " + str.tostring(magnitude_pct, "#.#") + "%"
Example Tooltip:
Win | PnL: +2.45%
Date: 2024.03.15 14:30
Trade #1,247 (Page 3)
Rank: 5 of 347
Percentile: 98.6%
Magnitude: 85.2%
Reference Lines & Statistics:
• Average Win Line: Horizontal reference showing typical winning trade size
• Average Loss Line: Horizontal reference showing typical losing trade size
• Zero Line: Threshold separating wins from losses
• Statistical Labels: EV, R-Ratio, and contribution analysis displayed on chart
What do the statistical metrics mean?
Expected Value (EV):
Represents the mathematical expectation per trade in percentage terms
EV = (Average Win × Win Rate) - (Average Loss × Loss Rate)
Interpretation:
• EV > 0: Profitable system with positive mathematical expectation
• EV = 0: Break-even system, profitability depends on execution
• EV < 0: Unprofitable system with negative mathematical expectation
Example: EV = +0.34% means you expect +0.34% profit per trade on average
Payoff Ratio (R):
Quantifies the risk-reward relationship of your trading system
R = Average Win ÷ |Average Loss|
Interpretation:
• R > 1.0: Wins are larger than losses on average (favorable risk-reward)
• R = 1.0: Wins and losses are equal in magnitude
• R < 1.0: Losses are larger than wins on average (unfavorable risk-reward)
Example: R = 1.5 means your average win is 50% larger than your average loss
Contribution Analysis (Σ):
Breaks down the components of expected value
Positive Contribution (Σ+) = Average Win × Win Rate
Negative Contribution (Σ-) = Average Loss × Loss Rate
Purpose:
• Shows how much wins contribute to overall expectancy
• Shows how much losses detract from overall expectancy
• Net EV = Σ+ - Σ- (Expected Value per trade)
Example: Σ+: 1.23% means wins contribute +1.23% to expectancy
Example: Σ-: -0.89% means losses drag expectancy by -0.89%
Win/Loss Rates:
Win Rate = Count(Wins) ÷ Total Trades
Loss Rate = Count(Losses) ÷ Total Trades
Shows the probability of winning vs losing trades
Higher win rates don't guarantee profitability if average losses exceed average wins
7. Demo Mode & Synthetic Data Generation
When using built-in sources (close, open, etc.), the indicator generates realistic demo trades for testing:
if isBuiltInSource(source_data)
// Generate random trade outcomes with realistic distribution
u_sign = prand(float(time), float(bar_index))
if u_sign < 0.5
v_push := -1.0 // Loss trade
else
// Skewed distribution favoring smaller wins (realistic)
u_mag = prand(float(time) + 9876.543, float(bar_index) + 321.0)
k = 8.0 // Skewness factor
t = math.pow(u_mag, k)
v_push := 2.5 + t * 8.0 // Win trade
Demo Characteristics:
• Realistic win/loss distribution mimicking actual trading patterns
• Skewed distribution favoring smaller wins over large wins
• Deterministic randomness for consistent demo results
• Includes jitter effects to prevent visual overlap
8. Performance Limitations & Optimizations
Display Constraints:
points_count = 500 // Maximum 500 dots per page for optimal performance
Pine Script v6 Limits:
• Label Count: Maximum 500 labels per indicator
• Line Count: Maximum 100 lines per indicator
• Box Count: Maximum 50 boxes per indicator
• Matrix Size: Efficient memory management with dual-matrix system
Optimization Strategies:
• Pagination System: Handle unlimited trades through 500-trade pages
• Priority Rendering: Largest trades displayed first for maximum visibility
• Dual-Matrix Architecture: Separate display (bounded) from statistics (unbounded)
• Smart Fallback: Automatic page clamping prevents empty displays
Impact & Workarounds:
• Visual Limitation: Only 500 trades visible per page
• Statistical Accuracy: Complete dataset used for all calculations
• Navigation: Use page input to browse through entire trade history
• Performance: Smooth operation even with thousands of trades
9. Statistical Accuracy Guarantees
Data Integrity:
• Complete Dataset: Statistics matrix stores ALL trades without limit
• Proper Aggregation: Separate tracking of wins, losses, and break-even trades
• Mathematical Precision: Pine Script v6's enhanced floating-point calculations
• Dual-Matrix System: Display limitations don't affect statistical accuracy
Calculation Validation:
// Verified formulas match standard trading mathematics
avg_win = pos_sum / pos_count // Standard average calculation
win_rate = pos_count / total_obs // Standard probability calculation
ev_value = (avg_win * win_rate) - (avg_loss * loss_rate) // Standard EV formula
Accuracy Features:
• Mathematical Correctness: Formulas follow established trading statistics
• Data Preservation: Complete dataset maintained for all calculations
• Precision Handling: Proper rounding and boundary condition management
• Real-Time Updates: Statistics recalculated on every new trade
10. Advanced Technical Features
Real-Time Animation Engine:
// Shimmer effects with sine wave modulation
offset = math.sin(shimmer_t + phase) * amp
// Dynamic transparency with organic flicker
new_transp = math.min(flicker_limit, math.max(-flicker_limit, cur_transp + dir * flicker_step))
• Sine Wave Shimmer: Dynamic glowing effects on bubbles
• Organic Flicker: Random transparency variations for natural feel
• Extreme Value Highlighting: Special visual treatment for outliers
• Smooth Animations: Tick-based updates for fluid motion
Magnitude-Based Priority Rendering:
// Sort trades by magnitude for optimal visual hierarchy
sort_indices_by_magnitude(values_mat)
• Largest First: Most important trades always visible
• Intelligent Sorting: Custom bubble sort algorithm for trade prioritization
• Performance Optimized: Efficient sorting for real-time updates
• Visual Hierarchy: Ensures critical trades never get hidden
Professional Tooltip System:
• Quantitative Data: Pure numerical information without interpretative language
• Contextual Ranking: Shows trade position within page dataset
• Percentile Analysis: Performance ranking as percentage
• Magnitude Scaling: Relative size compared to page maximum
• Professional Format: Clean, data-focused presentation
11. Quick Start Guide
Step 1: Add Indicator
• Search for "PnL Bubble | Fractalyst" in TradingView indicators
• Add to your chart (works on any timeframe)
Step 2: Configure Data Source
• Demo Mode: Leave source as "close" to see synthetic trading data
• Strategy Mode: Select your strategy's PnL% output as data source
Step 3: Customize Visualization
• Colors: Set positive (cyan), negative (red), and neutral colors
• Page Navigation: Use "Trade Page" input to browse trade history
• Visual Effects: Built-in shimmer and animation effects are enabled by default
Step 4: Analyze Performance
• Study bubble patterns for win/loss distribution
• Review statistical metrics: EV, R-Ratio, Win Rate
• Use tooltips for detailed trade analysis
• Navigate pages to explore full trade history
Step 5: Optimize Strategy
• Identify outlier trades (largest bubbles)
• Analyze risk-reward profile through R-Ratio
• Monitor Expected Value for system profitability
• Use contribution analysis to understand win/loss impact
12. Why Choose PnL Bubble Indicator?
Unique Advantages:
• Advanced Pagination: Handle unlimited trades with smart fallback system
• Dual-Matrix Architecture: Perfect balance of performance and accuracy
• Professional Statistics: Institution-grade metrics with complete data integrity
• Real-Time Animation: Dynamic visual effects for engaging analysis
• Quantitative Tooltips: Pure numerical data without subjective interpretations
• Priority Rendering: Intelligent magnitude-based display ensures critical trades are always visible
Technical Excellence:
• Built with Pine Script v6 for maximum performance and modern features
• Optimized algorithms for smooth operation with large datasets
• Complete statistical accuracy despite display optimizations
• Professional-grade calculations matching institutional trading analytics
Practical Benefits:
• Instantly identify system profitability through visual patterns
• Spot outlier trades and risk management issues
• Understand true risk-reward profile of your strategies
• Make data-driven decisions for strategy optimization
• Professional presentation suitable for performance reporting
Disclaimer & Risk Considerations:
Important: Historical performance metrics, including positive Expected Value (EV), do not guarantee future trading success. Statistical measures are derived from finite sample data and subject to inherent limitations:
• Sample Bias: Historical data may not represent future market conditions or regime changes
• Ergodicity Assumption: Markets are non-stationary; past statistical relationships may break down
• Survivorship Bias: Strategies showing positive historical EV may fail during different market cycles
• Parameter Instability: Optimal parameters identified in backtesting often degrade in forward testing
• Transaction Cost Evolution: Slippage, spreads, and commission structures change over time
• Behavioral Factors: Live trading introduces psychological elements absent in backtesting
• Black Swan Events: Extreme market events can invalidate statistical assumptions instantaneously