Untitled

 avatar
unknown
plain_text
a year ago
2.4 kB
5
Indexable
//@version=5
strategy(title="Take profit (% of instrument price)",
     overlay=true, pyramiding=3, backtest_fill_limits_assumption=1)

// STEP 1:
// Make inputs that set the take profit % (optional)
longProfitPerc = input.float(0.3, title="Long Take Profit (%)",
     minval=0.0, step=0.1) * 0.01

shortProfitPerc = input.float(0.3, title="Short Take Profit (%)",
     minval=0.0, step=0.1) * 0.01

// Calculate moving averages
fastSMA = ta.sma(close, 20)
slowSMA = ta.sma(close, 60)

// Calculate trading conditions
enterLong  = ta.crossover(fastSMA, slowSMA)
enterShort = ta.crossunder(fastSMA, slowSMA)

// STEP 2:
// Figure out take profit price
// Check if it's the first bar of the position
isFirstBar = bar_index == strategy.opentrades.entry_bar_index(0)

// var float longExitPrice = na
// var float shortExitPrice = na

// if enterLong and strategy.position_size == 0
firstBarLongTP = (close * longProfitPerc) / syminfo.mintick
laterBarLongTP = strategy.position_avg_price * (1 + longProfitPerc)

// if enterShort and strategy.position_size == 0
firstBarShortTP = (close * shortProfitPerc) / syminfo.mintick
laterBarShortTP = strategy.position_avg_price * (1 - shortProfitPerc)
    


// Submit entry orders
if enterLong and strategy.position_size == 0
    strategy.entry("Entry Long", strategy.long)

if enterShort and strategy.position_size == 0
    strategy.entry("Entry Short", strategy.short)

// STEP 3:
// Submit exit orders based on take profit price
// if strategy.position_size > 0
if isFirstBar
    strategy.exit("Exit Long", from_entry="Entry Long", profit=firstBarLongTP)
    strategy.exit("Exit Short", from_entry="Entry Short", profit=firstBarShortTP)
   
else 
    strategy.exit("Exit Long", from_entry="Entry Long", limit=laterBarLongTP)
    strategy.exit("Exit Short", from_entry="Entry Short", limit=laterBarShortTP)

// if strategy.position_size < 0

// Plot take profit values for confirmation
plot(strategy.position_size > 0 ? laterBarLongTP : na,
     color=color.green, style=plot.style_linebr,
     linewidth=3, title="Long Take Profit")

plot(strategy.position_size < 0 ? laterBarShortTP : na,
     color=color.red, style=plot.style_linebr,
     linewidth=3, title="Short Take Profit")

plotshape(isFirstBar, location=location.belowbar)

plot(strategy.position_avg_price)
Editor is loading...
Leave a Comment