Coding a BreakOut and BreakDown Strategy
The breakout strategy is one of the popular trading strategy
among traders. In the breakout strategy, a position is taken when price
breakout a previous swing high or swing low price point.
Although this is a simple strategy,
however, traders often find that this
strategy does not yield desired results. In most of the cases of breakout
strategy, either the traders are trapped in fake outs or the returns are low.
In this chapter, I will be discussing breakout strategy. We will be coding the
strategy with pinescript. The code is
also available as free on tradingview platform under the name of “achalmeena”.
The Result
The result that I have received through the above strategy
are very encouraging. The strategy script is showing percentage profit trades
between 70 to 90 for trending equities like Apple Inc, Bank scrips of Indian
Stock exchange on which I had primarily executed this script. On a daily chart,
the result of the script for 2 year period (Jan 2018 to Dec 2019) before the
global meltdown is shown below
|
APPL INC |
SBIN |
AMZN |
Number of Trades |
10 |
10 |
12 |
% profitable trades |
90 |
70 |
66.67 |
Profit per trade |
2.93% |
2.31% |
2.11 |
Avg bars under trade |
3 |
3 |
2 |
The above definitely proves that the breakout strategy can
work if applied with careful balanced filters. The above result can also be improved considerably, however, this article is only for educational purpose. What is the strategy? What are
the filters that can be applied? To know all this, you have to read this
article till the end.
Identifying Swing
High/ Low
In the book, “Tradingview pinescript programming from Scratch”, I have already discussed about ta.pivothigh
and ta.pivotlow functions for identification of swing high and swing low points
on the chart. In this example we can use the above functions for identification
of swing high and swing low points. It is suggested that the leftbars be set at
4 and rightbars under the setting of pivot functions be set as 2 or 1.
It must be noted that the more
the number of the right bars in the pivot functions, the strategy may have forwarding
looking bias. Some may argue that the
pivot points are marked after 1-2 bars after their formation hence the strategy
may have some biasness. You have a valid point, however for such a small number
as 1-2, rightbars in pivot function setting does not have any major impact on
the result of the strategy. The code for pivots is as under :
///code for Pivot Point/// leftBars =
input(4) rightBars = input(2) swh = pivothigh(leftBars, rightBars) swl = pivotlow(leftBars, rightBars) |
The Breakout strategy
There could be several ways to
implement this strategy. One could be to checks for the pivot high and pivot
low in the last 50 bars.
//-----------------find recent PH within last 50
bars----------- PH = 0.00001 Y = for i= 50 to 1 if(not
na(swh[i])) PH := swh[i] //-----------------find recent PH within last 50
bars----------- PL = 0.00001 Z = for i= 50 to 1 if(not
na(swl[i])) PL
:= swl[i] |
Some may use ta.highestbars()
function. Or you may also use ta.valuewhen() function
//-----------------find recent PH ----------- PH= ta.valuewhen(not na(swh[2]),swh[2],1) //-----------------find recent PH ----------- PL= ta.valuewhen(not na(swh[2]),swl[2],1) |
If you are not familier with
ta.valuewhen() function , I suggest you to go through my book or read
pinescript official manual. Till now you have located value of recent swing
high and swinglow. The value of recent swing high is stored in the variable “PH”
for recent swing low is stored in the variable “PL”.
The condition of breakout Strategy
The classic condition for
breakout can be described as under :
//bar just crossed recent PH open <= PH and close >= PH or close[1] <= PH and close >=PH //bar just crossed recent PL open >= PL and close <= PL or close[1]
>= PL and close <=PL |
Readers may ask a question why I have written code in such a manner and not defined breakout of swing high as close >= PH?
You are right, the breakout is
when close of current bar closes above recent pivot high. But this condition
will also remain true after breakout and remain true till a new swing high is
formed and price closes below that wing high.
The problem of fakout breakout
The only breakout condition will
provide too many entry and exit from the trade that profit if any would be
consumed in the trade commissions. You will also notice that the above
condition for breakout is giving too many trades and trying to capture every
possible breakout including fakeout breakout.
Fakeout in trading is a old
problem, you can also find fakeout breakdown when price looks as if it is about
to break support price. Fake out filtering trading strategy is required to
resolve the problem.
For those who do not know fakeout
meaning in forex or equity, check the below fake out example
In the above fake out chart
pattern, an established resistance line drawn at swing high is broken and close
of the fake out candle is above the resistance line. Fake out closure above
resistance line give a false impression that the resistance is broken and trend
shall continue. You can find such fake out pattern every where like fake out in
forex, fake out in stock, fake out in crypto.
These fakeout can be filtered by
using below code :
(high-low)/ta.atr(7))>1 |
The
above is measurement of volatility with respect to current bar. I have used a
parameter of 1 for comparing the range of current bar with the average true
value. You can use any number here or for the lookback period of ATR.
The complete code is as below :
//@version=4 strategy("Achal-Pivot Trade Strategy SL
implemented", overlay=true,calc_on_order_fills=false,pyramiding=1) //udemy course creating trade strategies and back testing using pinescript ///--------------------------------date
range-------------------------- // === INPUT BACKTEST RANGE === FromMonth = input(defval = 1, title = "From
Month", minval = 1, maxval = 12) FromDay =
input(defval = 1, title = "From Day", minval = 1, maxval = 31) FromYear =
input(defval = 2018, title = "From Year", minval = 2015) ToMonth =
input(defval = 12, title = "To Month", minval = 1, maxval = 12) ToDay =
input(defval = 31, title = "To Day", minval = 1, maxval = 31) ToYear = input(defval = 2019, title = "To Year", minval = 2015) start =
timestamp(FromYear, FromMonth, FromDay, 00, 00) // backtest start window finish =
timestamp(ToYear, ToMonth, ToDay, 23, 59) // backtest finish window window() => time >= start and time <= finish ? true : false // create function "within window of time" //---------------------------------------------------------------- ///code for Recent Pivot Point/// leftBars =
input(4) rightBars = input(2) swh = pivothigh(leftBars, rightBars) swl = pivotlow(leftBars, rightBars) swh_cond = not na(swh) swl_cond = not na(swl) plotshape(swh_cond, text = "PH", color
= color.green, style = shape.arrowdown, location = location.abovebar, offset
= -rightBars) plotshape(swl_cond, text = "PL", color
= color.red, style =
shape.arrowup, location =
location.belowbar, offset = -rightBars) //-----------------pivot drawing
ended-------------------------- //-----------------find recent PH within last 50
bars----------- PH = 0.00001 Y = for i= 50 to 1 if(not
na(swh[i])) PH := swh[i] //-----------------find recent PH within last 50
bars----------- PL = 0.00001 Z = for i= 50 to 1 if(not
na(swl[i])) PL := swl[i] //-----------trend finder---------------- sum = 0 X = for i = 1 to 14
if(close[i]>open[i]) sum
:=sum +1
if(close[i]<open[i]) sum :=sum -1 //----------trend finded ended------------ //-----Buy Condition1--------------------// // volitility + green bar + up trend // go_long = 0 if(((high-low)/atr(7))>1 and open < close
and sum > 1 )
go_long:= 1 //--------Condition 1 ends----- //-----Short Condition1------------------// //volitility + red bar + down trend go_short=0 if(((high-low)/atr(7))>1 and open >
close and sum < -1) go_short:=1 //Buy Condition2------- //bar just crossed recent PH go_long1 = 0 if(open <= PH and close >= PH or close[1]
<= PH and close >=PH) go_long1:=1 //short Condition2------- //bar just crossed recent PL go_short1 = 0 if(open >= PL and close <= PL or close[1]
>= PL and close <=PL) go_short1:=1 ordersize=floor(strategy.equity/(close)) strategy.entry("Long",
strategy.long,ordersize,limit=close, when = window() and go_long and
go_long1) strategy.entry("Short",
strategy.short,ordersize,limit=close, when = window() and go_short and
go_short1) var atr_data = 0.00001 atrValue = atr(7) if (go_long and go_long1)
atr_data := atrValue if (go_short and go_short1)
atr_data := atrValue p_data = strategy.position_avg_price - atr_data p_data1 = strategy.position_avg_price + atr_data plot(p_data1, color=color.green,linewidth=2) plot(p_data, color=color.red,linewidth=2) strategy.exit("Exit
long","Long", stop=strategy.position_avg_price - atr(7),trail_points
= atr(7)/syminfo.mintick,comment="Exit true") strategy.exit("Exit Short","Short",stop=strategy.position_avg_price + atr(7), trail_points = atr(7)/syminfo.mintick,comment="Exit true") close_long=0 if (strategy.position_size > 0 and close >
PH and go_short)
close_long:=1 close_short=0 if (strategy.position_size < 0 and close <
PL and go_long)
close_short:=1 strategy.close("Long",when=close_long,comment="Close
True") strategy.close("Short",when=close_short,comment="Close
True") |
Highest Rated Udemy Course on PineScript - Grab your Seat Now
Udemy Discount Coupan Code : UDEMY-NEWYEAR (Valid upto 3rd Jan 2022)