Pine Script: How to Identify the First Candle of the Day?

Identifying the first candle of the day in Pine Script is a fundamental task for many trading strategies and indicators. This capability allows traders to analyze opening price behavior, define daily ranges, and trigger actions based on the market’s initial movements. This article provides a comprehensive guide to accurately detect the first candle of the day, covering essential techniques and practical code examples.

Importance of Identifying the First Candle

Pinpointing the first candle is crucial for:

  • Defining Daily Trading Ranges: Establishing support and resistance levels based on the opening range.
  • Analyzing Opening Price Action: Understanding market sentiment at the start of the session.
  • Triggering Day-Specific Strategies: Executing trades based on specific criteria met at the opening.

Brief Overview of Pine Script and TradingView

Pine Script is TradingView’s proprietary language for creating custom indicators and strategies. It allows traders to backtest, optimize, and automate their trading ideas. This guide assumes a basic understanding of Pine Script syntax and the TradingView platform.

Understanding the time Variable and Session Information

The Role of the time Variable in Pine Script

The time variable in Pine Script represents the timestamp of each bar. It’s the foundation for identifying specific dates and times, including the first candle of the day.

How to Access Session Information for Daily Bars

TradingView automatically aggregates data into daily bars based on the chart’s timeframe and the asset’s trading hours. The time variable reflects the beginning timestamp of each daily bar.

Methods to Detect the First Candle of the Day

Using dayofmonth to Identify the First Candle

One method involves comparing the current bar’s dayofmonth value with the previous bar’s. If they differ, it signifies the start of a new day.

//@version=5
indicator("First Candle", overlay=true)

newDay = dayofmonth != dayofmonth[1]

plotshape(newDay, style=shape.flag, color=color.green, size=size.small, title = "New Day")

Explanation: This script checks if the current day of the month is different from the previous day of the month. If it is, it plots a flag shape to highlight the first candle of the day. This approach is simple and effective for basic identification.

Employing hour and minute to Precisely Locate the Opening Candle

To handle specific session start times, check the hour and minute values. For instance, if the session starts at 9:30 AM:

//@version=5
indicator("First Candle - Hour/Minute", overlay=true)

isFirstCandle = hour == 9 and minute == 30 and minute[1] != 30

plotshape(isFirstCandle, style=shape.circle, color=color.red, size=size.small, title = "First Candle")

Explanation: This script identifies the first candle when the hour is 9, the minute is 30, and the previous candle’s minute was not 30. Adapt the hour and minute values to match your desired session start time.

Combining Date and Time Conditions for Accuracy

For robustness, combine date and time checks. This guards against potential issues with data gaps or irregular trading hours. Check also that it is not the weekend (Saturday or Sunday).

//@version=5
indicator("First Candle - Combined", overlay=true)

newDay = dayofmonth != dayofmonth[1] and dayofweek != dayofweek.saturday and dayofweek != dayofweek.sunday
isOpeningTime = hour == 9 and minute == 30

isFirstCandle = newDay and isOpeningTime

plotshape(isFirstCandle, style=shape.diamond, color=color.blue, size=size.small, title = "First Candle")

Explanation: This script combines the dayofmonth check with hour and minute conditions. It checks for a new day and that the time is 9:30 AM. The and operator ensures that both conditions must be true to identify the first candle. It also exludes weekends

Practical Examples and Code Snippets

Simple Script to Highlight the First Candle

Here’s a basic script to highlight the first candle of each day using a background color:

//@version=5
indicator("Highlight First Candle", overlay=true)

newDay = dayofmonth != dayofmonth[1]

bgcolor(newDay ? color.new(color.green, 90) : na)

Explanation: This script changes the background color for the first candle. It uses the ternary operator to set the color to green with 90% transparency if it’s the first candle of the day, otherwise, it’s set to na (no color).

Adding Alerts for the First Candle

To trigger alerts on the first candle, use the alertcondition function:

//@version=5
indicator("Alert on First Candle", overlay=false)

newDay = dayofmonth != dayofmonth[1]

alertcondition(newDay, title="New Day", message="A new trading day has started!")

Explanation: When a new day is detected, an alert is triggered with the title “New Day” and the message “A new trading day has started!”.

Using the First Candle for Strategy Entry and Exit

Strategies can use the first candle’s high or low to set entry or exit points:

//@version=5
strategy("First Candle Strategy", overlay=true)

newDay = dayofmonth != dayofmonth[1]

var float firstCandleHigh = na
var float firstCandleLow  = na

if newDay
    firstCandleHigh := high
    firstCandleLow  := low

longCondition  = close > firstCandleHigh[1]
shortCondition = close < firstCandleLow[1]

if (longCondition)
    strategy.entry("Long", strategy.long)

if (shortCondition)
    strategy.entry("Short", strategy.short)

Explanation: This strategy enters a long position if the current close is higher than the previous day’s first candle high, and enters a short position if the current close is lower than the previous day’s first candle low. It is important to declare ‘firstCandleHigh’ and ‘firstCandleLow’ as variables, that way they can be assigned only once.

Advanced Techniques and Considerations

Handling Different Time Zones and Exchange Openings

TradingView charts display data in the exchange’s time zone. Adjust the hour and minute values accordingly to match the desired session start time in the correct time zone. No need to convert to UTC.

Dealing with Extended Hours and Premarket Data

If you’re working with assets that have extended hours, be mindful of how the data is aggregated. You may need to adjust your logic to correctly identify the first candle of the regular trading session, as opposed to the first candle of the extended hours session.

Optimizing Code for Performance

For complex indicators or strategies, optimize your code by minimizing calculations within the loop. Store frequently used values in variables and reuse them to reduce computational overhead. Using var keyword on variables that only need to be initialized once is a good optimization technique.

By understanding and applying these techniques, you can accurately identify the first candle of the day in Pine Script and build robust, effective trading indicators and strategies.


Leave a Reply