Implementing a Trailing Stop in Percentage for Trading Strategies

13 Mar 2017
0 comment
0 attachment

This code snippet demonstrates how to implement a trailing stop mechanism in percentage terms rather than fixed points or pips. A trailing stop is a dynamic stop-loss order that adjusts as the price of an asset moves in favor of the trade, helping to protect gains or limit losses.

trailingPercent = 0.5 //trailing stop function
if onmarket then
    trailingstart = tradeprice(1)*(trailingpercent/100) //trailing will start @trailinstart points profit
    trailingstep = tradeprice(1)*(trailingpercent/100) //trailing step to move the "stoploss"
endif
//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 THEN
        newSL = tradeprice(1)+trailingstep
    ENDIF
    //next moves
    IF newSL>0 AND close-newSL>trailingstep THEN
        newSL = newSL+trailingstep
    ENDIF
ENDIF
//manage short positions
IF SHORTONMARKET THEN
    //first move (breakeven)
    IF newSL=0 AND tradeprice(1)-close>=trailingstart THEN
        newSL = tradeprice(1)-trailingstep
    ENDIF
    //next moves
    IF newSL>0 AND newSL-close>trailingstep THEN
        newSL = newSL-trailingstep
    ENDIF
ENDIF
//stop order to exit the positions
IF newSL>0 THEN
    SELL AT newSL STOP
    EXITSHORT AT newSL STOP
ENDIF
//put the first stoploss if onmarket and newSL=0 and activatestoploss then
set stop loss trailingstart endif

The code snippet above is structured to manage both long and short positions using a trailing stop calculated as a percentage of the trade price. Here’s a step-by-step breakdown:

  • Initialization: The trailing stop percentage is set at 0.5%.
  • Calculation of Trailing Start and Step: When the market is entered, the trailing start and step are calculated as 0.5% of the initial trade price.
  • Reset Stop Loss: If not in the market, the stop loss is reset to zero.
  • Long Position Management: For long positions, the code first checks if the price has moved up by at least the trailing start from the entry price to set the initial stop loss (breakeven point). It then adjusts the stop loss upwards in increments of the trailing step as the price continues to rise.
  • Short Position Management: For short positions, the process is mirrored. The stop loss is adjusted downwards as the price falls.
  • Execution of Stop Orders: If a new stop loss level is set, the position is exited at this price when the market moves against the trade.
  • Initial Stop Loss Setting: If the market is entered and no stop loss has been set, the initial stop loss is placed at the trailing start distance from the entry price.

This approach helps in managing trades more dynamically, adjusting protections based on market movements and thus potentially locking in profits while limiting losses.

Related Post

Check out this related content for more information:

https://www.prorealcode.com/topic/cannot-set-trailing-stop-as-through-ig/#post-83701

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