Search code examples
pine-scriptpine-script-v5

Pinescript compare months


How do I compare months in pine script? As an example using a monthly chart I want to know if the current bar is for January etc, currently I can do this with daily bars using dayofweek however there is no equivalent monthofyear or similar.

So far I have been trying to use the following code to see if I can find a way to use the output of month() to identify which month the bar is in however I am not succeeding so far.

if barstate.islast
    x = bar_index
    y = close[0]
    txt = str.tostring(month(time[0]))
    label.new(x + 10, y, txt)

The end goal of this indicator is to identify which months on average have positive returns or negative returns and display that information through a label.


Solution

  • You are correct to use month() but, if you are uing this on Forex pairs, you will have issues when the current day's session starts on the previous calendar day.

    For those cases, there is another built-in variable called time_tradingday.

    time_tradingday

    The beginning time of the trading day the current bar belongs to, in UNIX format (the number of milliseconds that have elapsed since 00:00:00 UTC, 1 January 1970).

    REMARKS
    The variable is useful for overnight sessions, where the current day's session can start on the previous calendar day (e.g., on EURUSD the Monday session will start on Sunday, 17:00). Unlike time, which would return the timestamp for Sunday at 17:00 for the Monday daily bar, time_tradingday will return the timestamp for Monday, 00:00.

    When used on timeframes higher than 1D, time_tradingday returns the trading day of the last day inside the bar (e.g. on 1W, it will return the last trading day of the week).

    Here is a test code for you. The first part is your code without the lastbar check and the second part is the same code but using time_tradingday instead.

    //@version=5
    indicator("My script", overlay=true, max_labels_count=100)
    
    m1 = month(time[0])
    txt = str.tostring(m1)
    label.new(bar_index, high, txt)
    
    m2 = month(time_tradingday)
    txt2 = str.tostring(m2)
    label.new(bar_index, low, txt2, yloc=yloc.belowbar, style=label.style_label_up, color=color.green, textcolor=color.white)
    
    is_not_equal = (m1 != m2)
    bgcolor(is_not_equal ? color.new(color.red, 85) : na)
    

    The blue labels above the bars are your original code and the green labels below the bar are the new output. Red background is where those two values are different.

    EURUSD 1-Month timeframe:

    enter image description here