Implementing a Trailing Stop Strategy for Long and Short Trades

24 Aug 2024
0 comment
0 attachment

This ProBuilder code snippet demonstrates how to implement a trailing stop strategy that retains a specified percentage of profit for both long and short positions in trading. The strategy starts to trail the stop loss once a certain amount of profit (in pips) is achieved, and it continues to secure a percentage of the maximum profit as the price moves favorably.


ONCE TrailStart = 30 //30 Start trailing profits from this point
ONCE ProfitPerCent = 0.666 //66.6% Profit to keep
IF Not OnMarket THEN
    y1 = 0
    y2 = 0
ELSIF LongOnMarket AND close > (TradePrice + (y1 * pipsize)) THEN //LONG
    x1 = (close - tradeprice) / pipsize //convert price to pips
    IF x1 >= TrailStart THEN //go ahead only if 30+ pips
        y1 = max(x1 * ProfitPerCent, y1) //y = % of max profit
    ENDIF
    IF y1 THEN //Place pending STOP order when y>0
        SELL AT Tradeprice + (y1 * pipsize) STOP //convert pips to price
    ENDIF
ELSIF ShortOnMarket AND close < (TradePrice - (y2 * pipsize)) THEN //SHORT
    x2 = (tradeprice - close) / pipsize //convert price to pips
    IF x2 >= TrailStart THEN //go ahead only if 30+ pips
        y2 = max(x2 * ProfitPerCent, y2) //y = % of max profit
    ENDIF
    IF y2 THEN //Place pending STOP order when y>0
        EXITSHORT AT Tradeprice - (y2 * pipsize) STOP //convert pips to price
    ENDIF
ENDIF

Explanation of the Code:

  • Initialization: The variables TrailStart and ProfitPerCent are set once. TrailStart defines the minimum profit (in pips) required to start trailing, and ProfitPerCent specifies the percentage of profit to retain.
  • Checking Market Position: The code first checks if there is no open market position. If true, it resets the variables y1 and y2 to zero, which are used to store the trailing stop levels for long and short positions, respectively.
  • Long Position Logic: If a long position is open and the current closing price is greater than the trade price plus the pip-adjusted trailing stop (y1), the code calculates the profit in pips (x1) and updates y1 if the profit exceeds TrailStart.
  • Setting Long Trailing Stop: If y1 is positive, a trailing stop order is placed at the trade price plus the pip-adjusted y1.
  • Short Position Logic: Similar logic applies for short positions, but it checks if the closing price is less than the trade price minus the pip-adjusted trailing stop (y2).
  • Setting Short Trailing Stop: If y2 is positive, a trailing stop order is placed at the trade price minus the pip-adjusted y2.

This code snippet is a practical example of how to manage risk and secure profits in trading by dynamically adjusting stop orders based on market movements and predefined parameters.

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