Library · Pine Script v5 · Library

TimeFrameUtils

by Yavuz365

TimeFrameUtils is a Pine Script utility library providing functions for multi-timeframe data analysis.

View on GitHub

GitHub stars1on the repository
Pine versionv5runs as is
Lines of code212
Settings0inputs
LicenceMIT
Last update9 months ago19 Jan 2026

Add It to Your TradingView Chart

  1. 1Copy the scriptPress Copy script above, or the copy button on the code below.
  2. 2Open the Pine EditorOpen a TradingView chart and choose Pine Editor at the bottom of the screen.
  3. 3Paste over the templateCreate a new library, select all of the template text and paste. Press Save and give it a name.
  4. 4Publish or import itA library draws nothing. Publish it from the editor, then import its functions in your own scripts.

Source Code

212 lines of Pine Script v5 from libraries/TimeFrameUtils.pine, published under MIT. Keep the author's credit and licence lines when you reuse it.

TimeFrameUtils.pine
// This Pine Script™ code is subject to the terms of the Mozilla Public License 2.0
// © Yavuz365
// TimeFrameUtils Library - Multi-Timeframe Utility Functions with Anti-Repaint Protection

//@version=5
// @description Multi-Timeframe utility functions for TradingView indicators.
// Provides optimized MTF data fetching, timeframe conversion, and signal aggregation.
// OPTIMIZED: Single request.security() calls, repaint protection with barstate.isconfirmed
library("TimeFrameUtils", overlay=true)

// ============================================================================
// TIMEFRAME CONVERSION UTILITIES
// ============================================================================

// @function Converts timeframe string to minutes
// @param tf Timeframe string (e.g., "15", "60", "D", "W")
// @returns Number of minutes in the timeframe
export tfToMinutes(simple string tf) =>
    switch tf
        "1" => 1
        "3" => 3
        "5" => 5
        "15" => 15
        "30" => 30
        "45" => 45
        "60" => 60
        "120" => 120
        "180" => 180
        "240" => 240
        "D" => 1440
        "W" => 10080
        "M" => 43200
        => 60  // Default to 1 hour

// @function Checks if target timeframe is higher than current
// @param targetTf Target timeframe to compare
// @returns True if target is higher timeframe
export isHigherTimeframe(simple string targetTf) =>
    tfToMinutes(targetTf) > tfToMinutes(timeframe.period)

// ============================================================================
// MTF DATA FETCHING (Optimized for TradingView limits - ~40 request.* calls max)
// NOTE: Each request.security() call counts toward TradingView's limit
// Current implementation uses ~15-18 calls with 3 timeframes
// ============================================================================

// @function Gets RSI value from specified timeframe (1 request.security call)
// @param src Source series
// @param length RSI period
// @param tf Target timeframe
// @param confirmOnly If true, only returns value when bar is confirmed (no repaint)
// @returns RSI value from target timeframe
export mtfRSI(series float src, simple int length, simple string tf, simple bool confirmOnly = false) =>
    rsiVal = request.security(syminfo.tickerid, tf, ta.rsi(src, length), lookahead=barmerge.lookahead_off)
    confirmOnly and not barstate.isconfirmed ? na : rsiVal

// @function Gets MACD values from specified timeframe (OPTIMIZED: 1 request.security call instead of 3)
// @param src Source series
// @param fast Fast period
// @param slow Slow period
// @param signal Signal period
// @param tf Target timeframe
// @param confirmOnly If true, only returns value when bar is confirmed (no repaint)
// @returns [macdLine, signalLine, histogram]
export mtfMACD(series float src, simple int fast, simple int slow, simple int signal, simple string tf, simple bool confirmOnly = false) =>
    [macdVal, sigVal, histVal] = request.security(syminfo.tickerid, tf, ta.macd(src, fast, slow, signal), lookahead=barmerge.lookahead_off)
    if confirmOnly and not barstate.isconfirmed
        [na, na, na]
    else
        [macdVal, sigVal, histVal]

// @function Gets Stochastic values from specified timeframe (OPTIMIZED: 1 request.security call)
// @param length Stochastic period
// @param smoothK K smoothing
// @param smoothD D smoothing
// @param tf Target timeframe
// @param confirmOnly If true, only returns value when bar is confirmed (no repaint)
// @returns [K, D]
export mtfStoch(simple int length, simple int smoothK, simple int smoothD, simple string tf, simple bool confirmOnly = false) =>
    k = ta.stoch(close, high, low, length)
    kSmoothed = ta.sma(k, smoothK)
    dSmoothed = ta.sma(kSmoothed, smoothD)
    mtfK = request.security(syminfo.tickerid, tf, kSmoothed, lookahead=barmerge.lookahead_off)
    mtfD = request.security(syminfo.tickerid, tf, dSmoothed, lookahead=barmerge.lookahead_off)
    if confirmOnly and not barstate.isconfirmed
        [na, na]
    else
        [mtfK, mtfD]

// @function Gets EMA from specified timeframe (1 request.security call)
// @param src Source series
// @param length EMA period
// @param tf Target timeframe
// @param confirmOnly If true, only returns value when bar is confirmed (no repaint)
// @returns EMA value
export mtfEMA(series float src, simple int length, simple string tf, simple bool confirmOnly = false) =>
    emaVal = request.security(syminfo.tickerid, tf, ta.ema(src, length), lookahead=barmerge.lookahead_off)
    confirmOnly and not barstate.isconfirmed ? na : emaVal

// @function Gets SMA from specified timeframe (1 request.security call)
// @param src Source series
// @param length SMA period
// @param tf Target timeframe
// @param confirmOnly If true, only returns value when bar is confirmed (no repaint)
// @returns SMA value
export mtfSMA(series float src, simple int length, simple string tf, simple bool confirmOnly = false) =>
    smaVal = request.security(syminfo.tickerid, tf, ta.sma(src, length), lookahead=barmerge.lookahead_off)
    confirmOnly and not barstate.isconfirmed ? na : smaVal

// @function Gets ATR from specified timeframe (1 request.security call)
// @param length ATR period
// @param tf Target timeframe
// @param confirmOnly If true, only returns value when bar is confirmed (no repaint)
// @returns ATR value
export mtfATR(simple int length, simple string tf, simple bool confirmOnly = false) =>
    atrVal = request.security(syminfo.tickerid, tf, ta.atr(length), lookahead=barmerge.lookahead_off)
    confirmOnly and not barstate.isconfirmed ? na : atrVal

// ============================================================================
// SIGNAL GENERATION UTILITIES
// ============================================================================

// @function Standardizes signal to -1 (Sell), 0 (Neutral), 1 (Buy)
// @param bullish Bullish condition
// @param bearish Bearish condition
// @returns Standardized signal (-1, 0, or 1)
export standardSignal(bool bullish, bool bearish) =>
    bullish ? 1 : bearish ? -1 : 0

// @function Calculates confluence score from multiple signals
// @param signals Array of signals (-1, 0, 1)
// @returns Confluence score (sum of signals)
export confluenceScore(array<int> signals) =>
    score = 0
    for sig in signals
        score += sig
    score

// @function Checks if RSI shows divergence (ANTI-REPAINT: uses confirmed bars only)
// @param rsi RSI series
// @param price Price series
// @param lookback Lookback period for comparison
// @returns [bullishDiv, bearishDiv]
export rsiDivergence(series float rsi, series float price, simple int lookback) =>
    // Only compute on confirmed bars to prevent repainting
    if not barstate.isconfirmed
        [false, false]
    else
        // Price makes lower low but RSI makes higher low = Bullish Divergence
        priceLowerLow = price < ta.lowest(price, lookback)[1]
        rsiHigherLow = rsi > ta.lowest(rsi, lookback)[1]
        bullishDiv = priceLowerLow and rsiHigherLow and rsi < 30

        // Price makes higher high but RSI makes lower high = Bearish Divergence
        priceHigherHigh = price > ta.highest(price, lookback)[1]
        rsiLowerHigh = rsi < ta.highest(rsi, lookback)[1]
        bearishDiv = priceHigherHigh and rsiLowerHigh and rsi > 70

        [bullishDiv, bearishDiv]

// @function Checks if MACD shows divergence (ANTI-REPAINT)
// @param macd MACD line series
// @param price Price series
// @param lookback Lookback period
// @returns [bullishDiv, bearishDiv]
export macdDivergence(series float macd, series float price, simple int lookback) =>
    if not barstate.isconfirmed
        [false, false]
    else
        priceLowerLow = price < ta.lowest(price, lookback)[1]
        macdHigherLow = macd > ta.lowest(macd, lookback)[1]
        bullishDiv = priceLowerLow and macdHigherLow

        priceHigherHigh = price > ta.highest(price, lookback)[1]
        macdLowerHigh = macd < ta.highest(macd, lookback)[1]
        bearishDiv = priceHigherHigh and macdLowerHigh

        [bullishDiv, bearishDiv]

// ============================================================================
// TIMEFRAME ARRAY UTILITIES
// ============================================================================

// @function Creates standard MTF array
// @returns Array of common timeframes
export getStandardTimeframes() =>
    tfs = array.new_string()
    array.push(tfs, "15")
    array.push(tfs, "60")
    array.push(tfs, "240")
    array.push(tfs, "D")
    tfs

// @function Gets timeframe display name
// @param tf Timeframe string
// @returns Human-readable timeframe name
export tfDisplayName(simple string tf) =>
    switch tf
        "1" => "1m"
        "3" => "3m"
        "5" => "5m"
        "15" => "15m"
        "30" => "30m"
        "45" => "45m"
        "60" => "1H"
        "120" => "2H"
        "180" => "3H"
        "240" => "4H"
        "D" => "1D"
        "W" => "1W"
        "M" => "1M"
        => tf

Overview

TimeFrameUtils includes helpers to convert timeframe strings into minutes and check whether a given timeframe is higher than the chart's current resolution. The library packages optimized calls to retrieve multi-timeframe indicator data, including RSI, MACD, and Stochastic oscillators, minimizing security request limits. Functions feature an optional confirmed-bar filter alongside non-lookahead security calls to guard against real-time bar repainting. As a library, it produces no direct chart plots or standalone trade signals.

Details

Published by

Yavuz365 on GitHub

Type

Library, Pine Script v5

Draws

Library (no plots)

Markets

Any symbol

Timeframes

Any timeframe

Risk Notes

No repainting, lookahead or stacked entries were found in its code or README. That says nothing about how well it works: test it first.

Third-party code. ForexR did not write, test or endorse this script, and the summary above was generated automatically from its code and README. Indicators describe the past, and a strategy's backtest can look better than live trading, especially when a script repaints. Check it in the Strategy Tester and on a demo account before you rely on it.

Similar Pine Scripts

FunctionLinearRegression

by ricardosantos79
261 stars

This Pine Script v5 library provides functions to calculate and plot linear regression channels using sample point arrays. It evaluates paired X and Y arrays to calculate the regression slope, intercept, fitted values, maximum deviation, minimum deviation, and

Library v5 Trend
Updated 4 years ago · None stated GitHub repository of FunctionLinearRegression

PositionSizing

by iamrichardD
57 stars

This Pine Script v6 library calculates trade position sizes and provides risk management functions for external scripts. It computes position sizes from account equity, percentage risk, and stop-loss distance, and offers dynamic sizing adjustments based on vol

Library v6
Updated 1 year ago · Apache-2.0 GitHub repository of PositionSizing

Chart Patterns

by deepentropy
13 stars

Chart Patterns is a Pine Script v6 library designed to scan for and render technical chart patterns directly on the price chart. It defines custom user-defined types to configure scanning parameters, such as Zigzag pivot offsets, error ratios, flat ratios, and

Library v6 Repaints
Updated 6 months ago · MIT GitHub repository of Chart Patterns

AuthLib

by alboogycOdR
6 stars

AuthLib is a Pine Script utility library providing access control and state management structures for technical indicators. It checks callers against a hardcoded array of authorized TradingView usernames before executing operations. The library exports user-de

Library v5 SMC / ICT / price actionSessions & time
Updated 7 months ago · None stated GitHub repository of AuthLib

WebhookMessageLibrary

by TradersPost
6 stars

WebhookMessageLibrary is a helper library designed to construct structured JSON payload messages for automated trading integrations like TradersPost. It defines custom exported types and constants for trade actions, market sentiments, quantities, limit prices,

Library v5
Updated 1 year ago · None stated GitHub repository of WebhookMessageLibrary

PineDraw

by 345-strategies
5 stars

PineDraw is a Pine Script v6 library that provides object primitives for drawing and updating price levels on the chart. It enables indicators and strategies to maintain lines, boxes, and labels in place by updating existing objects instead of deleting and rec

Library v6 Support & resistance
Updated 2 days ago · MPL-2.0 GitHub repository of PineDraw

More libraries

Trade Your Charts With a Regulated Broker

Compare brokers that connect to TradingView, with spreads, minimum deposits and leverage side by side.

Compare brokers