Trailing Stop Loss Smart [TradingFinder] Market Trend + CVD/EMA🔵 Introduction
Trailing Stop Loss (TSL) is one of the most powerful tools available. A Trailing Stop Loss is a modification of a typical stop order that adjusts dynamically based on market price movement. It can be set at a defined percentage or dollar amount away from the security's current market price, making it a flexible tool for locking in profits while minimizing risk. Unlike standard stop-loss orders, a Trailing Stop follows the market in the direction of the trade, protecting gains without requiring constant manual adjustments.
The Trailing Stop Loss Smart (TFlab Trailing Stop) indicator takes this concept even further by incorporating advanced metrics like Cumulative Volume Delta (CVD), volume dynamics, and Average True Range (ATR). This combination not only enhances risk management but also acts as a trend identifier, providing traders with a powerful tool to capitalize on both short-term and long-term price movements.
This indicator also supports various Order Types, allowing for flexible strategies that include a trailing stop/stop-loss combo to maximize winning trades while minimizing losses. The trailing stop limit is particularly useful for traders who want to set their stop at a precise level relative to the current market price, either by a percentage or a dollar amount. The Trailing Stop Loss Smart indicator can help ensure that traders do not exit too early during trends, while the stop-loss feature kicks in during reversals.
The advantages of using a Trailing Stop Loss are its ability to protect profits and reduce the emotional decision-making process in volatile markets. However, like all trading strategies, it has disadvantages, such as the risk of triggering too early during normal market fluctuations. By understanding how the Trailing Stop Loss Smart indicator integrates features like CVD, ATR, and volume analysis, traders can leverage its full potential while navigating these pros and cons.
With its unique ability to track market movements and trends using Cumulative Volume Delta, volume dynamics, and ATR-based trailing stops, this indicator offers a complete solution for traders looking to secure profits while minimizing downside risk. Whether you're employing a simple trailing stop or a trailing stop/stop-loss combo, this tool provides all the flexibility and precision needed to execute winning trades in various markets, including Forex, Crypto, and Stock.
🔵 How to Use
The Trailing Stop Loss Smart indicator integrates multiple advanced components to provide traders with superior risk management and trend identification.
Here’s how each part of the logic works :
🟣 Cumulative Volume Delta (CVD) Logic
The CVD tracks buying and selling pressure by calculating the difference between upward and downward price movements. When there’s more buying pressure, the CVD is positive, indicating a potential bullish trend. Conversely, more selling pressure results in a negative CVD, pointing to a bearish trend.
CVD Trend Detection : The indicator determines whether the market is in a bullish or bearish phase by comparing the CVD to its moving average. A bullish trend is confirmed when the CVD is above its moving average and the price is closing higher.
A bearish trend occurs when the CVD is below its moving average and the price is closing lower. This trend detection is critical for determining whether the trailing stop should be placed below the price (bullish) or above it (bearish).
🟣 Volume Dynamics
Volume is a key factor in identifying market strength. The Trailing Stop Loss Smart indicator pulls volume data based on the market selected (Forex, Crypto, or Stock) and adjusts the trailing stop based on whether the market is experiencing high volume or low volume.
High Volume : When the current volume exceeds the average volume, the market is in a high-volume state. During these conditions, the trailing stop is placed closer to the price, as high volume often indicates strong trends with less chance of reversals.
Low Volume : In low-volume conditions, the trailing stop gives the market more room to breathe by placing the stop further away from the price. This prevents premature stop-outs in periods of reduced market activity.
🟣 ATR-Based Trailing Stop
The Average True Range (ATR) is used to measure market volatility. The Trailing Stop Loss Smart uses the ATR to dynamically adjust the stop-loss distance.
Bullish Market : When a bullish trend is detected, the trailing stop is placed below the lowest price of the recent bars (determined by the Bar Back parameter), and adjusted by the ATR Multiplier. This allows for tighter protection during strong bullish trends.
Bearish Market : When the market is bearish, the trailing stop is placed above the highest price of recent bars, also adjusted by the ATR Multiplier. This ensures that short positions are safeguarded against sudden reversals.
🟣 Dynamic Stop-Loss Updates
The trailing stop is updated every few bars (according to the Refiner parameter), ensuring it remains relevant to the most recent price action and volume changes. This dynamic feature ensures the stop-loss adapts to both trending and volatile market conditions, without requiring manual intervention.
High Volume with Trends : In periods of high volume and a confirmed trend, the stop-loss is positioned tightly to lock in profits while minimizing the risk of reversal.
Low Volume with Trends : In low-volume conditions, the stop-loss is placed further from the price, allowing the market to move freely without triggering premature exits.
🟣 Visual Representation
The indicator visually represents the trailing stop on the chart, with green lines indicating bullish trends and red lines for bearish trends. This visual aid helps traders quickly assess the state of the market and the position of their trailing stop in real-time.
🔵 Settings
The Trailing Stop Loss Smart indicator offers several customizable settings to suit various trading strategies. Understanding these inputs is key to optimizing the tool for your specific trading style.
🟣 General Settings
Cumulative Mode : This controls how the CVD is calculated.
You can choose between :
EMA : Exponential Moving Average smoothing.
Periodic : Sums the delta over a fixed period.
CVD Period : Defines the look-back period for CVD calculation. A longer period smooths the data, making it less sensitive to short-term fluctuations.
Ultra Data : This Boolean input aggregates volume across multiple exchanges for a more comprehensive view of market activity.
Market Ultra Data : Select between Forex, Crypto, and Stock to ensure the indicator pulls accurate volume data for your market.
🟣 Logical Settings
Moving Average CVD Period : Defines the period for the moving average of the CVD. A longer period smooths the trend, reducing noise.
Moving Average Volume Period : Sets the period for the moving average used to distinguish between high and low volume conditions.
Level Finder Bar Back : Determines how many bars to look back when identifying the highest or lowest price for trailing stop placement.
Levels update per candles : Sets how often (in bars) the trailing stop should be updated to remain in sync with market movements.
ATR On : Toggles the use of ATR to adjust the trailing stop based on volatility.
ATR Multiplie r: Defines how far the stop is placed from the price based on the ATR. A larger multiplier increases the stop distance, reducing the likelihood of getting stopped out during market fluctuations.
ATR Multiplier Adjusts the distance of the trailing stop based on the ATR. A higher multiplier places the stop further from the price, providing more breathing room in volatile markets.
🔵 Conclusion
The Trailing Stop Loss Smart indicator is a comprehensive tool for traders looking to manage risk while identifying market trends. By incorporating Cumulative Volume Delta (CVD) to detect buying and selling pressure, volume dynamics to gauge market activity, and ATR to adjust for volatility, this indicator ensures that stop-loss levels are both adaptive and protective.
Whether you’re trading in Forex, Crypto, or Stock markets, the Trailing Stop Loss Smart allows you to capitalize on trends while dynamically adjusting to changing market conditions. Its ability to distinguish between high-volume and low-volume periods ensures that you’re not stopped out prematurely during periods of consolidation or market hesitation.
By providing real-time visual feedback, dynamic adjustments, and trend identification, this indicator serves as a vital tool for traders aiming to maximize profits while minimizing risk. Its versatility and adaptability make it an essential part of any trader’s toolkit, helping you stay ahead in fast-moving markets while safeguarding your positions.
Trailingtakeprofit
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.
Trailing Take Profit - Close Based📝 Description
This script demonstrates a new approach to the trailing take profit.
Trailing Take Profit is a price-following technique. When used, instead of setting a limit order for the take profit target exiting from your position at the specified price, a stop order is conditionally set when the take profit target is reached. Then, the stop price (a.k.a trailing price), is placed below the take profit target at a distance defined by the user percentagewise. On regular time intervals, the stop price gets updated by following the "Trail Barrier" price (high by default) upwards. When the current price hits the stop price you exit the trade. Check the chart for more details.
This script demonstrates how to implement the close-based Trailing Take Profit logic for long positions, but it can also be applied for short positions if the logic is "reversed".
📢 NOTE
To generate some entries and showcase the "Trailing Take Profit" technique, this script uses the crossing of two moving averages. Please keep in mind that you should not relate the Backtesting results you see in the "Strategy Tester" tab with the success of the technique itself.
This is not a complete strategy per se, and the backtest results are affected by many parameters that are outside of the scope of this publication. If you choose to use this new approach of the "Trailing Take Profit" in your logic you have to make sure that you are backtesting the whole strategy.
⚔️ Comparison
In contrast to my older "Trailing Take Profit" publication where the trailing take profit implementation was tick-based, this new approach is close-based, meaning that the update of the stop price occurs at the bar close instead of every tick.
While comparing the real-time results of the two implementations is like comparing apples to oranges, because they have different dynamic behavior, the new approach offers better consistency between the backtesting results and the real-time results.
By updating the stop price on every bar close, you do not rely on the backtester assumptions anymore (check the Reasoning section below for more info).
The new approach resembles the conditional "Trailing Exit" technique, where the condition is true when the current price crosses over the take profit target. Then, the stop order is placed at the trailing price and it gets updated on every bar close to "follow" the barrier price (high). On the other hand, the older tick-based approach had more "tight" dynamics since the trailing price gets updated on every tick leaving less room for price fluctuations by making it more probable to reach the trailing price.
🤔 Reasoning
This new close-based approach addresses several practical issues the older tick-based approach had. Those issues arise mainly from the technicalities of the TV Backtester. More specifically, due to the assumptions the Broker Emulator makes for the price action of the history bars, the backtesting results in the TV Backtester are exaggerated, and depending on the timeframe, the backtesting results look way better than they are in reality.
The effect above, and the inability to reason about the performance of a strategy separated people into two groups. Those who never use this feature, because they couldn't know for sure the actual effect it might have in their strategy, (even if it turned out to be more profitable) and those who abused this type of "repainting" behavior to show off, and hijack some boosts from the community by boasting about the "fake" results of their strategies.
Even if there are ways to evaluate the effectiveness of the tick-based approach that is applied in an existing strategy (this is out of the topic of this publication), it requires extra effort to do the analysis. Using this closed-based approach we can have more predictable results, without surprises.
⚠️ Caveats
Since this approach updates the trailing price on bar close, you must wait for at least one bar to close after the price crosses over the take profit target.
TrailingTakeProfit exampleQuite recently I came upon a concept of Trailing Take Profit and I couldn't find a PineScript which implements it for the fastest possible execution, so here it is :)
Everybody knows Trailing StopLoss - an invisible mechanism follows the price and exits the trade once the price retreats too much from its recent most extended favourable value. Trailing TakeProfit does the similar thing, but at the opposite end - the trade gets closed if a price moves too well, in too favourable extent.
Why close the trade if it is going so good? Well, whatever goes up, must go down and vice versa. It is expected, that after fast rally a market will soon fall and after a dump it will go up. So Trailing TakeProfit's role is to secure profits.
But how does Trailing TakeProfit differ from the standard one? "Trailing" means, the exit level is moving. Its role is to be executed only after a rapid favourable move within 1-2 candles, not more. We never know when a rapid move happens, but when it does, we wanna catch those pips and quickly exit without looking back.
Visually Trailing TakeProfit levels are... bands. In this script example these are ATR multiplied bands (aka Keltner Channel), but they could also be Bollinger Bands or something else.
The code is simple just to focus on this single functionality, so you can quickly copy-paste it into your script. Entries are triggered by default SMA crosses.
P.S. I wouldn't be myself, if I didn't add alert messages compatible with the syntax of recently revamped TradingConnector - both in the code already and in the table showing them.
FRAMA & CPMA Strategy [CSM]The script is an advanced technical analysis tool specifically designed for trading in financial markets, with a particular focus on the BankNifty market. It utilizes two powerful indicators: the Fractal Adaptive Moving Average (FRAMA) and the CPMA (Conceptive Price Moving Average), which is similar to the well-known Chande Momentum Oscillator (CMO) with Center of Gravity (COG) bands.
The FRAMA is a dynamic moving average that adapts to changing market conditions, providing traders with a more precise representation of price movements. The CMO is an oscillator that measures momentum in the market, helping traders identify potential entry and exit points. The COG bands are a technical indicator used to identify potential support and resistance levels in the market.
Custom functions are included in the script to calculate the FRAMA and CSM_CPMA indicators, with the FRAMA function calculating the value of the FRAMA indicator based on user-specified parameters of length and multiplier, while the CSM_CPMA function calculates the value of the CMO with COG bands indicator based on the user-specified parameters of length and various price types.
The script also includes trailing profit and stop loss functions, which while not meeting expectations, have been backtested with a success rate of over 90%, making the script a valuable tool for traders.
Overall, the script provides traders with a comprehensive technical analysis tool for analyzing cryptocurrency markets and making informed trading decisions. Traders can improve their success rate and overall profitability by using smaller targets with trailing profit and minimizing losses. Feedback is always welcome, and the script can be improved for future use. Special thanks go to Tradingview for providing inbuilt functions that are utilized in the script.
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.
FFT Strategy Bi-Directional Stop/Profit/Trailing + VMA + AroonThis strategy uses the Fast Fourier Transform inspired from the source code of @tbiktag for the Fast Fourier Transform & @lazybear for the VMA filter.
If you are not familiar with the Fast Fourier transform it is a variation of the Discrete Fourier Transform. Veritasium on youtube has a great video on it with a follow up recommendation from 3brown1blue. In short it will extract all the frequencies from a set of data. @tbiktag laid the groundwork for creating the indicator which will allow you to isolate only those signals which are the most relevant and remove the noise. I recommend having @tbiktag's FFT Transform indicator side by side with this to understand what my variation is doing by setting similar settings .
Using this idea, you can then optimize a strategy to the frequencies that are best. The main entry signal is when the FFT Signal crosses above or below the 0 line .
Included with this strategy is the ability to optionally bi-directionally set:
Stop Loss
Trailing Stop Loss
Take Profit
Trailing Take Profit
Entries are optionally further filtered by use of the VMA using the algorithm from LazyBear which allows you to adjust a variable moving average with 3 market trend detections. Green represents upwards momentum; Blue sideways trading and Red downwards momentum. The idea being to filter out buy or sell entries unless the market is moving in that direction, and this makes a big difference as you can see for yourself when you turn it off or on. Turning it off will change the color of the FFT signal to orange instead of the green, blue, red colors .
I have added 2 custom stop loss types as well for experimentation:
1. VMA Filter stop loss to exit the trade if the VMA detects a market trend direction change matching the rules you have set. I have set this to off by default, but it is there so you can see what affect it may have on other tickers. It can increase the profit factor but usually at a cost of net profit.
2. The Aroon Filter stop loss with different lengths for the short or long direction. For the Aroon strategy (which is a trend change detector) it is considered bullish if the upper line (green in my code) is above 70 and the lower line (red in my code) is below 30 and the opposite for the bearish case. With this in mind, I have set it to filter by default only the extreme ends (99 and 1) to increase profit factor and net profit but I encourage you to try different settings and see how it affects things. Turning this off yields much higher net profit but at the cost of the profit factor and drawdown . To disable this just uncheck the 'Use Aroon Filter Long' (or short) and it will also hide the aroon graphics and crosses on the plot.
I will be adding more features in an attempt to lower the drawdown on this strategy but I hope you enjoy what I have so far!
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
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
Trailing Take Profit Trailing Stop LossThis script demonstrated a dual trailing take profit and stop loss strategy. Where you take 50% (configurable) of the profit when a price level is reached and then you get the rest when a trailing stop loss is hit.
Trailing Take ProfitThis script demonstrates how to do trailing take profit. With this approach instead of setting a limit order, when you hit the target you just follow the price upwards (for long positions) and you sell when the price drops by a small percentage. This approach will increase the profits (slightly) in every strategy! Be aware that the simulated data may produce unrealistic results.
MTF Trailing SL Alerts [QuantNomad]These are alerts for my MTF Trailing SL Strategy.
Entry Long position if all 4 time-frames agree on the long signal.
Exit Long positions when at least 2 time-frames disagree on the long signals.
Entry to Short position if all 4 time-frames agree on Short signal.
Exit from Short positions when at least 2 time-frames disagree on Short signal.
Use "Once Per Bar Close" when creating alerts.
Link to the strategy:
MTF Trailing SL Strategy [QuantNomad]This is a Multi-Timeframe version of my Trailing SL Strategy.
Few weeks ago I published Trailing SL Strategy. There I used only basic Trailing SL to enter positions.
It worked pretty well so I tried to work on it a bit. I thought what if you can use the same ATR TSL on different timeframes and combine them into one signal.
In this strategy you can use only ATR stops and choose 3 other higher timeframes in addition to your current timeframe.
You'll see Trailing SL plotted on the chart form all these timeframes.
Entry Long position if all 4 time-frames agree on long signal.
Exit Long positions when at least 2 time-frames disagree on long signal.
Entry to Short position if all 4 time-frames agree on Short signal.
Exit from Short positions when at least 2 time-frames disagree on Short signal.
Here is the link to my basic Trailing SL Strategy:
Trailing SL Alerts [QuantNomad]It's alerts version of my Trailing SL strategy:
Use "Once Per Bar" param when creating alerts.
Trailing SL Strategy [QuantNomad]I'm a big fan of simple strategies.
This one is a very simple one. So it consists only from one Trailing SL. When SL is hit, the position is reversed and SL is tracked for a new position.
You can choose one of 3 types of SL:
% of your price
ATR - it is calculated as current ATR * multiplier
Absolute
As you can see even this simple strategy can show pretty good results.
Trailing Stop Loss ATR + AlertI share this TSL indicator with alert (I use it only for Stocks), the configuration is very simple, you must select if it is a Short or Long operation, time at which the operation was opened,% of the daily ATR for TSL. It also contains:
- Alert
- Panel Info
BEST Trailing Take Profit StrategyHello traders
Hope you enjoyed your weekend on my behalf. Was staying home working ... ^^
This is my first strategy educational post I'm doing ever
While I'm generally against posting strategies because it's very easy to fake performance numbers... I cannot prevent myself from sharing a few cool strategy snippets anyway.
So from now on, I'll be sharing a few strategies also - generally not to showcase performance but only to show what pinescript can do.
As once again strategy performance can be faked is so many ways... :)
What's on the menu?
We all know what a trailing-stop is. right? right? Ok... sharing the definition here :)
A trailing stop is designed to protect gains by enabling a trade to remain open and continue to profit as long as the price is moving in the investor's favor. The order closes the trade if the price changes direction by a specified percentage or dollar amount.
But...do you know what a trailing profit is?
Short definition : Well the same but with your profit limit order.
Long definition : A trailing profit is designed to increase your gains by enabling a trade to remain open and continue to profit as long as the price is moving in the investor's favor. The order closes the trade if the price hits the trailing profit level specified percentage or dollar amount.
Some trading strategies used both a trailing stop AND trailing profit. Not making any recommendation here - only sharing what's possible in the realm of trading and pinescripting
Trigger me I'm famous
I developed many trading strategies in my career and often I've been asked to trigger a trailing-stop or trailing-profit once a certain % move has been made.
I integrated here a Take Profit trigger - once hit, it will activate the trailing profit
On the screenshot below, the TP trigger is plotted in orange. Once the price goes past that level for the first time, I'll start trailing the profit level.
In other words, when we see a price makes an interesting move in percentage value - we decide to offset the profit as we concluded that once it reached such distance - then it leads often to more profit
Of course, using only a trailing profit without stop/trailing-stop/invalidation isn't smart and the surest way to kiss goodbye a trading capital and trading and your good mood
See you tomorrow for another strategy snippet
All the BEST
Dave
TRAILING STOP LOSS TO LONG AND SHORT##THIS SCRIPT IS ON GITHUB
This TradingView strategy it is designed to integrate with other strategies with indicators.
It performs a trailing stop loss from entry and exit conditions.
In this strategy you can add conditions for long and short positions.
The strategy will ride up your stop loss when price moviment 1%.
The strategy will close your operation when the market price crossed the stop loss.
Also is possible to select the period that strategy will execute the backtest.
The strategy has the following parameters:
+ **INITIAL STOP LOSS** - Where can isert the value to first stop.
+ **POSITION TYPE** - Where can to select trade position.
+ **BACKTEST PERIOD** - To select range.
## DISCLAIMER
1. I am not licensed financial advisors or broker dealers. I do not tell you when or what to buy or sell. I developed this software which enables you execute manual or automated trades multiple trades using TradingView. The software allows you to set the criteria you want for entering and exiting trades.
2. Do not trade with money you cannot afford to lose.
3. I do not guarantee consistent profits or that anyone can make money with no effort. And I am not selling the holy grail.
4. Every system can have winning and losing streaks.
5. Money management plays a large role in the results of your trading. For example: lot size, account size, broker leverage, and broker margin call rules all have an effect on results. Also, your Take Profit and Stop Loss settings for individual pair trades and for overall account equity have a major impact on results. If you are new to trading and do not understand these items, then I recommend you seek education materials to further your knowledge.
**YOU NEED TO FIND AND USE THE TRADING SYSTEM THAT WORKS BEST FOR YOU AND YOUR TRADING TOLERANCE.**
**I HAVE PROVIDED NOTHING MORE THAN A TOOL WITH OPTIONS FOR YOU TO TRADE WITH THIS PROGRAM ON TRADINGVIEW.**
## NOTE
I accept suggestions to improve the script.
If you encounter any problems I will be happy to share with me.
+ Authors: @exit490
+ Revision: v1.0.0
+ Date: 03-Aug-2019
+ Pinescript version: 4
## LICENSE
Copyright 2019 Mauricio Pimenta / exit490
Trailing Stop Loss script may be freely distributed under the MIT license .