Implementing Trailing Stops for Long and Short Positions with Conditional Exit Strategies

11 Sep 2016
0 comment
0 attachment

This code snippet demonstrates how to implement trailing stops for both long and short trading positions in the ProBuilder language, with conditional logic to decide whether to exit the trade using a stop order, a limit order, or at the market price based on the current price’s relation to a defined distance.


//************************************************************************
//trailing stop function
trailingstartL = 20 //LONG trailing will start @trailinstart points profit
trailingstartS = 20 //SHORT trailing will start @trailinstart points profit
trailingstep = 5 //trailing step to move the "stoploss"
Distance = 6 * PipSize //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)>=trailingstartL*pipsize THEN
        newSL = tradeprice(1)+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 tradeprice(1)-close>=trailingstartS*pipsize THEN
        newSL = tradeprice(1)-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
    IF LongOnMarket THEN
        IF (close - Distance) > newSL THEN
            SELL AT newSL STOP
        ELSIF (close + Distance) < newSL THEN
            SELL AT newSL LIMIT
        ELSE
            SELL AT Market
        ENDIF
    ELSIF ShortOnMarket THEN
        IF (close - Distance) > newSL THEN
            EXITSHORT AT newSL LIMIT
        ELSIF (close + Distance) < newSL THEN
            EXITSHORT AT newSL STOP
        ELSE
            EXITSHORT AT Market
        ENDIF
    ENDIF
ENDIF
//************************************************************************

This code snippet is structured to manage trading positions by adjusting the stop loss dynamically as the trade moves into profit. Here's a breakdown of its functionality:

  • Initialization: Sets the parameters for when the trailing stop should start and the step size for moving the stop loss.
  • Checking Market Position: Determines if the trader is not in the market, and if so, resets the stop loss variable.
  • Long Position Management: For long positions, the code first checks if the profit has reached a specified start point to move the stop loss to a breakeven point, then continues to trail the stop loss as the price moves further into profit.
  • Short Position Management: Similar to long positions but adjusted for short trades, moving the stop loss down as the trade gains profit.
  • Conditional Exit Strategy: Depending on the price's relation to the stop loss and a defined distance, the trade is exited using a stop order, a limit order, or at the market price to optimize the exit based on market conditions.

This example is useful for understanding how to implement advanced trading strategies programmatically, focusing on maximizing profits and minimizing losses through dynamic stop loss adjustments.

Related Post

Check out this related content for more information:

https://www.prorealcode.com/topic/breakeven-stop-code-long-short/#post-172745

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