Fractalyst

AlgoBuilder [Trend-Following] | Fractalyst

Fractalyst Actualizado   
What's the strategy's purpose and functionality?

This strategy is designed for both traders and investors looking to rely on and trade based on historical and backtested data using automation. The main goal is to build profitable trend-following 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 trailing stop-loss 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 and sentiment function for traders who want to implement probabilities and market sentiment right into their trading strategies.

Performance summary, weekly, and monthly tables enable quick visualization of performance metrics like net profit, maximum drawdown, compound annual growth rate (CAGR), 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 (1x):
- 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 trend-following and risk management.
- (1x) This mode ensures no stacking of positions, allowing for only one running position or trade at a time.
◓: Mode | %: Risk percentage per trade

2. Trading (2x):
Similar to the 1x mode but allows for two pyramiding entries.
This approach enables traders to increase their position size as the trade moves in their favor, potentially enhancing profits during strong bullish trends.
◓: 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 100% 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.
- ◓: Mode | %: Risk not applied (In investing mode, the strategy uses 100% of equity to buy the asset)
-----
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.

MA #1: Fast MA | MA #2: Medium MA | MA #3: Slow MA
⍺: 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.
◧: 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.
◧: Pivot low left bars period | ◨: Pivot low right bars period

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) * 1.5
⍺: 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 (14) * 1.5
⍺: ADR period | Σ: ADR Multiplier

Application in Strategy:
- 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.

Trailing Stop-Loss:

One of the key elements of this strategy is its ability to detec buyside and sellside liquidity levels across multiple timeframes to trail the stop-loss once the trade is in running profits.
By utilizing this approach, the strategy allows enough room for price to run.
There are two built-in trailing stop-loss (SL) options you can choose from while in a trade:

1. External Trailing Stop-Loss:
- Uses sell-side liquidity to trail your stop-loss, allowing price to consolidate before continuation. This method is less aggressive and provides more room for price fluctuations.

Example - External - Wick below the trailing SL - 12H trailing timeframe
⍺: Exit type | Σ: Trailing stop-loss timeframe

2. Internal Trailing Stop-Loss:
- Uses the most recent swing low with a period of 2 to trail your stop-loss. This method is more aggressive compared to the external trailing stop-loss, as it tightens the stop-loss closer to the current price action.

Example - Internal - Close below the trailing SL - 6H trailing timeframe
⍺: Exit type | Σ: Trailing stop-loss timeframe

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:
- You can choose to set a break-even level at which your initial stop-loss moves to the entry price as soon as it hits, and your trailing stop-loss gets activated (if enabled).
- You can select either a percentage (%) or risk-to-reward (RR) based break-even, allowing you to set your break-even level as a percentage amount above the entry price or based on RR.

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.

The underlying calculations involve determining the price levels at which these actions are triggered. For break-even, it moves the initial stop-loss to the entry price and activate the trailing stop-loss once the break-even level is reached.

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.
⍺: 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.
>: 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.

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.

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.

Example - BSL > 50%
-----
What's the sentiment Filter? What are the underlying calculations?

Sentiment filter aims to calculate the percentage level of bullish or bearish fluctuations within equally divided price sections, in the latest price range.

Calculations:
This filter calculates the current sentiment by identifying the highest swing high and the lowest swing low, then evenly dividing the distance between them into percentage amounts. If the price is above the 50% mark, it indicates bullishness, whereas if it's below 50%, it suggests bearishness.

Sentiment Bias Identification:

Bullish Bias: The current price is trading above the 50% daily range.
Bearish Bias: The current price is trading below the 50% daily range.

Example - Sentiment Enabled | Bullish degree above 50% | Bullish sentimental bias
>: Minimum required sentiment for entry | %: Current sentimental degree in a (Bullish/Bearish) sentimental bias
-----
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 5% | Price must be in a bearish range
>: 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
θ: 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, Compound Annual Growth Rate (CAGR), MAR and more.

CAGR: It calculates the 'Compound Annual Growth Rate' first and last taken trades on your chart. The ​CAGR is a notional, annualized growth rate that assumes all profits are reinvested. It only takes into account the prices of the two end points — not drawdowns, so it does not calculate risk. It can be used as a yardstick to compare the performance of two strategies. Since it annualizes values, it requires a minimum 4H timeframe to display the CAGR value. annualizing returns over smaller periods of times doesn't produce very meaningful figures.

MAR: Measure of return adjusted for risk: CAGR divided by Max Drawdown. Indicates how comfortable the system might be to trade. Higher than 0.5 is ideal, 1.0 and above is very good, and anything above 3.0 should be considered suspicious and you need to make sure the total number of trades are high enough by running a Deep Backtest in strategy tester. (available for TradingView Premium users.)

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 trend-following successful strategies have a percent profitability of 15-40% 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.

Labels:
- OFF: Hides labels in the performance table.
- PnL: Shows the profit and loss of each trade individually, providing detailed insights into the performance of each trade.
- Range: Shows the range length and Average Day Range (ADR), offering additional context about market conditions during each trade.

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 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, MAR (Mar Ratio), CAGR (Compound Annual Growth Rate), 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.
-----
What makes this strategy original?

1. Incorporating direct integration of probabilities into the strategy.
2. Leveraging market sentiment to construct a profitable approach.
3. Utilizing built-in market structure-based trailing stop-loss mechanisms 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.
----
Strategy Properties

This script backtest is done on 4H BTCUSD , using the following backtesting properties:

Balance: $5000
Order Size: 10% of the equity
Risk % per trade: 1%
Commission: 0.04% (Default commission percentage according to TradingView competitions rules)
Slippage: 75 ticks
Pyramiding: 2
-----
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 prensa:
- Enhanced entry and exit logic for PineConnector automation alerts.
- Implemented status table for displaying current user-input automation license ID and risk %.
Notas de prensa:
- UI Table Addition: Introduced a new UI table that displays all user inputs within the AlgoBuilder settings, allowing users to effortlessly view their strategy parameters without cluttering their charts.
- Saving Customizations: Users can save their best customizations (UIs) along with strategy performance by taking a screenshot. This makes it easy to reference and compare settings during further optimization efforts.
Notas de prensa:
- Added more trade stats parameters to the summary table for enhanced data visibility.

- Removed user input for pyramiding trades; this setting can now be adjusted directly within the strategy properties.

- Added SL size filters based on ATR, ADR, or PIP values, allowing users to set minimum or maximum stop-loss sizes for trade entries.

- Implemented an average SL value table to provide insights on stop-loss filtering, showing the average stop-loss values used, helping users better understand the impact of their stop-loss settings.

- Introduced a user input option for table size, allowing users to adjust the size of tables according to their preferences.
Notas de prensa:
- Moving Average Filter: Added another moving average filter to provide more advanced filtering capabilities.

- MA Comparison Filter: Introduced an additional moving average comparison filter, enabling users to build strategies on lower timeframes.

- New MA Types: Added Arnaud Legoux Moving Average (ALMA), Zero Lag Exponential Moving Average (ZLEMA), and Triple Exponential Moving Average (TEMA) to the available moving average types, allowing for greater optimization and customization of strategies.

- Risk of Ruin (RoR): Included Risk of Ruin (RoR) in the performance summary to offer a more comprehensive evaluation of the potential risk associated with trading strategies.
Notas de prensa:
- Fixed a bug in plotting moving averages where the data points were misaligned, causing incorrect visualization.

📥┃Discord Community (𝗙𝗥𝗘𝗘):
discord.gg/yFAZp9HYcF
📥┃Indicators (𝐀𝐋𝐆𝐎𝐑𝐈𝐓𝐇𝐌𝐈𝐂):
fractalyst.net
📥┃Custom Script (𝐀𝐔𝐓𝐎𝐌𝐀𝐓𝐈𝐎𝐍):
www.fractalyst.net/customscript
Script que requiere invitación

El acceso a este script está restringido a los usuarios autorizados por el autor y, por regla general, es de pago. Puede añadirlo a sus favoritos, pero solo podrá usarlo si solicita permiso al autor y éste le autoriza. Póngase en contacto con Fractalyst para obtener más información o siga las siguientes instrucciones del autor.

TradingView recomienda no comprar ni utilizar un script si su autor no le ofrece total confianza o cuando no entienda cómo funciona. En muchos casos, puede encontrar una buena alternativa de código abierto de forma gratuita en nuestros Scripts de la comunidad.

Exención de responsabilidad

La información y las publicaciones que ofrecemos, no implican ni constituyen un asesoramiento financiero, ni de inversión, trading o cualquier otro tipo de consejo o recomendación emitida o respaldada por TradingView. Puede obtener información adicional en las Condiciones de uso.

Instrucciones del autor

📥┃Get access here ➙ www.fractalyst.net

¿Quiere utilizar este script en un gráfico?

Advertencia: Por favor, consulte antes de solicitar acceso.