TS CalculatorWhat is Trailing Stop?
A trailing stop is a type of stop-loss order that adjusts itself as the price of an asset moves in a favorable direction. It’s designed to lock in profits or limit losses by following the asset’s price movement. Here’s how it works:
How a Trailing Stop Works
Initial Setup: You set a trailing stop at a certain percentage or dollar amount below (for long trades) or above (for short trades) the current market price.
Price Movement: As the price moves in your favor, the trailing stop moves with it, maintaining the set distance.
Locking in Profits: If the price reverses direction by the set amount, the trailing stop triggers a market order to sell (for long trades) or buy (for short trades), locking in your profits or limiting your losses.
Example
Long Trade: If you buy a stock at $100 and set a trailing stop at 10%, the stop-loss order will initially be at $90. If the stock price rises to $120, the trailing stop moves up to $108 (10% below $120). If the price then drops to $108, the trailing stop triggers a sell order.
Short Trade: If you short a stock at $100 and set a trailing stop at 10%, the stop-loss order will initially be at $110. If the stock price falls to $80, the trailing stop moves down to $88 (10% above $80). If the price then rises to $88, the trailing stop triggers a buy order.
Benefits
Automated Risk Management: It helps manage risk without the need to constantly monitor the market.
Profit Protection: It locks in profits as the price moves in your favor.
Flexibility: It adjusts dynamically with the market price, unlike a fixed stop-loss order.
What this script does ?
This script plots the Trailing Stop from the point of entry to current date, until it hits the trailing stop. Some of the market did not give the trailing stop values exactly so this script may give you a wise view of that.
Variables
Date : Date with YYYY-MM-DD format
Time : Time with HH:MM:SS format
Entry Price : Activation Price of TS order
Bounceback Ratio : Ratio for TS
Order Type : Position of order as Long/Short
There is an also a table implemented which shows
Entry
Ratio
Position
Current Stop
For possible updates feel free to contact me via DM.
Trailingstoploss
AutoPilot | FractalystWhat’s the purpose of this indicator?
The AutoPilot indicator automates the management of your active trades by:
Breaks Even: Moves the stop-loss to the entry price once the trade reaches a 1:1 risk-reward ratio.
Closes Trades: Automatically exits trades when trailing stop-losses are triggered.
This automation is facilitated through PineConnector and TradingView webhook integration, allowing traders to manage multiple positions across various markets effortlessly without any manual intervention.
----
How does this indicator trail stop-loss using market structure?
The AutoPilot indicator utilizes an advanced market structure trailing stop-loss mechanism to manage trades based on market dynamics and probabilities.
Here's how it works:
Market Structure Identification: The indicator first identifies key market structures such as higher highs, lower lows.
These structures are pivotal points where the market has shown a change in direction or momentum.
Probability-Based Trailing: Once a trade is active, the stop-loss isn't just set at a fixed distance or percentage but is dynamically adjusted based on the probability of the market structure holding or breaking.
This involves:
Trend Continuation Probability: If the market structure suggests a strong trend continuation (e.g., a series of higher highs in an uptrend), the stop-loss might trail closer to the price, but with a buffer calculated by the probability of the trend continuing versus reversing.
Reversal Probability: Conversely, if there's a high probability of a trend reversal based on recent market structures (like a significant lower high in an uptrend), the stop-loss might be adjusted to a point where the market structure would need to break to confirm the reversal, thus protecting potential profits or minimizing losses.
Dynamic Adjustment: The trailing stop-loss adjusts in real-time as new market structures form. For instance, if a new higher high is formed in an uptrend, the stop-loss might move up but not necessarily to the exact previous swing low. Instead, it's placed at a level where the probability of the next swing low not breaking this level is high, based on historical price action.
Risk Management: By using market structure and probabilities, the indicator aims to balance between giving the trade room to breathe (allowing for normal market fluctuations) and tightening the stop-loss when the market behavior suggests a potential trend change or continuation with high confidence.
This approach ensures that the stop-loss isn't just a static or simple trailing mechanism but a sophisticated tool that adapts to the evolving market conditions, aiming to maximize profit while minimizing the risk of being stopped out prematurely due to market noise.
----
How are the probabilities calculated? What are the underlying calculations?
The probability is designed to enhance trade management by using buyside liquidity and probability analysis to filter out low/high probability conditions.
This helps in identifying optimal trailing points where the likelihood of a price continuation 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.
----
What does the automation table display?
The automation table in the AutoPilot indicator provides a summary of user-defined settings crucial for automated trade management through PineConnector and TradingView integration. It displays:
PineConnector License ID: This ensures that the indicator is linked to your specific PineConnector account, allowing for personalized and secure automation of your trades.
Order Type (Buy/Sell): Indicates whether the automation is set for buying or selling, which is essential for correctly executing your trading strategy.
Chosen Symbol: Specifies the trading pair or symbol in your broker's platform where the trade management commands (like closing orders) will be executed. This ensures that the automation targets the correct market or asset.
Risk Per Trade: Shows the percentage or amount of your capital you're willing to risk on each trade, helping you maintain consistent risk management across different trades.
Comment: A field for you to input notes or identifiers, particularly useful when trading across multiple markets or instruments. This helps in tracking and managing trades across different assets or strategies.
Comment: A field for you to input identifiers, particularly useful when trading across multiple timeframes or different enries.
Allowing users to manage specific comments for each previously taken entry, facilitating precise management of multiple trades with unique identifiers.
This table serves as a quick reference for your current settings, ensuring you're always aware of how your trades are being managed automatically before any adjustments are made or alerts are triggered.
----
How to use the indicator?
To use the AutoPilot indicator:
Purchase a License ID: Acquire a license ID from PineConnector.
Setup PineConnector EA: Install and configure the PineConnector Expert Advisor on your MetaTrader platform.
Input Settings: Enter your PineConnector license ID, choose the order type, set your risk per trade, add the order comment, and select the trading symbol in the indicator's settings.
Create Alert: Right-click on the automation table, and set up an alert with the provided webhook to connect with PineConnector.
Automatic Management: Once set, your active trades will be automatically managed according to the alert conditions you've set.
This setup ensures your trades are managed seamlessly without constant manual intervention.
----
What makes this indicator original?
Integration with PineConnector: The AutoPilot indicator's originality lies in its integration with PineConnector, which allows for real-time trade management directly from TradingView to your MetaTrader platform. This setup is unique as it combines the analytical capabilities of TradingView with the execution capabilities of MetaTrader through a custom indicator, providing a seamless bridge between analysis and action.
Market Structure-Based Trailing Stop-Loss: Unlike many indicators that might use fixed percentages or ATR (Average True Range) for stop-loss adjustments, the AutoPilot indicator uses market structure (higher highs, lower lows) to dynamically adjust the stop-loss.
Probability-Based Adjustments: The indicator doesn't just trail stop-losses based on price but incorporates the probability of market structure holding or breaking. This probability-based trailing mechanism is innovative, aiming to balance between giving trades room to breathe and tightening when market behavior suggests a potential reversal or continuation.
Customizable Automation Table: The automation table within the indicator allows for detailed customization, including setting specific comments for trades. This feature, while perhaps not unique in concept, is original in its implementation within trading indicators, providing users with a high degree of control and personalization over trade management.
Real-Time Trade Management Alerts: The ability to set up alerts directly from the indicator to manage trades in real-time via webhooks to PineConnector adds a layer of automation that's not commonly found in standard trading indicators. This real-time connection for trade management enhances its originality by reducing the lag between analysis and trade execution.
User-Centric Design: The design of the AutoPilot indicator focuses heavily on user interaction, allowing for inputs like risk per trade, specific order types, and comments. This user-centric approach, where the indicator adapts to the trader's strategy rather than the trader adapting to the tool, sets it apart.
External Integration for Enhanced Functionality: By leveraging external services like PineConnector for execution, the indicator extends its functionality beyond what's typically possible within TradingView alone, making it original in its ecosystem integration for trading purposes.
Practical Implication: This means if you're in a trade and the market structure suggests the trend is continuing (e.g., making higher highs in an uptrend), your stop-loss might trail closer to the price but not too close to avoid being stopped out by normal fluctuations. If the structure breaks (e.g., a lower high in an uptrend), the stop-loss could adjust more aggressively to protect profits or minimize losses, anticipating a potential trend change.
This combination of features creates an original tool that not only analyzes market conditions but actively manages trades based on sophisticated market structure analysis.
----
User-input settings and customizations
----
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. By utilizing our charting tools, the buyer acknowledges that neither the seller nor the creator assumes responsibility for decisions made using the information provided. The buyer assumes full responsibility and liability for any actions taken and their consequences, including potential financial losses. Therefore, by purchasing these charting tools, the customer acknowledges that neither the seller nor the creator is liable for any unfavorable outcomes resulting from the development, sale, or use of the products.
The buyer is responsible for canceling their subscription if they no longer wish to continue at the full retail price. Our policy does not include reimbursement, refunds, or chargebacks once the Terms and Conditions are accepted before purchase.
By continuing to use our charting tools, the user acknowledges and accepts the Terms and Conditions outlined in this legal disclaimer.
Trailing Stop ProTrailing Stop Pro is a sophisticated TradingView indicator designed to enhance your trading strategy by dynamically managing trailing stops based on market volatility. This tool leverages the Average True Range (ATR) to adjust stop levels, providing traders with a robust mechanism to protect profits and minimize losses.
Key Features:
Dynamic Trailing Stops: Automatically adjusts stop levels using ATR, allowing for responsive and adaptive risk management.
Customizable Inputs: Tailor the indicator to your trading style with adjustable parameters such as ATR Length, ATR Multiplier, and Source Vector.
Visual Clarity: Distinct color settings for long and short stops, with adjustable line thickness and transparency, ensuring clear visualization on your charts.
Professional Grade: The "Pro" designation signifies advanced features suitable for both novice and experienced traders seeking reliable and efficient stop management.
How It Works:
To set up the indicator, begin by defining the Chrono Point, which specifies the exact time you want the trailing stop mechanism to activate. This allows for precise control over when your stops begin to trail. Next, set the Credit Unit as the initial entry price for your trade, serving as the baseline from which the trailing stops will adjust.
The indicator uses ATR-based adjustments to determine stop levels. Customize the sensitivity of the trailing stop by adjusting the ATR Length (default is 14) and ATR Multiplier (default is 0.5). A longer ATR length smooths out volatility, while a higher multiplier increases the distance of the stop from the price.
Select your Source Vector from "High/Low," "Close," or "Open" prices as the basis for stop calculation. This flexibility allows you to align the indicator with your preferred trading strategy. The indicator plots trailing stops directly on the chart, with color-coded lines indicating long (teal) and short (red) positions. You can adjust the line thickness and transparency for optimal visibility.
The Mission Status feature automatically detects whether the trade is long or short and adjusts the trailing stop accordingly. If the price hits the trailing stop, the trade is considered exited, and the indicator calculates the profit or loss percentage.
Benefits:
Risk Management: Protect your trades from adverse market movements while locking in profits as prices move favorably.
Automation: Reduce manual intervention with automatic stop adjustments, allowing you to focus on strategic decision-making.
User-Friendly Interface: Intuitive settings and clear visual cues make it easy to integrate into your existing trading workflow.
Conclusion:
Trailing Stop Pro is an essential tool for traders looking to enhance their risk management strategies with precision and ease. By automating the trailing stop process and providing clear visual feedback, this indicator empowers you to navigate the markets with confidence. Whether you're a seasoned trader or just starting, Trailing Stop Pro offers the functionality and flexibility needed to optimize your trading performance.
The Trailing Stop Pro indicator is a tool designed to assist traders in managing risk and optimizing their trading strategies. However, it should not be considered as financial advice or a guarantee of profitability. Trading involves significant risk, and it is possible to lose more than your initial investment. Users are encouraged to thoroughly test the indicator in a demo environment and consider their own financial situation and risk tolerance before using it in live trading. Past performance is not indicative of future results, and users should seek advice from a qualified financial advisor if needed.
Market Structure Trailing Stop [BigBeluga]The Market Structure Trailing Stop indicator is an advanced tool for identifying market structure shifts, liquidity sweeps, and potential trend reversals using comprehensive volume analysis. This indicator combines the analysis of market structure pivots (CHoCH - Change of Character) with a sophisticated volume-based trailing stop logic. By evaluating delta volume at key structural points, it allows traders to identify high-probability trend continuations or reversals and manage their trades more effectively.
🔵 KEY FEATURES
● Market Structure Analysis
Pivot-Based Market Structure : The indicator identifies high and lows using user-defined periods, allowing traders to spot key market structure shifts.
Change of Character (CHoCH) : The first significant break of a market structure is marked as a CHoCH, indicating a potential trend reversal.
Break of Structure (BoS) : The indicator highlights subsequent breaks of structure after CHoCH, providing traders with crucial insights into trend strength.
● Advanced Volume Analysis
Delta Volume Evaluation : The indicator calculates delta volume (difference between up and down volume) at each ChoCh or BoS market structure point to assess the strength of the move. Identify Delta Volume from break point back to Pivot
● Trailing Stop Logic
Volume-Validated Trailing Stop : The indicator automatically plots a trailing stop if the delta volume at the UP CHoCH is positive and above the defined threshold and vice versa for Down CHoCH , allowing traders to protect their profits while riding the trend.
Trend Weakness Detection : If a subsequent BoS occurs with negative delta volume or lower volume than the input threshold, the trailing stop disappears, indicating potential trend exhaustion or reversal.
Dynamic Stop Placement : The trailing stop is dynamically adjusted based on market structure and volume, providing traders with a more adaptive stop-loss strategy.
Up Trend Trailing Stop:
Down Trend Trailing Stop:
● Liquidity Sweep Detection
Liquidity Sweep (X) Labels : The indicator identifies liquidity sweeps—points where the price temporarily reverses to sweep liquidity above or below a key level—marked with an “X” label.
Potential Reversal Zones : These liquidity sweeps are potential reversal zones, especially when accompanied by significant delta volume changes, providing traders with early warnings of potential trend reversals.
🔵 HOW TO USE
● Identifying Market Structure Shifts
Change of Character (CHoCH) : When a CHoCH occurs, the indicator calculates the total volume from the high point to the break point. If the delta volume is positive and exceeds the input threshold, a trailing stop is plotted, signaling potential trend continuation.
Break of Structure (BoS) : If BoS is enabled, subsequent breaks of structure are highlighted. If these BoS points show weaker volume or negative delta volume, the trailing stop will disappear, indicating that the trend may be losing strength.
● Using the Trailing Stop Feature
Protecting Profits : Once a CHoCH occurs and the delta volume validates the trend, the trailing stop will be plotted below (or above) the price to protect profits while allowing the trend to run.
Trend Reversal Signals : If the trailing stop disappears due to weak volume at subsequent BoS points, it may signal that the trend is losing momentum, and traders may consider closing their positions or tightening their stops manually.
● Liquidity Sweep Interpretation
Spotting Reversal Zones : Liquidity sweeps, marked with an “X” label, indicate zones where the price has swept liquidity. These areas can serve as potential reversal zones, especially when significant delta volume is observed at these points.
Early Reversal Warnings : Traders can use these liquidity sweep labels as early warnings for potential trend reversals, particularly in conjunction with other technical analysis methods.
🔵 CUSTOMIZATION
Highs and Lows Calculation : Customize the number of bars to the left and right for identifying pivots and market structure shifts.
Volume Threshold : Define the volume threshold to filter out weaker moves and focus on significant market structure shifts.
BoS and Liquidity Sweep Labels : Toggle on or off the BoS and Liquidity Sweep labels to tailor the indicator to your trading style.
Trend Color : Enable or disable trend coloring for candles to visually highlight uptrends and downtrends on the chart.
🔵 CONCLUSION
The Market Structure Trailing Stop indicator combines advanced volume analysis with market structure detection to provide traders with a powerful tool for identifying and managing trends. By leveraging delta volume at key structure points, it helps traders validate trend strength and manage their positions with a dynamic trailing stop strategy. The addition of liquidity sweep detection further enhances its utility, offering early warnings of potential trend reversals. This indicator is ideal for traders who want to gain a deeper understanding of market structure while incorporating volume-based insights into their trading strategies.
AlgoBuilder [Trend-Following] | FractalystWhat'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 COINBASE: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.
Trailing Stop-Loss Indicator (FinnoVent)The Dynamic 9 EMA Trailing Stop-Loss Indicator is a specialized tool designed for the TradingView community to enhance risk management in trading. This script dynamically adjusts a trailing stop-loss level based on the position of the price relative to a 9-period Exponential Moving Average (EMA), offering traders a systematic approach to protect potential profits and limit downside risk.
Functionality:
Adaptive Trailing Stop: The indicator calculates a trailing stop-loss that adjusts with the 9 EMA, providing a responsive method to secure gains or prevent extensive losses.
EMA Trend Indicator: The 9-period EMA serves as a momentum indicator, with the script adjusting the trailing stop-loss accordingly — above the EMA for short positions and below for long positions.
Entry Signal Visualization: Entry signals are visualized on the chart, indicating potential long and short positions based on price crossovers with the EMA.
Application:
This indicator is ideal for traders who utilize technical analysis to make informed decisions. By automatically adjusting the stop-loss level to the evolving market conditions, it is particularly useful for:
Day traders looking to capitalize on short-term price movements.
Swing traders aiming to secure positions during more extended market waves.
Any trading strategy that benefits from dynamic stop-loss management.
Usage:
To use the indicator, simply add it to your TradingView chart, and it will automatically plot the trailing stop levels. The green and red lines represent the trailing stops for long and short positions, respectively, providing clear visual cues for potential exit points.
Compliance with TradingView House Rules:
This script is provided for educational purposes and does not constitute investment advice. It is a unique creation that has been developed to contribute to the TradingView community by offering a tool that helps traders manage their trades more effectively.
Trailing stopHi all!
This script helps to alert you when a trailing stop is hit. More specifically it alerts you when the low of the candle crosses below your trailing stop. A trailing stop follows a price positive movements. It raises your stop when price goes up, but keeps it at the same level if price goes down, so it "locks" in your profit. You define your long entry bar and choose one of the following methods for the stop:
ATR
The Average True Range (ATR) is popular to trail stops. The trailing stop is raised by the low minus the ATR (times a factor that can be set under the settings for ATR).
EMA
The Exponential Moving Average (EMA) can be used to trail your stop. When the low goes below the EMA an alert is sent about the stop. Its length can be set in the settings.
SMA
The Simple Moving Average (SMA) can be used to trail your stop. When the low goes below the SMA an alert is sent about the stop. Its length can be set in the settings.
Source
An external source can be useful as a stop signal. You can use this option that will stop you out when the signal returns anything else than "na". E.g. if you want a stop when KivancOzbilgic script "SuperTrend" () turns red, you set the source to "Supertrend: Down Trend". This option will not draw pretty things on the chart, but it will alert you!
Please note that this is for long entries only.
Best of trading luck!
Auto Trailing stoploss By InvestYourAsset💥The Auto Trailing Stop-Loss indicator is a technical indicator that uses the ATR (Average True Range) to calculate a trailing stop-loss for both long and short positions.
💥The signals according to the indicator allows traders to exit from the position before its too late! The indicator can be used to determine when to enter and exit trades.
💥To use the indicator, you simply need to set the input parameters to suit your trading style and risk tolerance. The default values for the parameters are:
p: The ATR period (14)
q: The stop period (20)
x: The multiplier used to calculate the initial high and initial low (1.5)
Calculations:
📈Calculates the ATR using the specified period you can modify ATR period according to your trading style.
📈Calculates the initial high and low stop levels based on the highest high and lowest low over the user defined ATR period.
📈Calculates short and long stoploss levels using the initial high and low stops.
💥Once you have set the input parameters according to your trading style whether you are a day trader or a swing trader, the indicator will plot the short stoploss, long stoploss, and stoploss hit signals on your chart.
💥You can use the indicator to enter and exit trades in a various ways.
For example,
🚀 you could enter a long trade when the price crosses above both red and green lines plotted on the chart. (or when price crosses over both short stoploss and long stoploss.) You could also use the indicator to secure your profits by moving your stop-loss up as the price moves in your favor.
Here is an example of how you could use the indicator to enter and exit trades:
🚀Enter a long trade when the price crosses above the red line or short stoploss.
✅keep Moving your stop-loss upward with the long stoploss or green line.
✅Exit the trade when the price crosses below the long stoploss or green line.
💥You can also use the indicator to protect your existing trades. For example, if you are already in a long trade, you could move your stop-loss up to the short stop when the price moves up 10%. This will help you to protect your profits in case the price starts to move against you.
💥💥some additional tips for using the Auto Trailing Stop-Loss indicator:
✅Use the indicator in conjunction with other technical indicators or your own trading strategy to generate entry and exit signals.
✅Backtest your trading strategy before using it live to make sure that it is profitable.
✅Use the indicator to protect your profits by moving your stop-loss up as the price moves in your favor.
✅ Always follow risk management rules and manage your position sizing according to your risk appetite.
✅ Be aware of the overall trend direction. If the trend is up, you should be looking for bullish reversals or continuations. If the trend is down, you should be looking for bearish reversals or continuations.
This script essentially provides a visual representation of a trading strategy that automatically adjusts stop-loss levels based on market volatility (ATR). It also includes signals for entering long or short positions and visually highlights these signals on the chart.
📣📣Follow us for timely updates regarding future indicators and give it a like if you appreciate the work.📣📣
Sublime Trading | Trailing StoplossWhat kind of traders/investors are we?
We are trend followers. Our scripts are designed to be used on the higher timeframes (weekly/daily) to catch the large moves/trends in the market.
Most have heard of long-term trend following. Few know how to execute the strategy.
Our scripts are designed specifically to identify and invest in long-term market trends.
What does this script do?
The exit from a position is arguably more important than the entry.
Traders/Investors will regularly find themselves in an asset based on some logic, but the exit management is very much an afterthought.
Hence why traders often take profit too early and hold onto losing positions. It is emotionally driven.
The Trailing Stoploss script is designed to remove the guesswork and show you precise levels you will want to consider exiting a position when an asset reverses.
How is the trailing stoploss produced?
The script uses the formula ATR 15 x 4.
We use ATR as it produces a stoploss which is unique to the volatility of the asset. The more volatile the asset, the wider the stoploss.
We use ATR 15 as it brings an average reading across half a month, incorporating days of extreme volatility.
The multiplier 4 works well to avoid positions being stopped out prematurely on pullbacks.
When the trailing stoploss is hit, this is where you will want to consider taking profit.
What is the best timeframe to use the script?
We recommend the daily timeframe as this is where trend followers enter assets to maximise the potential of long-term trends.
The higher timeframes are where traders and investors take fewer positions and hold for longer time periods.
The trailing stoploss follows the price of the asset a distance away to give the trend structure enough space and time to develop.
A trend is ultimately a function of time. If you eliminate time, you eliminate the trend. If you eliminate the trend, you eliminate profit.
The Trailing Stoploss script is necessary for investors who appreciate that profit is accumulated by letting winning positions run and not taking profit too early.
What makes this script unique?
Exit management and knowing when to let go of an asset is one of the main struggles budding investors face. This script has been coded specifically for the daily timeframe to:
Create a trailing stoploss that is unique to the volatility of the asset.
Allow investors to stay in positions for the duration of the trend over many months.
To distinguish between a pullback and a market reversal, allowing for discretion.
This TSL script is designed to manage positions investors take in line with long-term market trends.
Spinn: SuperStopAdaptive Trailing Stop-Loss Indicator
This indicator will be beneficial for traders who have already opened a position and are looking to maximize their profits but are uncertain about the optimal time to exit. It provides clear and adaptive stop-loss levels based on market data, especially in highly volatile markets. It offers the ability to close trades automatically (through the use of web-hooks).
The algorithm is based on using the Average True Range (ATR) to set stop-loss levels. The scaling factor allows you to adjust the optimal distance from the stop-loss line to the price line.
A unique feature of this indicator is that the user can set the target timeframe (Target TF). This means that instead of just using the current chart's timeframe, you can set a multiplier or choose the target timeframe manually. This offers the ability to analyze volatility across different timeframes, which can be valuable for various trading strategies.
The timeframe multiplier is a highlight of this indicator. When switching the current timeframe, there is no need to manually change the target timeframe - this is very convenient.
The ability for automatic alerts when the price touches or crosses stop-loss levels is included.
--
Индикатор адаптивных плавающих Стоп-лоссов
Индикатор будет полезен для трейдеров, которые уже открыли сделку и хотят максимизировать свою прибыль, но не уверены в оптимальном моменте для выхода. Он предоставляет четкие и адаптивные уровни стоп-лоссов, основанные на рыночных данных, особенно при высокой волатильности. Дает возможность закрывать сделки в автоматическом режиме (через использование веб-хуков).
Алгоритм основан на использовании среднего истинного диапазона (ATR) для определения уровней стоп-лоссов. Коэффициент масштабирования дает возможность настроить оптимальное расстояние от линии стоп-лосса до линии цены.
Особенность индикатора в том, что пользователь может настроить целевой таймфрейм (Target TF). Это значит, что вместо того чтобы просто использовать текущий таймфрейм графика, можно установить множитель или выбрать целевой таймфрейм вручную. Это дает возможность анализировать волатильность на разных временных рамках, что может быть полезно для различных торговых стратегий.
Множитель таймфрейма - это фишка данного индикатора. При переключении текущего таймфрейма не придется вручную менять целевой таймфрейм - это очень удобно.
Предусмотрена возможность автоматических оповещений при касании или пересечении уровней стоп-лоссов.
Limit Order + ATR Stop-Loss [TANHEF]This indicator enables interactive placement of limit or stop-limit orders with a trailing ATR stop-loss and optional profit target (with alerts). Refer to the images below for further clarification.
Why use a trailing stop-loss?
A trailing stop-loss serves as an exit strategy when price moves against you, while also allowing you to adjust the exit point further into profit when price moves favorably. The ATR (Average True Range), a reliable measure of volatility, acts as an effective risk management tool, functioning as a trailing stop-loss.
Indicator Explanation
Initial indicator placement: Select Long Limit or Long-Stop Limit order.
Change Entry Type: Switch between Long and Short within settings.
Modify entry price: Drag circle, adjust in settings, or re-add indicator to chart.
Optional Profit Target: Use Risk/Reward ratio or specify price.
Entry anticipation: Estimated ATR stop-loss and profit target as blue circles (fluctuates with volatility changes).
Entry triggered: Actual ATR stop-loss and profit target plotted.
Exit conditions: Stop-loss or profit target hit, exit entry.
Update Frequency: Continuously, Bar Open, or Bar Open on entry then continuously.
ATR Overlap: no entry occurs if the ATR overlaps with price (stop-loss 'hit' already on entry bar)
Table: Displays input settings selected.
Show Only On Ticker: Ability to hide indicator on other tickers.
Long Limit
Long Stop-Limit
Short Limit
Short Stop-Limit
Alerts
1. 'Check' alerts to use within indicator settings (entry, trailing stop hit, profit target hit, and failed entry).
2. Select 'Create Alert'
3. Set the condition to 'Limit Order + ATR Stop-Loss''
4. Select create.
Additional details can be added to the alert message using these words in between Curly (Brace) Brackets:
{{trail}} = ATR trailing stop-loss (price)
{{target}} = Price target (price)
{{type}} = Long or Short stop-loss (word)
{{traildistance}} = Trailing Distance (%)
{{targetdistance}} = Target Distance (%)
{{starttime}} = Start time of position (day:hr:min)
{{maxdrawdown}} = max loss
{{maxprofit}} = max profit
{{update}} = stoploss update frequency
{{entrysource}} = entry as 1st bar source (yes/no)
{{triggerentry}} = Wick/Close Trigger entry input
{{triggerexit}} = Wick/Close Trigger exit input
{{triggertarget}} = Wick/Close Trigger target input
{{atrlength}} = ATR length input
{{atrmultiplier}} = ATR multiplier input
{{atrtype}} = ATR type input
{{ticker}} = Ticker of chart (word)
{{exchange}} = Exchange of chart (word)
{{description}} = Description of ticker (words)
{{close}} = Bar close (price)
{{open}} = Bar open (price)
{{high}} = Bar high (price)
{{low}} = Bar low (price)
{{hl2}} = Bar HL2 (price)
{{volume}} = Bar volume (value)
{{time}} = Current time (day:hr:min)
{{interval}} = Chart timeframe
{{newline}} = New line for text
Market Structure Trailing Stop [LuxAlgo]This script returns trailing stops on the occurrence of market structure (CHoCH/BOS labeling). Trailing stops are adjusted based on trailing maximums/minimums with the option for users to be able to control how quickly a trailing stop can converge toward the price.
🔶 SETTINGS
Pivot Lookback: Pivot length used for the detection of swing points.
Increment Factor %: Controls how fast trailing stops converge toward the price, with lower values returning slower converging trailing stops.
Reset Stop On: Determines if trailing stops are reset on CHoCH structure or all (CHoCH + BOS).
Show Structure: Determines if market structure is displayed.
🔶 USAGE
Trailing stops allow traders to protect them against downside risk while also guaranteeing a potential profit in case the market goes in the expected direction of the trade.
Users making use of market structure as a primary entry condition can benefit from having trailing stops based on these to either provide an additional exit condition or to provide points of support/resistance with the price.
Trailing stops can avoid being hit more frequently by using a lower Increment Factor % setting.
Finally, users can reset the trailing stop when any market structure is detected (or only on CHoCHs). Allowing trailing stops to reset on the detection of any market structure allows the indicator to return trailing stops closer to the price. CHoCH labels are highlighted as dashed lines while BOS labels are highlighted as dotted lines.
🔶 DETAILS
When a new structure (or only CHoCH if specified by the user) is detected, trailing stops will initially be set based on the maximum/minimum made on the previous trend. This will also set the trailing maximum/minimum to the current price value.
If an uptrend is detected (most recent market structure is bullish) then the trailing stop will increase if the trailing maximum increase, the increment is calculated as:
trailing stop = trailing stop + Increment Factor % of (trailing maximum - previous trailing maximum)
If a downtrend is detected (most recent market structure is bearish) then the trailing stop will decrease if the trailing minimum decrease, the decrement is calculated as:
trailing stop = trailing stop + Increment Factor % of (trailing minimum - previous trailing minimum)
Trail Blaze - (Multi Function Trailing Stop Loss) - [mutantdog]Shorter version:
As the title states, this is a 'Trailing Stop' type indicator, albeit one with a whole bunch of additional functionality, making it far more versatile and customisable than a standard trailing stop.
The main set of features includes:
Three independent trailing types each with their own +/- multipliers:
- Standard % change
- ATR (aka Supertrend)
- IQR (inter-quartile range)
These can be used in isolation or summed together. A subsequent pair of direction specific multipliers are also included.
Two separate custom source inputs are available, both feature the standard options alongside a selection of 'weighted inputs' and the option to use another indicator (selected via 'AUX'):
- 'Centre' determines the value about which the trailing sum will be added to define the stop level.
- 'Trigger' determines the value used for crossing of stops, initiating trend changes and triggering alerts.
A selection of optional filters and moving averages are available for both.
Furthermore there are various useful visualisation options available, including the underlying bands that govern the stop levels. Preset alerts for trend reversals are also included.
This is not really an 'out-of-the-box' indicator. Depending upon the market and timeframe some adjustments will be necessary for it to function in a useful manner, these can be as simple or complex as the feature-set allows. Basic settings are easy to dial in however and the default state is intended as a good starting point. Alternatively with some experimentation, a plethora of unique and creative configurations are possible, making this a great tool for tweaking. Below is a more detailed overview followed by a bunch of simple example settings.
------------------------
Lengthy Version :
DESIGN & CONCEPT
Before we start breaking this down, a little background. This started off as an attempt to improve upon the ever-popular Supertrend indicator. Of course there are many excellent user created variants available utilising some interesting methods to overcome the drawbacks of the basic version. To that end, rather than copying the work of others, the direction here shifted towards a hybrid trailing stop loss with a bunch of additional user customisation options. At some point, a completely different project involving IQR got morphed into this one. After sitting through months of sideways chop (where this proved to be of limited use), at the time of publication the market has began to form some near term trend direction and it appears to be performing well in many different timeframes.
And so with that out of the way...
INPUTS
The standard Supertrend (and most other variants) includes a single source input, as default set to 'hl2' (candle mid-range). This is the centre around which the atr bands are added/subtracted to govern the stop levels. This is not however the value which is used to trigger the trend reversal, that is usually hard-coded to 'close'. For this version both source values are adjustable: labelled 'centre' and 'trigger' respectively.
Each has custom input selectors including the usual options, a selection of 'weighted inputs' and the option to use another indicator (selected from the Aux input). The 'weighted inputs' are those introduced in Weight Gain 4000, for more details please refer to that listing. These should be treated as experimental, however may prove useful in certain configurations. In this case 'hl-oc2' can be considered an estimate of the candle median and may be a good alternative to the default 'centre' setting of 'hl2', in contrast 'cc-ohlc4' can tend to favour the extremes in the trend direction so could be useful as a faster 'trigger' than the default 'close'.
To cap them off both come with a selection of moving average filters (SMA, EMA, WMA, RMA, HMA, VWMA and a simple VWEMA - note: not elastic) aswell as median and mid-range. 'Centre' can also be set to the output of 'trigger' post-filter which can be useful if working with fast/slow crosses as the basis.
DYNAMICS
This is the main section, comprised of three separate factors: 'TSL', 'ATR' and 'IQR'. The first two should be fairly obvious, 'TSL' (trailing stop loss) is simply a percentage of the 'centre' value while 'ATR' (average true range) is the standard RMA-based version as used in Supertrend, Volatility Stop etc.
The third factor is less common however: 'IQR' (inter-quartile range). In case you are unfamiliar the principle here is, for a given dataset, the greatest 25% and smallest 25% of samples are removed. The remainder is then treated as a set and the range is calculated by highest - lowest. This is a commonly used method in statistical analysis, by removing the extremes it is less prone to influence by outliers and gives a good representation of the main dispersion around the median. In practise i have found it can be a good alternative to ATR, translating better across multiple time-frames due to it representing a fraction of the total range rather than an average of per-candle range like ATR. Used in combination with the others it can also add a factor more representative of longer-term/higher-timeframe trend. By discarding outliers it also benefits from not being impacted by brief pumps/volatility, instead responding only to more sustained changes in trend, such as rallies and parabolic moves. In order to give an accurate result the IQR is calculated using a dataset of high, low and hlcc4 values for all bars within the lookback length. Once calculated this value is then halved which, strictly speaking, makes it a semi-interquartile range.
All three of these components can be used individually or summed together to create a hybrid dynamics factor. Furthermore each multiplier can be set to both positive and negative values allowing for some interesting and creative possibilities. An optional smoothing filter can be applied to the sum, this is a basic SWMA-4 which is can reduce the impact of sudden changes but does incur a noticeable lag. Finally, a basic limiter condition has been hard-coded here to prevent the sum total from ever going below zero.
Capping off this section is a pair of direction multipliers. These simply take the prior dynamics sum and allow for further multiplication applied only to one side (uptrend/lo-stop and downtrend/hi-stop). To see why this is useful consider that markets often behave differently in each direction, we've all seen prices steadily climb over several weeks and then abruptly dump in the process of a day or two, shorter time frames are no stranger to this either. A lack of downside liquidity, a panicked market, aggressive shorts. All these things contribute to significant differences in downward price action. This function allows for tighter stops in one direction compared to the other to reflect this imbalance.
VISUALISATIONS
With all of these options and possibilities, some visual aids are useful. Beneath the dynamics' section are several visual options including both sources post-filter and the actual 'bands' created by the dynamics. These are what govern the stop levels and seeing them in full can help to better understand what our various configurations actually do. We can even hide the stop levels altogether and just use the bands, making this a kind of expanded Keltner Channel. Here we can also find colour and opacity settings for everything we've discussed.
EXAMPLES
The obvious first example here is the standard %-change trailing stop loss which, from my experience, tends to be the best suited for lower time frames. Filtering should probably minimal here. In both charts here we use the default config for source inputs, the top is a standard bi-directional setup with 1.5% tsl while the bottom uses a 2.5% tsl with the histop multiplier reduced to 0 resulting in an uptrend only stoploss.
Shown here in grey is the standard Supertrend which uses 'hl2' as centre and 'close' as trigger, ATR(10) multiplied by 3. On top we have the default filtered source config with ATR(8) multiplied by 2 which gives a different yet functionally similar result, below is the same source config instead using IQR(12) multiplied by 2. Notice here the more 'stepped' response from IQR following the central rally, holding back for a while before closing in on price and ultimately initiating reversal much sooner. Unlike ATR, the length parameter for IQR is absolute and can more significantly affect its responsiveness.
Next we focus on the visualisation options, on top we have the default source config with ATR(8) multiplied by 2 and IQR(12) multiplied by 1. Here we have activated the switch to show 'bands', from this we can see the actual summed dynamics and how it influences the stop levels. Below that we have an altogether different config utilising the included filters which are now visible. In this example we have created a basic 8/21 EMA cross and set a 1% TSL, notice the brief fakeout in the middle which ordinarily might indicate a buy signal. Here the TSL functions as an additional requirement which in this case is not met and thus no buy signal is given.
Finally we have a couple of more 'experimental' examples. On top we have Lazybear's 'Variable Moving Average' in white which has been assigned via 'aux' as the centre with no additional filtering, the default config for trigger is used here and a basic TSL of 1.5% added. It's a simple example but it shows how this can be applied to other indicators. At the bottom we return to the default source config, combining a TSL of 8% with IQR(24) multiplied by -2. Note here the negative IQR with greater length which causes the stop to close in on price following significant deviations while otherwise remaining fairly wide. Combining positive and negative multiples of each factor can yield mixed results, some more useful than others depending upon suitable market conditions.
Since this has been quite lengthy, i shall leave it there. Suffice to say that there are plenty more ways to use this besides these examples. Please feel free to share any of your own ideas in the comments below. Enjoy.
TrailingStopsLibrary "TrailingStops"
This library contains functions to output trailing stop lines.
f_marketStructureStop(_restartMode, _flipMode, _restartLowIn, _restartHighIn)
Parameters:
_restartMode - Defines how the stop lines persist. Allowed values are:
"Always On" - The stop lines are always present and they just reset when they're crossed.
"Flip" - The stop lines flip when they're crossed.
"Manual" - The stop lines turn off when they're crossed, and turn back on again when _restartLowIn or _restartHighIn are passed into the function as true.
_flipMode - Defines whether the stop lines are broken by wicks or closes. Allowed values are "Wick", and "Close".
_restartLowIn - If _restartMode is "Manual", passing this parameter as true restarts the Low stop line.
_restartHighIn - If _restartMode is "Manual", passing this parameter as true restarts the High stop line.
@returns - floats for the Low and High stop line.
Anti-trap Trailing Stop Loss by KalyanBetaAnti-trap Trailing Stop Loss by KalyanBeta or ATSL
ATSL changes color when there it identifies price manipulation/ SL Hunting / Traps by Smart Money.
Change in color may be an exit signal for your trade in current direction.
This is a very simple indicator which can be used to predict Traps or Stop-loss hunting.
This can help in Trailing Stop-loss and in Exit decisions along with your own strategy.
ATSL may be used in all timeframes.
Please back-test it along with your strategy and then use it for Trailing the Stop-loss without getting trapped by operators and stop-loss hunters.
All the best.
Do post your feedback in comments below. Thank you.
Interactive ATR Stop-Loss [TANHEF]This indicator is "Interactive" which means some inputs can are manually added through the first click after adding the indicator to the chart (ATR Trailing Stop-loss start point). See images below for more explanation.
Why use a trailing stop-loss?
A trailing stop-loss provides an exit when price moves against you but also enables you to move the exit point further into profit when price is moving in the desired direction of a trade. The ATR (Average True Range) which is used to measure volatility, is very effective at functioning as a trailing stop loss.
Indicator Explanation
Initially when this indicator is added to the chart, you will be prompted to select where to begin the ATR Trailing Stop-loss.
For a long stop-loss, select below price.
For a short stop-loss, select above price.
After this indicator is placed, it can be modified via dragging or from within the settings by modifying the time and the price input. Or simply re-add the indicator to the chart.
The ATR Stop Loss plotted. Note that the trailing value that is considered as the stop loss value is the value of the ATR from the prior candle. The settings for the ATR calculation can be modified within the settings.
An optional fixed profit target can be added within the settings. This profit target will only actively be plotted when the ATR Trailing Stop-loss has not be hit hit yet or until the profit target has been hit.
Here shows that the profit target was hit, then later on the ATR Trailing Stop-loss was hit.
Note, trailing stop-loss will continue to be plotted until it has been hit regardless of the profit target being hit or not.
Alerts
1. 'Check' alerts to use within indicator settings (trailing stop hit and/or profit target hit).
2. Select 'Create Alert'
3. Set the condition to 'Interactive ATR''
4. Select create.
Trailing Stop SnippetThis is an example snippet that should allow for adding a trailing stop and trailing stop activation to almost any script.
You can use it by setting a trailing stop alone. This will provide you standard trailing stop functionality allowing you to lock in profits and increase your stop-loss as the price moves in your direction.
You can also set the trailing stop activation to trigger the original trailing stop at a certain level. "Once price rises 5%, set a trailing stop at break even". This would be set as 5 and 5 in the settings.
[fpemehd] Strategy TemplateHello Guys! Nice to meet you all!
This is my fourth script!
This is the Strategy Template for traders who wants to make their own strategy.
I made this based on the open source strategies by jason5480, kevinmck100, myncrypto. Thank you All!
### StopLoss
1. Can Choose Stop Loss Type: Percent, ATR, Previous Low / High.
2. Can Chosse inputs of each Stop Loss Type.
### Take Profit
1. Can set Risk Reward Ratio for Take Profit.
- To simplify backtest, I erased all other options except RR Ratio.
- You can add Take Profit Logic by adding options in the code.
2. Can set Take Profit Quantity.
### Risk Manangement
1. Can choose whether to use Risk Manangement Logic.
- This controls the Quantity of the Entry.
- e.g. If you want to take 3% risk per trade and stop loss price is 6% below the long entry price,
then 50% of your equity will be used for trade.
2. Can choose How much risk you would take per trade.
### Plot
1. Added Labels to check the data of entry / exit positions.
2. Changed and Added color different from the original one. (green: #02732A, red: #D92332, yellow: #F2E313)
ATR Trailing Stop Loss [V5]A complete ATR Trailing Stop Loss in version 5.
Features Include:
Timeframe Option
Long/Short Triggers (Green/Red Triangles)
Long/Short Conditions (Bottom Colored Line)
"Golden" Long/Short Triggers (Yellow Triangles)(Hanging Man or Shooting Star Candlestick patterns breaking ATR trailing stop)
Alerts
ATR alerts & backtestingThe Basics
Alert will trigger if the current (real time) price surpasses the high of the ATR of the previous bar. (can also be set for the Low of the ATR). Each time the follow up candle surpasses the high of the previous ATR, the background will be coloured orange. This makes back testing easier on the eye. This can be turned off.
- Colours can be changed.
- Can also set a color and alert when the current price surpasses the Low of the ATR of the previous bar.
- ATR distance can be changed.
- Can be used on different chart types.
- Can be used as entry or exits in combination with bots.
- Can display only ATR top or bottom or both.
Example
An alert will trigger if the price of the current bar surpasses the red dot (ATR) of the previous bar.
Alerts can be created on all timeframes, if this is within your Tradingview plan.
Final Words
Disclaimer: Please use it with care and at own risk. The owner of this indicator is not liable for any financial losses.
Past performance is no guarantee of future returns.
Rob Hoffman's 50/80/90/Price Trailing Stop LossA trailing stop loss method by Rob Hoffman.
Set your entry, TP, and SL.
Once price is 50% of its way to the TP, set your stop loss at the gray line.
Once price is 80% of its way to the TP, set your stop loss at the light gray line.
Once price is 90% of its way to the TP set your stop loss at the white line.
Pivot Based Trailing Maxima & Minima [LuxAlgo]This indicator returns trailing maximums/minimums and the resulting average, each resetting on the occurrence of a pivot point high/low, thus allowing to highlight past and current support and resistance levels.
Note that the user has the option to make the indicator subject to backpainting or not. Backpainting would offset the indicator output to the past and as such would be less suited for real-time applications.
🔶 USAGE
🔹 Non Backpainting
The indicator can highlight points of support and resistance given by the trailing maximum/minimum average.
An uptrend is indicated when the trailing maximum is making a new higher high, while a downtrend is indicated when the trailing minimum makes a new lower low.
🔹 Backpainting
When backpainting is enabled the historical trailing maximum/minimum and their resulting average are offset to the past. However, we extend these to the most recent bar, allowing for real-time applications of the indicator.
Users can easily analyze past trends and determine their type by observing the trailing maximum/minimum behavior. For example, trailing maximums/minimums not making new higher high/lower low would indicate a ranging market.
The frequency of new higher high/lower low can also help determine how bullish/bearish a trend was.
🔶 SETTINGS
Length: Determines the pivot high/low lookback, with higher values allowing to detect longer-term tops and bottoms.
Backpaint: Determine if the indicator is subject to backpainting. Enabling this setting would offset the returned results in the past.
Template Trailing Strategy (Backtester)💭 Overview
💢 What is the "Template Trailing Strategy” ❓
The "Template Trailing Strategy" (TTS) is a back-tester orchestration framework. It supercharges the implementation-test-evaluation lifecycle of new trading strategies, by making it possible to plug in your own trading idea.
While TTS offers a vast number of configuration settings, it primarily allows the trader to:
Test and evaluate your own trading logic that is described in terms of entry, exit, and cancellation conditions.
Define the entry and exit order types as well as their target prices when the limit, stop, or stop-limit order types are used.
Utilize a variety of options regarding the placement of the stop-loss and take-profit target(s) prices and support for well-known techniques like moving to breakeven and trailing.
Provide well-known quantity calculation methods to properly handle risk management and easily evaluate trading strategies and compare them.
Alert on each trading event or any related change through a robust and fully customizable messaging system.
All the above, build a robust tool that, once learned, significant and repetitive work that strategy developers often implement individually on every strategy script is eliminated. Taking advantage of TradingView’s built-in backtesting engine the evaluation of the trading ideas feels natural.
By utilizing the TTS one can easily swap “trading logic” by testing, evaluating, and comparing each trading idea and/or individual component of a strategy.
Finally, TTS, through its per-event alert management (and debugging) system, provides a fully automated solution that supports automated trading with real brokers via webhooks.
NOTE: The “Template Trailing Strategy” does not dictate the way you can combine different (types of) indicators or how you should combine them. Thus, it should not be confused as a “Trading System”, because it gives its user full flexibility on that end (for better or worse).
💢 What is a “Signal Indicator” ❓
“Signal Indicator” (SI) is an indicator that can output a “signal” that follows a specific convention so that the “Template Trailing Strategy” can “understand” and execute the orders accordingly. The SI realizes the core trading logic signaling to the TTS when to enter, exit, or cancel an order. A SI instructs the TTS “when” to enter or exit, and the TTS determines “how” to enter and exit the position once the Signal Indicator generates a signal.
A very simple example of a Signal Indicator might be a 200-day Simple Moving Average Signal. When the price of the security closes above the 200-day SMA, a SI would provide TTS with a “long entry signal”. Once TTS receives the “long entry signal”, the TTS will open a long position and send an alert or automated trade message via webhook to a broker, based on the Entry settings defined in TTS. If the TTS Entry settings specify a “Market” order type, then the open long position will be executed by TTS immediately. But if the TTS Entry settings specify a “Stop” order type with a 1% Stop Distance, then when the price of the security rises by 1% after the “long entry signal” occurs, the TTS will open a long position and the Long Entry alert or webhook to the broker will be sent.
🤔 How to Guide
💢 How to connect a “signal” from a “Signal Indicator” ❓
The “Template Trailing Strategy” was designed to receive external signals from a “Signal Indicator”. In this way, a “new trading idea” can be developed, configured, and evaluated separately from the TTS. Similarly, the SI can be held constant, and the trading mechanics can change in the TTS settings and back-tested to answer questions such as, “Am I better with a different stop loss placement method, what if I used a limit order instead of a stop order to enter, what if I used 25% margin instead of trading spot market?”
To make that possible by connecting an external signal indicator to TTS, you should:
Add in the same chart, the “Signal Indicator” of your choice (e.g. “Two MA Signal Indicator” , “Click Signal Indicator” , “Signal Adapter” , “Signal Composer” ) and the “Template Trailing Strategy”.
Go to the “Settings/Inputs” tab in the “🛠️ STRATEGY” group of the TTS and change the "𝐃𝐞𝐚𝐥 𝐂𝐨𝐧𝐝𝐢𝐭𝐢𝐨𝐧𝐬 𝐌𝐨𝐝𝐞" to “🔨External”
Go to the “🔨 STRATEGY – EXTERNAL” group settings of the TTS and change the “🔌𝐒𝐢𝐠𝐧𝐚𝐥 🛈➡” to the output signal of the “Signal Indicator” you want to connect. The selected combo box option should look like “:🔌Signal to TTS” where should correspond to the short title of your “Signal Indicator”
💢 How to create a Custom Trading logic ❓
The “Template Trailing Strategy” provides two ways to plug in your custom trading logic. Both of them have their advantages and disadvantages.
✍️ Develop your own Customized “Signal Indicator” 💥
The first approach is meant to be used for relatively more complex trading logic. The advantages of this approach are the full control and customization you have over the trading logic and the relatively simple configuration setup by having two scripts only. The downsides are that you have to have some experience with pinescript or you are willing to learn and experiment. You should also know the exact formula for every indicator you will use since you have to write it by yourself. Copy-pasting from existing open-source indicators will get you started quite fast though.
The idea here is either to create a new indicator script from scratch or to copy an existing non-signal indicator and make it a “Signal Indicator”. To create a new script, press the “Pine Editor” button below the chart to open the “Pine Editor” and then press the “Open” button to open the drop-down menu with the templates. Select the “New Indicator” option. Add it to your chart to copy an existing indicator and press the source code {} button. Its source code will be shown in the “Pine Editor” with a warning on top stating that this is a read-only script. Press the “create a working copy”. Now you can give a descriptive title and a short title to your script, and you can work on (or copy-paste) the (other) indicators of your interest. Having all the information needed to make your decision the only thing you should do is define a DealConditions object and plot it like this:
import jason5480/tts_convention/4 as conv
// Calculate the start, end, cancel start, cancel end conditions
dealConditions = conv.DealConditions.new(
startLongDeal = ,
startShortDeal = ,
endLongDeal = ,
endShortDeal = ,
cnlStartLongDeal = ,
cnlStartShortDeal = ,
cnlEndLongDeal = ,
cnlEndShortDeal = )
// Use this signal in scripts like "Template Trailing Strategy" and "Signal Composer" that can use its value
// Emit the current signal value according to the "two channels mod div" convention
plot(series = conv.getSignal(dealConditions), title = '🔌Signal to TTS', color = color.olive, display = display.data_window + display.status_line, precision = 0)
You should write your deal conditions appropriately based on your trading logic and put them in the code section shown above by replacing the “…” part after “=”. You can omit the conditions that are not relevant to your logic. For example, if you use only market orders for entering and exiting your positions the cnlStartLongDeal, cnlStartShortDeal, cnlEndLongDeal, and cnlEndShortDeal are irrelevant to your case and can be safely omitted from the DealConditions object. After successfully compiling your new custom SI script add it to the same chart with the TTS by pressing the “Add to chart” button. If all goes well, you will be able to connect your “signal” to the TTS as described in the “How to connect a “signal” from a “Signal Indicator”?” guide.
🧩 Adapt and Combine existing non-signal indicators 💥
The second approach is meant to be used for relatively simple trading logic. The advantages of this approach are the lack of pine script and coding experience needed and the fact that it can be used with closed-source indicators as long as the decision-making part is displayed as a line in the chart. The drawback is that you have to have a subscription that supports the “indicator on indicator” feature so you can connect the output of one indicator as an input to another indicator. Please check if your plan supports that feature here
To plug in your own logic that way you have to add your indicator(s) of preference in the chart and then add the “Signal Adapter” script in the same chart as well. This script is a “Signal Indicator” that can be used as a proxy to define your custom logic in the CONDITIONS group of the “Settings/Inputs” tab after defining your inputs from your preferred indicators in the VARIABLES group. Then a “signal” will be produced, if your logic is simple enough it can be directly connected to the TTS that is also added to the same chart for execution. Check the “How to connect a “signal” from a “Signal Indicator”?” in the “🤔 How to Guide“ for more information.
If your logic is slightly more complicated, you can add a second “Signal Adapter” in your chart. Then you should add the “Signal Composer” in the same chart, go to the SIGNALS group of the “Settings/Inputs” tab, and connect the “signals” from the “Signal Adapters”. “Signal Composer” is also a SI so its composed “signal” can be connected to the TTS the same way it is described in the “How to connect a “signal” from a “Signal Indicator”?” guide.
At this point, due to the composability of the framework, you can add an arbitrary number (bounded by your subscription of course) of “Signal Adapters” and “Signal Composers” before connecting the final “signal” to the TTS.
💢 How to set up ⏰Alerts ❓
The “Template Trailing Strategy” provides a fully customizable per-even alert mechanism. This means that you may have an entirely different message for entering and exiting into a position, hitting a stop-loss or a take-profit target, changing trailing targets, etc. There are no restrictions, and this gives you great flexibility.
First of all, you have to enable the alerts of the events that interest you. Go to the “🔔 ALERT MESSAGES” module of the TTS settings and check the “Enable…” checkbox of the events you are interested in. For each specific event, you will find a text area where you can type the exact message you want to receive when the event occurs. What’s more, there are placeholders you can use that will be replaced by the TTS with the actual values before the message is sent. The placeholder categories are the following and the placeholder names are self-explanatory.
Chart info: {{ticker}}, {{base_currency}}, {{quote_currency}}
Quantities and percentages: {{base_quantity}}, {{quote_quantity}}, {{quote_quantity_perc}},
{{take_profit_base_quantity}}, {{remaining_quantity_perc}}, {{remaining_base_quantity}}, {{risk_perc}}
Target prices: {{stop_loss_price}}, {{entry_price}}, {{entry+_price}}, {{entry-_price}},
{{exit_price}}, {{exit+_price}}, {{exit-_price}}, {{take_profit_price_1}},
{{take_profit_price_2}}, {{take_profit_price_3}}, {{take_profit_price_4}}, {{take_profit_price_5}}
❗ To get the message on the other side you have to set a strategy alert as described here and use the {{strategy.order.alert_message}} placeholder as text in the “Message Box” that contains the message that came from the TTS.
💢 How to execute my orders in a broker ❓
To execute your orders in a broker that supports webhook integration, you should enable the appropriate alerts in the “Template Trailing Strategy” first (see the “How to set up Alerts?” guide above). Then you should go to the “Create Alert/Notifications” tab check the “Webhook URL” and paste the URL provided by your broker. You have to read the documentation of your broker for more information on what messages are expected.
Keep in mind that some brokers have deep integration with TradingView so a per-event alert approach might be overkill.
📑 Definitions
This section tries to give some definitions in terms that appear in the “Settings/Inputs" tab of the “Template Trailing Strategy”
💢 What is Trailing ❓
Trailing is a technique where a price target follows another “barrier” price (usually high or low) by trying to keep a maximum distance from the “barrier” when it moves in only one direction (up or down). When the “barrier” moves in the other direction the price target will not change. There are as many types of trailing as price targets, which means that there are entry trailing, exit trailing, stop-loss trailing, and take-profit trailing techniques.
💢 What is a Moonbag ❓
A Moonbag in a trade is the quantity of the position that is reserved and will not be exited even if all take-profit targets defined in the strategy are hit, the quantity will be exited only if the stop-loss is hit or a close signal is received. This makes the stop-loss trailing technique in a trend-following strategy a good candidate to take advantage of a Moonbag.
💢 What is Distance ❓
Distance is the difference between two prices.
💢 What is Bias ❓
Bias is a psychological phenomenon where you make decisions based on market sentiment. For example, when you want to enter a long position you have a long bias, and when you want to exit from the long position you have a short bias. It is the other way around for the short position.
💢 What is the Margin Distance of a price target ❓
The Margin Distance of a price target is the distance that the target will deviate from its initial price. The direction of this deviation depends on the bias of the market. For example, suppose you are in a long position, and you set a take-profit target to the local high (HHLL). In that case, adding a margin of five ticks will place your take-profit target 5 ticks below this local high because you have a short bias when exiting a long position. When the bias is long the margin will be added resulting in a higher target price and when you have a short bias the margin will be subtracted.
⚙️ Settings
In the “Settings/Inputs” tab of the “Template Trailing Strategy”, you can find all the customizable settings that are provided by the framework. The variety of those settings is vast; hence we will only scratch the surface here. However, for every setting, there is an information icon 🛈 where you can learn more if you mouse over it. The “Settings/Inputs” tab is divided into ten main groups. Each one of them is responsible for one module of the framework. Every setting is part of a group that is named after the module it represents. So, to spot the module of a setting find the title that appears above it comes with an emoji and uppercase letters. Some settings might have the same name but belong to different modules e.g. “Distance Method”. Some settings are indented, which means that are closely related to the non-indented setting above. Usually, intended settings provide further configuration for one or more options of the non-intended setting. The groups that correspond to each module of the framework are the following:
📆 FILTERS
In this module time filters are implemented. You can define a DateTime window for your strategy to run. You can also specify a session by selecting the days of the week and the time range you want to operate.
🛠️ STRATEGY
This module contains the "𝐃𝐞𝐚𝐥 𝐂𝐨𝐧𝐝𝐢𝐭𝐢𝐨𝐧𝐬 𝐌𝐨𝐝𝐞" that defines if the “Template Trailing Strategy” will operate using the Internal or the External (“Signal Indicator”) conditions. Some general settings can be applied regardless of the mode.
🔨 STRATEGY – EXTERNAL
This sub-module makes the connection between the external signal of the “Signal Indicator” and the “Template Trailing Strategy”. It takes effect only if the "𝐃𝐞𝐚𝐥 𝐂𝐨𝐧𝐝𝐢𝐭𝐢𝐨𝐧𝐬 𝐌𝐨𝐝𝐞" is set to “🔨External”.
🔧 STRATEGY – INTERNAL
This sub-module defines the internal strategy logic and it's used as an example to demonstrate this framework. It should produce the same results as if the “Two MA Signal Indicator” was used as a “signal” in external mode. It takes effect only if the "𝐃𝐞𝐚𝐥 𝐂𝐨𝐧𝐝𝐢𝐭𝐢𝐨𝐧𝐬 𝐌𝐨𝐝𝐞" is set to “🔧Internal”.
🎢 VOLATILITY
This module defines the volatility parameters that are used in various other settings like average true range and standard deviation. It also makes it clear whether their values are updated during a trade (DYNAMIC) or not (STATIC).
🔷 ENTRY
This module defines how the start deal conditions will be executed by defining the order type of your entry and all necessary parameters to execute them.
🎯 TAKE PROFIT
This module defines the take-profit targets placement logic. The number of the take-profit targets to use, their distance from the entry price, and the distance from each other are only some of the features that can be configured.
🛑 STOP LOSS
This module defines the stop-loss target placement logic. The distance from the entry price, move to break even, and start trailing after a take-profit target is hit are only some of the features that can be configured.
🟪 EXIT
This module defines how the end deal conditions will be executed by defining the order type of your exit and all necessary parameters to execute them.
💰 QUANTITY/RISK MANAGEMENT
This module defines the method that calculates the amount of money you will put into each trade. Also, the percentage of the Moonbag quantity can be configured.
📊 ANALYTICS
This module can visualize some extra analytics of the strategy in the chart and calculate some metrics to measure the overall performance.
🔔 ALERT MESSAGES
This module defines all the messages that can be emitted per event during the strategy execution.
😲 Caveats
💢 Does “Template Trailing Strategy” has a repainting behavior ❓
The answer is that the “Template Trailing Strategy” does not repaint as long as the “Signal Indicator” that is connected also does not repaint. If you developed your own SI make sure that you understand and know how to prevent this behavior. The publication by @PineCoders here will give you a good idea on how to avoid most of the repainting cases.
⚠️There is an exception though, when the “Enable Trail⚠️💹” checkbox is checked, the Take Profit trailing feature is enabled, and a tick-based approach is used, meaning that after a while, when the TradingView discards all the real-time data, assumptions will be made by the backtesting engine that will cause a form of repainting. To avoid making false assumptions please disable this feature in the early stages and evaluate its usefulness in your strategy later on, after first confirming the success of the logic without this feature. In this case, consider turning on the bar magnifier feature. This way you will get more accurate backtest results when the Take Profit trailing feature is enabled.
💢 Can “Template Trailing Strategy” satisfy all my trading strategies ❓
While this framework can satisfy quite a large number of trading strategies there are cases where it cannot do so. For example, if you have a custom logic for your stop-loss or take-profit placement, or if you want to dollar cost average, then it might be better to start a new strategy script from scratch.
⚠️ It is not recommended to copy the official TTS code and start developing unless you are a pine wizard! Even in that case, there is a stiff learning curve that might not be worth your time. Last, you must consider that I do not offer support for customized versions of the TTS script and if something goes wrong in the process you are all alone.
🤗 Thanks
Special thanks to @upslidedown and @metadimensional, who regularly gave feedback all those years and helped me to shape the framework as it is today! Thanks to @EltAlt, @PlusUltraTrading, and everyone else who contributed by either filing a “defect report” or asking questions that helped me to understand what improvements were necessary.
Enjoy!
Jason