Strategy = Multiple confirmations for alert - volume

I'm pretty much a beginner at coding but am trying to create an indicator with multiple confirmations and alerts but have come across a few issues.
My strategy is to use adx crossunders ,higher volume at the cross , engulfing candles and pivot points with all needing to happen at the same time.
I have started to code the first parameter which is the -DI cross under the plusDI and also the crossunder of plusDm and -DI to show on my chart. As further confirmation I am also trying to add engulfing candles at the point of a cross and two other confirmations which are increase in volume (last 2 bars) and price being at swing high or swing low maybe using fractal before any alerts are triggered. I am using this on lower timeframes eg 1min - 5min charts. If anyone could help with this or point me in the direction of how I combine them all into one alert it be would be massively appreciated.
Thank you!
//#version=5
indicator("My script")
//DMI + ADX
lensig = input.int(14, title="ADX Smoothing", minval=1, maxval=50)
len = input.int(14, minval=1, title="DI Length")
up = ta.change(high)
down = -ta.change(low)
plusDM = na(up) ? na : (up > down and up > 0 ? up : 0)
minusDM = na(down) ? na : (down > up and down > 0 ? down : 0)
trur = ta.rma(ta.tr, len)
plus = fixnan(100 * ta.rma(plusDM, len) / trur)
minus = fixnan(100 * ta.rma(minusDM, len) / trur)
sum = plus + minus
adx = 100 * ta.rma(math.abs(plus - minus) / (sum == 0 ? 1 : sum), lensig)
adxmax = input.int(50, title="ADX Max Buying Area", minval=1, maxval=100)
adxmin = input.int(0, title="ADX Min Buying Area", minval=0, maxval=99)
//identify engulfing candles
bullishEC = close > open[1] and close[1] < open[1]
bearishEC = close < open[1] and close [1] > close [1]
//plotshape( series=bearishEC, style = shape.cross , color=color.black, location=location.abovebar)
//plotshape( series=bullishEC, style = shape.circle , color=color.black, location=location.abovebar)
//DI cross alert
DIPcross = ta.crossover(plus, minus) ? plus : na
plotshape(DIPcross, style = shape.circle , color=color.teal, location=location.absolute)
DINcross = ta.crossover(minus, plus) ? minus : na
plotshape(DINcross, style = shape.circle , color=color.red, location=location.absolute)
plot(adx, color=color.orange, title="ADX", linewidth=2)
p1 = plot(plus, color=color.teal, title="+DI", linewidth=1)
p2 = plot(minus, color=color.yellow, title="-DI", linewidth=1)
adxmaxl = hline(adxmax, title="ADX MaxLine", color=color.silver, linestyle=hline.style_solid)
adxminl = hline(adxmin, title="ADX MinLine", color=color.silver, linestyle=hline.style_solid)

Related

How to plot line only on first value of crossover condition met in Pine Script

I need help in Pine script coding, i want to plot the first crossover value alone not entire series of values for whole day. so if crossover condition is true for 1st or 2nd or 3rd or n times, i need to plot the line from the first condition met to end of day and ignore 2nd or 3rd or 4th or nth series values to plot. how to do it? and i don't want to use line.new() since i want to backtest in tradingview.com, for historical bars i want to use Plot(). so kindly help me with the code.
Strategy im trying: Added 30pts above from 5mins High-Low, if 5 mins candle crossover the 30pts at first time from High need to plot line, ignore if condition met again in a day.
`
//#version=5
indicator(title="Crossover", shorttitle="Crossover", overlay=true)
//*5Mins High Low calculation*//
inputMax = input(5, title= "ORB total time (minutes)")
sess = input("0915-0920", title="Session Time")
t = time(timeframe.period, sess + ":1234567")
hide = timeframe.isintraday and timeframe.multiplier <= inputMax
is_newbar(res) => ta.change(time(res)) != 0
in_session = not na(t)
is_first = in_session and not in_session[1]
orb_high = float(na)
orb_low = float(na)
if is_first
orb_high := high
orb_low := low
else
orb_high := orb_high[1]
orb_low := orb_low[1]
if high > orb_high and in_session
orb_high := high
if low < orb_low and in_session
orb_low := low
plot(hide ? orb_high : na , style=plot.style_line, color=orb_high[1] != orb_high ? na : color.green , title="ORB High", linewidth=3)
plot(hide ? orb_low : na , style=plot.style_line, color=orb_low[1] != orb_low ? na : color.red, title="ORB Low", linewidth=3)
//*Crossover condition*//
var Up = 0.0
Up := orb_high + 30
var b_i = 0.0
cross_over_happened = if(ta.crossover(close, Up)) and barstate.isconfirmed
1
else
0
b_i := ta.valuewhen(cross_over_happened, close, 0)
plot(b_i, color = color.black, linewidth = 2)
`
the above code will plot whenever condition met, but i need to plot only the first value of crossover condition, not for entire series. Kindly help with the code.
I would go about this in a slightly different way (which is very close to what you have done). I would add a bool that will check if a cross already happened today, and will change the value of b_i only when the cross and the new bool are true.
First set the variables that we're going to need:
var float orb_high = na
var float orb_low = na
var bool already_had_crossover_today = false
var float b_i = na
Second, reset those variables on each new day:
if ta.change(time("D"))
orb_high := high
orb_low := low
already_had_crossover_today := false
b_i := na
Third, we'll check for the crossover, regardless if it's the first one on the day or not:
Up = orb_high + 30
cross_over_happened = ta.crossover(close, Up)
And lastly, we'll check if we had a crossover and during the day a crossover hasn't happened yet:
if cross_over_happened and not already_had_crossover_today
b_i := close
already_had_crossover_today := true
Than we can just use plot, and for better visualization use the style parameter:
plot(b_i, style = plot.style_linebr)

Color background within price range of only latest 5 candle ( highest and lowest price level)

I want to color the background of price range within the latest 5 candle.
Get the highest price and lowest price among them and color the background.
Other previous candle ( candle 6 and previous ) I just want to ignore.
I'm newbie and still learning.
I try using :
highest(5)
lowest(5)
and
highest(high, 5)
lowest(low, 5)
But it didn't work for me.
Here's the closet example form Kodify web. But need to enter the price range manually.
//#version=4
study(title="Colour background in price range", overlay=true)
// STEP 1:
// Configure price range with inputs
rangeUp = input(title="Price Range Upper Bound", type=input.float, defval=1, minval=0)
rangeDown = input(title="Price Range Lower Bound", type=input.float, defval=0.95, minval=0)
fullBarInRange = input(title="Full Bar In Range?", type=input.bool, defval=false)
// STEP 2:
// Check if bar falls in range, based on input
insideRange = if fullBarInRange
high < rangeUp and low > rangeDown
else
high > rangeDown and low < rangeUp
// STEP 3:
// Plot range's upper and lower bound
ubPlot = plot(series=insideRange ? rangeUp : na, style=plot.style_linebr, transp=100, title="Upper Bound")
lbPlot = plot(series=insideRange ? rangeDown : na, style=plot.style_linebr, transp=100, title="Lower Bound")
// STEP 4:
// Fill the background for bars inside the price range
fill(plot1=ubPlot, plot2=lbPlot, color=#FF8C00, transp=75)
Version 1
This will fill between the highest/lowest of the last 5 bars:
//#version=4
study("Hi/Lo Range", "", true)
p = input(5)
hi = highest(p)
lo = lowest(p)
p_hi = plot(hi, "Hi")
p_lo = plot(lo, "Lo")
fill(p_hi, p_lo)
Version 2
//#version=4
study("Hi/Lo Range", "", true)
p = input(5)
hi = highest(p)
lo = lowest(p)
p_hi = plot(hi, "Hi", show_last = 5)
p_lo = plot(lo, "Lo", show_last = 5)
fill(p_hi, p_lo, show_last = 5)

Plot precedence while plotting adx and price oscillator in [pine- script]

Hi I am a newbie to pine editor, I am trying to plot Price oscillator and ADX in the same window with the same precedence, but whenever I plot them ADX is coming on the top but it should be in reverse order. Plots are not coming correctly (when plotted individually it shows correctly). Please find the code which I have used and let me know where it needs to be corrected?
//#version=4
study(title="Price Oscillator", shorttitle="PPO", format=format.price, precision=2)
shortlen=input(12, minval=1)
longlen=input(26, minval=1)
src = input(close, title="Source")
short = ema(src, shortlen)
long = ema(src, longlen)
po = (short - long)/long*100
adxlen = input(14, title="ADX Smoothing")
dilen = input(14, title="DI Length")
dirmov(len) =>
up = change(high)
down = -change(low)
plusDM = na(up) ? na : (up > down and up > 0 ? up : 0)
minusDM = na(down) ? na : (down > up and down > 0 ? down : 0)
truerange = rma(tr, len)
plus = fixnan(100 * rma(plusDM, len) / truerange)
minus = fixnan(100 * rma(minusDM, len) / truerange)
[plus, minus]
adx(dilen, adxlen) =>
[plus, minus] = dirmov(dilen)
sum = plus + minus
adx = 100 * rma(abs(plus - minus) / (sum == 0 ? 1 : sum), adxlen)
sig = adx(dilen, adxlen)
plot(po, color=#990000, title="PPO")
plot(sig, color=color.red, title="ADX")`
I have attached the snapshot of the window as well for your referenceplotting PPO and ADX
That's because they don't have the same scale. It would be much easier and reliable to simply use each one separately and overlay them on in the same pane, on different scales.

How to mark High of today if it has a particular decimal say ".55" at end for a 5m interval chart in Tradingview using Pine script

What I want to do is to mark the candle in 5m chart for the current day if it meets following two condition:
1) The candle should be highest of the day and it's high=1234.75 (at end ".75" decimal)
2) The candle should be lowest of the day and it's low=900.25 (at end "0.25" decimal)
I could mark a candle if it's high value consist of ".75" decimal at end and low value consist of ".25" decimal behind any value using below code but it shows all candles whose high ends with "0.75". I want to mark only Day high candle if it meets 0.75 criteria. Please refer and help me out.. Thank you in advance
// This source code is subject to the terms of the Mozilla Public License 2.0 at
https://mozilla.org/MPL/2.0/
//#version=4
study("(75-25)", overlay=true)
ch = high[0]
cl = low[0]
truncate(number, decimals) =>
factor = pow(10, decimals)
int(number * factor) / factor
chA = truncate(ch,0)
chB = ch - chA
data = chB == 0.75
clA = truncate(cl,0)
clB = cl - clA
data1 = clB == 0.25
plotshape(data, style=shape.triangledown, size=size.small, location=location.abovebar,
color=color.red)
plotshape(data1, style=shape.triangleup, size=size.small, location=location.belowbar,
color=color.green)
You can use the security() function to get the daily high and lows. However, you would miss the intraday actions for backtesting. What you need I believe is, if the price is the daily high/low from the session start until that specific bar.
You can use the following method the keep track of the daily high/low and update the values if a new high/low forms.
var dailyHigh = high
var dailyLow = low
t = time("1440", session.regular) // Get the session open
isSessionFirstBar = na(t[1]) and not na(t) or t[1] < t // True: If first bar in the session
dailyHigh := iff(isSessionFirstBar, high, iff(high > dailyHigh, high, dailyHigh))
dailyLow := iff(isSessionFirstBar, low, iff(low < dailyLow, low, dailyLow))
Then you should combine this with your data and data1 variables.
data = (chB == 0.75) and (close == dailyHigh)
data1 = (clB == 0.25) and (close == dailyLow)

Calculate RSI indicator according to tradingview?

I would like to calculate RSI 14 in line with the tradingview chart.
According to there wiki this should be the solution:
https://www.tradingview.com/wiki/Talk:Relative_Strength_Index_(RSI)
I implemented this is in a object called RSI:
Calling within object RSI:
self.df['rsi1'] = self.calculate_RSI_method_1(self.df, period=self.period)
Implementation of the code the calculation:
def calculate_RSI_method_1(self, ohlc: pd.DataFrame, period: int = 14) -> pd.Series:
delta = ohlc["close"].diff()
ohlc['up'] = delta.copy()
ohlc['down'] = delta.copy()
ohlc['up'] = pd.to_numeric(ohlc['up'])
ohlc['down'] = pd.to_numeric(ohlc['down'])
ohlc['up'][ohlc['up'] < 0] = 0
ohlc['down'][ohlc['down'] > 0] = 0
# This one below is not correct, but why?
ohlc['_gain'] = ohlc['up'].ewm(com=(period - 1), min_periods=period).mean()
ohlc['_loss'] = ohlc['down'].abs().ewm(com=(period - 1), min_periods=period).mean()
ohlc['RS`'] = ohlc['_gain']/ohlc['_loss']
ohlc['rsi'] = pd.Series(100 - (100 / (1 + ohlc['RS`'])))
self.currentvalue = round(self.df['rsi'].iloc[-1], 8)
print (self.currentvalue)
self.exportspreadsheetfordebugging(ohlc, 'calculate_RSI_method_1', self.symbol)
I tested several other solution like e.g but non return a good value:
https://github.com/peerchemist/finta
https://gist.github.com/jmoz/1f93b264650376131ed65875782df386
Therefore I created a unittest based on :
https://school.stockcharts.com/doku.php?id=technical_indicators:relative_strength_index_rsi
I created an input file: (See excel image below)
and a output file: (See excel image below)
Running the unittest (unittest code not included here) should result in but is only checking the last value.
if result == 37.77295211:
log.info("Unit test 001 - PASSED")
return True
else:
log.error("Unit test 001 - NOT PASSED")
return False
But again I cannot pass the test.
I checked all values by help with excel.
So now i'm a little bit lost.
If I'm following this question:
Calculate RSI indicator from pandas DataFrame?
But this will not give any value in the gain.
a) How should the calculation be in order to align the unittest?
b) How should the calculation be in order to align with tradingview?
Here is a Python implementation of the current RSI indicator version in TradingView:
https://github.com/lukaszbinden/rsi_tradingview/blob/main/rsi.py
I had same issue in calculating RSI and the result was different from TradingView,
I have found RSI Step 2 formula described in InvestoPedia and I changed the code as below:
N = 14
close_price0 = float(klines[0][4])
gain_avg0 = loss_avg0 = close_price0
for kline in klines[1:]:
close_price = float(kline[4])
if close_price > close_price0:
gain = close_price - close_price0
loss = 0
else:
gain = 0
loss = close_price0 - close_price
close_price0 = close_price
gain_avg = (gain_avg0 * (N - 1) + gain) / N
loss_avg = (loss_avg0 * (N - 1) + loss) / N
rsi = 100 - 100 / (1 + gain_avg / loss_avg)
gain_avg0 = gain_avg
loss_avg0 = loss_avg
N is the number of period for calculating RSI (by default = 14)
the code is put in a loop to calculate all RSI values for a series.
For those who are experience the same.
My raw data contained ticks where the volume is zero. Filtering this OLHCV rows will directly give the good results.

Resources