Untitled

mail@pastecode.io avatarunknown
plain_text
2 months ago
1.8 kB
2
Indexable
Never
//@version=4
strategy("Dynamic Stop Loss Example", overlay=true)

// Define parameters
takeProfitPercent = 0.01 // 1% - Take profit percentage
stopLossPercent = 0.005 // 0.5% - Initial stop loss percentage
moveToBreakEvenThreshold = 0.0025 // 0.25% - Threshold to move stop loss to breakeven

// Calculate moving averages
fastMA = sma(close, 10)
slowMA = sma(close, 50)

// Define long and short entry conditions
longCondition = crossover(fastMA, slowMA)
shortCondition = crossunder(fastMA, slowMA)

// Enter long position when long condition is met
strategy.entry("Long", strategy.long, when=longCondition)

// Check if there is an open position
if (strategy.position_size > 0)
    initialPrice = strategy.position_avg_price // Get initial entry price
    currentPrice = close // Get current close price
    
    // Calculate current gain/loss percentage
    currentPLPercent = (currentPrice - initialPrice) / initialPrice
    
    // Calculate distance from initial price to take profit
    takeProfitDistance = abs(currentPrice - initialPrice * (1 + takeProfitPercent))
    
    // Calculate distance from initial price to break-even point
    breakEvenDistance = abs(initialPrice * (1 + moveToBreakEvenThreshold) - initialPrice)
    
    // Move stop loss to breakeven if price moves in your favor
    if currentPLPercent >= moveToBreakEvenThreshold
        strategy.exit("StopLoss", from_entry="Long", stop=initialPrice, when=currentPLPercent >= moveToBreakEvenThreshold)
    
    // Adjust stop loss to lock in profits as price moves towards take profit
    if currentPLPercent >= takeProfitPercent
        newStopLossPrice = initialPrice + takeProfitDistance - breakEvenDistance
        strategy.exit("TakeProfit", from_entry="Long", stop=newStopLossPrice, when=currentPLPercent >= takeProfitPercent)