Lower time frame in pine script indicator - share

I want to fix calculation time period of my indicator as 1 minute .
That means
if I am checking on 5 minute chart . I want to see the current 5 minute indicator value as some of 5 one minute indicator values included in the current 5 minute candle.
If I am checking on 15 minute chart. I want to see the current 15 minute indicator value as some of 15 one minute indicator values included in the current 15 minute candle.
Same for all.
And I coded it as bellow . But as chart time frame changes calculation also changes.
This is how I Coded it
indicator(title = "OBV MULTI" , overlay = false)
var a = 0.0
var b = 0.0
var c = 0.0
var d = 0.0
a := ta.change(time("D")) ? 0.0 : a
b := ta.change(time("W")) ? 0.0 : b
c := ta.change(time("M")) ? 0.0 : c
d := ta.change(time("12M")) ? 0.0 :d
src1 = request.security_lower_tf(syminfo.tickerid" ,"1",close)
src2 = request.security_lower_tf(syminfo.tickerid","1",open)
src3 = request.security_lower_tf(syminfo.tickerid, "1",volume)
a := (close>open) ? a+volume : (close<open) ? a-volume : ((close==open)and(a[1]>a[2])) ? a +volume : ((close==open))and(a[1]<a[2])) ? a-volume : 0
b := (close>close) ? b+volume : (close<open) ? b-volume : ((close==open)and(b[1]>b[2])) ? b +volume : ((close==open))and(b[1]<b[2])) ? b-volume : 0
c := (close>open) ? c+volume : (close<open) ? c-volume : ((close==open)and(c[1]>c[2])) ? c +volume : ((close==open))and(c[1]<c[2])) ? c-volume : 0
d := (close>open) ? d+volume : (close<open) ? d-volume : ((close==open)and(d[1]>d[2])) ? d +volume : ((close==open))and(d[1]<d[2])) ? d-volume : 0
Plot(a , title = "D Line" , color = color.blue)
Plot(b , title = "W Line" , color = color.green)
Plot(c , title = "M Line" , color = color.yellow)
Plot(d , title = "Y Line" , color = color.orange)
Plot(0 , title = "Zero Line", color = color.red)

Related

Pine Script V5 - Not getting expected breakout entry price and entry in expected bar

I have a long entry buy condition where
Candle time frame is 15 minutes
Alert candle high is below lower band of bollinger bands.
entry when next candle crossover the alert candle high
This script gives entry oh high breakout + 0.01 but it does not give entry in the exact breakout candle and gives entry when price comes next time on expected entry price i.e. alert candle high + 0.01.
Requesting solution to get entry in breakout candle itself and at expected breakout price.
//#version=5
strategy("Bands Reversion", overlay=true, calc_on_every_tick=true)
//// Indicator Bollinger Bands
source = close
length = input.int(20, minval=1)
mult = input.float(1.5, minval=0.001, maxval=50)
direction = input.int(0, title = "Strategy Direction", minval=-1, maxval=1)
strategy.risk.allow_entry_in(direction == 0 ? strategy.direction.all : (direction < 0 ? strategy.direction.short : strategy.direction.long))
basis = ta.sma(source, length)
dev = mult * ta.stdev(source, length)
upper = basis + dev
lower = basis - dev
plot(basis, color = color.red)
plot(upper)
plot(lower)
/// Trade entry time and squareoff time
TradeTime = input(title="Trade Timings",defval="0930-1130")
SqoffTime = input(title="Squareoff Timings",defval="1530-1545")
Barsinsession(TradeTime) => time(timeframe.period,TradeTime) != 0
Insession = Barsinsession(TradeTime) ? 1 : 0
endofsession = Insession == 0 and Insession[1] == 1
Sqsession = Barsinsession(SqoffTime) ? 1 : 0
SqTime = Sqsession == 1 and Sqsession[1] == 0
//// Input control and conditions
buy_condition = high[1] < lower[1] and ta.crossover(high, high[1]) and Insession
short_condition = low[1] > upper[1] and ta.crossunder(low, low[1]) and Insession
buy_alert_high = ta.valuewhen(buy_condition, high[1],0)
buy_alert_low = ta.valuewhen(buy_condition, low[1],0)
short_alert_low = ta.valuewhen(short_condition, low[1],0)
short_alert_high = ta.valuewhen(short_condition, high[1],0)
buy_alert_high1 = ta.valuewhen(buy_condition, high,0)
plot(buy_alert_high, style = plot.style_circles)
plot(buy_alert_low, style = plot.style_circles, offset = -2)
plot(short_alert_low, style = plot.style_circles)
plot(short_alert_high, style = plot.style_circles)
sell = ta.crossunder(close, low) or SqTime //// or SqTime if for intraday exit
cover = ta.crossover(close,high) or SqTime //// or SqTime if for intraday exit
plotshape(buy_condition, style = shape.triangleup, location = location.belowbar, color = color.green, text = "BUY")
plotshape(short_condition, style = shape.triangledown, location = location.abovebar, color = color.red, text = "SHORT")
long_price = ta.valuewhen(buy_condition, (buy_alert_high + 0.01),0 )
longstop = buy_alert_low - 0.01
longtgt = basis
short_price = ta.valuewhen(short_condition,short_alert_low - 0.01,0) ////short_alert_low - (0.01 * 100 * syminfo.mintick) //// ta.valuewhen(short_condition,short_alert_low - 0.01,0)
shortstop = short_alert_high + 0.01
shorttgt = basis
strategy.entry("long",direction = strategy.long, when = buy_condition, limit = long_price, comment ="BUY")
strategy.close("long", when = sell, comment = "SELL")
strategy.exit("long", from_entry = "long", stop = longstop, limit = longtgt, comment = "TG/SL_EXIT")
strategy.entry("short",direction = strategy.short, when = short_condition,limit = short_price, comment ="SHORT")
strategy.close("short", when = cover, comment = "COVER")
strategy.exit("short", from_entry = "short", stop = shortstop, limit = shorttgt, comment = "TG/SL_EXIT")
plot(strategy.position_size > 0 ? longstop : na, style = plot.style_linebr, color = color.red)
plot(strategy.position_size > 0 ? longtgt : na, style = plot.style_linebr, color = color.green)
plot(strategy.position_size < 0 ? shortstop : na, style = plot.style_linebr, color = color.red)
plot(strategy.position_size < 0 ? shorttgt : na, style = plot.style_linebr, color = color.green)

draw line and color the area above in indicator in Trading View with Pine Script

I want to draw a horizontal line at fixed value 30.000 and color the area above in light green in the DMI Indicator. How is this possible?
Thanks
//#version=5
indicator(title="Directional Movement Index", shorttitle="DMI", format=format.price, precision=4, timeframe="", timeframe_gaps=true)
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)
plot(adx, color=#F50057, title="ADX")
plot(plus, color=#2962FF, title="+DI")
plot(minus, color=#FF6D00, title="-DI")
You can use the hline and fill functions
https://www.tradingview.com/pine-script-reference/v5/#fun_fill
https://www.tradingview.com/pine-script-reference/v5/#fun_hline
hline(30, title = "30 Line", color=color.blue, linestyle=hline.style_solid, linewidth=2)
fill(30, 100, color = color.new(color.green, 90))

Code not plotting - Function should be called on each calculation for consistency. It is recommended to extract the call from this scope"

I am getting this as an orange error - not sure what I have done wrong or whether this error is the reason that the code doesn't plot. I am brand new to Pine-script and any assistance would be invaluable. Many thanks in advance Alastair
//#version=5
indicator("PCY TEST4")
//Get User Inputs
fast_length = input(title="Fast Length", defval=12)
slow_length = input(title="Slow Length", defval=26)
src = input(title="Source", defval=close)
signal_length = input.int(title="Signal Smoothing", minval = 1, maxval = 50, defval = 9)
sma_source = input.string(title="Oscillator MA Type", defval="EMA", options=["SMA", "EMA"])
sma_signal = input.string(title="Signal Line MA Type", defval="EMA", options=["SMA", "EMA"])
//Variables
a = 0.33
PCY = 0.0
PCYi = 0.0
// Calculating
fast_ma = sma_source == "SMA" ? ta.sma(src, fast_length) : ta.ema(src, fast_length)
slow_ma = sma_source == "SMA" ? ta.sma(src, slow_length) : ta.ema(src, slow_length)
macd = fast_ma - slow_ma
minMacd=0.0
for i = 0 to (signal_length[1])
minMacd := ta.min(macd)
maxMacd=0.0
for i = 0 to (signal_length[1])
maxMacd := ta.max(macd)
//maxMacd = ta.min(macd)
//minMacd = ta.max(macd)
//signal = sma_signal == "SMA" ? ta.sma(macd, signal_length) : ta.ema(macd, signal_length)
//hist = macd - signal
delta = maxMacd-(fast_ma - slow_ma)/(maxMacd -minMacd)
for i = 0 to (signal_length)
PCYi := a*((delta - PCYi[1])+PCYi[1])
PCYi
//Plotting
plot(PCYi)
I think it's because you're calculating the min/max in a for loop
Those functions should (not mandatory but strongly recommended) be calculated at every candle instead
for i = 0 to (signal_length[1])
minMacd := ta.min(macd)
maxMacd=0.0
for i = 0 to (signal_length[1])
maxMacd := ta.max(macd)
If you want to calculate the min/max over a X period of time, maybe use the ta.highest/ta.lowest functions instead :)
And of course, those 2 should be called at every candle (i.e. not in a if, for,... statement)

Max Drawdown in my Table is wrong, not same as in Overview (Tradingview)

Can you help me fix Drawdown in this table ? Is not the same as in Overview (Tradingview)
It shows a few percent difference and cannot figure a solution.
To measure an order’s drawdown, we take the difference between the entry price and worst price. Then multiply with the order’s size and increase the outcome with commission costs.
That price difference is for long orders the distance between the entry price and lowest price while the order was open. For short orders, it’s the distance between the entry price and the highest price during the order.
var balance = strategy.initial_capital
var totalTrades = strategy.closedtrades
var totalWins = strategy.wintrades
var totalLosses = strategy.losstrades
var maxDrawdown = 0.0
var maxBalance = 0.0
var drawdown = 0.0
var winsInRow = 0
var maxWinsInRow = 0
var lossesInRow = 0
var maxLossesInRow = 0
if strategy.wintrades > strategy.wintrades[1]
balance := strategy.initial_capital + strategy.netprofit
// totalWins := totalWins + 1 < not necessary as we're just using strategy.wintrades now
if balance > maxBalance
maxBalance := balance
winsInRow := winsInRow + 1
if winsInRow > maxWinsInRow
maxWinsInRow := winsInRow
lossesInRow := 0 // reset loss counter as we've just taken a win
if strategy.losstrades > strategy.losstrades[1]
balance := strategy.initial_capital + strategy.netprofit
// totalLosses := totalLosses same as above
drawdown := (maxBalance - balance) / maxBalance // I've changed this, but left your original here > (balance / maxBalance) - 1
if drawdown > maxDrawdown // drawdown will now hold, as a decimal, the max % drop from maxBalance
maxDrawdown := drawdown
lossesInRow := lossesInRow + 1
if lossesInRow > maxLossesInRow
maxLossesInRow := lossesInRow
winsInRow := 0 // reset the win counter as we've just taken a loss
var table testTable = table.new(position.bottom_right, 2, 4 , border_width=1, border_color=color.white, frame_color=color.white, frame_width=1)
fillCell(table, column, row, title, value, bgcolor, txtcolor) =>
cellText = title + "\n" + value
table.cell(table, column, row, cellText, bgcolor=bgcolor, text_color=txtcolor)
var bgcolor = color.new(color.blue,50)
green = color.new(color.green,50)
red = color.new(color.red,50)
if barstate.islastconfirmedhistory
dollarReturn = strategy.netprofit
fillCell(testTable, 0, 0, "Total Trades:", str.tostring(strategy.closedtrades), bgcolor, color.white)
fillCell(testTable, 1, 0, "Win Rate:", str.tostring(math.round((strategy.wintrades/strategy.closedtrades)*100,2))+"%", strategy.wintrades/strategy.closedtrades >= 0.5 ? green : red, color.white)
fillCell(testTable, 0, 1, "Starting:", "$" + str.tostring(strategy.initial_capital), bgcolor, color.white)
fillCell(testTable, 1, 1, "Ending:", "$" + str.tostring(math.round(balance, 2)),strategy.netprofit > 0 ? green :red, color.white)
fillCell(testTable, 0, 3, "Wins In Row", str.tostring(maxWinsInRow), maxWinsInRow > maxLossesInRow ? green : red , color.white)
fillCell(testTable, 1, 3, "Losses In Row", str.tostring(maxLossesInRow), maxWinsInRow > maxLossesInRow ? green : red, color.white)
fillCell(testTable, 1, 2, "Max Drawdown", str.tostring(math.round(maxDrawdown * 100, 2))+"%", strategy.netprofit > maxDrawdown ? green : red, color.white)
fillCell(testTable, 0, 2, "Net Profit", str.tostring(math.round(strategy.netprofit/strategy.initial_capital*100,2))+"%", strategy.netprofit/strategy.initial_capital *100 > 0 ? green : red, color.white)```

PineScript - zigzag trend change counter

I've made an indicator that is similiar to zigzag. I want to write a formula that will count number of up trends or number of trend changes (from up to down and from down to up). I have problem with it, because my variable is still setting to 0. Could you help me to correct it?
//#version=3
study("ZigZag Poker", overlay=true)
//INPUTS
trend = 0
trend := na(trend[1]) ? 1 : trend[1] //Beggining trend set to up
LL = 0.0
LL := na(LL[1]) ? low : LL[1] //LastLow
HH = 0.0
HH := na(HH[1]) ? high : HH[1] //LastHigh
LO = 0.0
LO := na(LO[1]) ? open : LO[1] //LastOpen
LC = 0.0
LC := na(LC[1]) ? close : LC[1] //LastClose
LOLO = 0.0
LOLO := na(LOLO[1]) ? low : LOLO[1] //LowestLow
HIHI = 0.0
HIHI := na(HIHI[1]) ? high : HIHI[1] //HighestHigh
zigzag = na
kolor = 0 //variable that counts number of trend changes
imp = input(true, "Alt imp")
kolor := imp == true ? 2 : 0
if (trend > 0) // trend is up, look for new swing low
if close >= min(LO, LC)
LC := close
LL := low
LO := open
LOLO := low
HIHI := high
else
zigzag := HIHI
trend := -1
HH := high
HIHI := high > HIHI ? high : HIHI
LC := close
LL := low
LO := open
LOLO := low
kolor := kolor[1] + 1
else // trend is down, look for new swing high
if close <= max(LO, LC)
HH := high
HIHI := high
LC := close
LL := low
LO := open
LOLO := low < LOLO ? low : LOLO
else
zigzag := LOLO
trend := 1
HH := high
LC := close
LL := low
LO := open
kolor: = kolor[1] + 1
plot(kolor)
plot(zigzag, color = trend < 0 ? blue : orange, linewidth=2, offset=-1)
I know it's too late to help the OP, but the error is in the line
kolor := imp == true ? 2 : 0, that always sets the value of kolor to 2 or 0, for all the candles that are in the current trend.
What is missing is copying the last kolor's value on every loop, so kolor[1] can have a valid counter.
Replacing that line with kolor := na(kolor[1])? 0: kolor[1] will do it.