CommonMarkup
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © foosmoo

//@version=5

// @description Provides functions for chart markup, such as indicating recession bands.
library("CommonMarkup")

markRecessionBands(string title, int start, int end, float y) =>
    if (time >= start and time <= end)
        var line0a = line.new(start, 0, start, 0, xloc=xloc.bar_time, color = color.new(color.gray, 35), width = 2, extend = extend.both, style=line.style_dotted)           
        var line0b = line.new(end, 0, end, 0, xloc=xloc.bar_time, color = color.new(color.gray, 35), width = 2, extend = extend.both, style=line.style_dotted)
        var l0 = label.new(end, y, xloc = xloc.bar_time, text = title, textalign = text.align_left, size=size.small, color = color.orange, style = label.style_label_left, tooltip = title)

// @function Mark vertical bands and show recession band labels if argument showBands is true. Example "markRecessionBands(bar_index[0],3.0"
// @param showBands - show vertical recession bands when true. Functionally equiv to no op when false
// @param twoQrtsOfNegativeGDPIsRecession - if true, then periods with two consecutive quarters of negative GDP is considered a recession. Defaut is false.  
// @param labelY - y-axis value for label positioning
// @return true - always answers the value of showBands
export markRecessionBands(bool showBands, bool twoQrtsOfNegativeGDPIsRecession, float labelY) =>  

    if showBands

        // 2001 recession band
        var r0s = timestamp("UTC", 2001, 1, 1, 00, 00, 00) 
        var r0e = timestamp("UTC", 2001, 6, 30, 23, 59, 59)
        if (time >= r0s and time <= r0e)
            markRecessionBands("2001", r0s, r0e, labelY)

        // 2009 recession band
        var r1s = timestamp("UTC", 2008, 1, 1, 00, 00, 00) 
        var r1e = timestamp("UTC", 2009, 6, 30, 23, 59, 59) 
        if (time >= r1s and time <= r1e)
            markRecessionBands("2009", r1s, r1e, labelY)

        // 2020 recession band. -5.1 Q1, -31.2, Q2
        var r2s = timestamp("UTC", 2020, 1, 1, 00, 00, 00) 
        var r2e = timestamp("UTC", 2020, 6, 30, 23, 59, 59) 
        if (time >= r2s and time <= r2e)
            markRecessionBands("2020", r2s, r2e, labelY)
        
        // 2022 recession band. -1.6 Q1, -0.9 Q2
        var r3s = timestamp("UTC", 2022, 1, 1, 00, 00, 00) 
        var r3e = timestamp("UCT", 2022, 6, 30, 23, 59, 59) 
        if (twoQrtsOfNegativeGDPIsRecession and time >= r3s and time <= r3e)
            markRecessionBands("2022", r3s, r3e, labelY)
    
    showBands
