Jonathan S
Jonathan S

Reputation: 39

Pine script: Switch trendline based on if statement

How do I set my trendline color and plot based on an if statement i.e. if stock data is > 1 year then use trendline 1 else use trendline method 2:

trend_1 = sma(close, 15)
trend_2 = sma(close, 30)

bearish = true

for i = 0 to trendConfirmationLength - 1
    bearish := bearish and (close[i] < trend[i])

bullish = not bearish

// Set the color of the plot based on whether we are bullish (green) or not (red)
c = bullish ? color.green : color.red

// Plot the trend line
trend = 
if (len(close) > 252)
   trend_1
if (len(close) < 252)
   trend_2

trend_plot = plot(trend, title='Trend', color = c)

Thanks

Upvotes: 0

Views: 339

Answers (1)

rumpypumpydumpy
rumpypumpydumpy

Reputation: 3813

trend_1 = sma(close, 15)
trend_2 = sma(close, 30)

float trend = na

if bar_index >= 252
    trend := trend_1
else
    trend := trend_2

bool foundBearish = false
bool foundBullish = false

for i = 0 to trendConfirmationLength - 1
    if close[i] < trend[i]
        foundBearish := true
    else if close[i] > trend[i]
        foundBullish := true

bullish = foundBullish and not foundBearish
bearish = foundBearish and not foundBullish
neutral = not bullish and not bearish

color c = na
if bullish
    c := color.green
else if bearish
    c := color.red
else if neutral
    c := color.blue

trend_plot = plot(trend, title='Trend', color = c)

If all closes within trendConfirmationLength are below trend then foundBearish will be true and foundBullish will be false (and vice versa). If both foundBearsh and foundBullish are true, it means we had closes both above and below trend.

Alternatively you could do this to keep the trend color until a new trend is formed rather than show a neutral color.

color c = na
if bullish
    c := color.green
else if bearish
    c := color.red

trend_plot = plot(trend, title='Trend', color = fixnan(c))

Upvotes: 1

Related Questions