Implementing a Dynamic Trailing Stop in Trading Automation

13 Oct 2022
0 comment
0 attachment

This code snippet demonstrates how to implement a dynamic trailing stop mechanism for automated trading strategies. A trailing stop is used to protect gains by enabling a trade to remain open and continue to profit as long as the price is moving in the favorable direction, but closes the trade if the price changes direction by a specified amount.


// trailing stop function
trailingstart = 10 //10 trailing will start @trailinstart points profit
trailingstep = 5 //5 trailing step to move the "stoploss"

//reset the stoploss value
IF NOT ONMARKET THEN
    newSL=0
ENDIF

//manage long positions
IF LONGONMARKET THEN
    //first move (breakeven)
    IF newSL=0 AND HIGH-tradeprice(1)>=trailingstart*pipsize THEN
        //close --> HIGH
        newSL = tradeprice(1)+trailingstep*pipsize
        // new coding
        IF newSL > close THEN
            //if current closing price is < new SL then exit IMMEDIATELY!
            SELL AT MARKET
        ENDIF
        // end new coding
    ENDIF

    //next moves
    IF newSL>0 AND close-newSL>=trailingstep*pipsize THEN
        newSL = newSL+trailingstep*pipsize
        // new coding
        IF newSL > close THEN
            //if current closing price is < new SL then exit IMMEDIATELY!
            SELL AT MARKET
        ENDIF
        // end new coding
    ENDIF
ENDIF

//manage short positions
IF SHORTONMARKET THEN
    //first move (breakeven)
    IF newSL=0 AND tradeprice(1)-LOW>=trailingstart*pipsize THEN
        //close --> LOW
        newSL = tradeprice(1)-trailingstep*pipsize
        // new coding
        IF newSL < close THEN
            //if current closing price is > new SL then exit IMMEDIATELY!
            EXITSHORT AT MARKET
        ENDIF
        // end new coding
    ENDIF

    //next moves
    IF newSL>0 AND newSL-close>=trailingstep*pipsize THEN
        newSL = newSL-trailingstep*pipsize
        // new coding
        IF newSL < close THEN
            //if current closing price is > new SL then exit IMMEDIATELY!
            EXITSHORT AT MARKET
        ENDIF
        // end new coding
    ENDIF
ENDIF

//stop order to exit the positions
IF newSL>0 THEN
    SELL AT newSL STOP
    EXITSHORT AT newSL STOP
ENDIF

The code is structured to manage both long and short positions in the market:

  • Initialization: The trailing stop parameters are set, and the stop loss value is reset if not in the market.
  • Long Position Management: For long positions, the code checks if the high price minus the trade price has reached the trailing start threshold to adjust the stop loss (newSL). If the new stop loss is greater than the closing price, the position is sold at market price.
  • Short Position Management: For short positions, the logic is similar but inverted. It checks if the trade price minus the low price has reached the trailing start threshold to adjust the stop loss. If the new stop loss is less than the closing price, the short position is exited at market price.
  • Stop Order Execution: Finally, if there is an active new stop loss, the code places a stop order to exit the positions accordingly.

This approach ensures that the trailing stop adjusts dynamically based on price movements, aiming to protect gains while allowing profitable positions to run.

Related Post

Check out this related content for more information:

https://www.prorealcode.com/topic/modified-nicolas-trailing-stop-code/#post-73306

Visit Link
What is a Snippet? A snippet is a small, reusable chunk of code designed to solve specific tasks quickly. Think of it as a shortcut that helps you achieve your coding goals without reinventing the wheel. How to Use: Simply copy the snippet and paste it into your project where needed. Don't forget to tweak it to fit your context. Snippets are not just time-savers; they're also learning tools to help you become a more efficient coder.
robertogozzi Master
Roberto https://www.ots-onlinetradingsoftware.com
Author’s Profile

Comments

Search Snippets

Showing some results...
Sorry, no result found!

Snippets Categories

global
35
indicator
133
strategy
171

Recent Snippets

How to Create a Simple MTF Trend Dashboard with EMA and SMA
indicator
This indicator builds a compact multi-timeframe (MTF) dashboard that shows whether price is trading above or below a [...]
How to Display Per-Bar Volume Accumulation in Real Time (Intrabar Updates)
global
This snippet tracks and displays the current bar’s accumulated volume while the bar is still forming, instead of only [...]
Ticks Counter: Count Tick Updates Per Bar on Tick or Time Charts
global
This snippet counts how many tick updates have occurred for the current bar by incrementing a per-bar counter on each [...]
How to Build a Step-Based Trailing Stop That Moves to Break-Even First
strategy
This snippet implements a step trailing stop that advances in fixed increments once price reaches predefined profit [...]
Utilizing Arrays to Track and Compare Indicator Values Within the Same Bar in ProBuilder
indicator
This ProBuilder code snippet demonstrates how to use arrays to compare the values of an indicator (RSI in this case) [...]
Logo Logo
Loading...