How to get an open order's entry time in TradingView Pine Script?
TL;DR
Usestrategy.opentrades.entry_time(tradeIndex)to fetch the bar timestamp of any open order, then convert it into human-readable text or holding-period metrics.
At a Glance
Section titled “At a Glance”| Difficulty | Intermediate |
| Time to implement | 10-15 min |
| Category | Order Management |
Quick Actions
Section titled “Quick Actions”Quick Start
Section titled “Quick Start”//@version=6strategy("Entry time demo", overlay=true)
if strategy.position_size == 0 and ta.crossover(close, ta.sma(close, 20)) strategy.entry("Breakout", strategy.long)
if strategy.opentrades > 0 newest = strategy.opentrades - 1 entryStamp = strategy.opentrades.entry_time(newest) pretty = tostring(entryStamp, "yyyy-MM-dd HH:mm") label.new(bar_index, high, "Opened at " + pretty, textcolor=color.white, bgcolor=color.new(color.blue, 65))Why It Matters
Section titled “Why It Matters”Knowing when a position opened lets you manage exposure by age: you can trail stops after N minutes, flag trades that overstay their welcome, or calculate session boundaries for partial exits. strategy.opentrades.entry_time() exposes that timestamp so you can surface it in labels, tables, or risk checks without manually tracking every fill.
What You’ll Learn
Section titled “What You’ll Learn”- Identify which open trade index you want (oldest vs newest entry).
- Convert entry timestamps into readable strings or elapsed time values.
- Display entry times on-chart and inside automation logic.
- Handle multi-entry strategies by looping across
strategy.opentrades.
Quick Reference
Section titled “Quick Reference”| Call | Purpose |
|---|---|
strategy.opentrades | Returns the number of open orders the strategy currently holds. |
strategy.opentrades.entry_time(idx) | Provides the entry bar’s timestamp (int, milliseconds) for the given open order index. |
tostring(value, format) | Formats timestamps into readable strings such as yyyy-MM-dd HH:mm. |
time | Current bar’s opening timestamp; subtract to compute holding duration. |
label.new() | Annotates the chart with the entry time or age of the trade. |
Implementation Blueprint
Section titled “Implementation Blueprint”-
Pick the trade index
Zero (0) targets the oldest open order, whilestrategy.opentrades - 1gives you the most recent fill.oldestIndex = 0newestIndex = math.max(strategy.opentrades - 1, 0) -
Fetch and format the timestamp
Grab the raw milliseconds and turn them into text or durations.entryMs = strategy.opentrades.entry_time(newestIndex)entryText = tostring(entryMs, "yyyy-MM-dd HH:mm")minutesInTrade = (time - entryMs) / 60000.0 -
Surface the information
Use labels, tables, or conditional logic to react when a trade gets too old.if minutesInTrade > 90alert("Trade has been open for " + str.tostring(minutesInTrade, format.mintick) + " minutes")
Example Playbook
Section titled “Example Playbook”//@version=6strategy("Breakout age tracker", overlay=true, default_qty_type=strategy.percent_of_equity, default_qty_value=5)
len = input.int(40, "Breakout length", minval=2)targetAge = input.int(120, "Minutes before attention", minval=5)
top = ta.highest(high, len)btm = ta.lowest(low, len)enterLong = ta.crossover(high, top)enterShort = ta.crossunder(low, btm)
if enterLong strategy.entry("LONG", strategy.long)if enterShort strategy.entry("SHORT", strategy.short)
plot(top, "Breakout high", color=color.new(color.green, 60))plot(btm, "Breakout low", color=color.new(color.red, 60))
if strategy.opentrades > 0 oldest = 0 newest = strategy.opentrades - 1 firstTime = strategy.opentrades.entry_time(oldest) lastTime = strategy.opentrades.entry_time(newest)
minutesSinceFirst = (time - firstTime) / 60000.0 minutesSinceLast = (time - lastTime) / 60000.0
txt = "First fill: " + tostring(firstTime, "MMM dd HH:mm") + "\nAge: " + str.tostring(minutesSinceFirst, format.mintick) + " min" + "\nLatest fill age: " + str.tostring(minutesSinceLast, format.mintick) + " min"
label.new(bar_index, high, txt, textcolor=color.white, style=label.style_label_down, bgcolor=color.new(color.blue, 60))
if strategy.position_size > 0 and minutesSinceFirst > targetAge strategy.close("LONG", comment="Time-based exit") if strategy.position_size < 0 and minutesSinceFirst > targetAge strategy.close("SHORT", comment="Time-based exit")- The code watches both the oldest and newest fills, so pyramided positions have accurate age tracking.
- Formatting the timestamp keeps labels human-friendly and consistent with chart time zone settings.
- Age thresholds let you automate time-based exits or alerts without manually storing entry bars.
Pro Tips & Pitfalls
Section titled “Pro Tips & Pitfalls”- Guard every call with
strategy.opentrades > 0—entry_time()returnsnawhen no open trade exists. - Remember that the returned time is the bar open, not the exact tick when the order filled. Use smaller chart resolutions if you need finer precision.
- Loop from
0tostrategy.opentrades - 1to inspect each leg when pyramiding. - Convert timestamps to your preferred zone with
timestamptz(entryMs, session.timezone)if you need session-aware reporting.
Troubleshooting & FAQ
Section titled “Troubleshooting & FAQ”I get na for entry time
Section titled “I get na for entry time”This occurs when the strategy has no open orders. Check strategy.opentrades > 0 before accessing any index, and ensure the index you request is within bounds.
The reported time is earlier than the fill I saw live
Section titled “The reported time is earlier than the fill I saw live”entry_time() returns the bar’s opening timestamp. If the order filled later within that bar, you’ll see an earlier time. Consider running the strategy on a lower timeframe for more granular bar opens.
How do I see the entry time in my local timezone?
Section titled “How do I see the entry time in my local timezone?”Wrap the timestamp with timestamptz(entryMs, "America/New_York") (or your zone) before formatting. Pine will adjust the milliseconds to the specified timezone.
Key Takeaways
Section titled “Key Takeaways”strategy.opentrades.entry_time()exposes the bar timestamp for each open order.- Always guard against empty positions and out-of-range indexes.
- Subtract the timestamp from
timeto compute holding duration in minutes or hours. - Surface the information in labels, alerts, or risk checks to keep trades on schedule.
Keep Going
Section titled “Keep Going”- Open AI Editor to apply the pattern with guided assistance
- Browse Strategy Examples for ready-to-run templates
- Connect to Live Trading when you are ready to automate