Balaram64x
Pine Script Rookie
Pine Script Rookie
Posts: 1
Joined: August 9th, 2022

Example of a simple strategy

Hello, please tell me an example of a simple strategy. I need the price to be compared every day from 12:00 to 13:00 if it has grown, then a long opens from 13:00. If the price has fallen, then the shorts will open from 13:00. The position is closed 3 hours after the position is opened.

zwp
Pine Script Scholar
Pine Script Scholar
Posts: 17
Joined: September 18th, 2021
Contact: TradingView Profile

Re: Example of a simple strategy

Hello,
here is my solution to your request. Happy to get feedback

Code: Select all

//@version=5
strategy("daily price comparison", overlay=true)
//get user input
i_timeStart = input.float(12.00, 'starting time of session')
i_timeEnd = input.float(13.00, 'starting time of session')
i_tradeDuration = input.float(3.00, 'How long do you want to hold to your trade?')

//get variables
var float priceStart = na
var float priceEnd   = na
var inTrade          = false

//new day filter - we want to have one trade per day on our conditions
isNewDay = ta.change(dayofweek)
bgcolor(isNewDay ? color.new(color.gray, 90) : na)

//get time stamps for start, end and exit time based on user input
timeStart = hour(time_close) == i_timeStart and barstate.isconfirmed
timeEnd = hour(time_close) == i_timeEnd and barstate.isconfirmed
timeSellValue = i_timeEnd + i_tradeDuration
timeSell = hour(time_close) == timeSellValue and barstate.isconfirmed

plotshape(timeStart)
plotshape(timeEnd)
plotshape(timeSell, color=color.red)

//assign prices from timeStart and timeEnd
if timeStart
    priceStart := close
if timeEnd
    priceEnd := close

plot(priceStart, color=na)
plot(priceEnd, color=na)

//long and short buying orders conditions
longBO = timeEnd and priceStart < priceEnd and inTrade == false
shortBO = timeEnd and priceStart > priceEnd and inTrade == false

//strategy orders
if longBO
    strategy.entry('long', strategy.long)
    inTrade := true

if shortBO
    strategy.entry('short',strategy.short)
    inTrade := true

if timeSell
    strategy.close_all('close')

//filter making sure we have only 1 order per day
if isNewDay
    inTrade := false

Return to “Request Scripts”