Implementing a Trailing Stop Strategy for Cumulative Positions in Trading

21 Jun 2019
0 comment
0 attachment

This code snippet demonstrates how to implement a trailing stop strategy for cumulative positions in trading using the ProBuilder language. A trailing stop is a type of stop-loss order that moves with the market price and is designed to protect gains by enabling a trade to remain open and continue to profit as long as the price is moving in the investor’s favor. The code specifically handles the complexity of adjusting the stop-loss level when additional positions are cumulated.


//*********************************************************************************
// https://www.prorealcode.com/blog/trading/complete-trailing-stop-code-function/
//
// trailing stop function
//-------------------------------------------------------------
//reset the stoploss value
IF NOT ONMARKET THEN
    NewSL = 0
    MyPositionPrice = 0
ENDIF
//-------------------------------------------------------------
// Update locked in profit, if any, after comulating positions
PositionCount = abs(CountOfPosition)
IF NewSL > 0 THEN
    IF PositionCount > PositionCount[1] THEN
        IF LongOnMarket THEN
            NewSL = max(NewSL,PositionPrice * NewSL / MyPositionPrice)
        ELSE
            NewSL = min(NewSL,PositionPrice * NewSL / MyPositionPrice)
        ENDIF
    ENDIF
ENDIF
//-------------------------------------------------------------
trailingstart = 20 //trailing will start @trailinstart points profit
trailingstep = 5 //trailing step to move the "stoploss"
//manage long positions
IF LONGONMARKET THEN
    //first move (breakeven)
    IF newSL=0 AND close-PositionPrice>=trailingstart*pipsize THEN
        newSL = PositionPrice+trailingstep*pipsize
    ENDIF
    //next moves
    IF newSL>0 AND close-newSL>=trailingstep*pipsize THEN
        newSL = newSL+trailingstep*pipsize
    ENDIF
ENDIF
//manage short positions
IF SHORTONMARKET THEN
    //first move (breakeven)
    IF newSL=0 AND PositionPrice-close>=trailingstart*pipsize THEN
        newSL = PositionPrice-trailingstep*pipsize
    ENDIF
    //next moves
    IF newSL>0 AND newSL-close>=trailingstep*pipsize THEN
        newSL = newSL-trailingstep*pipsize
    ENDIF
ENDIF
//stop order to exit the positions
IF newSL>0 THEN
    SELL AT newSL STOP
    EXITSHORT AT newSL STOP
ENDIF
MyPositionPrice = PositionPrice
//*********************************************************************************

Explanation of the Code:

  • Reset Stop-Loss: At the beginning, if the trader is not in the market, the stop-loss (NewSL) and the position price (MyPositionPrice) are reset to zero.
  • Update Stop-Loss for Cumulative Positions: If new positions are added (detected by an increase in the absolute count of positions), the stop-loss is adjusted based on whether the market is long or short. For long positions, it sets the stop-loss to the higher of the current stop-loss or the adjusted position price. For short positions, it sets it to the lower.
  • Trailing Stop Parameters: Defines the points at which the trailing stop starts (trailingstart) and the step size for the stop movement (trailingstep).
  • Manage Long and Short Positions: Adjusts the stop-loss for both long and short positions as the market price moves favorably, ensuring the stop-loss is moved in steps defined by trailingstep, starting after a profit defined by trailingstart.
  • Execute Stop Orders: If the stop-loss is greater than zero, the positions are exited at the stop-loss price, effectively locking in profits and limiting losses.

This code is a practical example of how to manage and adjust trailing stops dynamically in a trading environment, particularly useful for strategies involving cumulative positions.

Related Post

Check out this related content for more information:

https://www.prorealcode.com/topic/trailing-stop-with-cumulative-orders/#post-146951

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.
Nicolas Master
I created ProRealCode because I believe in the power of shared knowledge. I spend my time coding new tools and helping members solve complex problems. If you are stuck on a code or need a fresh perspective on a strategy, I am always willing to help. Welcome to the community!
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...