Time Window Analysis in Pine Script

This lesson demonstrates how to analyze price action within a specific window of time. It's a simple script, but it can easily be adapted to make a backtesting date filter etc.

Check out my other free lessons!

Source Code

// This Pine Script™ code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © ZenAndTheArtOfTrading
// @version=5
indicator("TOTAL PERIOD RETURN")

// Get user input
StartDate = input.time(timestamp("1 July 2023"))
EndDate = input.time(timestamp("1 Jan 2024"))

// Total return variables
var float startPrice = na
var float endPrice = na
var int startIndex = na

// Other variables
var float lowestPrice = na
var float highestPrice = na

// Detect first bar that prints on or after start date
if time >= StartDate
    if na(startPrice)
        startPrice := open
        startIndex := bar_index
        line.new(bar_index, open, bar_index, close, extend=extend.both, color=color.white)
    else
        if na(lowestPrice) or close < lowestPrice
            lowestPrice := close
        if na(highestPrice) or close > highestPrice
            highestPrice := close

// Converting the difference of two values into percentage
ToPercent(_num1, _num2) => ((_num1 - _num2) / _num2) * 100

// Detect final bar on our chart / time window
if (barstate.islastconfirmedhistory or time >= EndDate) and na(endPrice)
    endPrice := close

    // Draw price lines
    line.new(startIndex, highestPrice, bar_index, highestPrice, color=color.black)
    line.new(startIndex, lowestPrice, bar_index, lowestPrice, color=color.black)
    line.new(startIndex, endPrice, bar_index, endPrice, color=color.red)
    line.new(startIndex, startPrice, bar_index, startPrice, color=color.green)
    line.new(bar_index, open, bar_index, close, extend=extend.both, color=color.white)

    // Prepare text label
    string info = syminfo.ticker + ":\n\n"
    float totalReturn = ToPercent(endPrice, startPrice)
    float highestReturn = ToPercent(highestPrice, startPrice)
    float lowestReturn = ToPercent(lowestPrice, startPrice)
    info := info + "Return: " + (totalReturn > 0 ? "+" : "") + str.tostring(totalReturn, format.percent) + "\n\n"
    info := info + "MFE: " + (highestReturn > 0 ? "+" : "") + str.tostring(highestReturn, format.percent) + "\n"
    info := info + "MAE: " + (lowestReturn > 0 ? "+" : "") + str.tostring(lowestReturn, format.percent)
    label.new(bar_index + 1, high, info, xloc.bar_index, yloc.price, color.black, label.style_label_left, color.white, size.normal, text.align_right)

// Plot closing price
plot(not na(startPrice) and na(endPrice[1]) ? close : na, color=color.blue)