How do I get a signal only on the last candle on the chart - pine-script-v5

Newbie on PineScript on Tradingview, so please excuse if this is silly.
I am trying out the following script on Tradingview,
//#version=5
strategy("My Strategy", overlay=true)
shortSMA = ta.sma(close, 10)
longSMA = ta.sma(close, 30)
rsi = ta.rsi(close, 14)
longCondition = ta.crossover(shortSMA, longSMA)
if (longCondition)
strategy.entry("long", strategy.long, 100, when = rsi > 50)
When I save and add the script to my chart, it gives me a long signal only for the first instance where the condition was met.
So when I add pyramiding to the script,
//#version=5
strategy("My Strategy", overlay=true, pyramiding=250)
shortSMA = ta.sma(close, 10)
longSMA = ta.sma(close, 30)
rsi = ta.rsi(close, 14)
longCondition = ta.crossover(shortSMA, longSMA)
if (longCondition)
strategy.entry("long", strategy.long, 100, when = rsi > 50)
I get a signal for all the instances where the condition is met.
What I am trying to achieve is get a signal only on the last candle (if the condition is met, of course), the previous ones can just go. Is there any way to do this?

Related

Counting bars since highest high of last 50 bars in Pine Script

i am trying to count number o fbars since highest high of last 50 bars in pine script. But it is giving me error that "Study error, too many candles referenced in history". Can anyone help
//#version=5
indicator("Trendline" , overlay = true)
h1=ta.highest(high, 50)
l1=ta.lowest(low, 50)
bari=ta.barssince(h1)
bari2=ta.barssince(l1)
if(barstate.islast)
highline=line.new(x1=bari, y1=high[h1], x2=bar_index, y2=high)
line.set_color(highline, color.red)
line.set_extend(highline, extend.none)
line.set_width(highline, 2)
line.delete(highline[1])``
at x2, it should be the last candle (bar_index). so x1 must be the last candle minus 50 periods
y1 and y2, must be the value of highest high (h1)
Something like that:
//#version=5
indicator("Trendline" , overlay = true)
h1 = ta.highest(high, 50)
if(barstate.islast)
highline=line.new(x1=bar_index - 50, y1=h1, x2=bar_index, y2=h1)
line.set_color(highline, color.red)
line.set_extend(highline, extend.none)
line.set_width(highline, 2)
line.delete(highline[1])

I want to write a pine code strategy but everytime I get a malfunction that says 'could not find indicator 'sma'

i want to create a strategy with pine code that gives me a buy signal everytime when the price of the stock is above the SMA200 and the MACD is below 0 and when the MACD level line crosses the MACD signal line up. Furthermore I want it to give me a short signal everytime the price of the stock is below the SMA200 and when the MACD is above 0 and when the MACD level line crosses the MACD signal line down.
Here is my code
//#version=5
strategy("MACD Strategy", overlay=true)
// EMA200
ema200 = sma(close, 200)
// MACD
macdLine = sma(close, 12) - sma(close, 26)
macdSignal = sma(macdLine, 9)
// MACD Level crosses MACD Signal Line up
macdCrossUp = crossover(macdLine, macdSignal)
// MACD Level crosses MACD Signal Line down
macdCrossDown = crossunder(macdLine, macdSignal)
// MACD is above 0
macdAboveZero = macdLine > 0
// MACD is below 0
macdBelowZero = macdLine < 0
// Buy signal
buySignal = close > ema200 and macdCrossUp and macdBelowZero
// Short signal
shortSignal = close < ema200 and macdCrossDown and macdAboveZero
// Plot signals
plot(macdCrossUp ? 1 : na, "MACD Cross Up", color=color.green)
plot(macdCrossDown ? 1 : na, "MACD Cross Down", color=color.red)
// Buy and Short strategy
if (buySignal)
strategy.entry("Buy", buySignal, when = buy)
I expected it to show me Buy and Short signals on my TradingView chart. Unfortunately this did not happen as it can not find the indicator called 'sma'.
But it does not work and says everytime that it could not find the function 'sma'
I would really appreciate it if somebody could help me. :)
And sorry for my bad english.
If you need further information, just tell me.
Thank you very much!
Functions have been moved to dedicated namespaces in v5.
So for functions like, sma, crossover, you should use the ta namespace.
macdSignal = ta.sma(macdLine, 9)
macdCrossUp = ta.crossover(macdLine, macdSignal)
Of course you need to fix that in other places too.

fibUp = fibonacci(high,"up")

```// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © r
//#version=5
// This script triggers a trade when RSI is overbought/oversold and there is a convergence with MACD
// It also implements Tom Demark signals and only triggers a trade when all conditions are met
// The trade is only triggered when near a Fibonacci resistance or support line
// Define constants
rsiLength = 14
overbought = 70
oversold = 30
macdLength = 12
signalLength = 26
// Include libraries
study(title="Trade Trigger", overlay=true)
// Get current symbol and time frame
symbol = syminfo.ticker
timeframe = syminfo.timeframe
// Calculate RSI
rsi = rsi(close, rsiLength)
// Calculate MACD and signal line
macd = macd(close, macdLength, signalLength)
signal = macd[1]
// Check if RSI is overbought/oversold and there is a convergence with MACD
if (rsi > overbought and macd > signal) or (rsi < oversold and macd < signal)
// Calculate Fibonacci levels
fibUp = fibonacci(high,"up")
if (close > high) or (close < low)
fibDown = fibonacci(low, "down")
// Check if price is near a Fibonacci resistance or support line
if (close > high) or (close < low)
// Trigger trade
trade()
endif
endif```
is fibUp = fibonacci(high,"up") a valid statement?
In PineScript I get the compilation error: mismatched input 'fibUp' expecting 'end of line without line continuation'.
I tried removing indents and spaces without any improvement, error still occurs.
in your code you must change :
if (rsi > overbought and macd > signal) or (rsi < oversold and macd < signal)
// Calculate Fibonacci levels
fibUp = fibonacci(high,"up")
if (close > high) or (close < low)
by this code : the idea is to respect to ´if’ block with 4 spaces after (only 4)
if (rsi > overbought and macd > signal) or (rsi < oversold and macd < signal)
// Calculate Fibonacci levels
fibUp = fibonacci(high,"up")
if (close > high) or (close < low)
.. and so on ..

Pinescript V5 Multi Timeframe Strategy vs Indicator

I have an indicator working the way I want, but I'm trying to convert it to a strategy for backtesting.
I have bollinger bands plotted on the 15 minute timeframe, and on the one hour. This works in the indicator, but it does not work properly in the strategy.
The error I get is:
The strategy function does not have an argument with the name timeframe or timeframe_gaps
I tried removing that in the strategy, but now the 1 hr bollinger bands are incorrect:
strategy(shorttitle="BB Multi", title="Bollinger Bands Strategy", overlay=true)
Here is the full code of the strategy:
//#version=5
strategy(shorttitle="BB Multi", title="Bollinger Bands Strategy", overlay=true)
entryPrice = close
// Set input parameters
length = input.int(20, minval=1)
mult = input.float(2.5, minval=0.001, maxval=50)
offset = input.int(0, "Offset", minval = -500, maxval = 500)
// Calculate Bollinger Bands using 15 minute data
src = close
middle = ta.sma(src, length)
dev = mult * ta.stdev(src, length)
upper = middle + dev
lower = middle - dev
// Calculate Bollinger Bands using 1 hour data
src1h = request.security(syminfo.tickerid, '60', close)
middle1h = ta.sma(src1h, length)
dev1h = mult * ta.stdev(src1h, length)
upper1h = middle1h + dev1h
lower1h = middle1h - dev1h
// Enter long position when 15 minute chart Bollinger Band is touched and 1hr band is touched (or previous 1 hr candle)
longCondition = ta.crossover(close, lower) and (ta.crossover(low, lower1h) or ta.crossover(low[1], lower1h))
if longCondition
strategy.entry("BB Long", strategy.long)
entryPrice = close
// Enter short position when 15 minute chart Bollinger Band is touched and 1hr band is touched (or previous 1 hr candle)
shortCondition = ta.crossunder(close, upper) and (ta.crossover(high, upper1h) or ta.crossover(high[1], upper1h))
if shortCondition
strategy.entry("BB Short", strategy.short)
entryPrice = close
// Calculate profit target
profitTarget = 1 + 0.1 // 10% profit target
// Exit long position when profit target is reached
exitLongCondition = close > entryPrice * profitTarget
if exitLongCondition
strategy.close("BB Long")
// Exit short position when profit target is reached
exitShortCondition = close < entryPrice / profitTarget
if exitShortCondition
strategy.close("BB Short")
// Plot Bollinger Bands
plot(upper, color=color.red, linewidth=2)
plot(lower, color=color.red, linewidth=2)
plot(upper1h, color=color.blue, linewidth=2)
plot(lower1h, color=color.blue, linewidth=2)
Here is the full code of the indicator (Which plots the bands correctly)
// Function to plot Bollinger Bands on a 1 hour timeframe
// Define function and set input parameters
//#version=5
indicator(shorttitle="BB Multi", title="Bollinger Bands Strategy", overlay=true, timeframe="", timeframe_gaps=true)
//study("Bollinger Bands - 1 Hour", overlay=true)
length = input.int(20, minval=1)
src = input(close, title="Source")
mult = input.float(2.5, minval=0.001, maxval=50, title="StdDev")
middle = ta.sma(src, length)
dev = mult * ta.stdev(src, length)
upper = middle + dev
lower = middle - dev
offset = input.int(0, "Offset", minval = -500, maxval = 500)
// Calculate Bollinger Bands using 1 hour data
src1h = request.security(syminfo.tickerid, '60', close)
middle1h = ta.sma(src1h, length)
dev1h = mult * ta.stdev(src1h, length)
upper1h = middle1h + dev1h
lower1h = middle1h - dev1h
// Plot Bollinger Bands
plot(upper, color=color.red, linewidth=2)
plot(lower, color=color.red, linewidth=2)
plot(upper1h, color=color.blue, linewidth=2)
plot(lower1h, color=color.blue, linewidth=2)
How can I use multi timeframe correctly in a strategy? The tutorials I found all use the indicator function, but I really need to backtest this!
Thanks!
I tried removing timeframe and timeframe_gaps from the strategy function, but the result is that the 1 hour Bollinger bands are incorrect.
Try this:
Change
src1h = request.security(syminfo.tickerid, '60', close)
To
src1h = request.security(syminfo.tickerid, '60', close, lookahead=barmerge.lookahead_on, gaps=barmerge.gaps_on)
I haven't tested this but have experienced something vaguely similar before, let us know how it goes.

Use candle stick count rather than resolution - Pine Script

Looking for a simple way to set my input for a cumulative volume range indicator to a specified amount of CANDLES rather than selecting a RESOLUTION to look back at.
is_new_day = change(time(cTimeFrame)) != 0 ? 1 : 0
cnt_new_day = barssince(is_new_day)
// Accumulation
cvol = 0.0
for i = 0 to cnt_new_day
cvol := cvol + volume[i]
plot(cvol, "Cumulative Volume", style=plot.style_columns, color= color.yellow)
You need to accumulate volume in one variable and reset it every N bar
//#version=5
indicator("My Script")
length = input.int(1, "Length", minval=1)
cvol = volume
cvol += bar_index % length == 0 ? 0 : cvol[1]
plot(cvol, "Cumulative Volume", style=plot.style_columns, color= color.yellow)