INVITE-ONLY SCRIPT
Atualizado

Quantify [Trading Model] | Fractalyst

267
Note: In this description, "TM" refers to Trading Model (not trademark) and "EM" refers to Entry Model

What’s the indicator’s purpose and functionality?

You know how to identify market bias but always struggle with figuring out the best exit method, or even hesitating to take your trades?

I've been there. That's why I built this solution—once and for all—to help traders who know the market bias but need a systematic and quantitative approach for their entries and trade management.

A model that shows you real-time market probabilities and insights, so you can focus on execution with confidence—not doubt or FOMO.

snapshot

How does this Quantify [Trading Model] differentiate from Quantify [Entry Model]?
Have you managed to code or even found an indicator that identifies the market bias for you, so you don’t have to manually spend time analyzing the market and trend?

Then that’s exactly why you might need the Quantify Trading Model.

With the Trading Model (TM) version, the script automatically uses your given bias identification method to determine the trend (bull vs bear and neutral), detect the bias, and provide instant insight into the trades you could’ve taken.

To avoid complications from consecutive signals, it uses a kNN machine learning algorithm that processes market structure and probabilities to predict the best future patterns.

(You don’t have to deal with any complexity—it’s all taken care of for you.)

Quantify TM uses the k-Nearest Neighbors (kNN) machine learning algorithm to learn from historical market patterns and adapt to changing market structures. This means it can recognize similar market conditions from the past and apply those lessons to current trading decisions.

On the other hand, Quantify EM requires you to manually select your directional bias. It then focuses solely on generating entry signals based on that pre-determined bias.

snapshot

While the entry model version (EM) uses your manual bias selection to determine the trend, it then provides insights into trades you could’ve taken and should be taking.

Trading Model (TM)

- Uses `input.source()` to incorporate your personal methodology for identifying market bias

- Automates everything—from bias detection to entry and exit decisions

- Adapts to market bias changes through kNN machine learning optimization

- Reduces human intervention in trading decisions, limiting emotional interference


Entry Model (EM)

- Focuses specifically on optimizing entry points within your pre-selected directional bias

- Requires manual input for determining market bias

- Provides entry signals without automating alerts or bias rules

Can the indicator be applied to any market approach/trading strategy?

Yes, if you have clear rules for identifying the market bias, then you can code your bias detection and then use the input.source() user input to retrieve the direction from your own indicator, then the Quantify [TM] uses machine-learning identify the best setups for you.

Here's an example:

Pine Script®
//@version=6
indicator('Moving Averages Bias', overlay = true)

// Input lengths for moving averages
ma10_length = input.int(10, title = 'MA 10 Length')
ma20_length = input.int(20, title = 'MA 20 Length')
ma50_length = input.int(50, title = 'MA 50 Length')

// Calculate moving averages
ma10 = ta.sma(close, ma10_length)
ma20 = ta.sma(close, ma20_length)
ma50 = ta.sma(close, ma50_length)

// Identify bias
var bias = 0
if close > ma10 and close > ma20 and close > ma50 and ma10 > ma20 and ma20 > ma50
    bias := 1 // Bullish
    bias
else if close < ma10 and close < ma20 and close < ma50 and ma10 < ma20 and ma20 < ma50
    bias := -1 // Bearish
    bias
else
    bias := 0 // Neutral
    bias

// Plot the bias
plot(bias, title = 'Identified Bias', color = color.blue,display = display.none)


Once you've created your custom bias indicator, you can integrate it with Quantify [TM]:

- Add your bias indicator to your chart
- Open the Quantify settings
- Set the Bias option to "Auto"
- Select your custom indicator as the bias source

The machine learning algorithms will then analyze historical price action and identify optimal setups based on your defined bias parameters. Performance statistics are displayed in summary tables, allowing you to evaluate effectiveness across different timeframes.

snapshot

Can the indicator be used for different timeframes or trading styles?

Yes, regardless of the timeframe you’d like to take your entries, the indicator adapts to your trading style.

snapshot

Whether you’re a swing trader, scalper, or even a position trader, the algorithm dynamically evaluates market conditions across your chosen timeframe.

How Quantify [TM] Helps You Trade Profitably?
The Quantify Trading Model offers several powerful features that can significantly improve your trading profitability when used correctly:

Real-Time Edge Assessment
It displays real-time probability of price moving in your favor versus hitting your stoploss
This gives you immediate insight into risk/reward dynamics before entering trades
You can make more informed decisions by knowing the statistical likelihood of success

Historical Edge Validation
Instantly shows whether your trading approach has demonstrated an edge in historical data
Prevents you from trading setups that historically haven't performed well
Gives confidence when entering trades that have proven statistical advantages

Optimized Position Sizing
Analyzes each setup's success rate to determine the adjusted Kelly criterion formula
Customizes position sizing based on your selected maximum drawdown tolerance
Helps prevent account-destroying losses while maximizing growth potential

Advanced Exit Management
Utilizes market structure-based trailing stop-loss mechanisms
Maximizes the average risk-reward ratio profit per winning trade
Helps capture larger moves while protecting gains during market reversals

Emotional Discipline Enforcement
Eliminates emotional bias by adhering to your pre-defined rules for market direction
Prevents impulsive decisions by providing objective entry and exit signals
Creates psychological distance between your emotions and trading decisions

Overtrading Prevention
Highlights only setups that demonstrate positive expectancy
Reduces frequency of low-probability trades
Conserves capital for higher-quality opportunities

Systematic Approach Benefits
By combining machine learning algorithms with your personal bias identification methods, Quantify helps transform discretionary trading approaches into more systematic, probability-based strategies.

What Entry Models are used in Quantify Trading Model version?
The Quantify Trading Model utilizes two primary entry models to identify high-probability trade setups:

Breakout Entry Model
- Identifies potential trade entries when price breaks through significant swing highs and swing lows
- Captures momentum as price moves beyond established trading ranges
- Particularly effective in trending markets when combined with the appropriate bias detection
- Optimized by machine learning to filter false breakouts based on historical performance

snapshot

Fractals Entry Model
- Utilizes fractal patterns to identify potential reversal or continuation points
- Also uses swing levels to determine optimal entry locations
- Based on the concept that market structure repeats across different timeframes
- Identifies local highs and lows that form natural entry points
- Enhanced by machine learning to recognize the most profitable fractal formations

snapshot

- These entry models work in conjunction with your custom bias indicator to ensure trades are taken in the direction of the overall market trend. The machine learning component analyzes historical performance of these entry types across different market conditions to optimize entry timing and signal quality.

How Does This Indicator Identify Market Structure?

1. Swing Detection
• The indicator identifies key swing points on the chart. These are local highs or lows where the price reverses direction, forming the foundation of market structure.

2. Structural Break Validation
• A structural break is flagged when a candle closes above a previous swing high (bullish) or below a previous swing low (bearish).

• Break Confirmation Process:
To confirm the break, the indicator applies the following rules:
• Valid Swing Preceding the Break: There must be at least one valid swing point before the break.

3. Numeric Labeling
• Each confirmed structural break is assigned a unique numeric ID starting from 1.
• This helps traders track breaks sequentially and analyze how the market structure evolves over time.

4. Liquidity and Invalidation Zones
• For every confirmed structural break, the indicator highlights two critical zones:
1. Liquidity Zone (LIQ): Represents the structural liquidity level.
2. Invalidation Zone (INV): Acts as Invalidation point if the structure fails to hold.

snapshot

How does the trailing stop-loss work? what are the underlying calculations?

A trailing stoploss is a dynamic risk management tool that moves with the price as the market trend continues in the trader’s favor. Unlike a fixed take profit, which stays at a set level, the trailing stoploss automatically adjusts itself as the market moves, locking in profits as the price advances.

snapshot

In Quantify, the trailing stoploss is enhanced by incorporating market structure liquidity levels (explain above). This ensures that the stoploss adjusts intelligently based on key price levels, allowing the trader to stay in the trade as long as the trend remains intact, while also protecting profits if the market reverses.

What is the Kelly Criterion, and how does it work in Quantify?

The Kelly Criterion is a mathematical formula used to determine the optimal position size for each trade, maximizing long-term growth while minimizing the risk of large drawdowns. It calculates the percentage of your portfolio to risk on a trade based on the probability of winning and the expected payoff.

Quantify integrates this with user-defined inputs to dynamically calculate the most effective position size in percentage, aligning with the trader’s risk tolerance and desired exposure.

How does Quantify use the Kelly Criterion in practice?

Quantify uses the Kelly Criterion to optimize position sizing based on the following factors:
1. Confidence Level: The model assesses the confidence level in the trade setup based on historical data and sample size. A higher confidence level increases the suggested position size because the trade has a higher probability of success.

2. Max Allowed Drawdown (User-Defined): Traders can set their preferred maximum allowed drawdown, which dictates how much loss is acceptable before reducing position size or stopping trading. Quantify uses this input to ensure that risk exposure aligns with the trader’s risk tolerance.

3. Probabilities: Quantify calculates the probabilities of success for each trade setup. The higher the probability of a successful trade (based on historical price action and liquidity levels), the larger the position size suggested by the Kelly Criterion.

How can I get started to use the indicator?

1. Set Your Market Bias
• Choose Auto.
• Select the source you want Quantify to use as for bias identification method (explained above)

snapshot

2. Choose Your Entry Timeframes
• Specify the timeframes you want to focus on for trade entries.
• The indicator will dynamically analyze these timeframes to provide optimal setups.

snapshot

3. Choose Your Entry Model and BE/TP Levels
• Choose a model that suits your personality
• Choose a level where you'd like the script to take profit or move stop-loss to BE

snapshot

4. Set and activate the alerts

snapshot

What tables are used in the Quantify?

• Quarterly

snapshot

• Monthly

snapshot

• Weekly

snapshot

Terms and Conditions | Disclaimer

Our charting tools are provided for informational and educational purposes only and should not be construed as financial, investment, or trading advice. They are not intended to forecast market movements or offer specific recommendations. Users should understand that past performance does not guarantee future results and should not base financial decisions solely on historical data.

Built-in components, features, and functionalities of our charting tools are the intellectual property of Fractalyst Unauthorized use, reproduction, or distribution of these proprietary elements is prohibited.

- By continuing to use our charting tools, the user acknowledges and accepts the Terms and Conditions outlined in this legal disclaimer and agrees to respect our intellectual property rights and comply with all applicable laws and regulations.
Notas de Lançamento
Enhanced
Improved multi-timeframe table colorization logic that highlights the most profitable timeframes based on profit factor, enabling faster identification of optimal trading setups.

snapshot
Notas de Lançamento
- Streamlined User Interface: Completely redesigned the user flow to remove subjective decision points, resulting in a more consistent experience.

- Automated Machine Learning: The script now automatically adjusts machine learning parameters based on usage patterns, eliminating the need for manual configuration.
Improvements

- Enhanced Kelly Criterion: Refined the Kelly criterion calculation for more accurate position sizing and improved risk management.

snapshot
Notas de Lançamento
- Minor improvement and bug fixes
Notas de Lançamento
- Added detailed and visually formatted tooltips for all major input categories.

- Tooltips now include additional notes and tips to improve usability and provide guidance for traders on selecting optimal settings.
Notas de Lançamento
New Features
- Auto Level Detection: Added "Auto" option in level detection functionality. The script now intelligently determines the optimal or trailing stoploss method based on market conditions.

- Daily PnL Table: Implemented a new daily table showing Risk-Reward PnL comparison between current and previous week. Helps traders track performance improvements over time.

Improvements
- Enhanced models performance by optimizing calculation method

snapshot
Notas de Lançamento
- Fixed an issue with breakout entries
Notas de Lançamento
- Fixed a visual bug with entries
Notas de Lançamento
- Added manual bull/bear bias selection for custom bias integration
Notas de Lançamento
- Enhanced Backtesting Table: Implemented comprehensive quantitative metrics to provide deeper insights into strategy performance:

- Profit Factor: Ratio of gross profits to gross losses, measuring the system's profitability efficiency.

- Expectancy: Represents the average expected profit per trade.

- Win/Loss Statistics: Detailed breakdown of wins, losses, and break-even percentages, along with maximum consecutive wins/losses to evaluate strategy consistency.

- Drawdown Metrics: Added Maximum Drawdown (largest peak-to-trough decline) and Average Drawdown measurements to better assess risk exposure.

- Sharpe Ratio: Risk-adjusted return metric that compares profitability against volatility, with higher values indicating better risk-adjusted performance.

- Ulcer Index: Measures the depth and duration of drawdowns, focusing on downside volatility. Lower values indicate less painful drawdowns and faster recovery periods.

- MAE/MFE: Maximum Adverse Excursion/Maximum Favorable Excursion analysis to show how far trades move against or in favor before closing, helping optimize entry/exit timing.

- Risk of Ruin (RoR): Calculates the probability of losing your entire trading capital or reaching a point where continued trading becomes impossible.

- Duration Analysis: Average trade duration statistics to help traders understand typical holding periods for different market conditions.

- Aggressive Trailing Stop-Loss: Implemented a new trailing stop-loss algorithm specifically optimized for forex markets:
- Dynamically adjusts based on market volatility
- Helps capture larger portions of trends while protecting profits
- Configurable sensitivity settings

Improved
- Performance Optimization: Refactored code logic for significantly faster calculations:
- Reduced memory usage by 30%
- Decreased indicator loading time on large datasets
- Optimized loop structures for better performance on historical data analysis

snapshot
Notas de Lançamento
- Improved alerts
Notas de Lançamento
- Improved script calculation logic for smoother user experience
Notas de Lançamento
## Pyramiding (Position Stacking) Enhancement

**Major Feature Addition: Pyramiding Trades**
- Compounding Performance Calculations
- Completely revamped performance metrics to calculate based on compounding effects rather than R-multiples for more realistic performance measurement
- Added support for pyramiding (position stacking) that allows adding positions after the initial trade's stop-loss has moved to breakeven
- Implemented user toggleable pyramiding with "ON/OFF" setting via user interface
- Added maximum pyramid entries control (currently supports 1 additional position)
- Created pyramid entry detection logic that automatically triggers when stop-loss moves to breakeven
- Implemented separate risk calculation for pyramid entries to maintain consistent risk management
- Added visual indicators and alerts for pyramid entries on the chart
- Integrated pyramid position management with existing trailing stop mechanism

snapshot

**Risk Management for Pyramiding**
- Implemented separate position sizing calculation for pyramid entries based on market conditions
- Incorporated pyramid trade results in performance statistics accounting for compound risk effect
- Enhanced profit calculation to account for multiple entry points in the same trade direction

snapshot

## Backtesting Table and Metrics Improvements

**Enhanced Performance Metrics**
- Added robust Sharpe Ratio calculation for risk-adjusted return measurement
- Implemented Ulcer Index to measure depth and duration of drawdowns
- Added Risk of Ruin calculation based on Kelly Criterion
- Integrated CAGR (Compound Annual Growth Rate) for annualized performance comparison
- Added MAE/MFE (Maximum Adverse Excursion/Maximum Favorable Excursion) ratio to measure trade efficiency
- Implemented recovery factor and peak equity tracking

snapshot

**Table UI and Visualization Improvements**
- Reorganized backtesting table for better readability with logical grouping of metrics
- Added comprehensive tooltips explaining each metric with performance benchmarks
- Implemented color-coding system to quickly identify strengths and weaknesses
- Enhanced visibility of key performance indicators with conditional formatting
- Created separate view options for Backtest, Monthly, Weekly, and Daily performance analysis
- Improved confidence level calculation based on sample size

snapshot

**Statistical Analysis Enhancements**
- Added tracking for maximum consecutive wins and losses
- Implemented separate statistics tracking for bullish and bearish trades
- Added combined total performance statistics across all trade types
- Enhanced drawdown analysis with separate tracking for realized and maximum drawdowns
- Improved trade duration tracking and reporting

snapshot

## Calculation Logic and Performance Optimization

**Algorithmic Improvements**
- Implemented efficient single-pass algorithm for statistical calculations to reduce computational overhead
- Optimized Sharpe ratio and standard deviation calculations for better performance
- Enhanced Ulcer Index calculation with more efficient implementation
- Improved Kelly Criterion calculation with better handling of edge cases
- Optimized bias detection with pre-calculated values

snapshot

**Code Optimization**
- Reduced redundant calculations by caching frequently used values
- Improved handling of array operations to minimize memory usage
- Implemented grouped assignments to reduce code size and improve readability
- Optimized conditional logic for better performance in trade management
- Pre-calculated array sizes to avoid multiple calls to array.size function

**Trade Management Refinements**
- Improved trailing stop logic for better trade exit timing
- Enhanced breakeven detection and management
- Optimized position sizing based on dynamic risk calculation
- Improved drawdown tracking during active trades
- Refined trade duration calculation for more accurate reporting
Notas de Lançamento
- Improved accuracy and removed all discrepancies between tables and trades on charts
- Improved RoR calculation based on Kelly criterion formula
- Improved color threshold of metrics to be aligned with the detailed tooltips
- Improved script performance
- Added more detailed alerts

snapshot
Notas de Lançamento
New Performance Metrics Added
- Added Monthly Avg: Implemented compounded monthly return calculation for more granular periodic performance tracking
- Added Calmar Ratio: New risk-adjusted performance metric to assess returns relative to maximum drawdown risk
- Added p-value: Statistical significance testing to validate trading results against random chance hypothesis

snapshot
Notas de Lançamento
Major Enhancements
- Added support for custom entry models that can be integrated seamlessly with Quantify's risk management
- Implemented ability to use external indicators as entry signals where +1 triggers long entries and -1 triggers short entries
- Enhanced bias detection with custom indicator support, allowing users to define their own market bias rules

Chart Visualization Improvements
- Redesigned trade labels with clearer R-multiple values and trade statistics
- Added position-specific labels for pyramid entries (marked as "#1" and "#2") to track multiple positions
- Implemented gap detection visualization in labels that highlights price gaps at trade entries/exits
- Color-coded win/loss percentages for improved visual assessment of trade outcomes

Performance Analytics
- Enhanced Backtesting Metrics
- Added comprehensive tooltips to all backtesting metrics explaining calculation methods and interpretation
- Statistical significance testing (p-value) for strategy validation
- Added gap statistics tracking to analyze the impact of overnight gaps on strategy performance
- Implemented risk-of-ruin calculation that adjusts position sizing based on statistical confidence
- Improved visualization of current risk levels with real-time updates

- Streamlined code for faster backtest processing
- Optimized statistics calculation for real-time updates
- Improved alert messages with detailed trade information and key statistics
- Added trade duration tracking and reporting in human-readable format
- Cleaner visualization with less chart clutter while maintaining detailed information

snapshot
Notas de Lançamento
- Custom Exit Integration - Added support for using your own indicators to determine stop loss positions along with bias and entry parameters

- TP Level Approach - Implemented new take-profit methodology for the exit model, specifically optimized for high winrate trading strategies

- Alert Enhancements - Improved alert details for better trading decision visibility and notification clarity

snapshot
Notas de Lançamento
Walk-Forward Analysis Implementation
- Added WFE (Walk-Forward Efficiency) - Implemented robust calculation of the ratio between out-of-sample and in-sample performance to measure strategy resilience.
- Added Maximum Segment Contribution tracking - New metric measuring if any single period dominates total returns (should remain under 50%). Helps identify strategies that might be overly dependent on specific market conditions.
- Added Percentage of Profitable Segments - Tracks consistency of strategy performance across different market regimes.
- Improved segment boundary detection - Enhanced algorithm now properly identifies transitions between in-sample and out-of-sample periods, delivering more accurate WFA metrics.

Statistical Significance Improvements
- Enhanced p-value calculation accuracy using polynomial approximation of normal CDF instead of stepped approximation:
- Implemented two-tailed test handling - Now correctly calculates significance for both positive and negative deviations from expected performance.

Tooltip & User Interface Enhancements
- Added actionable insights to tooltips - Each metric now includes specific thresholds and practical interpretation guidance:
- WFE: "≥ 0.50: Strategy maintains at least 50% of its performance on unseen data (good)"
Profitable Segments: "≥ 70%: Strategy shows consistent profitability across different market regimes"
- Maximum Segment Contribution: "≤ 50%: Strategy profit is well-distributed across segments"
- Integrated color-coding based on metric health - Performance indicators now visually highlight whether metrics meet recommended thresholds.
- Added detailed component breakdowns in tooltips - Each metric now shows its underlying components for deeper analysis (e.g., in-sample vs. out-of-sample profit values).

snapshot
Notas de Lançamento
- Decreased Fractal Model Rules to Avoid Curve-Fitting and Increase WFE
- Reduced the number of pattern recognition rules in the fractal model to improve robustness
- Added Treynor Ratio to Risk Metrics Dashboard
- Implemented the Treynor ratio to measure excess return per unit of systematic risk
Formula used: (Portfolio Return - Risk-Free Rate) / Portfolio Beta

snapshot
Notas de Lançamento
• The script now calculates Walk-Forward Analysis (WFA) metrics separately for the bullish and bearish sides.
• Users can view distinct performance metrics for long (bullish) and short (bearish) strategies.
• Enhanced performance insights and more granular strategy evaluation.

snapshot
Notas de Lançamento
- Improved Kelly Criterion risk calculation accuracy
- Improved visualizations

snapshot
Notas de Lançamento
- Improved calculation logic for monthly, weekly, and daily performance tables
- Replaced Treynor ratio with Omega ratio to provide more actionable insights

snapshot
Notas de Lançamento
- Improved pyramiding risk management resulting in increased expectancy of pyramiding trades.

snapshot
Notas de Lançamento
- Added Median EV (Expected Value) calculation to the Monte Carlo simulation framework to provide a more robust assessment of trading strategy performance on unseen/future data

- Enhanced metrics help traders make more informed decisions about strategy viability

- Combined with Walk-Forward Analysis (WFA) metrics for comprehensive strategy validation
Provides statistical confidence about how strategies might perform in future market conditions
Helps identify whether past performance is likely to continue or was merely the result of curve-fitting

snapshot
Notas de Lançamento
- Integrated a comprehensive Monte Carlo simulation engine to provide deeper insight into trading strategy robustness and expected performance ranges. This major enhancement allows traders to better understand the true potential outcomes of their strategies beyond basic backtesting results.

What is Monte Carlo Simulation?
The Monte Carlo method runs hundreds of simulations by randomly reshuffling your historical trades to create different possible future scenarios. This helps identify how much of your strategy's performance might be due to luck versus skill, and provides a more realistic view of backtests.

- Full Distribution Analysis: Calculates not just average outcomes but the complete range of possible results: best-case, worst-case, and most likely scenarios.

snapshot
Notas de Lançamento
- Improved monte carlo table to show selected bias and method along with its direction as text color
- Improved built-in directional bias calculation logic

snapshot

Aviso legal

As informações e publicações não devem ser e não constituem conselhos ou recomendações financeiras, de investimento, de negociação ou de qualquer outro tipo, fornecidas ou endossadas pela TradingView. Leia mais em Termos de uso.