Home Forums Trading view How can I create a trailing stop-loss in Pine Script?

How can I create a trailing stop-loss in Pine Script?

  • Author
    Posts
    • I’m creating a trading strategy in Pine Script and I want to add a trailing stop-loss to it.

      How can I create a trailing stop that automatically moves in the direction of the trade as the price moves in my favor?

      A simple example would be really helpful.

      Thanks!

    • Yes, you can create a trailing stop-loss in Pine Script using the strategy.exit() function.

      For example, if you want to trail the stop by a fixed number of points, you can use the trail_points parameter.

      //@version=6
      strategy("Trailing Stop Example", overlay = true)
      
      fastEMA = ta.ema(close, 9)
      slowEMA = ta.ema(close, 21)
      
      buyCondition = ta.crossover(fastEMA, slowEMA)
      
      if buyCondition
          strategy.entry("Long", strategy.long)
      
      strategy.exit("Trailing Stop", from_entry = "Long", trail_points = 100, trail_offset = 100)
      

      Here:

      • trail_points defines the trailing distance.
      • trail_offset defines the distance from the entry before the trailing stop starts.

      Once the trade moves in your favor, the stop-loss automatically follows the price. If the price reverses and reaches the trailing stop, the position is closed.

      You can change the trailing values according to your strategy and the instrument you are trading.

      I hope this helps!

Viewing 1 reply thread
×

Start a Discussion

Get help from the AlgoDelta community.

×

Welcome Back!

Enter your email to sign in or create an account. No passwords needed.

⚠️

Delete This?

Are you sure you want to delete this? This action is permanent and cannot be undone.

Scroll to Top