Untitled

 avatar
unknown
plain_text
a year ago
2.7 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
    longExitPrice := close * (1 + longProfitPerc)
//     longExitPrice := strategy.position_avg_price * (1 + longProfitPerc)


if enterShort and strategy.position_size == 0
    shortExitPrice := close * (1 - shortProfitPerc)
//     shortExitPrice := strategy.position_avg_price * (1 - shortProfitPerc)
    


// if enterLong and strategy.position_size == 0
//     if isFirstBar
//         longExitPrice := close * (1 + longProfitPerc)
//     if isFirstBar == false 
//         longExitPrice := strategy.position_avg_price * (1 + longProfitPerc)

// if enterShort and strategy.position_size == 0
//     if isFirstBar
//         shortExitPrice := close * (1 - shortProfitPerc)
//     if isFirstBar == false
//         shortExitPrice := 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
strategy.exit("Exit Long", from_entry="Entry Long", limit=longExitPrice)
  
// if strategy.position_size < 0
strategy.exit("Exit Short", from_entry="Entry Short", limit=shortExitPrice)

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

plot(strategy.position_size < 0 ? shortExitPrice : 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