Introduction to Trading Hours in Pine Script
Why Define Trading Hours in Pine Script?
Defining trading hours in Pine Script is crucial for several reasons. Many trading strategies are designed to operate only during specific periods when market activity aligns with the strategy’s logic. For instance, a day trading strategy might focus solely on the most volatile hours of the market open. By restricting strategy execution to these hours, you can avoid unnecessary trades and improve overall performance. Properly defining sessions is also vital for accurate backtesting and analysis, ensuring that your results reflect real-world conditions.
Basic Concepts: Sessions and Time Zones
In trading, a session refers to a specific period during which a market is open for trading. These sessions can vary greatly depending on the exchange and the asset being traded. Common examples include the New York Stock Exchange (NYSE) open, the London session, or specific periods during the Asian trading day. Understanding time zones is equally critical. Pine Script operates in UTC by default, so accurately converting and adjusting for time zone differences is essential when defining trading hours for different markets.
Implementing Trading Hours with time() Function
Understanding the time() Function Syntax and Arguments
The time() function is a fundamental tool for working with time in Pine Script. Its basic syntax is time(timeframe, session), where:
timeframe: specifies the timeframe for which the time is returned (e.g.,period,1D,1H).session: Defines the session string to check if the current bar’s time falls within it.
Defining a Single Trading Session
To define a single trading session, you specify the desired start and end times in the session argument. For example, to define a session from 9:30 AM to 4:00 PM (Eastern Time), converted to UTC, you could use:
//@version=5
indicator("Single Session", overlay=true)
ny_open_utc = "0930-1600" // New York Session in EST
in_session = time(timeframe.period, ny_open_utc)
plot(in_session ? high : na, color=color.green)
This code snippet plots high price only during the New York trading session.
Specifying Multiple Trading Sessions
To include multiple trading sessions, concatenate the session strings separated by a comma. For example, defining both a morning and afternoon session:
//@version=5
indicator("Multiple Sessions", overlay=true)
sessions = "0800-1200,1400-1700" // Example: two sessions
in_session = time(timeframe.period, sessions)
plot(in_session ? high : na, color=color.green)
Handling Time Zone Differences
The time() function operates in UTC. If your desired trading session is in a different time zone, you must adjust the session times accordingly. If your broker provides data in a specific time zone, ensure that your Pine Script accounts for this difference. For example, if your broker uses EST (UTC-5) and you want to trade from 9:30 AM to 4:00 PM EST, you’ll need to convert these times to UTC. 9:30 AM EST is 2:30 PM UTC, and 4:00 PM EST is 9:00 PM UTC. Therefore, your session string would be “1430-2100”.
Using the session() Function
Understanding the session() Function Syntax and Arguments
The session() function provides a more direct way to check if the current bar falls within a specified trading session. The syntax is session.ismarket, where market is the symbol identifier such as ‘NYSE’, however you can specify a custom session. More common and flexible is using the custom session:
session.custom(session_string).
Defining Custom Trading Sessions with session()
The session.custom() function allows you to define custom trading sessions using a string similar to the time() function. For example:
//@version=5
indicator("Custom Session", overlay=true)
ny_session = "0930-1600" // New York Session
in_session = session.custom(ny_session)
plot(in_session ? high : na, color=color.blue)
Combining session() with Other Conditions
The session() function can be combined with other conditions to refine trading rules. For example, you might only want to enter a trade if a specific indicator signal occurs during the defined session:
//@version=5
indicator("Session and RSI", overlay=true)
ny_session = "0930-1600"
rsi_oversold = 30
rsi_length = 14
rsi = ta.rsi(close, rsi_length)
in_session = session.custom(ny_session)
longCondition = in_session and rsi < rsi_oversold
plotshape(longCondition, style=shape.triangleup, color=color.green, size=size.small)
Advanced Techniques for Trading Hour Management
Creating Flexible Session Schedules with Input Options
For strategies that need adaptable trading hours, use input options to allow users to customize the session times. This provides flexibility and allows for easy adjustments without modifying the script’s code:
//@version=5
indicator("Adjustable Session", overlay=true)
session_input = input.session("0930-1600", title="Trading Session")
in_session = session.custom(session_input)
plot(in_session ? high : na, color=color.purple)
Highlighting Trading Sessions on the Chart
Visually highlighting trading sessions on the chart can be helpful for analysis and backtesting. Use the bgcolor() function in conjunction with your session definition:
//@version=5
indicator("Highlight Session", overlay=true)
ny_session = "0930-1600"
in_session = session.custom(ny_session)
bgcolor(in_session ? color.new(color.green, 90) : na)
plot(close)
Using Trading Hours to Filter Alerts and Strategies
Filter alerts and strategy entries/exits based on trading hours to ensure that your strategy operates only during the intended sessions:
//@version=5
strategy("Session Filtered Strategy")
ny_session = "0930-1600"
in_session = session.custom(ny_session)
longCondition = ta.crossover(ta.sma(close, 20), ta.sma(close, 50)) and in_session
shortCondition = ta.crossunder(ta.sma(close, 20), ta.sma(close, 50)) and in_session
if (longCondition)
strategy.entry("Long", strategy.long)
if (shortCondition)
strategy.entry("Short", strategy.short)
Practical Examples and Common Mistakes
Example 1: Limiting Strategy Execution to Specific Hours
This example demonstrates limiting a simple moving average crossover strategy to the New York trading session:
//@version=5
strategy("Session SMA Crossover", overlay=true)
fast_length = input.int(20, title="Fast SMA Length")
slow_length = input.int(50, title="Slow SMA Length")
ny_session = input.session("0930-1600", title="NY Session")
fast_ma = ta.sma(close, fast_length)
slow_ma = ta.sma(close, slow_length)
in_session = session.custom(ny_session)
longCondition = ta.crossover(fast_ma, slow_ma) and in_session
shortCondition = ta.crossunder(fast_ma, slow_ma) and in_session
if (longCondition)
strategy.entry("Long", strategy.long)
if (shortCondition)
strategy.entry("Short", strategy.short)
plot(fast_ma, color=color.blue)
plot(slow_ma, color=color.red)
Example 2: Displaying Session Information on the Chart
This example displays whether the current bar is within the defined New York session on the chart:
//@version=5
indicator("Session Info", overlay=true)
ny_session = "0930-1600"
in_session = session.custom(ny_session)
plotshape(in_session, title="In Session", style=shape.labelup, location=location.bottom, color=color.green, text="NY Open")
Common Mistakes and Troubleshooting Tips
- Incorrect Time Zone Conversions: Always double-check your time zone conversions. Using incorrect times can lead to trades being executed at unintended hours.
- Using
time()incorrectly: Ensure you use correct timeframe, and be sure to specify the ‘session’ argument correctly. - Not Considering Weekend Data: Pine Script includes weekend data. Be aware that strategies may trigger signals on weekends if not properly filtered.
- Forgetting Time Zone Shifts: Daylight Saving Time (DST) can cause time zone shifts. If your strategy trades during DST transitions, account for this change.
- Backtesting Issues: Always backtest your strategy thoroughly across different time periods and market conditions to ensure its robustness during the defined trading hours.