Rajandran R Creator of OpenAlgo Sketchmaker, RagZ. Building GenAI Applications. Telecom Engineer turned Full-time Derivative Trader. Mostly Trading Nifty, Banknifty, High Liquid Stock Derivatives. Trading the Markets Since 2006 onwards. Using Market Profile and Orderflow for more than a decade. Designed and published 100+ open source trading systems on various trading tools. Now the recent curiosity on building Trading AI Agents.

Code Snippet – Simple Intraday Trading System with Target and Stoploss – Tradingview Pinescript

9 min read

This Pine Script intraday strategy template gives you buy and sell signals from an EMA crossover, a fixed target and stoploss in points, a trading window (9:30 am to 3:00 pm) and an automatic square-off at 3:15 pm. The original 2020 code is in Pine Script v4; below it you will find updated v6 versions as an indicator and as a backtestable strategy.

Thought of implementing a simple intraday trading system with stoploss and target controls with time-based entry and exit controls. Traders can use this code as a prototype to design their own intraday trading strategy

Key takeaways
  • Entry: fast EMA (5) crosses above slow EMA (10) inside the 9:30 to 15:00 trade window.
  • Exits: stoploss, target, opposite EMA cross, or square-off at 15:15, whichever comes first.
  • Target and stop levels are plotted as dotted circles while a trade is open.
  • The original is a v4 visual study; the 2026 updates add a v6 indicator with alerts and a v6 strategy for the Strategy Tester.
  • With a 30 point stop and a 20 point target, the system needs to win 60% of the trades that hit either level just to break even.

Tradingview Pinescript brings more interesting way of implementing pure intraday trading system with target and stoploss.

Pine Script V6 AI Masterclass

TRADINGVIEW

Pine Script V6 AI Masterclass

Write, debug and backtest TradingView indicators and strategies faster with AI as your coding partner.

  • Pine Script V6 from the ground up
  • Indicators, strategies and alerts
  • AI-assisted coding workflow

Here is a simple Intraday Trading System Module. Sort of a Coding Snippet to create your own intraday trading system with the following signals

  1. Buy Signal
  2. Sell Signal
  3. Stop Exit
  4. Target Exit
  5. Square.Off Exit

Note: It is not a Tradingview strategy but more of visual indications. Kindly use the module to build your strategy on top of this code. For simplicity purpose explained with EMA crossover strategy.

Intraday Trading System: Pine Script v4 Module (Visual Stop and Target Levels)

// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © marketcalls_in
//Coded by Rajandran R (Founder - Marketcalls/Co-Founder - Algomojo)

//@version=4
study("Simple Intraday Trading System",overlay=true)

ema1 = input(title="Fast EMA",type = input.integer, defval=5,minval=1,maxval=200)
ema2 = input(title="Slow EMA",type = input.integer, defval=10,minval=1,maxval=200)
TradeTime = input(title="Trade Timings",defval="0930-1500", type=input.session)
SqoffTime = input(title="Squareoff Timings",defval="1515-1530", type=input.session)
stop = input(title="Stoploss (Points)",type = input.integer, defval=30,minval=1,maxval=1000,step=0.05)
target = input(title="Target (Points)",type = input.integer, defval=20,minval=1,maxval=1000,step=0.05)
displayema = input(title="Display EMA",type=input.bool,defval=true)

Barsinsession(TradeTime) => time(timeframe.period,TradeTime) != 0



Insession = Barsinsession(TradeTime) ? 1 : 0
endofsession = Insession == 0 and Insession[1] == 1  


Sqsession = Barsinsession(SqoffTime) ? 1 : 0
SqTime = Sqsession == 1 and Sqsession[1] ==0



Buy = crossover(ema(close,ema1),ema(close,ema2)) and Insession
Sell = (crossunder(ema(close,ema1),ema(close,ema2)) and Insession) or SqTime


BuyPrice = valuewhen(Buy,close,0)


targetprice = BuyPrice + target
stopprice = BuyPrice - stop

emacrossexit = crossunder(ema(close,20),ema(close,50))
Targethit = crossover(high,targetprice)
Stophit = crossunder(low,stopprice)

Sell := Sell or Targethit or Stophit

exitprice = valuewhen(emacrossexit or SqTime,close,0)
targetexitprice = valuewhen(Targethit,targetprice,0)
stopexitprice = valuewhen(Stophit,stopprice,0)


newday = dayofmonth != dayofmonth[1]

var isLong = false
var isSell = false

//Removing Excessive Signals
Buy := not isLong and Buy
Sell := not isSell and Sell

if Buy
    isLong := true
    isSell := false

if Sell
    isLong := false
    isSell := true
    
    
//flip
buycontinue = barssince(Buy) < barssince(Sell)
sellcontinue = barssince(Sell) < barssince(Buy)



plot(buycontinue? targetprice : na,color=color.blue,style=plot.style_circles,linewidth=1 )
plot(buycontinue? stopprice : na,color=color.red,style=plot.style_circles,linewidth=1 )



plotshape(Buy,style=shape.labelup,location = location.belowbar,color=color.green,title = "Buy",text="Buy",textcolor=color.white)

plotshape(Sell and not SqTime and not Targethit and not Stophit,style=shape.labeldown,location = location.abovebar,color=color.red,title = "Sell",text="Sell",textcolor=color.white)
plotshape(Sell and SqTime and not Targethit and not Stophit,style=shape.labeldown,location = location.abovebar,color=color.orange,title = "Squareoff.Exit",text="Squareoff.Exit ",textcolor=color.white)

plotshape(Sell and not SqTime and Targethit and not Stophit,style=shape.labeldown,location = location.abovebar,color=color.blue,title = "Sell",text="Target.Exit",textcolor=color.white)
plotshape(Sell and not SqTime and not Targethit and Stophit,style=shape.labeldown,location = location.abovebar,color=color.red,title = "Squareoff.Exit",text="Stop.Exit",textcolor=color.white)



plot(displayema ? ema(close,ema1) : na,color=color.aqua,style=plot.style_line,linewidth=1)
plot(displayema ? ema(close,ema2) : na,color=color.lime,style=plot.style_line,linewidth=1)

How the code works

  • Session filter: time(timeframe.period, TradeTime) returns na outside the session, so Insession is 1 only between 9:30 and 15:00. SqTime is true on the first bar of the 15:15 to 15:30 window.
  • Entry price: valuewhen(Buy, close, 0) stores the close of the buy bar; target and stop are measured in points from it.
  • Exit detection: crossover(high, targetprice) and crossunder(low, stopprice) flag the bar where price touches the levels.
  • Signal cleaning: the isLong and isSell flags stop repeated buy or sell labels while a trade is already open or closed.
  • Labels: each exit type has its own plotshape colour so you can see at a glance why a trade closed.

Use a chart timeframe that divides the session cleanly (1, 3, 5 or 15 minutes). On NSE the market opens at 9:15 am, so the first 15 minutes are skipped by the 9:30 start time.

Updated version (2026): Pine Script v6 indicator

TradingView released Pine Script v6 on 10 December 2024 (TradingView announcement). Scripts written in v4 still run, but new features only come to the latest version. This v6 version keeps the same rules and labels, uses input.int, input.float and input.session, the ta. namespace, and stores the trade state in var variables. Because v6 evaluates and/or lazily, the EMA crossovers are calculated on their own lines so they update on every bar. Alert conditions are added for webhook automation.

//@version=6
indicator("Simple Intraday Trading System (v6)", overlay = true)

// Inputs
ema1       = input.int(5, "Fast EMA", minval = 1, maxval = 200)
ema2       = input.int(10, "Slow EMA", minval = 1, maxval = 200)
TradeTime  = input.session("0930-1500", "Trade Timings")
SqoffTime  = input.session("1515-1530", "Squareoff Timings")
stop       = input.float(30, "Stoploss (Points)", minval = 0.05, step = 0.05)
target     = input.float(20, "Target (Points)", minval = 0.05, step = 0.05)
displayema = input.bool(true, "Display EMA")

// Session helpers: time() returns na outside the session
inSession(sess) => not na(time(timeframe.period, sess))

Insession = inSession(TradeTime)
sqWindow  = inSession(SqoffTime)
SqTime    = sqWindow and not sqWindow[1]          // first bar of the square-off window

// Indicators are calculated on every bar (v6 evaluates and/or lazily)
fastEma   = ta.ema(close, ema1)
slowEma   = ta.ema(close, ema2)
bullCross = ta.crossover(fastEma, slowEma)
bearCross = ta.crossunder(fastEma, slowEma)

// Trade state
var bool  inTrade  = false
var float BuyPrice = na

Buy = not inTrade and Insession and bullCross
if Buy
    inTrade  := true
    BuyPrice := close

targetprice = BuyPrice + target
stopprice   = BuyPrice - stop

// Exits are checked from the bar after entry
Stophit   = inTrade and not Buy and low <= stopprice
Targethit = inTrade and not Buy and high >= targetprice and not Stophit
SqExit    = inTrade and not Buy and SqTime and not Stophit and not Targethit
CrossExit = inTrade and not Buy and Insession and bearCross and not Stophit and not Targethit and not SqExit

showLevels = inTrade
if Stophit or Targethit or SqExit or CrossExit
    inTrade := false

// Plots
plot(showLevels ? targetprice : na, "Target", color.blue, 1, plot.style_circles)
plot(showLevels ? stopprice : na, "Stop", color.red, 1, plot.style_circles)

plotshape(Buy, "Buy", shape.labelup, location.belowbar, color.green, text = "Buy", textcolor = color.white)
plotshape(CrossExit, "Sell", shape.labeldown, location.abovebar, color.red, text = "Sell", textcolor = color.white)
plotshape(SqExit, "Squareoff.Exit", shape.labeldown, location.abovebar, color.orange, text = "Squareoff.Exit", textcolor = color.white)
plotshape(Targethit, "Target.Exit", shape.labeldown, location.abovebar, color.blue, text = "Target.Exit", textcolor = color.white)
plotshape(Stophit, "Stop.Exit", shape.labeldown, location.abovebar, color.red, text = "Stop.Exit", textcolor = color.white)

plot(displayema ? fastEma : na, "Fast EMA", color.aqua, 1)
plot(displayema ? slowEma : na, "Slow EMA", color.lime, 1)

// Alerts for automation (for example via webhook)
alertcondition(Buy, "Buy", "Intraday Buy")
alertcondition(Stophit or Targethit or SqExit or CrossExit, "Exit", "Intraday Exit")

Updated version (2026): Pine Script intraday strategy (v6) for backtesting

As noted above, the original is a visual study, so it does not appear in the Strategy Tester. This strategy version places the target and stoploss with strategy.exit (in ticks from the actual fill price), closes on the opposite EMA cross and squares off everything at 15:15. Set the commission and quantity to match your instrument before reading the results.

//@version=6
strategy("Simple Intraday Strategy with Target and Stop (v6)", overlay = true,
     initial_capital = 100000, default_qty_type = strategy.fixed, default_qty_value = 1,
     commission_type = strategy.commission.cash_per_order, commission_value = 20)

ema1      = input.int(5, "Fast EMA", minval = 1, maxval = 200)
ema2      = input.int(10, "Slow EMA", minval = 1, maxval = 200)
TradeTime = input.session("0930-1500", "Trade Timings")
SqoffTime = input.session("1515-1530", "Squareoff Timings")
stopPts   = input.float(30, "Stoploss (Points)", minval = 0.05, step = 0.05)
targetPts = input.float(20, "Target (Points)", minval = 0.05, step = 0.05)

inTradeWindow = not na(time(timeframe.period, TradeTime))
inSqoff       = not na(time(timeframe.period, SqoffTime))

fastEma   = ta.ema(close, ema1)
slowEma   = ta.ema(close, ema2)
bullCross = ta.crossover(fastEma, slowEma)
bearCross = ta.crossunder(fastEma, slowEma)

if bullCross and inTradeWindow and strategy.position_size == 0
    strategy.entry("Long", strategy.long)

// Target and stop in ticks from the fill price; active from the entry bar
strategy.exit("TP/SL", "Long", profit = targetPts / syminfo.mintick, loss = stopPts / syminfo.mintick)

if bearCross and inTradeWindow
    strategy.close("Long", comment = "EMA Exit")

if inSqoff
    strategy.close_all(comment = "Squareoff")

plot(fastEma, "Fast EMA", color.aqua)
plot(slowEma, "Slow EMA", color.lime)

For a full walkthrough of strategy settings and the Strategy Tester, read Creating and Backtesting a TradingView Pine Script Trading Strategy.

Check the risk-reward before you trade it

Try it
Target and stoploss break-even calculator

The default inputs (30 point stop, 20 point target) need a high win rate. Change the points, quantity and costs to see what your system has to achieve.

How to customise this intraday template

  • Replace the entry logic: swap the EMA crossover for your own condition (Supertrend, VWAP cross, opening range breakout). Keep the session and exit code as is.
  • Use ATR based stops: replace the fixed points with a multiple of ta.atr(14) so the stop adapts to volatility.
  • Add short trades: mirror the logic with ta.crossunder, a short entry, and target below and stop above the entry.
  • Automate it: connect the alert conditions to your broker through a webhook. See TradingView webhook automation with a buy/sell/short/cover module for an example.

Common mistakes with intraday Pine Script systems

  • Wrong exchange time zone: sessions use the symbol’s exchange time. On an NSE symbol that is IST; on a crypto or US symbol the 0930-1500 window means something else.
  • Trusting labels on the current bar: a target or stop label can appear and disappear while the bar is still forming. Act on confirmed bars or use the strategy version.
  • Both target and stop inside one bar: on a wide candle the script cannot know which level was hit first. The v6 indicator assumes the stop (the conservative choice); use a lower timeframe to reduce this.
  • Ignoring costs: on a 20 point target, brokerage, STT and slippage take a real share of each winner.

Frequently Asked Questions

How do I add stoploss and target in Pine Script?

In a strategy, call strategy.exit() with profit and loss in ticks or with limit and stop prices. In an indicator, store the entry price in a var variable, calculate target and stop from it, and check high and low against those levels on each bar, as in the code above.

How do I square off intraday positions at a fixed time in Pine Script?

Define a session input such as “1515-1530” and check not na(time(timeframe.period, session)). On the first bar inside that window, close all positions with strategy.close_all() in a strategy or plot an exit label in an indicator.

Will my old Pine Script v4 code still work?

Yes. TradingView continues to run scripts written in earlier versions, but new features are only added to the latest version. Use the “Convert code to v6” option in the Pine Editor and fix any remaining errors by hand.

Which timeframe is best for a Pine Script intraday strategy?

The 5 minute chart is a common starting point for Nifty and Bank Nifty futures. Test 3, 5 and 15 minutes in the Strategy Tester and keep the one that is stable across months, not just the most profitable.

Marketcalls Elite Traders Club

MEMBERSHIP

Marketcalls Elite Traders Club

Every Marketcalls course and live mentorship in one membership: 127 courses and 2,500+ hours of learning.

  • Market Profile, Orderflow, AFL, Pine Script and Python
  • Live mentorship and TradEdge trading room
  • Premium tools and the Elite Slack community

Learn by watching: free videos every week

Market Profile, order flow, Python, AI and OpenAlgo tutorials on YouTube.

Rajandran R Creator of OpenAlgo Sketchmaker, RagZ. Building GenAI Applications. Telecom Engineer turned Full-time Derivative Trader. Mostly Trading Nifty, Banknifty, High Liquid Stock Derivatives. Trading the Markets Since 2006 onwards. Using Market Profile and Orderflow for more than a decade. Designed and published 100+ open source trading systems on various trading tools. Now the recent curiosity on building Trading AI Agents.

2 Replies to “Code Snippet – Simple Intraday Trading System with Target…”

  1. Super script sir, how can we get buy signal candle low is stop loss and target buy signal low +high total sum is target, ple help me sir

Leave a Reply

Get Notifications, Alerts on Market Updates, Trading Tools, Automation & More