Search code examples
pine-scriptpine-script-v5tradingview-apipine-script-v4

TradingView PineScript has unexpected return value for cross function


I am setting up an alertcondition for when the current price of an asset crosses either up or down the previous week's high, but my alert is firing when it should not be.

I have attached the relevant snippets of code. I would expect that the cross function would only return true if the price of close is equal to the price of weeklyh_open, and false every other time.

[weeklyh_time, weeklyh_open] = request.security(syminfo.tickerid, 'W', [time[1], high[1]], lookahead=barmerge.lookahead_on)

alertcondition(ta.cross(close, weeklyh_open), title='Weekly High', message='{ "content": "Symbol = {{ticker}} {{interval}} Crossing Weekly High" }')

I added the following line for debugging purposes and I repro'ed the unexpected behavior.

label.new(bar_index, high, str.tostring(close) + ' ' + str.tostring(weeklyh_open) + '= ' + str.tostring(ta.cross(close, weeklyh_open)), textcolor=color.white)

Sample outputs:

output

For the Bitcoin 4H chart, the candle that opened on Monday 2/23 at 00:00 UTC closed with a value of 24416.9 and had a high of 24471.8. The previous week's high is 25296.1 so how can the ta.cross function return true for this scenario?

Does anyone have any advice for what I could do to get this figured out?


Solution

  • Nothing is unexpected here.

    The way ta.cross() works is, it compares the state on the previous bar with the state on the current bar.

    You can write it as:

    f_cross(exp1, exp2) => ((exp1[1] < exp2[1]) and (exp1 >= exp2)) or ((exp1[1] > exp2[1]) and (exp1 <= exp2))
    

    Instead of plotting the weekly high manually, you should have plotted weeklyh_open with your script and then maybe it would have been more clear to you. At 00:00 UTC, the weekly value you get from the security() function changes. Therefore, when ta.cross() is called, it uses two different weekly values.

    I believe what you want is simply:

    ((open < weeklyh_open) and (close >= weeklyh_open)) or ((open > weeklyh_open) and (close <= weeklyh_open))
    

    enter image description here