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

Asked by Radhesh Joshi · SOLVED
1 reply 457 views Jump to solution Reply
Radhesh Joshi Original Post
Strategy Builder

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!

Posted Aug 10
Reply

    1 Reply

    Tech Support AlgoDelta
    Tech Support AlgoDelta Automation Expert ·

    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!

    Verified Solution
      Markdown supported · ```json for code blocks · paste or drop screenshots

      Be specific and kind. Never share API keys, passwords or personal account details.

      Welcome to the community

      Log in or create your account in under a minute.

      1. 1Mobile
      2. 2E-mail
      3. 3Password
      +91

      Have a password?

      By continuing you agree to the community guidelines. We’ll send a one-time code by SMS.