pine-scriptpine-script-v5

Streaks/runs in pine


I'm trying to code it so that if the close is greater than the close yesterday, that counts as a streak of 1. If the next close is > yesterday then the streak continues on as 2 etc etc. If the close is lower than yesterday however, the streak starts at -1, then if the close is lower than the close yesterday again, its now -2 etc etc If the close is the same as the close yesterday the streak is 0

These are my workings out so far, but i can't seem to get it to carry on the streak. eg for the up streak it just gets stuck at 2.

var int streak = 0 

for i = 0 to 0
    if close[i] > open[i] 
        streak := 1
    if close[i] < open[i]
        streak := -1 
    if streak[1] > 0 
        streak +=1

Any help would be great, Thanks


Solution

  • you must initialize the first candle on the chart

    var int streak = 0
    
    if barstate.isfirst
        if close > open
            streak :=  1
        if close < open
            streak := -1
    

    Then, with a switch, you can make a counter according to the previous state of var streak

    switch
        streak[1] >=  1 and close > close[1] => streak +=  1
        streak[1] <= -1 and close < close[1] => streak += -1
        streak[1] <= -1 and close > close[1] => streak :=  1
        streak[1] >=  1 and close < close[1] => streak := -1