0

I've composed a simple script and want to insert a couple of conditions to close the trade. Either it hits the stop loss / take profit or after 30mins the trade is closed.

I have done the the stop loss / take profit part, I need assistance with closing the trade after 30mins?

strategy("S1", overlay=true)

source = close
length = input(20, minval=1)
mult = input(1.0, minval=0.001, maxval=50)

basis = sma(source, length)

sl_inp = input(100, title='Stop Loss in Ticks')
tp_inp = input(200, title='Take Profit in Ticks')


strategy.entry("buy", true, 1, when = crossover(close[0],basis))
strategy.exit("buy", loss=sl_inp, profit=tp_inp)
hello11
  • 115
  • 4
  • 15

1 Answers1

0

Try this out. Please note that depending on timeframe that the strategy tester may show a slightly different time duration if only the time portion is used. This is due to the way the strategy.close function is calculated on the historical bar. If a condition became true mid-bar, it will show an exit at the close of the bar. In real time it will exit as soon as the condition is true.

//@version=4
strategy("S1", overlay=true)

source = close
length = input(20, minval=1)
mult = input(1.0, minval=0.001, maxval=50)

basis = sma(source, length)

sl_inp = input(100, title='Stop Loss in Ticks')
tp_inp = input(200, title='Take Profit in Ticks')

var TIME = 0.0
FLAT = strategy.position_size == 0
LONG = strategy.position_size > 0

if crossover(close,basis) and FLAT
    strategy.entry("buy", true, 1)
    TIME := time

if (time - TIME) > 1.8e+6
    strategy.close("buy", comment="Time out")

if FLAT and LONG[1]
    TIME := 0.0

strategy.exit("buy", loss=sl_inp, profit=tp_inp, comment="Exit")
Dharman
  • 30,962
  • 25
  • 85
  • 135
Bjorgum
  • 2,054
  • 2
  • 4
  • 11