Strategy · Pine Script v5 · On the chart

Morning Scalp

by benso87

This strategy tracks an opening session time range to establish directional bias and triggers pullback trades using Stochastic RSI.

View on GitHub

GitHub stars24on the repository
Pine versionv5runs as is
Lines of code174
Settings14inputs
LicenceMPL-2.0
Last update4 years ago5 Oct 2022

Add It to Your TradingView Chart

  1. 1Copy the scriptPress Copy script above, or the copy button on the code below.
  2. 2Open the Pine EditorOpen a TradingView chart and choose Pine Editor at the bottom of the screen.
  3. 3Paste over the templateCreate a new strategy, select all of the template text and paste. Press Save and give it a name.
  4. 4Add it to the chartPress Add to chart. The trades and results appear in the Strategy Tester tab; adjust the settings with the gear icon.

Source Code

174 lines of Pine Script v5 from Morning Scalp Strategy.pine, published under MPL-2.0. Keep the author's credit and licence lines when you reuse it.

Morning Scalp Strategy.pine
//@version=5
//
// Author: benso87
// benso87.com
//
//
strategy("Morning Scalp", overlay=true, initial_capital=1000, default_qty_value=100, default_qty_type=strategy.percent_of_equity, process_orders_on_close=true, backtest_fill_limits_assumption=1, pyramiding=0)

noColor = color.new(color.white, transp=100)
////////////////////////////////////////////////////////////
// Inputs

//Dates
// startDate    = input.time    (timestamp('1 Jan 2022 00:00'), title='Start', group='Dates')
// endDate        = input.time    (timestamp('1 Jan 2100 00:00'), title='End', group='Dates')
useWknd = input.bool(false, title='Include Weekends', group='Dates')

// Range Time
timeRange = input.session('0900-0930', title='Session', group='Range Time')
endOfDayIn = input.session('1600-1700', title='End of Day', group='Range Time')

// Targets
slType = input.string('Pips', title='Stop Loss Type', options=['Pips', 'Range', 'Percent'], group='Targets')
slPips = input.int(90, title='Stop Loss Pips', group='Targets')
slPct = input.float(1, title='Stop Loss %', group='Targets')
rrRatio = input.float(2, title='Reward:Risk Ratio', group='Targets')

// Stoch RSI
smoothK = input.int(3, "K", minval=1, group='Stoch RSI')
smoothD = input.int(3, "D", minval=1, group='Stoch RSI')
lengthRSI = input.int(14, "RSI Length", minval=1, group='Stoch RSI')
lengthStoch = input.int(14, "Stochastic Length", minval=1, group='Stoch RSI')
src = input(close, title="RSI Source", group='Stoch RSI')
sHigh = input.float(70, title='Overbought', minval=0, maxval=100, group='Stoch RSI')
sLow = input.float(30, title='Oversold', minval=0, maxval=100, group='Stoch RSI')


////////////////////////////////////////////////////////////
// Calculations

// Time range
inRange = time == time(timeframe.period, timeRange)
endOfDay = time == time(timeframe.period, endOfDayIn)

// Weekends
isWknd = dayofweek == dayofweek.saturday or dayofweek == dayofweek.sunday
wkndCheck = not isWknd or useWknd

// Find high and low in time range
var float rangeHigh = na
var float rangeLow = na

rangeHigh := wkndCheck and inRange and high > rangeHigh ? high : inRange and not inRange[1] ? high : rangeHigh
rangeLow := wkndCheck and inRange and low < rangeLow ? low : inRange and not inRange[1] ? low : rangeLow
rangeDiff = rangeHigh - rangeLow

outOfPriceRange = close < rangeLow or close > rangeHigh

// Stoch RSI
rsi1 = ta.rsi(src, lengthRSI)
k = ta.sma(ta.stoch(rsi1, rsi1, rsi1, lengthStoch), smoothK)
d = ta.sma(k, smoothD)

overbought = k >= sHigh
oversold = k <= sLow

crossup = ta.crossover(k, d)
crossdown = ta.crossunder(k, d)

// Determine direction
var string bias = na

if not inRange and bias == na
    if close > rangeHigh
        bias := 'long'
    else if close < rangeLow
        bias := 'short'

bias := inRange and not inRange[1] ? na : bias

// Entries
var bool tradedToday = na

longEntry = bias == 'long' and outOfPriceRange and oversold and crossup and not tradedToday
shortEntry = bias == 'short' and outOfPriceRange and overbought and crossdown and not tradedToday

// Trade variables
var float entryPrice = na
var float slLong = na
var float slShort = na
var float tpLong = na
var float tpShort = na
var int loss = na
var int profit = na
var string tradeType = na

if longEntry and strategy.position_size == 0
    entryPrice := close
    slLong := slType == 'Range' ? entryPrice - rangeDiff : slType == 'Percent' ? entryPrice - (entryPrice * slPct / 100) : na
    tpLong := slType == 'Range' or slType == 'Percent' ? entryPrice + ((entryPrice - slLong) * rrRatio) : na
    loss := slType == 'Pips' ? slPips : na
    profit := slType == 'Pips' ? math.round(slPips * rrRatio) : na
    tradeType := 'long'

if shortEntry and strategy.position_size == 0
    entryPrice := close
    slShort := slType == 'Range' ? entryPrice + rangeDiff : slType == 'Percent' ? entryPrice + (entryPrice * slPct / 100) : na
    tpShort := slType == 'Range' or slType == 'Percent' ? entryPrice + ((entryPrice - slShort) * rrRatio) : na
    loss := slType == 'Pips' ? slPips : na
    profit := slType == 'Pips' ? math.round(slPips * rrRatio) : na
    tradeType := 'short'

stopLoss = tradeType == 'long' ? slLong : tradeType == 'short' ? slShort : na
stopLossPips = tradeType == 'long' ? entryPrice - loss * syminfo.mintick : tradeType == 'short' ? entryPrice + loss * syminfo.mintick : na
takeProfit = tradeType == 'long' ? tpLong : tradeType == 'short' ? tpShort : na
takeProfitPips = tradeType == 'long' ? entryPrice + profit * syminfo.mintick : tradeType == 'short' ? entryPrice - profit * syminfo.mintick: na


//////////////////////////////////////////////////////////////
// Strategy

// Entries
strategy.entry('Long', strategy.long, when=longEntry)
strategy.entry('Short', strategy.short, when=shortEntry)

// Exits
if slType == 'Range' or slType == 'Percent'
    strategy.exit('Long Exit', from_entry='Long', stop=slLong, limit=tpLong)
    strategy.exit('Short Exit', from_entry='Short', stop=slShort, limit=tpShort)
else
    strategy.exit('Long Exit', from_entry='Long', loss=loss, profit=profit)
    strategy.exit('Short Exit', from_entry='Short', loss=loss, profit=profit)

// Close at end of day
strategy.close_all(when=endOfDay)

tradedToday := longEntry[1] or shortEntry[1] ? true : inRange and not inRange[1] ? false : tradedToday


////////////////////////////////////////////////////////////
// Plots

// Plot range
bgcolor(wkndCheck and inRange ? color.new(color.blue, transp=70) : na)

// Range highs and lows
plot(not tradedToday ? rangeHigh : na, title='Range High', color=color.green, style=plot.style_linebr)
plot(not tradedToday ? rangeLow : na, title='Range Low', color=color.red, style=plot.style_linebr)

// Trades
stopLossPlot = slType == 'Pips' ? stopLossPips : stopLoss
takeProfitPlot = slType == 'Pips' ? takeProfitPips : takeProfit 

sl = plot(strategy.position_size != 0 or strategy.position_size[1] != 0 ? stopLossPlot : na, title='Stop Loss', color=color.red, style=plot.style_linebr)
e = plot(strategy.position_size != 0 or strategy.position_size[1] != 0 ? entryPrice : na, title='Entry', color=color.yellow, style=plot.style_linebr)
tp = plot(strategy.position_size != 0 or strategy.position_size[1] != 0 ? takeProfitPlot : na, title='Take Profit', color=color.green, style=plot.style_linebr)

fill(sl, e, color=color.new(color.red, transp=80))
fill(tp, e, color=color.new(color.green, transp=80))


//////////////////////////////////////////////////////////////
// Testing

plotchar(longEntry, title='long signal', location=location.abovebar, color=color.new(color.white, transp=100))
plotchar(shortEntry, title='short signal', location=location.abovebar, color=color.new(color.white, transp=100))
plotchar(inRange, title='in range', location=location.abovebar, color=color.new(color.white, transp=100))

plotchar(stopLoss, title='SL', location=location.abovebar, color=color.new(color.white, transp=100))
plotchar(takeProfit, title='TP', location=location.abovebar, color=color.new(color.white, transp=100))
plotchar(loss, title='loss', location=location.abovebar, color=color.new(color.white, transp=100))
plotchar(profit, title='profit', location=location.abovebar, color=color.new(color.white, transp=100))

plotchar(tradedToday, title='traded today', location=location.abovebar, color=color.new(color.white, transp=100))

Overview

Once price breaks out of the initial range, it establishes a directional bias and enters when the Stochastic RSI crosses over in oversold territory for long trades or crosses under in overbought territory for short trades. Position exits are managed using customizable stop loss types (range, percent, or pips), a fixed risk-to-reward take profit target, and an end-of-day session close. It executes trades directly on the price chart.

Details

Published by

benso87 on GitHub

Type

Strategy, Pine Script v5

Draws

On the price chart

Category

Sessions & time, Breakout, Oscillators & momentum, Scalping

Markets

Any symbol

Timeframes

M1-M5, M15-H1

Risk Notes

No repainting, lookahead or stacked entries were found in its code or README. That says nothing about how well it works: test it first.

Settings

The inputs you can change from the gear icon on the chart. Defaults are the author's.

SettingTypeDefaultVariable
Include WeekendsboolfalseuseWknd
Sessionsession0900-0930timeRange
End of Daysession1600-1700endOfDayIn
Stop Loss TypestringPipsslType
Stop Loss Pipsint90slPips
Stop Loss %float1slPct
Reward:Risk Ratiofloat2rrRatio
Kint3smoothK
Dint3smoothD
RSI Lengthint14lengthRSI
Stochastic Lengthint14lengthStoch
RSI Sourcesourceclosesrc
Show all 14 settings
SettingTypeDefaultVariable
Overboughtfloat70sHigh
Oversoldfloat30sLow
Third-party code. ForexR did not write, test or endorse this script, and the summary above was generated automatically from its code and README. Indicators describe the past, and a strategy's backtest can look better than live trading, especially when a script repaints. Check it in the Strategy Tester and on a demo account before you rely on it.

Similar Pine Scripts

53 stars

This strategy enters long or short on the price chart when price is on the correct side of a 200-period EMA, MACD agrees, RSI is not at the opposing extreme, ADX exceeds a threshold, volume beats a 20-bar average, and close breaks the recent high or low. A tim

Strategy v6 TrendOscillators & momentum
Updated 2 months ago · MPL-2.0 GitHub repository of BTCUSD 5M Optimized Strategy

Turtle MACD Time-Zone Filter

by skywalker0803r
42 stars

This strategy enters long when price closes above the prior Donchian high and short when it closes below the prior Donchian low, only while flat and inside a Taipei-hour window. It exits on a MACD histogram reversal or through an ATR stop and a percentage take

Strategy v5 BreakoutOscillators & momentum
Updated 2 months ago · None stated GitHub repository of Turtle MACD Time-Zone Filter
10 stars

The Reverse RSI Strategy is a scalping system designed for forex pairs during specific trading sessions. It combines a smoothed RSI indicator with five Exponential Moving Averages to identify mean-reversion trade opportunities. Position sizing dynamically adju

Strategy v4 Oscillators & momentumMoving averages
Updated 3 years ago · GPL-3.0 GitHub repository of Strategy - Reverse RSI

ORB + Fib + MACD Strategy

by alboogycOdR
6 stars

This strategy builds a timed opening range and tracks session high and low on the price chart. It flags bullish and bearish breakouts of that range and uses Fibonacci levels for an entry zone, a default stop, and an optional take-profit extension. Take profit

Strategy v5 BreakoutSupport & resistance
Updated 7 months ago · None stated GitHub repository of ORB + Fib + MACD Strategy
3 stars

This strategy evaluates price movement over a specified lookback period against custom percentage or price change thresholds. It generates buy or sell signals when movement rules are met, overlaid directly on the price chart. Users can customize entry criteria

Strategy v5 BreakoutOscillators & momentum
Updated 5 months ago · None stated GitHub repository of Bars%Move Strategy

Gap and Go

by Basant1Saini
1 stars

This strategy trades opening gap continuation on the price chart. It measures the gap between the daily open and the prior daily close, then enters long after a qualifying gap up or short after a qualifying gap down when price stays beyond the open and a trend

Strategy v5 BreakoutOscillators & momentum Repaints
Updated 7 months ago · None stated GitHub repository of Gap and Go

More strategys

Trade Your Charts With a Regulated Broker

Compare brokers that connect to TradingView, with spreads, minimum deposits and leverage side by side.

Compare brokers