How to Build Time-Based Trading Strategies in EasyLanguage
Time-based trading strategies focus on trading during specific hours rather than reacting to every market signal. These strategies are especially useful for futures and forex traders, where market behavior changes throughout the day. For example, Euro currency futures often see the most activity between 8:00 AM and 11:00 AM Central Time. Using EasyLanguage, a beginner-friendly coding tool, you can create strategies that leverage these time windows for better precision and control.
Here’s what you’ll learn:
- How to configure your trading platform for time-based strategies.
-
Using EasyLanguage functions like
TimeandTimeToMinutesto define trading windows. - Examples of strategies such as Market Open Breakout, Mid-Morning Mean Reversion, and End-of-Day Positioning.
- Tips for backtesting, optimizing, and deploying your strategies using tools like TradeStation and QuantVPS.
With clear coding examples and practical advice, this guide helps you build strategies that align with specific market sessions, reduce trading costs, and improve execution efficiency.
Setting Up Your EasyLanguage Development Environment
QuantVPS Plan Comparison for Time-Based Trading Strategies
QuantVPS Plan Comparison for Time-Based Trading Strategies
Configuring Your Trading Platform
To build your time-based strategy, start by opening the TradeStation Development Environment (TDE). Navigate to File > New > Strategy, then select either a template or a blank workspace to begin crafting your strategy.
For intraday trading, apply your strategy directly to a chart. Head to Studies > Edit Strategies, and under the Data Settings tab, set your desired bar interval (like 1-minute or 5-minute bars) and specify the amount of historical data to load. This ensures your time-based triggers align with the data.
Use the Print Log feature to verify that your time-specific triggers are functioning correctly by printing timestamps and variable values during execution. Additionally, the EasyLanguage Utilization Monitor is a handy tool to check the efficiency of your strategies, even when applied to multiple charts. With this setup, you're ready for precise backtesting and seamless live deployment, ensuring your time-based strategies perform exactly as intended.
Once your platform is configured, it’s time to choose a QuantVPS plan that matches the computing power your strategy requires.
Selecting a QuantVPS Plan
After preparing your development environment, selecting the right QuantVPS plan is crucial for smooth backtesting and live trading. The QuantVPS Pro plan, priced at $99.99 per month (or $69.99 per month with an annual subscription), includes 6 cores, 16GB RAM, and 150GB NVMe storage - ideal for managing 3-5 charts. For more demanding tasks, the QuantVPS Ultra plan offers 24 cores, 64GB RAM, and is available at $189.99 per month (or $132.99 per month annually).
Both plans provide ultra-low latency (0-1ms) and guarantee 100% uptime, ensuring your strategies execute flawlessly and run continuously, regardless of your local system's condition. This reliability is key to maintaining consistent performance in both backtesting and live trading.
EasyLanguage Functions for Time-Based Trading
Working with Time Functions
EasyLanguage evaluates your strategy bar-by-bar, analyzing each statement based on the "current bar". The Time function provides the closing time of the current bar in HHMM military format. For example, 1:30 PM is represented as 1330. To define a trading window, you can use a condition like this:
If Time > 0930 and Time < 1600 then …
For more precise time calculations, the TimeToMinutes function converts an HHMM time into the total minutes elapsed since midnight. This simplifies working with time intervals. As George Pruitt, Author and Director of Research, explains:
TimeToMinutes returns the number of minutes between midnight and the users' input (HHMM format.)
TimeToMinutes returns the number of minutes between midnight and the users' input (HHMM format.)
However, handling strategies that span midnight can be tricky. A direct comparison like If Time > 2100 and Time < 0400 fails because 2130 is not less than 0400 after the clock resets at midnight.
To address such challenges, EasyLanguage offers additional functions like Date, sessionStartTime(0, 1), and sessionEndTime(0, 1) to access session-specific data. You can also extract the hour using intPortion(Time/100) and the minutes with mod(Time, 100). For efficiency, place these calculations inside a Once block to ensure they only run on the first bar, improving your strategy's performance.
Once you’ve set up time functions, the next step is to control how often trades occur within your defined intervals.
Controlling Trade Frequency
Using time-based functions as a foundation, you can control trade frequency to align with specific intervals. The reserved word EntriesToday helps limit the number of trades your strategy executes in a single day. However, this function resets at midnight, which can disrupt overnight or continuous strategies. Jeff Swanson, Founder of EasyLanguage Mastery, highlights this limitation:
EntriesToday assumes the regular session and will reset the trade counter when the day changes – right in the middle of your trading. What if you wish to limit the number of trades over a given week? Nope, can't do it with EntriesToday.
EntriesToday assumes the regular session and will reset the trade counter when the day changes – right in the middle of your trading. What if you wish to limit the number of trades over a given week? Nope, can't do it with EntriesToday.
To create custom trade limits that span multiple days or specific sessions, you can implement your own trade counter using MarketPosition (MP). For example, increment the counter whenever a new trade is detected:
If (MarketPosition <> 0) and (MarketPosition[3] <> MarketPosition) then TradesCounter = TradesCounter + 1;
NEVER MISS A TRADE
Your algos run 24/7
even while you sleep.
99.999% uptime • Chicago, New York, London & Amsterdam data centers • From $59.99/mo
You can reset this counter daily (e.g., at 9:30 AM) or at any custom interval:
If Time = 0930 then TradesCounter = 0;
3 Time-Based Strategy Examples with Code
Market Open Breakout Strategy
The Market Open Breakout strategy focuses on capturing momentum during the first part of the trading day. It defines an opening range (9:30–10:00 AM ET) and triggers entries when the price moves beyond this range. Below is an example for ES futures:
Inputs: OpeningRangeDuration(30), PriceOffset(2), windowDuration(190), openWindowOffset(20);
Variables: RangeHigh(0), RangeLow(0), RangeSet(False);
// Define the opening range
If Time >= 0930 and Time <= calcTime(0930, OpeningRangeDuration) then begin
If RangeSet = False then begin
RangeHigh = High;
RangeLow = Low;
end else begin
RangeHigh = MaxList(High, RangeHigh);
RangeLow = MinList(Low, RangeLow);
end;
RangeSet = True;
end;
// Enter on breakout with offset
If Time > calcTime(0930, openWindowOffset) and Time < calcTime(0930, windowDuration) and EntriesToday(date) = 0 then begin
Buy ("BO Long") next bar at RangeHigh + PriceOffset stop;
Sell Short ("BO Short") next bar at RangeLow - PriceOffset stop;
end;
SetExitOnClose;
Research indicates that waiting 20 minutes after the market opens (9:30 AM ET) and exiting after 190 minutes yields strong statistical results for ES futures. Adding a small offset, such as 2 ticks, can help reduce false breakouts. Experimenting with different opening range durations - 15, 30, or 60 minutes - can further refine the strategy for current market conditions.
Now, let's shift focus to a mid-morning strategy that leans on RSI to identify quick mean reversion opportunities.
Mid-Morning Mean Reversion Strategy
During the mid-morning period (10:00–11:00 AM ET), market volatility often stabilizes, making it a good time for mean reversion strategies. This example uses the RSI indicator to spot oversold or overbought conditions:
Inputs: RSILength(9), OversoldLevel(30), OverboughtLevel(70), StartTime(1000), EndTime(1100);
Variables: RSIValue(0);
RSIValue = RSI(Close, RSILength);
// Trade strictly between 10:00 and 11:00 AM
If Time >= StartTime and Time <= EndTime and EntriesToday(date) < 2 then begin
If RSIValue < OversoldLevel then
Buy ("Mean Rev Long") next bar at market;
If RSIValue > OverboughtLevel then
Sell Short ("Mean Rev Short") next bar at market;
end;
// Exit at window close
If Time > EndTime then begin
Sell ("Exit Long") next bar at market;
Buy to Cover ("Exit Short") next bar at market;
end;
Testing suggests that a 9-period RSI provides quicker intraday signals, improving net profitability after accounting for trading costs. This setup works well in quieter market conditions, offering a balance of precision and speed.
Finally, we examine a strategy designed for end-of-day trading.
End-of-Day Position Strategy
This strategy targets the final 15 minutes of the trading session (3:45–4:00 PM ET) to take advantage of daily momentum. The use of SetExitOnClose ensures all positions are closed by the session's end.
Inputs: EntryTime(1545);
Variables: DailyMomentum(0);
DailyMomentum = Close - Close[1];
// Enter during the final 15 minutes
If Time >= EntryTime and Time < sessionEndTime(0, 1) and EntriesToday(date) = 0 then begin
If DailyMomentum > 0 then
Buy ("EOD Long") next bar at market;
If DailyMomentum < 0 then
Sell Short ("EOD Short") next bar at market;
end;
SetExitOnClose;
The sessionEndTime(0, 1) function dynamically adjusts to the session's scheduled end time, making the strategy adaptable across various time zones and instruments.
| Parameter | Purpose | Optimization Range |
|---|---|---|
| OpeningRangeDuration | Defines the opening range window | Test 15, 30, or 60 minutes |
| openWindowOffset | Delay before entry after market open | Around 20 minutes for ES |
| windowDuration | Validity period for breakout signals | 190 to 240 minutes |
| RSILength | Sensitivity of RSI for mean reversion | Test 7, 9, or 14 periods |
| EntryTime | Timing for end-of-day trades | Test 3:30, 3:45, or 3:50 PM |
Testing and Optimizing Your Strategies
Using TradeStation Performance Reports
TradeStation evaluates your strategy step-by-step, offering three key tools: onscreen cues, the Strategy Performance Report, and the Strategy Equity Indicator. Onscreen cues help pinpoint timing issues, while the Performance Report provides detailed metrics like profit, drawdown, return on account, and the largest winning trade. The Equity Indicator tracks your account balance over time - consistent upward trends suggest steady performance, while erratic jumps may reveal dependence on a few standout trades.
Keep in mind, the default report doesn’t account for real-world trading costs. Always factor in broker commissions, slippage, and margin requirements manually to ensure your profit figures align with actual trading conditions. Once you’ve gathered these insights, the next step is fine-tuning your strategy for better results.
Running Fast Optimizations with QuantVPS
After analyzing performance, you can optimize your strategy parameters more efficiently with QuantVPS's high-powered infrastructure. Complex tasks - like testing multiple parameters across years of 1-minute data - require significant computational resources. QuantVPS Ultra+, equipped with 24 cores and 64GB RAM, drastically reduces optimization time compared to standard desktop setups.
QuantVPS Ultra+ also delivers ultra-low latency (0–1 ms), which is especially important for strategies that rely on precise timing, such as End-of-Day Position Strategies. Lower latency ensures your backtest results are closer to live trading conditions, where even a millisecond can impact fill prices on fast-moving ES contracts. To further streamline testing, use TradeStation’s EasyLanguage Utilization Monitor to identify and fix inefficient code, ensuring faster and more accurate optimizations.
Avoiding Common Mistakes
Managing Time Zones Correctly
Mishandling time zones can wreak havoc on live trading. In EasyLanguage, midnight is represented as 0, so it's essential to compare times carefully, especially for trading sessions that span past midnight. George Pruitt, Director of Research at Futures Truth, highlights this issue:
2400 is okay in Military Time but not in TradeStation... All we need to do is check to see if timeSum = 2400 and if so, just simply reset to zero.
2400 is okay in Military Time but not in TradeStation... All we need to do is check to see if timeSum = 2400 and if so, just simply reset to zero.
To avoid time-related errors, validate historical data to ensure your timing parameters align with the current session schedule. Using a "Once" block is a practical way to confirm session timestamps. Once time zones are properly managed, you can shift your focus to another critical area: preventing overfitting.
Preventing Overfitting
Overfitting can severely undermine your trading strategy. David Bergstrom, Founder of Build Alpha, puts it bluntly:
STOP LOSING TO LATENCY
Execute faster than
your competition.
Sub-millisecond execution • Direct exchange connectivity • From $59.99/mo
Curve fitting is the black plague for system traders. The initial investment is often better donated than trading overfit strategies based on bloated hypothetical performance results.
Curve fitting is the black plague for system traders. The initial investment is often better donated than trading overfit strategies based on bloated hypothetical performance results.
To reduce overfitting risk, keep the number of parameters in your strategy to a minimum - ideally one to three. When optimizing, resist the temptation to choose the single "best" value that maximizes profit. Instead, aim for a stable region where the strategy performs consistently across a range of values. Jeff Swanson, Founder of EasyLanguage Mastery, emphasizes:
Your job as an algorithmic trader is not to build a perfect-looking equity curve. That's easy to do. Your job is to construct a strategy that can generalize to new data.
Your job as an algorithmic trader is not to build a perfect-looking equity curve. That's easy to do. Your job is to construct a strategy that can generalize to new data.
Always reserve the last 30% of your historical data for out-of-sample testing before moving to live trading. By addressing overfitting, you set the stage for deploying a robust strategy.
Deploying Live Strategies on QuantVPS
Even the most carefully coded strategy is useless if your system goes down during a critical trade. Time-sensitive strategies demand continuous uptime, as missing a scheduled entry or exit can turn a profitable trade into a disaster. QuantVPS ensures uninterrupted execution with features like DDoS protection, automatic backups, and global accessibility - so your strategy keeps running even if your home internet fails.
Once you've nailed time management, ensure live deployment is seamless. The 0–1 ms latency offered by QuantVPS Performance Plans is especially crucial for End-of-Day Position Strategies, where even a millisecond can affect fill prices on fast-moving ES contracts. Before going live, enable TradeStation's server-side stops setting. This ensures that if your VPS connection drops, your exit orders remain active on the broker's infrastructure.
Conclusion
Creating time-based trading strategies with EasyLanguage is straightforward, even for those without a programming background, thanks to its user-friendly, English-like syntax. As TradeStation explains:
EasyLanguage is designed for traders, not programmers. No coding knowledge necessary.
EasyLanguage is designed for traders, not programmers. No coding knowledge necessary.
The most important part of developing these strategies is managing time accurately, especially when trading windows extend past midnight.
George Pruitt highlights the importance of error handling to catch issues with inputs. Using functions like isTimeWithinWindow and wrapping initialization code in Once blocks are essential practices for writing reliable code. However, building robust code is just one side of the equation - ensuring smooth live execution is equally important.
When deploying strategies live, maintaining continuous uptime is crucial. QuantVPS Performance Plans, for example, offer 0–1 ms latency and uninterrupted execution, which is vital during critical entry and exit periods. This is particularly important for fast-moving markets, such as ES futures, where milliseconds can make a difference.
To avoid overfitting, keep strategy parameters limited to one to three and aim for consistent performance in stable regions rather than chasing a perfect equity curve. Together, these practices lay the groundwork for a durable and effective time-based trading strategy.
FAQs
How do I handle time windows that cross midnight in EasyLanguage?
When dealing with time windows that cross midnight in EasyLanguage, you need to handle the scenario where the end time is earlier than the start time. To address this, use a condition that checks if the current time is either greater than the start time or less than or equal to the end time. Here's how it looks:
If Time > StartTime or Time <= EndTime then...
This approach ensures your time window operates correctly, even when it spans across midnight.
How can I limit trades by session if EntriesToday resets at midnight?
When dealing with sessions that span across midnight - where EntriesToday resets - you'll need to implement time-based conditions to manage this effectively. Here's how you can do it:
-
Define the session's start time (
StartTime) and end time (EndTime). -
If the session's
EndTimeis later thanStartTime(i.e., within the same day), use this condition:
If Time >= StartTime and Time <= EndTime -
If the session's
EndTimeis earlier thanStartTime(crossing midnight), modify the condition like this:
If (Time >= StartTime) or (Time <= EndTime)
This approach ensures that sessions are tracked correctly, regardless of whether they extend past midnight.
How should I validate a time-based strategy before going live on a VPS?
Before rolling out a time-based strategy on a VPS, it's crucial to conduct thorough backtesting. This ensures your strategy performs as expected within the specific time window you're targeting - particularly if it crosses midnight or extends over multiple days. Use historical data from different trading sessions, like New York or London, to uncover potential issues. Once backtesting is complete, run the strategy in a paper trading or simulation environment. This step helps verify its accuracy and reliability before going live.
When dealing with time windows that cross midnight in EasyLanguage, you need to handle the scenario where the end time is earlier than the start time. To address this, use a condition that checks if the current time is either greater than the start time or less than or equal to the end time. Here's how it looks:
When dealing with sessions that span across midnight - where EntriesToday resets - you'll need to implement time-based conditions to manage this effectively. Here's how you can do it:
- Define the session's start time (
StartTime) and end time (EndTime). - If the session's
EndTimeis later thanStartTime(i.e., within the same day), use this condition:
If Time >= StartTime and Time <= EndTime - If the session's
EndTimeis earlier thanStartTime(crossing midnight), modify the condition like this:
If (Time >= StartTime) or (Time <= EndTime)
This approach ensures that sessions are tracked correctly, regardless of whether they extend past midnight.
Before rolling out a time-based strategy on a VPS, it's crucial to conduct thorough backtesting. This ensures your strategy performs as expected within the specific time window you're targeting - particularly if it crosses midnight or extends over multiple days. Use historical data from different trading sessions, like New York or London, to uncover potential issues. Once backtesting is complete, run the strategy in a paper trading or simulation environment. This step helps verify its accuracy and reliability before going live.
"}}]}



