Nothing Special   »   [go: up one dir, main page]

Plot RSI

Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 11

// This source code is subject to the terms of the Mozilla Public License 2.

0 at
https://mozilla.org/MPL/2.0/
//@version=5

indicator(title='My indicator', shorttitle='plot RSI', max_bars_back =


1000,max_lines_count=400, max_labels_count=500)

ha_t = ticker.heikinashi(syminfo.tickerid)
candle_type = input.string('true', title='heikinashi ??', options=['true',
'false'])
var x = true
if candle_type == 'true'
x = true
x
else
x = false
x
clos = request.security(ha_t, timeframe.period, close,
lookahead=barmerge.lookahead_on)
src = clos
len = input(21, 'Length RSI')
ad = input(true, 'RSI Advanced ?? (Recommend)')
cdob = input.string('Candle', title='Candle or Bar or Line?', options=['Candle',
'Bar', 'Line'])
uc = input(color.green, 'Up Color')
dc = input(color.red, 'Down Color')
timeframe_rsi2 = input.timeframe(defval='30', title='RSI timeframe 2')

//lma1 = input(5,"MA length 1")


lma2 = input(20, 'MA length 2')
lma3 = input(50, 'MA length 3')
lma4 = input(200, 'MA length 4')
lma5 = input(550, 'MA length 5')
lma6 = input(750, 'MA length 6')

_rsi(src, len) =>


u = math.max(src - src[1], 0) // upward change
d = math.max(src[1] - src, 0) // downward change
rs = ta.rma(u, len) / ta.rma(d, len)
res = 100 - 100 / (1 + rs)
res

_rma(src, length) =>


a = 1 / length
sum = 0.0
sum := na(sum[1]) ? ta.sma(src, length) : a * src + (1 - a) * nz(sum[1])
sum

//_rma = a*src + (1-a) * _rma[1]

//_rma_next = a * src_next + (1-a) * _rma

u = math.max(src - src[1], 0)
d = math.max(src[1] - src, 0)
a = 1 / len
ruh = a * math.max(high - close[1], 0) + (1 - a) * ta.rma(u, len)[1]
rdh = (1 - a) * ta.rma(d, len)[1]

rul = (1 - a) * ta.rma(u, len)[1]


rdl = a * math.max(close[1] - low, 0) + (1 - a) * ta.rma(d, len)[1]

function(rsi, len) =>


f = -math.pow(math.abs(math.abs(rsi - 50) - 50), 1 + math.pow(len / 14, 0.618)
- 1) / math.pow(50, math.pow(len / 14, 0.618) - 1) + 50
rsiadvanced = if rsi > 50
f + 50
else
-f + 50
rsiadvanced

rsiha = 100 - 100 / (1 + ruh / rdh)


rsila = 100 - 100 / (1 + rul / rdl)
rsia = ta.rsi(src, len)

rsih = if ad
function(rsiha, len)
else
rsiha

rsil = if ad
function(rsila, len)
else
rsila
rsi = if ad
function(rsia, len)

else
rsia

col = ta.change(rsi) > 0 ? uc : dc


colc = if cdob == 'Candle'
col
colb = if cdob == 'Bar'
col
cold = if cdob == 'Line'
col

plotcandle(rsi[1], rsih, rsil, rsi, color=colc, wickcolor=colc, bordercolor=colc)


plotbar(rsi[1], rsih, rsil, rsi, color=colb)
plot(rsi, color=cold)

mid = hline(50, title='Middle Line', linestyle=hline.style_dashed, linewidth=2,


color=color.white)
u90 = hline(90, title='Upper Line', linestyle=hline.style_dashed, linewidth=1,
color=color.green)
u80 = hline(80, title='Upper Line', linestyle=hline.style_solid, linewidth=1,
color=color.green)
u75 = hline(75, title='Upper Line', linestyle=hline.style_dashed, linewidth=1,
color=color.green)
u70 = hline(70, title='Upper Line', linestyle=hline.style_solid, linewidth=1,
color=color.green)
u65 = hline(65, title='Upper Line', linestyle=hline.style_dashed, linewidth=1,
color=color.green)
u60 = hline(60, title='Upper Line', linestyle=hline.style_solid, linewidth=1,
color=color.green)
d40 = hline(40, title='Lower Line', linestyle=hline.style_solid, linewidth=1,
color=color.red)
d35 = hline(35, title='Lower Line', linestyle=hline.style_dashed, linewidth=1,
color=color.red)
d30 = hline(30, title='Lower Line', linestyle=hline.style_solid, linewidth=1,
color=color.red)
d25 = hline(25, title='Lower Line', linestyle=hline.style_dashed, linewidth=1,
color=color.red)
d20 = hline(20, title='Lower Line', linestyle=hline.style_solid, linewidth=1,
color=color.red)
d10 = hline(10, title='Lower Line', linestyle=hline.style_dashed, linewidth=1,
color=color.red)

//ma1_rsi = ema(rsi,lma1)
ma2_rsi = ta.ema(rsi, lma2)
ma3_rsi = ta.ema(rsi, lma3)
ma4_rsi = ta.ema(rsi, lma4)
ma5_rsi = ta.ema(rsi, lma5)
ma6_rsi = ta.ema(rsi, lma6)

//plot(ma1_rsi, title = "MA", linewidth = 2, transp = 0, style=plot.style_line,


color=color.fuchsia)
plot(ma2_rsi, title='MA', linewidth=2, style=plot.style_line,
color=color.new(color.orange, 0))
plot(ma3_rsi, title='MA', linewidth=2, style=plot.style_line,
color=color.new(#39E120, 0))
plot(ma4_rsi, title='MA', linewidth=2, style=plot.style_line,
color=color.new(#2DE1CF, 0))
//plot(ma5_rsi, title='MA', linewidth=2, style=plot.style_line,
color=color.new(#2DE1CF, 0))
//plot(ma6_rsi, title='MA', linewidth=2, style=plot.style_line,
color=color.new(#2DE1CF, 0))

/// divergence
prd = input.int(defval=5, title='Pivot Period', minval=1, maxval=50)
source = input.string(defval='Close', title='Source for Pivot Points',
options=['Close', 'High/Low'])
searchdiv = input.string(defval='Regular/Hidden', title='Divergence Type',
options=['Regular', 'Hidden', 'Regular/Hidden'])
showindis = input.string(defval='Full', title='Show Indicator Names',
options=['Full', 'First Letter', 'Don\'t Show'])
showlimit = input.int(1, title='Minimum Number of Divergence', minval=1, maxval=11)
maxpp = input.int(defval=10, title='Maximum Pivot Points to Check', minval=1,
maxval=20)
maxbars = input.int(defval=200, title='Maximum Bars to Check', minval=5,
maxval=200)
shownum = input(defval=true, title='Show Divergence Number')
showlast = input(defval=false, title='Show Only Last Divergence')
dontconfirm = input(defval=false, title='Don\'t Wait for Confirmation')
showlines = input(defval=false, title='Show Divergence Lines')
showpivot = input(defval=false, title='Show Pivot Points')
calcmacd = input(defval=true, title='MACD')
calcmacda = input(defval=true, title='MACD Histogram')
calcrsi = input(defval=true, title='RSI')
calcstoc = input(defval=true, title='Stochastic')
calccci = input(defval=true, title='CCI')
calcmom = input(defval=false, title='Momentum')
calcobv = input(defval=true, title='OBV')
calcvwmacd = input(true, title='VWmacd')
calccmf = input(true, title='Chaikin Money Flow')
calcmfi = input(true, title='Money Flow Index')
calcext = input(false, title='Check External Indicator')
externalindi = input(defval=close, title='External Indicator')
pos_reg_div_col = input(defval=color.yellow, title='Positive Regular Divergence')
neg_reg_div_col = input(defval=color.navy, title='Negative Regular Divergence')
pos_hid_div_col = input(defval=color.lime, title='Positive Hidden Divergence')
neg_hid_div_col = input(defval=color.red, title='Negative Hidden Divergence')
pos_div_text_col = input(defval=color.black, title='Positive Divergence Text
Color')
neg_div_text_col = input(defval=color.white, title='Negative Divergence Text
Color')
reg_div_l_style_ = input.string(defval='Solid', title='Regular Divergence Line
Style', options=['Solid', 'Dashed', 'Dotted'])
hid_div_l_style_ = input.string(defval='Dashed', title='Hdden Divergence Line
Style', options=['Solid', 'Dashed', 'Dotted'])
reg_div_l_width = input.int(defval=2, title='Regular Divergence Line Width',
minval=1, maxval=5)
hid_div_l_width = input.int(defval=1, title='Hidden Divergence Line Width',
minval=1, maxval=5)
showmas = input.bool(defval=false, title='Show MAs 50 & 200', inline='ma12')
cma1col = input.color(defval=color.lime, title='', inline='ma12')
cma2col = input.color(defval=color.red, title='', inline='ma12')

plot(showmas ? ta.sma(close, 50) : na, color=showmas ? cma1col : na)


plot(showmas ? ta.sma(close, 200) : na, color=showmas ? cma2col : na)

// set line styles


var reg_div_l_style = reg_div_l_style_ == 'Solid' ? line.style_solid :
reg_div_l_style_ == 'Dashed' ? line.style_dashed : line.style_dotted
var hid_div_l_style = hid_div_l_style_ == 'Solid' ? line.style_solid :
hid_div_l_style_ == 'Dashed' ? line.style_dashed : line.style_dotted

// get indicators
rsidd = ta.rsi(rsi, 14) // RSI
[macd, signal, deltamacd] = ta.macd(rsi, 12, 26, 9) // MACD
moment = ta.mom(rsi, 10) // Momentum
cci = ta.cci(rsi, 10) // CCI
Obv = ta.obv // OBV
stk = ta.sma(ta.stoch(rsi, rsih, rsil, 14), 3) // Stoch
maFast = ta.vwma(rsi, 12) // volume weighted macd
maSlow = ta.vwma(rsi, 26)
vwmacd = maFast - maSlow
Cmfm = (rsi - rsil - (rsih - rsi)) / (rsih - rsi) // Chaikin money flow
Cmfv = Cmfm * volume
cmf = ta.sma(Cmfv, 21) / ta.sma(volume, 21)
Mfi = ta.mfi(rsi, 14) // Moneyt Flow Index

// keep indicators names and colors in arrays


var indicators_name = array.new_string(11)
var div_colors = array.new_color(4)
if barstate.isfirst
// names
array.set(indicators_name, 0, showindis == 'Full' ? 'MACD' : 'M')
array.set(indicators_name, 1, showindis == 'Full' ? 'Hist' : 'H')
array.set(indicators_name, 2, showindis == 'Full' ? 'RSI' : 'E')
array.set(indicators_name, 3, showindis == 'Full' ? 'Stoch' : 'S')
array.set(indicators_name, 4, showindis == 'Full' ? 'CCI' : 'C')
array.set(indicators_name, 5, showindis == 'Full' ? 'MOM' : 'M')
array.set(indicators_name, 6, showindis == 'Full' ? 'OBV' : 'O')
array.set(indicators_name, 7, showindis == 'Full' ? 'VWMACD' : 'V')
array.set(indicators_name, 8, showindis == 'Full' ? 'CMF' : 'C')
array.set(indicators_name, 9, showindis == 'Full' ? 'MFI' : 'M')
array.set(indicators_name, 10, showindis == 'Full' ? 'Extrn' : 'X')
//colors
array.set(div_colors, 0, pos_reg_div_col)
array.set(div_colors, 1, neg_reg_div_col)
array.set(div_colors, 2, pos_hid_div_col)
array.set(div_colors, 3, neg_hid_div_col)

// Check if we get new Pivot High Or Pivot Low


float ph = ta.pivothigh(source == 'Close' ? rsi : rsih, prd, prd)
float pl = ta.pivotlow(source == 'Close' ? rsi : rsil, prd, prd)
plotshape(ph and showpivot, text='H', style=shape.labeldown,
color=color.new(color.white, 100), textcolor=color.new(color.red, 0),
location=location.abovebar, offset=-prd)
plotshape(pl and showpivot, text='L', style=shape.labelup,
color=color.new(color.white, 100), textcolor=color.new(color.lime, 0),
location=location.belowbar, offset=-prd)

// keep values and positions of Pivot Highs/Lows in the arrays


var int maxarraysize = 20
var ph_positions = array.new_int(maxarraysize, 0)
var pl_positions = array.new_int(maxarraysize, 0)
var ph_vals = array.new_float(maxarraysize, 0.)
var pl_vals = array.new_float(maxarraysize, 0.)

// add PHs to the array


if ph
array.unshift(ph_positions, bar_index)
array.unshift(ph_vals, ph)
if array.size(ph_positions) > maxarraysize
array.pop(ph_positions)
array.pop(ph_vals)

// add PLs to the array


if pl
array.unshift(pl_positions, bar_index)
array.unshift(pl_vals, pl)
if array.size(pl_positions) > maxarraysize
array.pop(pl_positions)
array.pop(pl_vals)

// functions to check Regular Divergences and Hidden Divergences

// function to check positive regular or negative hidden divergence


// cond == 1 => positive_regular, cond == 2=> negative_hidden
positive_regular_positive_hidden_divergence(src, cond) =>
divlen = 0
prsc = source == 'Close' ? rsi : rsi
// if indicators higher than last value and close price is higher than las
close
if dontconfirm or src > src[1] or rsi > rsi[1]
startpoint = dontconfirm ? 0 : 1 // don't check last candle
// we search last 15 PPs
for x = 0 to maxpp - 1 by 1
len = bar_index - array.get(pl_positions, x) + prd
// if we reach non valued array element or arrived 101. or previous
bars then we don't search more
if array.get(pl_positions, x) == 0 or len > maxbars
break
if len > 5 and (cond == 1 and src[startpoint] > src[len] and
prsc[startpoint] < nz(array.get(pl_vals, x)) or cond == 2 and src[startpoint] <
src[len] and prsc[startpoint] > nz(array.get(pl_vals, x)))
slope1 = (src[startpoint] - src[len]) / (len - startpoint)
virtual_line1 = src[startpoint] - slope1
slope2 = (rsi[startpoint] - rsi[len]) / (len - startpoint)
virtual_line2 = rsi[startpoint] - slope2
arrived = true
for y = 1 + startpoint to len - 1 by 1
if src[y] < virtual_line1 or nz(rsi[y]) < virtual_line2
arrived := false
break
virtual_line1 -= slope1
virtual_line2 -= slope2
virtual_line2

if arrived
divlen := len
break
divlen

// function to check negative regular or positive hidden divergence


// cond == 1 => negative_regular, cond == 2=> positive_hidden
negative_regular_negative_hidden_divergence(src, cond) =>
divlen = 0
prsc = source == 'Close' ? rsi : rsih
// if indicators higher than last value and close price is higher than las
close
if dontconfirm or src < src[1] or rsi < rsi[1]
startpoint = dontconfirm ? 0 : 1 // don't check last candle
// we search last 15 PPs
for x = 0 to maxpp - 1 by 1
len = bar_index - array.get(ph_positions, x) + prd
// if we reach non valued array element or arrived 101. or previous
bars then we don't search more
if array.get(ph_positions, x) == 0 or len > maxbars
break
if len > 5 and (cond == 1 and src[startpoint] < src[len] and
prsc[startpoint] > nz(array.get(ph_vals, x)) or cond == 2 and src[startpoint] >
src[len] and prsc[startpoint] < nz(array.get(ph_vals, x)))
slope1 = (src[startpoint] - src[len]) / (len - startpoint)
virtual_line1 = src[startpoint] - slope1
slope2 = (rsi[startpoint] - nz(rsi[len])) / (len - startpoint)
virtual_line2 = rsi[startpoint] - slope2
arrived = true
for y = 1 + startpoint to len - 1 by 1
if src[y] > virtual_line1 or nz(rsi[y]) > virtual_line2
arrived := false
break
virtual_line1 -= slope1
virtual_line2 -= slope2
virtual_line2
if arrived
divlen := len
break
divlen

// calculate 4 types of divergence if enabled in the options and return divergences


in an array
calculate_divs(cond, indicator_1) =>
divs = array.new_int(4, 0)
array.set(divs, 0, cond and (searchdiv == 'Regular' or searchdiv ==
'Regular/Hidden') ? positive_regular_positive_hidden_divergence(indicator_1, 1) :
0)
array.set(divs, 1, cond and (searchdiv == 'Regular' or searchdiv ==
'Regular/Hidden') ? negative_regular_negative_hidden_divergence(indicator_1, 1) :
0)
array.set(divs, 2, cond and (searchdiv == 'Hidden' or searchdiv ==
'Regular/Hidden') ? positive_regular_positive_hidden_divergence(indicator_1, 2) :
0)
array.set(divs, 3, cond and (searchdiv == 'Hidden' or searchdiv ==
'Regular/Hidden') ? negative_regular_negative_hidden_divergence(indicator_1, 2) :
0)
divs

// array to keep all divergences


var all_divergences = array.new_int(44) // 11 indicators * 4 divergence = 44
elements
// set related array elements
array_set_divs(div_pointer, index) =>
for x = 0 to 3 by 1
array.set(all_divergences, index * 4 + x, array.get(div_pointer, x))

// set divergences array


array_set_divs(calculate_divs(calcmacd, macd), 0)
array_set_divs(calculate_divs(calcmacda, deltamacd), 1)
array_set_divs(calculate_divs(calcrsi, rsidd), 2)
array_set_divs(calculate_divs(calcstoc, stk), 3)
array_set_divs(calculate_divs(calccci, cci), 4)
array_set_divs(calculate_divs(calcmom, moment), 5)
array_set_divs(calculate_divs(calcobv, Obv), 6)
array_set_divs(calculate_divs(calcvwmacd, vwmacd), 7)
array_set_divs(calculate_divs(calccmf, cmf), 8)
array_set_divs(calculate_divs(calcmfi, Mfi), 9)
array_set_divs(calculate_divs(calcext, externalindi), 10)

// check minimum number of divergence, if less than showlimit then delete all
divergence
total_div = 0
for x = 0 to array.size(all_divergences) - 1 by 1
total_div += math.round(math.sign(array.get(all_divergences, x)))
total_div

if total_div < showlimit


array.fill(all_divergences, 0)

// keep line in an array


var pos_div_lines = array.new_line(0)
var neg_div_lines = array.new_line(0)
var pos_div_labels = array.new_label(0)
var neg_div_labels = array.new_label(0)
// variables for Alerts
pos_reg_div_detected = false
neg_reg_div_detected = false
pos_hid_div_detected = false
neg_hid_div_detected = false

// to remove lines/labels until we met new // PH/PL


var last_pos_div_lines = 0
var last_neg_div_lines = 0
var remove_last_pos_divs = false
var remove_last_neg_divs = false
if pl
remove_last_pos_divs := false
last_pos_div_lines := 0
last_pos_div_lines
if ph
remove_last_neg_divs := false
last_neg_div_lines := 0
last_neg_div_lines

// draw divergences lines and labels


divergence_text_top = ''
divergence_text_bottom = ''
distances = array.new_int(0)
dnumdiv_top = 0
dnumdiv_bottom = 0
top_label_col = color.white
bottom_label_col = color.white
old_pos_divs_can_be_removed = true
old_neg_divs_can_be_removed = true
startpoint = dontconfirm ? 0 : 1 // used for don't confirm option

for x = 0 to 10 by 1
div_type = -1
for y = 0 to 3 by 1
if array.get(all_divergences, x * 4 + y) > 0 // any divergence?
div_type := y
if y % 2 == 1
dnumdiv_top += 1
top_label_col := array.get(div_colors, y)
top_label_col
if y % 2 == 0
dnumdiv_bottom += 1
bottom_label_col := array.get(div_colors, y)
bottom_label_col
if not array.includes(distances, array.get(all_divergences, x * 4 + y))
// line not exist ?
array.push(distances, array.get(all_divergences, x * 4 + y))

// set variables for alerts


if y == 0
pos_reg_div_detected := true
pos_reg_div_detected
if y == 1
neg_reg_div_detected := true
neg_reg_div_detected
if y == 2
pos_hid_div_detected := true
pos_hid_div_detected
if y == 3
neg_hid_div_detected := true
neg_hid_div_detected

// get text for labels


if div_type >= 0
divergence_text_top += (div_type % 2 == 1 ? showindis != 'Don\'t Show' ?
array.get(indicators_name, x) + '\n' : '' : '')
divergence_text_bottom += (div_type % 2 == 0 ? showindis != 'Don\'t Show' ?
array.get(indicators_name, x) + '\n' : '' : '')
divergence_text_bottom

// draw labels
if showindis != 'Don\'t Show' or shownum
if shownum and dnumdiv_top > 0
divergence_text_top += str.tostring(dnumdiv_top)
divergence_text_top
if shownum and dnumdiv_bottom > 0
divergence_text_bottom += str.tostring(dnumdiv_bottom)
divergence_text_bottom
if divergence_text_top != ''

array.push(neg_div_labels, label.new(x=bar_index, y=math.max(rsih,


rsih[1]), text=divergence_text_top, color=top_label_col,
textcolor=neg_div_text_col, style=label.style_label_down, size=size.tiny))

if divergence_text_bottom != ''

array.push(pos_div_labels, label.new(x=bar_index, y=math.min(rsil,


rsil[1]), text=divergence_text_bottom, color=bottom_label_col,
textcolor=pos_div_text_col, style=label.style_label_up, size=size.tiny))

////////////////////////
// breakout
////////////////////////
// === BACKTEST RANGE ===
From_Year = input(defval=2019, title='From Year')
From_Month = input.int(defval=1, title='From Month', minval=1, maxval=12)
From_Day = input.int(defval=1, title='From Day', minval=1, maxval=31)
To_Year = input(defval=9999, title='To Year')
To_Month = input.int(defval=1, title='To Month', minval=1, maxval=12)
To_Day = input.int(defval=1, title='To Day', minval=1, maxval=31)
Start = timestamp(From_Year, From_Month, From_Day, 00, 00) // backtest start
window
Finish = timestamp(To_Year, To_Month, To_Day, 23, 59) // backtest finish window

// A switch to control background coloring of the test period - Use for easy
visualization of backtest range and manual calculation of
// buy and hold (via measurement) if doing prior periods since value in Strategy
Tester extends to current date by default
testPeriodBackground = input(title='Color Background - Test Period?', defval=false)
testPeriodBackgroundColor = testPeriodBackground and time >= Start and time <=
Finish ? #00FF00 : na
bgcolor(testPeriodBackgroundColor, transp=95)
// == FILTERING ==
// Inputs
useMaFilter = input(title='Use MA for Filtering?', defval=false)
maType = input.string(defval='SMA', options=['EMA', 'SMA'], title='MA Type For
Filtering')
maLength = input.int(defval=200, title='MA Period for Filtering', minval=1)

// Declare function to be able to swap out EMA/SMA


ma(maType, src, length) =>
maType == 'EMA' ? ta.ema(src, length) : ta.sma(src, length) //Ternary Operator
(if maType equals EMA, then do ema calc, else do sma calc)
maFilter = ma(maType, rsi, maLength)
//plot(maFilter, title = "Trend Filter MA", color = color.green, linewidth = 3,
style = plot.style_line, transp = 50)

// Check to see if the useMaFilter check box is checked, this then inputs this
conditional "maFilterCheck" variable into the strategy entry
maFilterCheck = if useMaFilter == true
maFilter
else
0

// === PLOT SWING HIGH/LOW AND MOST RECENT LOW TO USE AS STOP LOSS EXIT POINT ===
// Inputs
//pvtLenL = input(3, minval=1, title="Pivot Length Left Hand Side") //use if
you want to change this to an input
//pvtLenR = input(3, minval=1, title="Pivot Length Right Hand Side") //use if
you want to change this to an input
pvtLenL = 3
pvtLenR = 3

// Get High and Low Pivot Points


pvthi_ = ta.pivothigh(rsih, pvtLenL, pvtLenR)
pvtlo_ = ta.pivotlow(rsil, pvtLenL, pvtLenR)

// Force Pivot completion before plotting.


Shunt = 1 //Wait for close before printing pivot? 1 for true 0 for flase
maxLvlLen = 0 //Maximum Extension Length
pvthi = pvthi_[Shunt]
pvtlo = pvtlo_[Shunt]

// Count How many candles for current Pivot Level, If new reset.
counthi = ta.barssince(not na(pvthi))
countlo = ta.barssince(not na(pvtlo))

pvthis = fixnan(pvthi)
pvtlos = fixnan(pvtlo)
hipc = ta.change(pvthis) != 0 ? na : color.maroon
lopc = ta.change(pvtlos) != 0 ? na : color.green

// Display Pivot lines


plot(maxLvlLen == 0 or counthi < maxLvlLen ? pvthis : na, color=hipc, linewidth=1,
offset=-pvtLenR - Shunt, title='Top Levels', transp=0)
plot(maxLvlLen == 0 or countlo < maxLvlLen ? pvtlos : na, color=lopc, linewidth=1,
offset=-pvtLenR - Shunt, title='Bottom Levels', transp=0)
plot(maxLvlLen == 0 or counthi < maxLvlLen ? pvthis : na, color=hipc, linewidth=1,
offset=0, title='Top Levels 2', transp=0)
plot(maxLvlLen == 0 or countlo < maxLvlLen ? pvtlos : na, color=lopc, linewidth=1,
offset=0, title='Bottom Levels 2', transp=0)
// Stop Levels
stopBuff = input.float(0.0, minval=-2, title='Stop Loss Buffer off Swing Low (%)')
stopPerc = stopBuff * .01 // Turn stop buffer input into a percentage
stopLevel = ta.valuewhen(pvtlo_, rsil[pvtLenR], 0) //Stop Level at Swing Low
stopLevel2 = stopLevel - stopLevel * stopPerc // Stop Level with user-defined
buffer to avoid stop hunts and give breathing room
plot(stopLevel2, style=plot.style_line, color=color.new(color.orange, 50),
show_last=1, linewidth=1, trackprice=true)
buyLevel = ta.valuewhen(pvthi_, rsih[pvtLenR], 0) //Buy level at Swing High
buyLevel2 = buyLevel + buyLevel * stopPerc // Buy-stop level with user-defined
buffer to avoid stop hunts and give breathing room
plot(buyLevel2, style=plot.style_line, color=color.new(color.aqua, 50),
show_last=1, linewidth=1, trackprice=true)

// Conditions for entry and exit


buySignal = rsih > buyLevel2
buy = buySignal and time > Start and time < Finish and buyLevel2 >
maFilterCheck // All these conditions need to be met to buy
sellSignal = rsil < stopLevel2 // Code to act like a stop-loss for the Study

// (STRATEGY ONLY) Comment out for Study


// strategy.entry("Long", strategy.long, stop = buyLevel2, when = time > Start and
time < Finish and buyLevel2 > maFilterCheck)
// strategy.exit("Exit Long", from_entry = "Long", stop=stopLevel2)

// == (STUDY ONLY) Comment out for Strategy ==


// Check if in position or not
inPosition = bool(na)
inPosition := buy[1] ? true : sellSignal[1] ? false : inPosition[1]
flat = bool(na)
flat := not inPosition
buyStudy = buy and flat
sellStudy = sellSignal and inPosition
//Plot indicators on chart and set up alerts for Study
if buyStudy
label.new(x=bar_index, y=math.min(rsih, rsih[1]), text="B", color=color.blue,
textcolor=color.white, style=label.style_label_up, size=size.tiny)

if sellStudy
label.new(x=bar_index, y=math.min(rsil, rsil[1]), text="S",
color=color.fuchsia, textcolor=color.white, style=label.style_label_down,
size=size.tiny)

//plotshape(buyStudy, style=shape.triangleup, location=location.abovebar,


color=color.new(#1E90FF, 0), text='Buy', size=size.small)
//plotshape(sellStudy, style=shape.triangledown, location=location.belowbar,
color=color.new(#EE82EE, 0), text='Sell', size=size.small)
alertcondition(buyStudy, title='Breakout Trend Follower Buy', message='Breakout
Trend Follower Buy')
alertcondition(sellStudy, title='Breakout Trend Follower Sell', message='Breakout
Trend Follower Sell')

You might also like