Implementing a Dynamic Trailing Stop Strategy with Initial Stop Loss and Take Profit

11 Mar 2023
0 comment
0 attachment

This code snippet demonstrates how to implement a dynamic trailing stop strategy in ProBuilder language, starting from an initial stop loss position and adjusting the stop loss as the market price moves favorably. The strategy also includes a take profit condition to close trades under certain conditions.


// Definition of code parameters
DEFPARAM CumulateOrders = False // Cumulating positions deactivated

// Conditions to enter long positions
indicator1 = Average[20](close)
indicator2 = Average[100](close)
c1 = (indicator1 CROSSES under indicator2)
IF c1 AND Not OnMarket THEN
    BUY 1 CONTRACT AT MARKET
    NewSL = 0
    TSON = 0
ENDIF

// Conditions to exit long positions
indicator3 = Average[20](close)
indicator4 = Average[100](close)
c2 = (indicator3 crosses over indicator4)
IF OnMarket AND Not OnMarket[1] THEN
    NewSL = TradePrice - (A46 * PipSize)
ENDIF
If C2 AND OnMarket Then
    TSON = 1
Endif
If TSON Then
    // Stops and targets
    trailingstart = A21 //10 //trailing will start @trailinstart points profit
    trailingstep = A22 //30 //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 close-tradeprice(1)>=trailingstart*pipsize THEN
        //newSL = tradeprice(1)+trailingstep*pipsize
        //ENDIF
        //next moves
        //IF newSL>0 AND close-newSL>=trailingstep*pipsize THEN
        IF close>=NewSL+(trailingstep*pipsize*2) THEN
            newSL = newSL+trailingstep*pipsize
        ENDIF
    ENDIF
    //stop order to exit the positions
    IF newSL>0 THEN
        SELL AT newSL STOP
    ENDIF
Endif
TSOUT = Close < newSL AND C2 = 1
//GRAPH Close < newSL
SET STOP pLOSS A46 //500
set target pProfit A46*A99
//GRAPH C2
//GRAPH TSOUT
graphonprice NewSL coloured(0,0,255,255)
graphonprice tradeprice

Explanation of the Code:

  • Initial Setup: Cumulative orders are deactivated to ensure that each trade is executed independently.
  • Entry Conditions: A buy order is placed when a short-term moving average (20 periods) crosses under a long-term moving average (100 periods), indicating a potential upward trend.
  • Initial Stop Loss: When a new trade is entered, the initial stop loss is set based on a predefined number of pips (A46).
  • Trailing Stop Logic: If the market price moves favorably by twice the trailing step (defined in A22) from the current stop loss, the stop loss is adjusted upwards by the trailing step amount to secure profits.
  • Exit Conditions: The position is closed either when the stop loss is hit or when the take profit condition is met, calculated as a multiple (A99) of the initial risk (A46).
  • Graphical Representation: The new stop loss level and the trade entry price are graphically represented on the price chart for better visualization.

Related Post

Check out this related content for more information:

https://www.prorealcode.com/topic/trigger-trailing-sl-if-target-is-met/page/4/#post-198551

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...