INVITE-ONLY SCRIPT

AlgoBuilder [Mean-Reversion] | Fractalyst

Atualizado
What's the strategy's purpose and functionality?

This strategy is designed for both traders and investors looking to rely and trade based on historical and backtested data using automation.

The main goal is to build profitable mean-reversion strategies that outperform the underlying asset in terms of returns while minimizing drawdown.

For example, as for a benchmark, if the S&P 500 (SPX) has achieved an estimated 10% annual return with a maximum drawdown of -57% over the past 20 years, using this strategy with different entry and exit techniques, users can potentially seek ways to achieve a higher Compound Annual Growth Rate (CAGR) while maintaining a lower maximum drawdown.

Although the strategy can be applied to all markets and timeframes, it is most effective on stocks, indices, future markets, cryptocurrencies, and commodities and JPY currency pairs given their trending behaviors.

In trending market conditions, the strategy employs a combination of moving averages and diverse entry models to identify and capitalize on upward market movements. It integrates market structure-based moving averages and bands mechanisms across different timeframes and provides exit techniques, including percentage-based and risk-reward (RR) based take profit levels.

Additionally, the strategy has also a feature that includes a built-in probability function for traders who want to implement probabilities right into their trading strategies.

Performance summary, weekly, and monthly tables enable quick visualization of performance metrics like net profit, maximum drawdown, profit factor, average trade, average risk-reward ratio (RR), and more.
This aids optimization to meet specific goals and risk tolerance levels effectively.
-----
How does the strategy perform for both investors and traders?
The strategy has two main modes, tailored for different market participants: Traders and Investors.

Trading:

1. Trading:
- Designed for traders looking to capitalize on bullish trending markets.
- Utilizes a percentage risk per trade to manage risk and optimize returns.
- Suitable for active trading with a focus on mean-reversion and risk per trade approach.
snapshot
◓: Mode | %: Risk percentage per trade
3. Investing:
- Geared towards investors who aim to capitalize on bullish trending markets without using leverage while mitigating the asset's maximum drawdown.
- Utilizes pre-define percentage of the equity to buy, hold, and manage the asset.
- Focuses on long-term growth and capital appreciation by fully investing in the asset during bullish conditions.
snapshot
- ◓: Mode | %: Risk not applied (In investing mode, the strategy uses 10% of equity to buy the asset)
-----
What's is FRMA? How does the triple bands work? What are the underlying calculations?

Middle Band (FRMA):
The middle band is the core of the FRMA system. It represents the Fractalyst Moving Average, calculated by identifying the most recent external swing highs and lows in the market structure.
By determining these external swing pivot points, which act as significant highs and lows within the market range, the FRMA provides a unique moving average that adapts to market structure changes.

Upper Band:
The upper band shows the average price of the most recent external swing highs.
External swing highs are identified as the highest points between pivot points in the market structure.
This band helps traders identify potential overbought conditions when prices approach or exceed this upper band.

Lower Band:
The lower band shows the average price of the most recent external swing lows.
External swing lows are identified as the lowest points between pivot points in the market structure.

The script utilizes this band to identify potential oversold conditions, triggering entry signals as prices approach or drop below the lower band.

Adjustments Based on User Inputs:
Users can adjust how the upper and lower bands are calculated based on their preferences:

Upper/Lower: This method calculates the average bands using the prices of external swing highs and lows identified in the market.

Percentage Deviation from FRMA: Alternatively, users can opt to calculate the bands based on a percentage deviation from the middle FRMA. This approach provides flexibility to adjust the width of the bands relative to market conditions and volatility.
snapshot
-----
What's the purpose of using moving averages in this strategy? What are the underlying calculations?
Using moving averages is a widely-used technique to trade with the trend.
The main purpose of using moving averages in this strategy is to filter out bearish price action and to only take trades when the price is trading ABOVE specified moving averages.
The script uses different types of moving averages with user-adjustable timeframes and periods/lengths, allowing traders to try out different variations to maximize strategy performance and minimize drawdowns.
By applying these calculations, the strategy effectively identifies bullish trends and avoids market conditions that are not conducive to profitable trades.

The MA filter allows traders to choose whether they want a specific moving average above or below another one as their entry condition.

This comparison filter can be turned on (>) or off.
For example, you can set the filter so that MA#1 > MA#2, meaning the first moving average must be above the second one before the script looks for entry conditions. This adds an extra layer of trend confirmation, ensuring that trades are only taken in more favorable market conditions.

snapshot
⍺: MA Period | Σ: MA Timeframe
-----
What entry modes are used in this strategy? What are the underlying calculations?

The strategy by default uses two different techniques for the entry criteria with user-adjustable left and right bars: Breakout and Fractal.

1. Breakout Entries:
- The strategy looks for pivot high points with a default period of 3.
- It stores the most recent high level in a variable.
- When the price crosses above this most recent level, the strategy checks if all conditions are met and the bar is closed before taking the buy entry.
snapshot
◧: Pivot high left bars period | ◨: Pivot high right bars period

2. Fractal Entries:
- The strategy looks for pivot low points with a default period of 3.
- When a pivot low is detected, the strategy checks if all conditions are met and the bar is closed before taking the buy entry.
snapshot
◧: Pivot low left bars period | ◨: Pivot low right bars period

2. Hunt Entries:
- The strategy identifies a candle that wicks through the lower FRMA band.
- It waits for the next candle to close above the low of the wick candle.
- When this condition is met and the bar is closed, the strategy takes the buy entry.
snapshot

By utilizing these entry modes, the strategy aims to capitalize on bullish price movements while ensuring that the necessary conditions are met to validate the entry points.
-----
What type of stop-loss identification method are used in this strategy? What are the underlying calculations?
Initial Stop-Loss:

1. ATR Based:
The Average True Range (ATR) is a method used in technical analysis to measure volatility. It is not used to indicate the direction of price but to measure volatility, especially volatility caused by price gaps or limit moves.

Calculation:
- To calculate the ATR, the True Range (TR) first needs to be identified. The TR takes into account the most current period high/low range as well as the previous period close.
The True Range is the largest of the following:
- Current Period High minus Current Period Low
- Absolute Value of Current Period High minus Previous Period Close
- Absolute Value of Current Period Low minus Previous Period Close
- The ATR is then calculated as the moving average of the TR over a specified period. (The default period is 14).

Example - ATR (14) * 2
snapshot
⍺: ATR period | Σ: ATR Multiplier

2. ADR Based:
The Average Day Range (ADR) is an indicator that measures the volatility of an asset by showing the average movement of the price between the high and the low over the last several days.

Calculation:
- To calculate the ADR for a particular day:
- Calculate the average of the high prices over a specified number of days.
- Calculate the average of the low prices over the same number of days.
- Find the difference between these average values.
- The default period for calculating the ADR is 14 days. A shorter period may introduce more noise, while a longer period may be slower to react to new market movements.

Example - ADR (20) * 2
snapshot
⍺: ADR period | Σ: ADR Multiplier

3. PL Based:

This method places the stop-loss at the low of the previous candle.
If the current entry is based on the hunt entry strategy, the stop-loss will be placed at the low of the candle that wicks through the lower FRMA band.
Example:

If the previous candle's low is 100, then the stop-loss will be set at 100.
This method ensures the stop-loss is placed just below the most recent significant low, providing a logical and immediate level for risk management.
snapshot

Application in Strategy (ATR/ADR):
- The strategy calculates the current bar's ADR/ATR with a user-defined period.
- It then multiplies the ADR/ATR by a user-defined multiplier to determine the initial stop-loss level.

By using these methods, the strategy dynamically adjusts the initial stop-loss based on market volatility, helping to protect against adverse price movements while allowing for enough room for trades to develop.

Each market behaves differently across various timeframes, and it is essential to test different parameters and optimizations to find out which trailing stop-loss method gives you the desired results and performance.
-----
What type of break-even and take profit identification methods are used in this strategy? What are the underlying calculations?
For Break-Even:

Percentage (%) Based:

Moves the initial stop-loss to the entry price when the price reaches a certain percentage above the entry.
Calculation:
Break-even level = Entry Price * (1 + Percentage / 100)
Example:
If the entry price is $100 and the break-even percentage is 5%, the break-even level is $100 * 1.05 = $105.
Risk-to-Reward (RR) Based:

Moves the initial stop-loss to the entry price when the price reaches a certain RR ratio.
Calculation:
Break-even level = Entry Price + (Initial Risk * RR Ratio)
Example:
If the entry price is $100, the initial risk is $10, and the RR ratio is 2, the break-even level is $100 + ($10 * 2) = $120.
FRMA Based:

Moves the stop-loss to break-even when the price hits the FRMA level at which the entry was taken.
Calculation:
Break-even level = FRMA level at the entry
Example:
If the FRMA level at entry is $102, the break-even level is set to $102 when the price reaches $102.

For TP1 (Take Profit 1):
- You can choose to set a take profit level at which your position gets fully closed or 50% if the TP2 boolean is enabled.
- Similar to break-even, you can select either a percentage (%) or risk-to-reward (RR) based take profit level, allowing you to set your TP1 level as a percentage amount above the entry price or based on RR.

For TP2 (Take Profit 2):
- You can choose to set a take profit level at which your position gets fully closed.
- As with break-even and TP1, you can select either a percentage (%) or risk-to-reward (RR) based take profit level, allowing you to set your TP2 level as a percentage amount above the entry price or based on RR.

When Both Percentage (%) Based and RR Based Take Profit Levels Are Off:

The script will adjust the take profit level to the higher FRMA band set within user inputs.
Calculation:
Take profit level = Higher FRMA band length/timeframe specified by the user.

This ensures that when neither percentage-based nor risk-to-reward-based take profit methods are enabled, the strategy defaults to using the higher FRMA band as the take profit level, providing a consistent and structured approach to profit-taking.

For TP1 and TP2, it's specifying the price levels at which the position is partially or fully closed based on the chosen method (percentage or RR) above the entry price.
These calculations are crucial for managing risk and optimizing profitability in the strategy.
snapshot
⍺: BE/TP type (%/RR) | Σ: how many RR/% above the current price
-----
What's the ADR filter? What does it do? What are the underlying calculations?
The Average Day Range (ADR) measures the volatility of an asset by showing the average movement of the price between the high and the low over the last several days.
The period of the ADR filter used in this strategy is tied to the same period you've used for your initial stop-loss.

Users can define the minimum ADR they want to be met before the script looks for entry conditions.

ADR Bias Filter:
- Compares the current bar ADR with the ADR (Defined by user):
- If the current ADR is higher, it indicates that volatility has increased compared to ADR (DbU).(⬆)
- If the current ADR is lower, it indicates that volatility has decreased compared to ADR (DbU).(⬇)

Calculations:
1. Calculate ADR:
- Average the high prices over the specified period.
- Average the low prices over the same period.
- Find the difference between these average values in %.

2. Current ADR vs. ADR (DbU):
- Calculate the ADR for the current bar.
- Calculate the ADR (DbU).
- Compare the two values to determine if volatility has increased or decreased.

By using the ADR filter, the strategy ensures that trades are only taken in favorable market conditions where volatility meets the user's defined threshold, thus optimizing entry conditions and potentially improving the overall performance of the strategy.
snapshot
>: Minimum required ADR for entry | %: Current ADR comparison to ADR of 14 days ago.
-----
What's the probability filter? What are the underlying calculations?

The probability filter is designed to enhance trade entries by using buyside liquidity and probability analysis to filter out unfavorable conditions.
This filter helps in identifying optimal entry points where the likelihood of a profitable trade is higher.

Calculations:
1. Understanding Swing highs and Swing Lows
Swing High: A Swing High is formed when there is a high with 2 lower highs to the left and right.
Swing Low: A Swing Low is formed when there is a low with 2 higher lows to the left and right.
2. Understanding the purpose and the underlying calculations behind Buyside, Sellside and Equilibrium levels.
snapshot

3. Understanding probability calculations
1. Upon the formation of a new range, the script waits for the price to reach and tap into equilibrium or the 50% level. Status: "⏸" - Inactive
2. Once equilibrium is tapped into, the equilibrium status becomes activated and it waits for either liquidity side to be hit. Status: "▶" - Active
3. If the buyside liquidity is hit, the script adds to the count of successful buyside liquidity occurrences. Similarly, if the sellside is tapped, it records successful sellside liquidity occurrences.
5. Finally, the number of successful occurrences for each side is divided by the overall count individually to calculate the range probabilities.
snapshot

Note: The calculations are performed independently for each directional range. A range is considered bearish if the previous breakout was through a sellside liquidity. Conversely, a range is considered bullish if the most recent breakout was through a buyside liquidity.
snapshot

Example - BSL > 55%
snapshot
-----
What's the range length Filter? What are the underlying calculations?
The range length filter identifies the price distance between buyside and sellside liquidity levels in percentage terms. When enabled, the script only looks for entries when the minimum range length is met. This helps ensure that trades are taken in markets with sufficient price movement.
Calculations:
Range Length (%) = ( ( Buyside Level − Sellside Level ) / Current Price ) ×100

Range Bias Identification:

Bullish Bias: The current range price has broken above the previous external swing high.
Bearish Bias: The current range price has broken below the previous external swing low.

Example - Range length filter is enabled | Range must be above 1%
snapshot
>: Minimum required range length for entry | %: Current range length percentage in a (Bullish/Bearish) range
-----
What's the day filter Filter, what does it do?

The day filter allows users to customize the session time and choose the specific days they want to include in the strategy session. This helps traders tailor their strategies to particular trading sessions or days of the week when they believe the market conditions are more favorable for their trading style.

Customize Session Time:

Users can define the start and end times for the trading session.
This allows the strategy to only consider trades within the specified time window, focusing on periods of higher market activity or preferred trading hours.
Select Days:

Users can select which days of the week to include in the strategy.
This feature is useful for excluding days with historically lower volatility or unfavorable trading conditions (e.g., Mondays or Fridays).
Benefits:

Focus on Optimal Trading Periods:
By customizing session times and days, traders can focus on periods when the market is more likely to present profitable opportunities.

Avoid Unfavorable Conditions:
Excluding specific days or times can help avoid trading during periods of low liquidity or high unpredictability, such as major news events or holidays.
Increased Flexibility: The filter provides increased flexibility, allowing traders to adapt the strategy to their specific needs and preferences.

Example - Day filter | Session Filter
snapshot
θ: Session time | Exchange time-zone
-----
What tables are available in this script?

Table Type:
- Summary: Provides a general overview, displaying key performance parameters such as Net Profit, Profit Factor, Max Drawdown, Average Trade, Closed Trades and more.

Avg Trade: The sum of money gained or lost by the average trade generated by a strategy. Calculated by dividing the Net Profit by the overall number of closed trades. An important value since it must be large enough to cover the commission and slippage costs of trading the strategy and still bring a profit.

MaxDD: Displays the largest drawdown of losses, i.e., the maximum possible loss that the strategy could have incurred among all of the trades it has made. This value is calculated separately for every bar that the strategy spends with an open position.

Profit Factor: The amount of money a trading strategy made for every unit of money it lost (in the selected currency). This value is calculated by dividing gross profits by gross losses.

Avg RR: This is calculated by dividing the average winning trade by the average losing trade. This field is not a very meaningful value by itself because it does not take into account the ratio of the number of winning vs losing trades, and strategies can have different approaches to profitability. A strategy may trade at every possibility in order to capture many small profits, yet have an average losing trade greater than the average winning trade. The higher this value is, the better, but it should be considered together with the percentage of winning trades and the net profit.

Winrate: The percentage of winning trades generated by a strategy. Calculated by dividing the number of winning trades by the total number of closed trades generated by a strategy. Percent profitable is not a very reliable measure by itself. A strategy could have many small winning trades, making the percent profitable high with a small average winning trade, or a few big winning trades accounting for a low percent profitable and a big average winning trade. Most mean-reversion successful strategies have a percent profitability of 40-80% but are profitable due to risk management control.

BE Trades: Number of break-even trades, excluding commission/slippage.

Losing Trades: The total number of losing trades generated by the strategy.

Winning Trades: The total number of winning trades generated by the strategy.

Total Trades: Total number of taken traders visible your charts.

Net Profit: The overall profit or loss (in the selected currency) achieved by the trading strategy in the test period. The value is the sum of all values from the Profit column (on the List of Trades tab), taking into account the sign.

- Monthly: Displays performance data on a month-by-month basis, allowing users to analyze performance trends over each month.
- Weekly: Displays performance data on a week-by-week basis, helping users to understand weekly performance variations.

- OFF: Hides the performance table.

Profit Color:
- Allows users to set the color for representing profit in the performance table, helping to quickly distinguish profitable periods.

Loss Color:
- Allows users to set the color for representing loss in the performance table, helping to quickly identify loss-making periods.

These customizable tables provide traders with flexible and detailed performance analysis, aiding in better strategy evaluation and optimization.
-----
User-input styles and customizations:
To facilitate studying historical data, all conditions and rules can be applied to your charts. By plotting background colors on your charts, you'll be able to identify what worked and what didn't in certain market conditions.

Please note that all background colors in the style are disabled by default to enhance visualization.
-----
How to Use This Algobuilder to Create a Profitable Edge and System:

Choose Your Strategy mode:

- Decide whether you are creating an investing strategy or a trading strategy.

Select a Market:

- Choose a one-sided market such as stocks, indices, or cryptocurrencies.

Historical Data:

- Ensure the historical data covers at least 10 years of price action for robust backtesting.

Timeframe Selection:

- Choose the timeframe you are comfortable trading with. It is strongly recommended to use a timeframe above 15 minutes to minimize the impact of commissions/slippage on your profits.

Set Commission and Slippage:

- Properly set the commission and slippage in the strategy properties according to your broker or prop firm specifications.

Parameter Optimization:

- Use trial and error to test different parameters until you find the performance results you are looking for in the summary table or, preferably, through deep backtesting using the strategy tester.

Trade Count:

- Ensure the number of trades is 100 or more; the higher, the better for statistical significance.

Positive Average Trade:

- Make sure the average trade value is above zero.

(An important value since it must be large enough to cover the commission and slippage costs of trading the strategy and still bring a profit.)

Performance Metrics:

- Look for a high profit factor, and net profit with minimum drawdown.
- Ideally, aim for a drawdown under 20-30%, depending on your risk tolerance.

Refinement and Optimization:

- Try out different markets and timeframes.
- Continue working on refining your edge using the available filters and components to further optimize your strategy.

Automation:

- Once you’re confident in your strategy, you can use the automation section to connect the algorithm to your broker or prop firm.
- Trade a fully automated and backtested trading strategy, allowing for hands-free execution and management.

snapshot
-----
What makes this strategy original?

1. Incorporating direct integration of probabilities into the strategy.
2. Utilizing built-in market structure-based moving averages across various timeframes.
4. Offering both investing and trading strategies, facilitating optimization from different perspectives.
5. Automation for efficient execution.
6. Providing a summary table for instant access to key parameters of the strategy.
-----
How to use automation?

For Traders:
1. Ensure the strategy parameters are properly set based on your optimized parameters.
2. Enter your PineConnector License ID in the designated field.
3. Specify the desired risk level.
4. Provide the Metatrader symbol.
5. Check for chart updates to ensure the automation table appears on the top right corner, displaying your License ID, risk, and symbol.
6. Set up an alert with the strategy selected as Condition and the Message as {{strategy.order.alert_message}}.
7. Activate the Webhook URL in the Notifications section, setting it as the official PineConnector webhook address.
8. Double-check all settings on PineConnector to ensure the connection is successful.
9. Create the alert for entry/exit automation.

For Investors:
1. Ensure the strategy parameters are properly set based on your optimized parameters.
2. Choose "Investing" in the user-input settings.
3. Create an alert with a specified name.
4. Customize the notifications tab to receive alerts via email.
5. Buying/selling alerts will be triggered instantly upon entry or exit order execution.

-----
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
- Added pre-defined parameters for optimization, allowing users to choose from a selection of markets for executing a mean-reversion trading strategy.
Notas de Lançamento
- Bug fix & properties adjustments
Notas de Lançamento
- Improved range and probability(%) calculation logic
algorithmictradingmeanreversionMoving AveragesmultitimeframeprofitabletradingquanttradingstatisticalprobabilityTrend Analysis

Script apenas com convite

O acesso a este script é restrito aos usuários autorizados pelo autor e pode requerir pagamento. Você pode adicioná-lo a seus favoritos, mas só poderá utilizá-lo após solicitar permissão e obtê-la do autor. Contate Fractalyst para mais informações, ou siga as instruções do autor abaixo.

TradingView does not suggest paying for a script and using it unless you 100% trust its author and understand how the script works. In many cases, you can find a good open-source alternative for free in our Community Scripts.

Instruções do autor

📥┃Get Lifetime Access Here ➙ http://www.fractalyst.net/tools

Quer usar esse script no gráfico?

Aviso: por favor leia antes de solicitar acesso.

📥┃𝐅𝐫𝐞𝐞 𝐎𝐮𝐭𝐥𝐨𝐨𝐤𝐬:
discord.gg/B2e52B3D7U

📥┃𝐒𝐰𝐢𝐧𝐠 𝐓𝐫𝐚𝐝𝐢𝐧𝐠 𝐒𝐭𝐫𝐚𝐭𝐞𝐠𝐲 + 𝐁𝐮𝐢𝐥𝐭-𝐢𝐧 𝐈𝐧𝐝𝐢𝐜𝐚𝐭𝐨𝐫:
fractalyst.net/

📥┃ 𝐅𝐫𝐞𝐞 𝐒𝐜𝐫𝐞𝐞𝐧𝐞𝐫:
fractalyst.net/screener
Também em:

Aviso legal