Skip to main content

Pine Script: Closing Positions at End of Day

· 8 min read

Ever find yourself staring at the ceiling at 3 AM, wondering if your overnight positions are about to blow up? Yeah, me too. That gut-wrenching feeling when you're holding trades after market close and some random news could gap your stock down 10% before you even wake up.

That's exactly why I started using Pine Script to automatically close all my day trades before the market closes. It's honestly one of the best decisions I've made for my trading sanity.

Pine Script day trading example

Why Automatically Close Day Trading Positions?

Look, day trading is stressful enough without adding overnight risk to the mix. I learned this lesson the hard way when I held what I thought was a "sure thing" overnight, only to wake up to a 7% gap down because of some earnings surprise I completely missed.

Here's the thing about overnight gaps:

  • They're unpredictable - Even the best analysis can't predict after-hours news
  • They're often brutal - Gaps of 3-5% aren't uncommon
  • They kill your risk management - Your stop loss becomes useless in a gap scenario

When you close everything at day's end, you eliminate overnight risk entirely. Sure, you might miss some profitable gap-ups, but trust me, the gap-downs you avoid will more than make up for it.

The Simple Pine Script Solution

The Best Pine Script Generator

The beauty of Pine Script is that it makes this automation really straightforward. The strategy.close_all() function is your best friend here - it does exactly what it sounds like.

Here's the basic approach I use:

// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Pineify

//@version=6
strategy('End of Day Close Strategy', overlay = true)

// Function to detect end of trading day
isEndOfDay() =>
not na(time) and (year(timenow) != year(time) or month(timenow) != month(time) or dayofmonth(timenow) != dayofmonth(time))

// Close all positions when day ends
if isEndOfDay()
strategy.close_all(comment = 'EOD Close')

This code checks if we've moved to a new day and automatically closes everything. It's not millisecond-precise, but it gets the job done reliably.

The Precision Approach: Time-Based Exits

Sometimes you want more control over exactly when your positions close. Maybe you're trading the power hour and want to exit 15 minutes before the close to avoid that end-of-day craziness.

Here's how I handle time-specific exits:

// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Pineify

//@version=6
strategy('Precise Time Close', overlay = true)

// Close all positions at 3:45 PM Eastern
if (hour == 15 and minute == 45)
strategy.close_all(comment="15:45 Close")

I personally use 3:45 PM for most of my strategies because it gives me a buffer before the 4:00 PM close, but you can adjust this based on your trading style.

For different markets, you'd adjust the time accordingly:

  • Forex: Maybe 4:30 PM before the New York session ends
  • Crypto: Since it's 24/7, you might choose a specific time that works with your schedule
  • Futures: Depends on the contract, but often similar to stock market hours

Combining with Stop Losses and Take Profits

Here's where it gets interesting. You can combine end-of-day closes with your regular stop loss strategies to create a robust risk management system:

//@version=6
strategy('Complete Risk Management', overlay = true)

// Your entry logic here (simplified example)
if (ta.crossover(ta.sma(close, 10), ta.sma(close, 20)))
strategy.entry("Long", strategy.long)

// Regular stop loss and take profit
strategy.exit("Exit", from_entry="Long", stop=close*0.98, limit=close*1.04)

// End of day close as backup
if (hour == 15 and minute == 45)
strategy.close_all(comment="EOD Close")

This way, you have multiple layers of protection. Your trades can exit on normal stop/profit conditions, but if nothing triggers, they'll automatically close at day's end.

Visual Strategy Building with No-Code Tools

Pineify visual editor

Not everyone wants to write code from scratch (honestly, I get it). If you prefer a visual approach, you can use tools like Pineify to build these strategies by dragging and dropping components.

The visual approach is especially handy when you want to combine time-based exits with other conditions like:

  • Technical indicator signals - Close positions if RSI hits overbought levels AND it's after 3:30 PM
  • Volume conditions - Exit if volume drops below average in the last hour
  • Price action triggers - Close if price moves against you by a certain percentage after 3:00 PM

Real-World Results: What I've Noticed

After using this approach for about two years, here's what I've observed:

The Good Stuff

  • Better sleep - No joke, not worrying about overnight gaps is a huge stress relief
  • Improved discipline - Forces you to stick to day trading rules instead of accidentally becoming a swing trader
  • Cleaner backtests - Your strategy performance becomes more predictable when you eliminate overnight variables
  • Better position sizing - When you know exactly when trades end, you can size positions more aggressively

The Trade-offs

  • Missing gap-ups - Sometimes stocks gap up overnight in your favor
  • Reduced holding time - Some winning trades might have run further if held longer
  • Less flexibility - You can't adapt to late-day developments

But here's the thing: for every profitable gap you miss, you probably avoid two or three painful ones. The math works out in your favor most of the time.

Implementation Tips That Actually Matter

Start with paper trading - I cannot stress this enough. Test your end-of-day close strategy for at least a month before going live.

Consider your broker's execution - Make sure your broker can handle the exit orders when your strategy triggers them. Some brokers get wonky during high-volume periods.

Account for different time zones - If you're trading US markets from Europe, make sure your time calculations are correct.

Test around daylight saving changes - This caught me off guard once. Market hours shift but your computer time might not automatically adjust.

Advanced Techniques

If you want to get fancy, you can create more sophisticated exit rules. For example, closing positions earlier if certain market conditions are met:

// Close early if VIX spikes or volume is unusually high
isHighVolatility = ta.roc(close, 1) > 0.02 or volume > ta.sma(volume, 20) * 2

if (hour >= 15 and isHighVolatility) or (hour == 15 and minute == 45)
strategy.close_all(comment="Risk-Based Close")

You could also implement partial position closing, where you reduce position size throughout the day rather than closing everything at once.

Beyond Basic End-of-Day Strategies

Once you're comfortable with basic EOD closes, you might want to explore more advanced concepts like trailing stop losses or automated trading systems that can adapt to market conditions throughout the day.

The key is starting simple and building complexity gradually. Master the basic end-of-day close first, then add bells and whistles.

Getting Started: Your Action Plan

Ready to implement this? Here's exactly what to do:

  1. Open TradingView and navigate to the Pine Editor (it's free)
  2. Create a new strategy (not an indicator - strategies can actually execute trades)
  3. Copy one of the code examples above and paste it in
  4. Run a backtest on some historical data to see how it would have performed
  5. Paper trade for at least 2-3 weeks to make sure everything works as expected
  6. Go live with small position sizes until you're confident

Remember, the goal isn't to create the perfect strategy overnight. It's to build something reliable that manages your risk and lets you sleep better.

The Bottom Line

Automatically closing day trading positions at the end of the day isn't glamorous, but it's one of those simple things that can dramatically improve your trading results and peace of mind.

Will it make you rich? Probably not by itself. But it might keep you from going broke, which is honestly more important in the long run.

If you're serious about day trading, implementing end-of-day closes should be near the top of your priority list. Your future self (and your sleep schedule) will thank you.

Want to explore more Pine Script strategies? Check out our guide on building complete trading strategies or learn about Pine Script strategy examples that actually work in real markets.