FAQ

How to Enter/Exit Positions on Bar Close in Pine Script Strategies

How to Enter/Exit Positions on Bar Close in Pine Script Strategies

Order placement commands are quite important to your TradingView strategy. But many people are surprised by the default behavior of PineScript when it executes market orders.

Sample Strategy 

For an illustration, the Pine Script code below highlights a super simple strategy. 

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

long_condition  = ta.crossover( ta.sma(close, 14), ta.sma(close, 28))
close_condition = ta.crossunder(ta.sma(close, 14), ta.sma(close, 28))

plotshape(long_condition,  color = color.green)
plotshape(close_condition, color = color.red)

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

if (close_condition)
    strategy.close("Long")

In this strategy, we enter and exit long positions using market orders. We also plot a cross for the signal bar. 

Entry and Exit

Let’s check the chart to better understand what is going on. 

Here is an example of an Entry: 

Here is an example of Exit: 

The Blue arrow for entry and the violet arrow for exit indicates the price at which the order was executed. You can spot that for both cases the order wasn’t executed at the same bar close, but it was executed at the next bar open. This is the default behavior of Pine Script, this way you might get more reasonable backtests.

Execute Your Orders on Bar Close

Sometimes, however, you might want to execute your orders on bar close anyway. There is a simple way to do that in Pine Script. You can do that by adding one parameter in the strategy() function: process_orders_on_close = true. This will solve that issue and will execute orders at the same bars close:

Here is the entire code for the strategy that solves it:

//@version=5
strategy("My Strategy", overlay=true, process_orders_on_close = true)

long_condition  = ta.crossover( ta.sma(close, 14), ta.sma(close, 28))
close_condition = ta.crossunder(ta.sma(close, 14), ta.sma(close, 28))

plotshape(long_condition,  color = color.green)
plotshape(close_condition, color = color.red)

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

if (close_condition)
    strategy.close("Long")

So as you can see it’s fairly easy to fix this issue.


Follow me on TradingView and YouTube.

This image has an empty alt attribute; its file name is wide.png
Pine Script Programming Courses
Pine Script Programming Courses
Learn to build your own TradingView Indicators and Strategies
Sidebar Signup Form
If you want to be the first in this business, subscribe to the latest news