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

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.

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)

Finite Element Analysis with Gridap.jl; how to define external forces?

I'm following this tutorial in order to try and do an FEA of a model.msh that I have to see how it would deform given different external forces in different places.
There they define the weak form as
a(u,v) = ∫( ε(v) ⊙ (σ∘ε(u)) )*dΩ
l(v) = 0
and they state "The linear form is simply l(v) = 0 since there are not external forces in this example."
As mentioned, I would like to analyse the different deformation that different external forces would cause on my model, but I can't seem to find anywhere an example of this. Could someone help me on defining this linear form for external forces different than 0?
Thanks.
Maybe this helps you out. It was written in a hurry, so please do not mind if you encounter spelling mistakes or other beauty issues :)
# define where the output shall go
output_Path ="Output/3_Gridap/1_Lin_FEA/FE_8"
mkpath(output_Path)
output_Name ="pde_6"
using Gridap
# please load the model that is shown in: https://gridap.github.io/Tutorials/dev/pages/t001_poisson/
model = DiscreteModelFromFile("Code/Meshes/Data/possion.json")
# just in case you want to see the model using paraview
writevtk(model,"$(output_Path)/md")
order = 1
reffe = ReferenceFE(lagrangian,VectorValue{3,Float64},order)
V0 = TestFESpace(model,reffe;
conformity=:H1,
# to see which elements belongs to "bottom" open the model which is saved through "writevtk(model,"$(output_Path)/md")"
dirichlet_tags=["bottom"],
# activate/deactivate the boundary conditions
dirichlet_masks=[
(true, true, true), # clamp the bottom
])
# define displacement
clamping(x) = VectorValue(0.0,0.0,0.0)
U = TrialFESpace(V0,[clamping])
const E = 7e+7
const ν = 0.33
const λ = (E*ν)/((1+ν)*(1-2*ν))
const μ = E/(2*(1+ν))
σ(ε) = λ*tr(ε)*one(ε) + 2*μ*ε
degree = 2*order
Ω = Triangulation(model)
dΩ = Measure(Ω,degree)
# Neumann boundary conditions
# here we define the surface on which we want an external force
Γ_Tr = BoundaryTriangulation(model,tags=["triangle"])
dΓ_Tr = Measure(Γ_Tr,degree)
# a force shall be applied on the y-direction
f_Tr(x) = VectorValue(0.0, 1e+6, 0.0)
# mass forces due to gravity, the value is set quite high, such that an impact can be seen
mass_Forces(x) = VectorValue(0.0, -1e+7, 0.0)
# Weak form
a(u,v) = ∫( ε(v) ⊙ (σ∘ε(u)) )*dΩ
l(v) = ∫( v ⋅ mass_Forces )* dΩ + ∫( v ⋅ f_Tr )* dΓ_Tr
op = AffineFEOperator(a,l,U,V0)
uh = solve(op)
writevtk(Ω,"$(output_Path)/$(output_Name)",
cellfields=[
"uh" => uh,
"epsi" => ε(uh),
"sigma" => σ∘ε(uh)])

Strategy = Multiple confirmations for alert

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)

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.

Looking to find the sum in R

I keep getting NA for the code below to find the sum of vector in R without using sum():
total <- 0
for ()) {
add = gg[n] + gg[n+1]
total = total + add
}
Your getting a NA because gg[n+1] does not exist when last step (length(gg)) : so it finally adds NA to your sum.
Use for (n in (1:(length(gg)-1)) ) instead
(and tip to debug : print the contents of your variables at each steps using print() - launch code below to see your issue :
total <- 0
for (n in (1:length(gg)) ) {
print(paste("n: ",n))
print(paste("gg for n : ",gg[n], "and n+1: ",gg[n+1]))
add = gg[n] + gg[n+1]
print(paste("add when loop = ", n, ":", add))
total = total + add
print(total)
}
total

Resources