ATR Trailing Stop v5 One of my favorite stops is the ATR Trailing Stop-loss. With the implementation of PineScript v5, a code update was needed in order to use this stop/exit-strategy with newer strategy scripts. A timeframe selector that was not featured on earlier versions is also included. This new version can be plugged into PineScript v5 strategies, and also has a simpler/cleaner code that makes the code logic easier to follow than prior versions.
For those that are unfamiliar with the ATR Trailing Stop exit strategy; it is a trailing stop that takes into account the volatility of the underlying asset by trailing the price series using a multiple of the Average True Range (ATR). In practice I’ve found that this exit can be more effective than traditional trailing stops, depending on the volatility of the asset you are trading. More detailed information can be found at www.stockopedia.com
How do I use it? Add it to your chart as an indicator to visualize where the ATR stop would be with your settings. Or, copy and add it to your v5 strategy with the addition of a ta.crossunder(close, ATRTrailingStop) or ta.crossover(close, ATRTrailingStop) function. Special thanks and credit to HPotter who coded an earlier version of this in pine!
Средний истинный диапазон (ATR)
UT Bot v5This is an update by request, on someone elses strategy! well more of an edit, but also update from pine v4 to pine v5.
//CREDITS to HPotter for the orginal code. The guy trying to sell this as his own is a scammer lol.
//Edited and converted to @version=5 by SeaSide420 for Paperina
The UT Bot v5 is Movinging average (the MA) vs ATR (the ATR is in the form intended for use as trailing stop loss (ATR_TSL))
Entry logic:
buy = the MA > ATR_TSL and Price > ATR_TSL
sell = the MA < ATR_TSL and Price < ATR_TSL
The Moving average type can be changed in the settings:
options = "SMA", "EMA", "WMA", "HMA"]
the edits i made were:
convert to v5
Add TP and SL
Add Buy only or Sell only option
Add MA type option
Add price source option
Draw MA and ATR_TSL on-chart
Logarithmic Average True Range
In the case of ATR, it is known to represent volatility by simply expressing the price range.
However, of course, as the value of an asset increases, it is not possible to simply compare it with a numerical value, so the ATR was expressed as a percentage using a logarithmic function.
This way we can see the volatility even with ATR.
ATR의 경우 단순하게 가격의 범위만을 표현하여 변동성을 나타낸다고 알려져있습니다.
하지만 당연하게도 자산의 가치가 높아질수록 단순하게 수치만으로 비교할 수는 없고, 따라서 로그함수를 사용해 %로 ATR을 표현하였습니다.
이렇게 표현하면 ATR로도 변동성을 볼 수 있습니다.
Mean Reversion Strategy v2 [KL]Description :
This strategy will enter a position when the following conditions are met:
a) Main signal: When source data (ATR) diverts from its moving average value, and
b) Confirmation: If predicted direction of trend is favorable.
Assumptions :
During periods of high price volatility, ATR diverts from its moving average value. Eventually, ATR should revert. But since just knowing the magnitude of increase/decrease of ATR does not indicate a trend signal, we need to introduce a model to predict the current trend.
In short:
• Trend Prediction : This strategy calculates the expected logarithmic return of the security (the "Drift") and considers prices to be moving in uptrend if the drift curve is upward sloping.
• Assessment of ATR diversion : To determine "yes/no" regarding whether ATR at a given point in time has diverted, this script conducts a two-tailed hypothesis test at each candlestick period. The null hypothesis (H0) is that the fast moving average value should equal the slow moving average value (say, denoted as H0: atr14 == atr28; it is assumed that atr28 is more meaningful for the purpose of describing the current trend because it has a larger sample size). Investopedia has an article summarizing this topic .
Exit Condition :
When trailing stop loss hits.
Previous version :
This strategy is based on Version 1 published back in September . This older version considers +/- one standard deviation to be the critical values relative to average ATR when testing whether ATR has diverted from the mean. This does not take Standard Error ("SE") into account. As a result, the threshold is often too wide and it generates too many entry signals.
ATRSLTPTwo adjustable ATRs are drawn on the screen for gradual stop, the ATR multiplier can be changed in the settings. the green line shows the target point with 5 ATR (cannot be changed)
[CP]Pivot Boss Floor Pivots with ATR Dilation and Dynamic LevelsINTRODUCTION:
Compared to all the Pivot Indicators available on Trading View Public Library, this Floor Pivots Indicator differentiates itself in two major original ways:
Dilates the Pivot Support/Resistance Levels into Support/Resistance Bands based on volatility
Displays the S/R Levels Dynamically , that is, only those levels will be shown that are close enough to the price resulting in much cleaner looking charts.
There were a few features whose logic I had figured out, but I could not implement them due Pine Script’s Limitation (they should really work on increasing Pine Script’s capacity instead of adding more and more features to the language in order to make it look ‘better’):
Showing multiple timeframe pivots at the same time (not possible due to Pine Script’s limitation on the ‘Max Number of Outputs’ )
Automatic Detection of highly profitable Double Hot Pivot Zones (DPZ), also due to the ‘Max Number of Outputs’ limit
GENERAL USER INPUTS:
Most of the settings are self-explanatory, however, a few of them need some explanation:
Show Floor Pivots Dynamically – This will turn ON the dynamic pivot levels, please note that this function will work ONLY IN INTRADAY timeframes.
Dynamic Pivot ATR Period – Period over which the ATR value is calculated to show the pivots dynamically.
ATR Threshold for Dynamic Floor Pivots – Simply put, the indicator will start displaying Pivot Levels if they fall within the 2*ATR distance (default value) of the price. You can increase this number if the volatility increases and vice-versa.
Use ATR to Dilate Intraday Pivot Levels – This will turn ON Floor Pivot Dilation, turning pivot ‘lines’ into ‘bands’ .
ATR Dilation Factor – This number decides the width of the Pivot bands. Larger this number, thicker the bands. Typically, high volatility stocks will require a higher number.
ATR Period – Same as Dynamic Pivot ATR Period, but for Pivot Level Dilation.
INDICATOR USAGE EXAMPLES:
This indicator works great in conjunction with my Pivot Boss Candlestick Scanner indicator.
There are a lot of optimizations I have done in the code, although it looks trivial at first glance, but it's fairly complex.
Feel free to use it and modify it as you wish.
Here are a few examples where the indicator has shown great entries and exits, with the default settings:
NIFTY 5m Chart
Reliance 5m Chart
Tesla 5m Chart
Bitcoin-USDT 15m Chart
FINAL WORDS:
Please understand that I have Cherry Picked the examples to showcase the capability of the indicator and its usage.
DO NOT conflate the accuracy of examples with the accuracy of this indicator.
Once you start using floor pivots, you will realize that a lot of days simply don’t give any high probability setups and you will simply sit out of the market and do nothing (which is a good thing).
If you really want to learn how to use Pivots, read the book ’Secrets of a Pivot Boss’ . This book can change your life.
Trend Strategy by zdmreThis Strategy is a trend following indicator. It is plotted on price and the current trend can be determined by its placement vis-a-vis price. It is constructed with just three parameters: Period, Multiplier and Entry/Exit Point with Superformula.
The default parameters are 14 for Average True Range (ATR) and 4 for its multiplier. The average true range (ATR) plays a key role in ‘Trend’ as the indicator uses ATR to compute its value and it signals the degree of price volatility. You should note that any changes to these numbers can affect the use of the Trend indicator.
While you using this indicator, you should not avoid putting your stop loss.
For a long position, you can put stop loss right at the red indicator line. For a short position, you can put it at the green indicator line. You can insert your own settings as well.
Using Trend Strategy along with a stop loss pattern is the best way for earning the best wealth in trading.
There is no best setting for any trading indicator.
RSI c/w MA, ADX and ATR data I have added 3 items to the RSI indicator which helps me to get more information at the same time.
1) ADX value - when ADX is above 25 we have a strong trend
2) ATR Value - helps me to calculate my daily targets and stop-loss levels at a glance.
3) A simple moving average - This shows me the trend of RSI. If the price breaks a trend line and at the same time RSI crosses above the MA, it shows me a breakout has happened. In longer timeframes, it can show you in advance if you should expect a reversal in the trend.
You can turn on or off the MA as well as the ADX line.
Bjorgum AutoTrailOne Time Trade Risk Management
Incorporating the new interactive feature, this script is meant as a one time trailing stop for the active trader to manage positional risk of an ongoing trade. As a crypto trader or Fx trader, many may find themselves in a position late into the evening, or perhaps daily life is calling while a trade progresses in their favor. Adding a trailing stop to a position thats trending can help to keep you in the trade and lock in gains if things turn around when you are unable to react.
To use the trail, the user would add the script to the chart. Once added, a set of crosshairs will appear allowing the user to choose a point to begin. Often choosing to start a trail from a swing high/ low can be an ideal option. This tends to provide some protection for a stop by placing it under support for a long trade or above resistance for a short trade.
Price based trail
The trail will automatically plot and the offset is a factor of the distance from price action selected by the crosshairs. If placed above price action the script will plot a short trail, if placed below it will trail for a long position.
Additionally, there are several other trail types other than price based. There is also percent based, which offsets the trail as a percent from close. A hard stop is placed at the cross hair value, then once the distance is exceeded by the percentage specified, the trail begins.
There are 2 more volatility based trails. There is a PSAR trail which can provide quicker and tighter stops that accelerate with the trend locking in gains faster, and an ATR trail that keeps a distance from price action as a function of volatility. Volatility levels can be adjusted from the menu.
Volatility based trail (ATR)
Volatility based trail (PSAR)
Lastly, within the code for more the more technical savvy, is some starting setups for string alerts to be sent to exchanges via 3rd party or custom API applications. Some string manipulation is required for specific providers to meet their requirements, but there is some building block alerts that will take the ticker symbol, recognize the asset your trading (Fx, Crypto, etc) and take input quantity or exchange names from the settings via inputs.
Complex strings can be built to perform almost any trade related task when to comes to alerts via web hook. A little setup this way with some technology to back your system can mean a semi-automated half man, half machine setup that actually manages your trail stop while you cannot. For those that don’t go this far, there is some basic alert functionality that well trigger when a trail is hit so you can react and make a decision.
Please note that for now, interactive mode is engaged only when the script is added to the chart. Additional stops, or for adjustments to be made it is best to add a new version. Also as real trades could be at play managing an actual position, alerts are designed to go off only once to ensure no duplicate orders are sent meaning alerts are not reoccurring. Once an alert is triggered, a new trail is to be set up.
A modified version of the TradingView built in SAR equation was used in this script. To provide the value of the SAR on the stop candle, it was necessary to alter the equation to extract this value as the regular SAR “flips” at this point. Thank you to TradingView for supplying access to the built in formula so that this SAR could behave the same as the built-in function outside of these alterations
Example of SAR value maintained in trigger candle
Cheers and happy trading.
Kaufman's Efficiency Ratio Strategy [KL]I recently published an indicator called "Kaufman's Efficiency Ratio Indicator". In the description of that script, I hypothesized about how the Efficiency Ratio could be applied to identify bullish moves in instances where price had already gone up steeply, but rests for a while, allowing for entry in expectation that price will continually rise. I decided to test out this idea with Pinescript.
About Kaufman's Efficiency Ratio ("ER")
ER was developed by a systematic trader by the name of Perry J. Kaufman.
Formula
The formula is:
= A divided by B,
where:
A = Current closing price minus the closing price at the start of the lookback period
B = Sum of differences between closing prices (in absolute terms) of consecutive bars over the lookback period
How this strategy enters a trade (Long):
- code: entry_signal_long = ER > 0 and ER_is_mid
- meaning: when ER is positive, strategy assumes price has risen. Usually ER value begins high (red), and unless it is a false move, then it should stay positive. This strategy will patiently wait until ER drops to medium (yellow), and then place a trade.
- how low/medium/high is dynamically determined: Refer to the description of my other script("Kaufman's Efficiency Ratio Indicator") for details. Trying to keep this as short as possible.
How this strategy exits a trade (Long):
- when price hits stop limit; stop limit is based on low of bars, trails upward based on ATR
- included a feature called "tightening TSL", which tries to reduce the stop-buffer during periods of high volatility implied by ER (very experimental, opening the floor for suggestions on how this can be improved)
ADR PercentUses past 5 day's daily average ranges and calculates average ADR percentage with respect to latest day's open
Acknowledgement - Uses code from another excellent indicator from critian.d
Weekly Put SaleWeekly Put Sale
This study is a tool I use for selling weekly puts at the suggested strike prices.
1. The suggested strike prices are based on the weekly high minus an ATR multiple which can be adjusted in the settings
2. You can also adjust the settings to Monthly strike prices if you prefer selling options further out
3. I suggest looking for Put sale premium that is between 0.25% to 0.75% of the strike price for weekly Puts and 1% to 3% of the strike price for monthly Puts
Disclaimers: Selling Puts is an advanced strategy that is risky if you are not prepared to acquire the stock at the strike price you sell at on the expiration date. You must make your own decisions as you will bear the risks associated with any trades you place. To sum it up, trading is risky, and do so at your own risk.
RSI Trend LineI took a concept similar to the "Adaptive RSI" to get the RSI overlaid on a price chart. The problem I have with the Adaptive RSI is to me it sticks too closely to price. I wanted something much more visually helpful that can provide actual tradable signals and strategies.
The orange line you are seeing is the "RSI Trend Line"
The further the RSI moves away from a value of 50 (the "zero line"), the more you see this orange line move away from price. This helps visualize the strength of price pushing away from a neutral value to a position of strength or weakness-- if orange is below price then relative strength is high; if orange is above price then relative strength is low. When price is equal to the orange RSI line, the RSI is at a value of 50.
In addition to the trend line, you can enable bands which reflect Overbought and Oversold levels . If you leave the responsiveness to a value of 1.0 and removed any smoothing, these should pretty accurately reflect an actual RSI chart topping the OB and OS lines (default 70 and 30, respectively). (They're still very close with different responsiveness and smoothing values)
The conversion or scaling of RSI value onto price comes with a bit of a quirk which I decided to leave to the user to determine how they want it applied. So the setting "Responsiveness" will impact the sort of aggressiveness of the RSI trend line as well as the the size of the bands. You could think of this in some ways as the OPPOSITE of the multiple setting on a Bollinger or Keltner band-- 1.0 will make for the widest band, 2.0 is the default and my preference, and you can move it up to a value of 5.0.
Here are some examples of how you could use the indicator for trade signals--
And here's my thought on the current state (as of 10/06) on indices with regards to this indicator-
ATR Trailing Stops S/R [LM]Hello Traders,
I would like to introduce you ATR Trailing Stops S/R . The idea is to look for important levels that are identified by trailing stop line, where it usualy spents a lot of time without any move usualy turns out to be good level for bounces.
Script for atr trailing line is originaly taken from: script made by @dgmoon
It has various setting
Timeframe and atr settings
Show lines
Extend lines
Line count - how many lines will be rendered
Candle count - how many candles has to trailing line spend at the same level
Colors - controls color of plot and lines
I hope you will enjoy it, as I enjoyed to write it.
Lukas
+ ATR Support and ResistanceThis, a very different script from most of mine, is my attempt at making a useful, and not messy, support and resistance indicator. If you've never looked into trader xkavalis, and his scripts and discord, I would highly recommend it. He talks about "pay attention candles" a lot. It got me thinking about what those are. Best as I can tell all he means by that phrase is large, impulsive candles. Sometimes these lead to break outs of ranges, or they may signal tops, bottoms, or near-tops and bottoms. The only way I could make sense of this in a mathematical way was by using the average true range. Basically, any candle's true range outside of the ATR is considered a "pay attention candle," by my definition.
This script originally began as just a candle coloring exercise with some optional shapes plotted above/below certain candles, but I quickly realized I wanted to draw lines or zones from these candles, so eventually, after many hours spent figuring out and learning 'line.new' and 'box.new' I got things sorted.
Essentially, my line of thinking is that on impulsive candles down, the origin of the impulse is more important than the close (not always of course, as there are no unbreakable rules in what markets can do), and with impulsive candles up, the same theory applies.
So, for upward impulsive candles I've marked out the zone from the open to the low as a support (until broken, in which case it may become resistance). For downward impulsive candles the zone encompasses the open to the high. I've given the option to plot a line from the close for all of these. It's turned off by default as it's just less stuff on the chart, but you may like it.
The line length is customizable in a menu. It does funny things on low timeframes on forex and stock charts (long lines that result in chart compression), but for some reason very rarely on crypto charts. If someone who is smart (not me) and has much experience with pinescript could perhaps help me out with a fix for this, that would be great. I suspect it has something to do with my "bar_index_duration" that I defined using the time function, but I'm not sure how or why.
Line length on time frames of one hour and up it is typically fine.
Use the ATR multiple to change the sensitivity of the indicator. This is basically the determination of when a candle is beyond the ATR. A multiple of two is two times the ATR. With lower volatile pairs you can maybe make this lower. On lower time frames or with more volatile pairs (illiquid alts in particular) a higher multiple might serve better. I find the default 1.75 is mostly acceptable.
As I started this I also thought adding some sort of volume information to the candles might be useful as well, so I added a simple candle coloring feature referencing the OBV and a 21 period EMA. Candles are colored based on the OBV's relation to its moving average.
I added some plot shapes and candle coloring utilizing the RSI as well. Options to turn on or off shapes plotted for overbought and oversold across the top of the chart. The most interesting feature that I implemented here is a support/resistance zone around the centerline of the RSI. If the RSI is between 49 and 51 then you can have optional candle coloring, shapes plotted above the candles, and s/r zones drawn on the chart. In trending markets the centerline of the RSI will frequetly act as support or resistance, so by being alerted of this condition on the chart you can use that with actual levels marked off in order to help make a judgement on a trade. I think it's a nice addition, and an oft overlooked aspect of the usefulness of the RSI.
I've also included a calculation, with candle coloring and/or plot shapes, for something like a stop run on high volume. The calculation for that is in its section below, and should be pretty self explanatory.
Lastly, typing this as I'm posting it, this indicator could also be useful for helping to find placement for trailing a stop. Just a thought!
Volume Power Flow - Taylor V1Combination of Volume Average Trend & Volume Power Range
Able to Change Average Moving Type & Length = Depending on How Volatility /Smooth is Require on your Strategy
1# Color Green = The Volume On Trend Up
2# Color Red = The Volume On Trend Down
3# Spiking Higher Volume = End of the Top/ Bottom
%-[Guz] Vortex Indicator Custom// Custom Vortex Strategy (backtester)
// Custom version of the Vortex indicators that adds many features:
// -Triggers trades after a threshold is reached instead of the normal vortex lines cross (once the difference between the 2 lines is important enough)
// -Smooths the Vortex lines with an EMA
// -Adds Take Profit and Stop Loss selection
// -Adds the possibility to go Long only, Short only or both of them
// ! notice that it uses 10% position size and 0.04% trade fee, found on some crypto exchanges futures contracts
// Allows testing leverage with position size modification (values above 100% position size, to be done with caution)
// Not an investment advice
Rate Of Change ATRThis is a very basic, but powerful script.
It gives you the ratio between the rate of change of the last x days and the average true range of the last y days.
---> ROC-ATR Ratio = ROC/ATR
Therefore, you can see how much the price has moved relative to the prices in the past.
This is important because (in my opinion) the basic ROC indicator is not very meaningful if you don't look at the average volatility of recent history.
For example, a ROC of 5% over the last 3 days might be very high for Forex but very small for some crypto.
Consequently, this indicator makes it possible to compare (and be used on) every instrument in every industry the same way.
Generally speaking, it makes more sense if the ATR length is larger than the ROC length.
HPH's SuperKeltnerThis indicator combines the Supertrend (to determine the main trend direction) with two Keltner channels (used for add and take profit signals) to construct a trend trading system.
These are the available settings:
General
UseTrendChange ➞ toggle trend change alerts and labels
UseAdds ➞ toggle add to position alerts and labels
UseTakeProfits ➞ toggle take profit alerts and labels
PrematureAdds ➞ toggle adding to position as soon as the add channels are left (default is false, so the add signal will only fire once the channels are re-entered)
PrematureTakeProfits ➞ toggle taking profit as soon as the tp channels are left (default is false, so the tp signal will only fire once the channels are re-entered)
Visualization
Show Add Keltner ➞ toggle display of the channels used for adding to the position
Show TP Keltner ➞ toggle display of the channels used for taking profit
Show SuperTrend ➞ toggle display of the Supertrend
Keltner
Standard Keltner channels settings except for the fact that there are two different multipliers. The Keltner TP Multiplier should generally be bigger than the Keltner Add Multiplier , as the channels are hit differently in trending markets. I recommend you to use the visualization settings to show the channels and adjust the settings to your liking.
Supertrend
Standard Supertrend settings, nothing to add here.
Alerts
Use the alert messages to customize what alert text the indicator will send. This makes it possible to use the script to automate trading bots.
By default, the alerts are sent after the candle has closed. This ensures that no repainting is happening. If you like the risk, you can toggle the corresponding WaitFor Confirmation if you wish to receive the signals earlier (max. once per bar).
Enjoy!
[KL] Mean Reversion (ATR) StrategyThis strategy will enter into a position when price volatility is relative high, betting that price will subsequently trend in a favourable direction.
Hypothesis : During periods of high price volatility, ATR will divert from its moving average by at least +/- one standard deviation. Eventually, ATR will revert back to the mean. However, just knowing the magnitude of increase/decrease of ATR does not give a trend signal, so we need to introduce a model in this script to predict whether the next bars will be up/down.
Trend Prediction : This strategy calculates the expected logarithmic return of the security (the "Drift") and considers prices to be moving in uptrend if the drift curve is upward sloping or if the drift value is positive.
Entry Conditions : Long position is entered when:
(a) ATR has diverted from mean by one standard deviation, and
(b) trend is predicted to move in our favor.
Exit Condition : When trailing stop loss is hit.
Results from backtesting against VOO (1H timeframe):
- approx 46% win rate over 491 trades, on average holding for 20 hours per trade
- price at the beginning of backtest (Jan. 2015) was $187.52, giving holding period return of ~120% had we not sold in between ("HPR of HODL'ing")
- this strategy gained ~159%, exceeding ~120% HPR of HODL'ing
Berzerker IndexSome pairs have their own distinct behavior. That includes volatility, news reactiveness, trend x chop day discrepancy, and other qualities.
At first, I tried to measure this with the Choppiness Index, but it looks pretty much alike when you compare symbols like EURNZD and GBPCAD, but my testing shows some major behavioral differences between the two. Hence, I decided to build my own measurement which I later decided to call Berzerker Index.
• The calculation takes the previous value and adds 1, 3, 7, or 15 depending on how many standard deviations the price beats.
• Deviations use Jurik Moving Average as a central line. If there is no new penetration, the total value will not be increased.
• At the end of the value update, the result will decay whether it is changed or not. The readings decay significantly faster if the price is between the bands.
• The beginning of the calculation is the beginning of the chart. There isn't any period for the calculation.
As you can see, from the beginning of the year, the maximum readings on EURNZD are 49.8 and 73.6 for GBPCAD. This is what I wanted to achieve - find some way to clearly differentiate the pairs. Later, I went on EURUSD to confirm the results. EURUSD should be a calmer pair and it shows 33.5 which supports the theory.
The symbols with small bars and explosions on events and bank meetings will reach high values, whereas those that are more predictable with less extreme movements will be found below 45.
Lastly, you may identify long periods of continuous descend on the indicator as setting up for a large explosion. This is not the original idea but could work nevertheless.
Of course, I will further update this indicator if I get improvement ideas...
FAQ:
► Does this repaint?
• No.
► Where is the buy signal?
• There isn't one. The purpose is to study repeated behavioral patterns of different symbols, not to drink from the holy grail.
► Why is it called the 'Berzerker' Index?
• I don't know.
I used @everget's version of Jurik's Moving Average with his consent.
What do ya thing?
Wavy Tunnel + Trend ATR Buy Sell Signal by PaRnWavy Tunnel + Trend ATR Buy Sell Signal by PaRn
Originality by PaRn
First Combination of Wavy Tunnel + Trend ATR Buy Sell Signal by PaRn
"Buy Sell Signal" is base on Volatility Stop 20, Multiplier 2.5
"Trend Signal" is based on EMA crossover between EMA12(Close) and EMA26(Close)
Take Profit Line is EMA15(Default)
Wavy line Base on EMA34(high,close,low)
Tunnel line Base on EMA144(close),EMA169(close)
Green Candle Bar = "Uptrend"
Red Candle Bar = "Downtrend"
Buy when "Buy" Signal present
Follow Trend till the end of the trend : "Sell" Signal present
Buy More (Optional) = Green Arrow present on Uptrend
How to use Wavy Tunnel + Trend ATR Buy Sell Signal by PaRn
- Wavy Tunnel + Trend Signal can be used in any timeline from 5 Minutes to Weeks
- Price above both Wavy & Tunnel = "Uptrend"
- Green Candle Bar = Uptrend
- Buy when "Buy" Signal present
- Buy More (Optional) = Green Arrow present on Uptrend
- Hold your possition and Follow Trend till the end of the trend : "Sell" Signal present, It's time to sell all position
NOT RECOMMEND TO USE ON SIDEWAY MARKET
Strategy Template - V2This is an educational script created to demonstrate few basic building blocks of a trend based strategy and how to achieve different entry and exit types. My initial intention was to create a comprehensive strategy template which covers all the aspects of strategy. But, ended up creating fully fledged strategy based on trend following.
This is an enhancement on Strategy-Template But this script is comparitively more complex. Hence I decided to create new version instead of updating the existing one.
Lets dive deep.
SIMPLE COMPONENTS OF TREND FOLLOWING STRATEGY
TREND BIAS - This defines the direction of trend. Idea is not to trade against the trend direction. If the bias is bullish, look for long opportunities and if bias is bearish, look for short opportunities. Stay out of the market when the bias is neutral.
Often, trend bias is determined based on longer timeframe conditions. Example - 200 Moving Average, Higher timeframe moving averages, Higher timeframe high-lows etc. can be used for determining the trend bias.
In this script, I am using Weekly donchian channels combined with daily donchian channels to define trend bias.
Long Bias - 40 Day donchian channel sits completely in upper portion of 40 Week dochnial channel.
Short Bias - 40 Day donchian channel sits completely in lower portion of 40 Week donchian channel.
ENTRY CONDITION - Entry signals are generated only in the direction of bias. Hence, when in LongBias, we only get Long signals and when in short bias, we only get short signals.
In our case, when in Long Bias - if price hits 40 day high for the first time, this creates our long entry signal. Similarly when in Short Bias , price hitting 40 day low will create signal for going short. Since we do not take trades opposite to trend, no entry conditions are formed when price hits 40 day high in Short Bias or 40 day low in Long Bias.
EXIT CONDITION - Exit conditions are formed when we get signals of trend failure.
In our case, when in long trade, price hitting 40 day low creates exit signal. Similarly when in short trade price hitting 40 day high creates exit signal for short trade.
DIFFERENT TYPES OF ENTRY AND EXIT
In this script, I have tried to demonstrate different entry and exit types.
Entry types
Market - Enter immediately when entry signal is received. That is, in this case when price crossover over high in long bias and crosses under low in short bias
Stop - This method includes estimating at what level new highs are made and creating a stop buy order at that level. This way, we do not miss if the break out is stronger. But, susciptible to fail during fakeouts.
Limit - This method includes executing a limit order to buy at lower price or sell at higher price. In trend following methods, downside of limit order is when there is genuine breakout, these limit orders may not hit and during trend failures the limit orders are likely to hit and go straight to stop.
Stop-Limit - this is same as stop order but will also place a limit condition to avoid buying on overextended breakout or with lots of slippage.
Exit types
Market - whether to keep the existing trade running or whether to close it is determined after close of each bar and exit orders are executed manually upon receiving exit signal.
Stop - We place stop loss orders beforehand when there is a trade in place. This can help in avoiding big movements against trade within bar. But, this may also stop on false signals or fakeouts.
Take profit
Stop - No take profits are configured.
Target - 30% of the positions are closed when take profit levels are hit. Take profit levels are defined by risk reward.
USING THE CODE AS TEMPLATE
As mentioned earlier, I intended to create a fully fledged strategy template. But, ended up creating a fully fledged stratgy. However, you can take some part of this code and use it to start your own strategy. Will explain what all things can be adopted without worrying about the strategy implementation within
Strategy definition : This can be copied as is and just change the title of strategy. This defines some of the commonly used parameters of strategy which can help with close to realistic backtesting results for your coded strategy and comparison with buy and hold.
Generic Strategy Parameters : The parameter which defines controlling alllowed trade direction and trading window are present here. This again can be copied as is and variable inDateRange can be directly used in entry conditions.
Generic Methods : f_getMovingAverage and f_secureSecurity are handy and can be used as is. atr method provideded by pine gives you ATR based on RMA. If you want SMA or any other moving average based ATR, you can use the method f_getCustomAtr
Trade Statements : This section has all types of trading instructions which includes market/stop/limit/stop-limit type of entries and exits and take profit statements. You can adopt the type of entry you are interested in and change when condition to suit your strategy.
Trade conditions and levels : This section is required. But, cannot be copied. All the trade logic goes here which also sets parameters which are used in when of Trade Statements.
Hope this helps.