Building robust trading indicators and strategies often requires accessing historical data from different timeframes. The ‘Day High’ is a fundamental piece of information widely used in various trading methodologies. Accessing this specific data point accurately and efficiently in Pine Script is crucial for developers.
Introduction to Day High in Pine Script
Understanding the Concept of ‘Day High’
The ‘Day High’ refers to the highest price reached by a financial instrument during a single trading day. This is a standard data point available for most assets traded on exchanges, reflecting the peak price within a 24-hour period or a defined trading session (e.g., NYSE session). Unlike the high of the current bar, which changes throughout the bar’s duration, the Day High represents a fixed value for the entire day once the day closes.
Importance of Day High in Trading Strategies
The Day High serves as a significant reference point for traders. It often acts as:
- Resistance Level: Price reaching or failing to break the previous or current day’s high can indicate potential selling pressure.
- Breakout Signal: A move above the previous day’s high is a common signal for potential upward momentum.
- Volatility Measure: The distance between the Day High and Day Low (the daily range) provides insight into the instrument’s volatility.
- Stop Loss/Take Profit Placement: Traders frequently place stops or targets relative to the Day High.
Incorporating the Day High into automated strategies can lead to more informed entry, exit, and risk management decisions.
Why Accessing Day High in Pine Script is Useful
Accessing the Day High allows Pine Script developers to:
- Develop indicators that plot daily resistance levels automatically.
- Create strategies that trigger trades based on breakouts or failures at the Day High.
- Implement backtesting scenarios that test the efficacy of Day High-based strategies.
- Build custom screeners or alerts based on price action relative to the Day High.
Direct access to this data simplifies script logic and improves the potential for creating powerful trading tools.
Methods to Access the Day High in Pine Script
Pine Script provides several ways to access data from other timeframes, with the security() function being the most common and versatile approach for retrieving the Day High.
Using ‘security()’ function to fetch Day High data
The security() function allows a script running on one timeframe (e.g., 15-minute chart) to request data from a different timeframe (e.g., 1-day chart). The syntax is security(symbol, timeframe, expression, lookahead, gaps). To get the Day High, we typically need the timeframe parameter set to 'D' (or timeframe.period when referencing the current chart’s timeframe if it’s daily or higher) and the expression parameter set to high.
The most straightforward way to get the Day High for the current bar’s trading day is:
// Get the 'high' value from the 'D' (Daily) timeframe
float dailyHigh = security(syminfo.tickerid, 'D', high, lookahead=barmerge.lookahead_off, gaps=barmerge.gaps_off)
syminfo.tickerid: Ensures we are requesting data for the current chart’s symbol.'D': Specifies the Daily timeframe.high: The data series we want from the Daily timeframe.lookahead=barmerge.lookahead_off: Prevents future data leakage in historical bars.gaps=barmerge.gaps_off: Fills gaps with the previous value if the requested timeframe bar doesn’t align perfectly with the current chart bar. Forhigh,gaps=barmerge.gaps_offis generally preferred to avoid plotting zero orNaNwhere no daily data point aligns.
Utilizing ‘timeframe.period’ to specify Daily timeframe
While 'D' is a literal string for the daily timeframe, you can also use timeframe.period if your script is already running on a daily or higher timeframe. This isn’t directly used to fetch data from a different timeframe using security, but it’s relevant if you’re simply using the built-in high variable on a daily chart. On a daily chart, the built-in high variable already represents the Day High for that specific daily bar.
If your script is designed to run on any timeframe but needs the Day High, the security(..., 'D', ...) approach is necessary.
Implementing workarounds for real-time Day High Calculation
The security() function, by default, provides the closed value of the Daily bar. During the trading day, the Day High is a running value. The security(..., 'D', high, lookahead=barmerge.lookahead_off) call will give you the Day High of the previous day’s completed bar if the current bar is part of the current day’s session. To get the real-time Day High of the current trading day, you need a different approach.
A common workaround involves using Pine Script’s time functions to identify the start of a new day and then tracking the highest price since that point. The request.security_lower_tf() function can also be used, but managing its nuances can be complex. A simpler, yet effective, method relies on tracking the day’s start using time() and timeframe.isintraday, or dayofmonth changing:
// Check if it's the first bar of the day
var float dailyHighRT = na
bool isNewDay = dayofmonth(time) != dayofmonth(time[1])
// Reset on new day, update with current high otherwise
if isNewDay
dailyHighRT := high
else
dailyHighRT := math.max(dailyHighRT[1], high)
// dailyHighRT now holds the real-time Day High for the current session.
This approach calculates the running high since the start of the current trading day. Note that dayofmonth() is based on the chart’s timezone. For robust solutions across sessions, considering time() with session specification or ta.change(time('D')) might be more appropriate.
Practical Examples and Pine Script Code Snippets
Let’s look at practical applications of accessing the Day High.
Example 1: Plotting the Day High on the Chart
This script fetches and plots the Day High from the completed daily bar using security(). It plots the previous day’s high on the current day’s bars.
//@version=5
indicator("Previous Day High", shorttitle="PrevDHigh", overlay=true)
// Fetch previous day's high using security function
float prevDayHigh = security(syminfo.tickerid, 'D', high[1], lookahead=barmerge.lookahead_off, gaps=barmerge.gaps_off)
// Plot the fetched value
plot(prevDayHigh, title="Previous Day High", color=color.blue, linewidth=2, style=plot.style_stepline)
// Note: high[1] in security fetches the high of the *previous* daily bar.
// If you want the high of the daily bar *corresponding* to the current intraday bar, use high without [1].
// The first method plots a constant line for the day.
// To plot the *real-time* current day's high (running value):
var float currentDayHighRT = na
bool isNewDayRT = timeframe.isintraday and dayofmonth(time) != dayofmonth(time[1])
if isNewDayRT
currentDayHighRT := high
else
currentDayHighRT := math.max(nz(currentDayHighRT[1]), high)
plot(currentDayHighRT, title="Current Day High (RT)", color=color.red, linewidth=1, style=plot.style_stepline)
Example 2: Creating Alerts when Price Breaks Day High
This script demonstrates how to trigger an alert when the price close crosses above the real-time calculated Day High.
//@version=5
indicator("Day High Breakout Alert", shorttitle="DH Alert", overlay=true)
// --- Real-time Day High Calculation ---
var float currentDayHighRT = na
bool isNewDayRT = timeframe.isintraday and dayofmonth(time) != dayofmonth(time[1])
if isNewDayRT
currentDayHighRT := high
else
currentDayHighRT := math.max(nz(currentDayHighRT[1]), high)
// Plot the real-time Day High (optional)
plot(currentDayHighRT, title="Current Day High (RT)", color=color.red, linewidth=1, style=plot.style_stepline)
// --- Alert Condition ---
bool breakoutCondition = ta.crossover(close, currentDayHighRT)
// --- Alert Call ---
if breakoutCondition
alert("Price broke above current day's high! Symbol: " + syminfo.tickerid + ", Price: " + str.tostring(close), alert.freq_once_per_bar)
// You can configure alerts from the TradingView UI by right-clicking the indicator or chart.
Example 3: Combining Day High with Other Indicators
Here, we combine the previous day’s high with a simple Moving Average to create a potential strategy condition: Buy if the price is above the MA and breaks the previous day’s high.
//@version=5
strategy("MA & Day High Breakout", shorttitle="MA+DH Strategy", overlay=true)
// --- Inputs ---
int maLength = input.int(20, "MA Length", minval=1)
// --- Calculate Indicators ---
float ma = ta.sma(close, maLength)
// --- Fetch Previous Day High ---
float prevDayHigh = security(syminfo.tickerid, 'D', high[1], lookahead=barmerge.lookahead_off, gaps=barmerge.gaps_off)
// --- Strategy Conditions ---
bool aboveMA = close > ma
bool prevDayHighBroken = ta.crossover(close, prevDayHigh)
// --- Entry Logic ---
if aboveMA and prevDayHighBroken
strategy.entry("Buy", strategy.long)
// --- Exit Logic (Simple) ---
// Example: Exit after N bars or on crossing below MA
// strategy.close("Buy", comment="Exit MA Cross", when=ta.crossunder(close, ma))
// Plotting for visualization (optional)
plot(ma, title="MA", color=color.orange)
plot(prevDayHigh, title="Prev Day High", color=color.blue, linewidth=2, style=plot.style_stepline)
This example demonstrates how to use the Day High as part of a broader trading logic. Remember to add exit conditions and proper risk management for a real-world strategy.
Advanced Techniques and Considerations
Working with data from different timeframes and real-time values introduces complexities that need careful handling.
Handling edge cases (e.g., pre-market data)
Some instruments trade pre-market or post-market. The standard ‘D’ timeframe often refers to the regular trading session. If your strategy needs to consider highs outside the regular session, you might need to:
- Use a
time()check withsession.extendedor specific time ranges to define your trading day. - Request data using
security()on a timeframe like ‘240’ (4-hour) or a lower timeframe and manually track the high across your defined ‘day’ using the real-time tracking method based on your session definition.
Always test how security('D', ...) behaves with extended hours data for the specific instrument you are trading.
Optimizing script performance when fetching Day High
Frequent calls to security() within complex loops or on every bar of a very low timeframe chart can impact script performance. For fetching a single value like the Day High, security(..., 'D', ...) is generally efficient as it only needs to process one daily bar per current bar’s day.
However, if you were fetching data from many timeframes or performing complex calculations within the security call’s expression, optimization might involve:
- Caching results where possible (less relevant for a single Day High fetch).
- Ensuring
lookahead=barmerge.lookahead_offandgaps=barmerge.gaps_offare used correctly. - Using
request.security_lower_tf()for specific scenarios, although this has its own performance characteristics and limitations.
For the standard Day High fetch, performance is rarely a significant bottleneck unless combined with many other cross-timeframe requests.
Potential issues with timeframe manipulation
Mixing timeframes can lead to NaN values or unexpected behavior if not handled correctly. The gaps=barmerge.gaps_off argument in security() helps mitigate NaN issues when lower timeframe bars don’t align perfectly with higher timeframe bars by carrying forward the last known value.
Be mindful of Pine Script’s execution model: security() fetches data corresponding to the time of the current bar. The high[1] inside security() refers to the previous bar of the requested timeframe (‘D’ in this case), not the previous bar of the current chart’s timeframe.
Understanding the difference between fetching the previous day’s closed high (security(..., 'D', high[1], ...)) and calculating the current day’s real-time running high is crucial for correct implementation.
Conclusion
Accessing the Day High is a fundamental technique for Pine Script developers building indicators and strategies on TradingView. While the security() function provides a robust way to fetch the closed Day High from completed daily bars, accessing the real-time running Day High for the current session requires a workaround involving time checks and variable tracking.
Recap of accessing and using Day High in Pine Script
- Use
security(syminfo.tickerid, 'D', high, ...)to fetch the high of the daily bar corresponding to the current intraday bar’s day. - Use
security(syminfo.tickerid, 'D', high[1], ...)to fetch the previous day’s closed high. - Implement manual tracking logic using
time()ordayofmonth()and avar floatvariable to calculate the real-time Day High during the current session. - Day High is invaluable for identifying support/resistance, breakout points, and volatility.
Further Exploration and Resources
To deepen your understanding, explore:
- Fetching other daily values like Open, Low, Close (
open,low,closeinsecurity). - Calculating the Daily Range (
security(..., 'D', high - low, ...)). - Implementing session-specific Day High tracking for markets with distinct trading hours.
- Combining Day High analysis with volume profiles or other advanced techniques.
The TradingView Pine Script documentation is your primary resource for understanding function details and behaviors. Experiment with the provided code examples and adapt them to your specific trading ideas.