OPEN-SOURCE SCRIPT

PnL Bubble [%] | Fractalyst

67
1. 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.

ảnh chụp nhanh

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


ảnh chụp nhanh

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.


ảnh chụp nhanh

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


ảnh chụp nhanh

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


ảnh chụp nhanh

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.


ảnh chụp nhanh

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:
Pine Script®
// 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:
Pine Script®
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:
Pine Script®
total_obs = pos_count + neg_count + zero_count win_rate = pos_count / total_obs loss_rate = neg_count / total_obs


Expected Value (EV):
Pine Script®
ev_value = (avg_win × win_rate) - (avg_loss × loss_rate)


Payoff Ratio (R):
Pine Script®
R = avg_win ÷ |avg_loss|


Contribution Analysis:
Pine Script®
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:
Pine Script®
//@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[1] 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)

ảnh chụp nhanh

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 [(N-1)*500+1] to [N*500]

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)

ảnh chụp nhanh

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:
Pine Script®
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, "#.#") + "%"


ảnh chụp nhanh

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
Pine Script®
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
Pine Script®
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
Pine Script®
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:
Pine Script®
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


ảnh chụp nhanh

7. Demo Mode & Synthetic Data Generation

When using built-in sources (close, open, etc.), the indicator generates realistic demo trades for testing:

Pine Script®
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

ảnh chụp nhanh

8. Performance Limitations & Optimizations

Display Constraints:
Pine Script®
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

ảnh chụp nhanh

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:
Pine Script®
// 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

ảnh chụp nhanh

10. Advanced Technical Features

Real-Time Animation Engine:
Pine Script®
// 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:
Pine Script®
// 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

ảnh chụp nhanh

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

ảnh chụp nhanh

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

ảnh chụp nhanh

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

Thông báo miễn trừ trách nhiệm

Thông tin và ấn phẩm không có nghĩa là và không cấu thành, tài chính, đầu tư, kinh doanh, hoặc các loại lời khuyên hoặc khuyến nghị khác được cung cấp hoặc xác nhận bởi TradingView. Đọc thêm trong Điều khoản sử dụng.