Implementing Dynamic Trailing Stops and Market Entry Based on Moving Average Crossover

09 Jul 2016
0 comment
0 attachment

This ProBuilder code snippet demonstrates how to implement a trading strategy that enters the market based on a moving average crossover and manages open positions with a dynamic trailing stop mechanism. The trailing stop adjusts its distance from the current price as the trade moves into profit, tightening the stop as the price approaches the target profit (TP).


Avg = average[100,0](close)
IF not OnMarket THEN
    IF close CROSSES OVER Avg THEN
        BUY AT MARKET
    ELSIF close CROSSES UNDER Avg THEN
        SELLSHORT AT MARKET
    ENDIF
    SL = close / 100 * 2 //2% SL
    SET STOP LOSS SL
ENDIF

// incremental Trailing Stop (based on Percentages)
NewTrade = (OnMarket AND Not OnMarket[1]) OR (LongOnMarket AND ShortOnMarket[1]) OR (LongOnMarket[1] AND ShortOnMarket)
IF Not OnMarket OR NewTrade THEN
    //reset to default values when a new trade has been opened
    PerCentTP = 2.0 //2.0% is TP
    PerCentStart = 0.2 //0.2% is the Trailing Stop trigger level
    PerCentStep = 0.2 //0.2% is each subsequent step
    PerCentSaved = 0.1 //0.1% is how much profit has to be saved when trailing starts and every step
    Multiplier = 1.5 //1.5 is how much PerCentSaved is incremented each trailing step
    Distance = 6 //6 pip distance from current price (if required by the broker)
    MySL = 0
    ProfitPerCent = 0
ENDIF

IF OnMarket THEN
    IF MySL = 0 THEN
        PCent = PositionPrice * PerCentTP / 100
        PStart = PositionPrice * PerCentStart / 100
        PStep = PositionPrice * PerCentStep / 100
        PSaved = PositionPrice * PerCentSaved / 100
    ENDIF

    // check if Trailing Stop has to be triggered
    IF MySL = 0 THEN
        IF LongOnMarket THEN
            IF (close - PositionPrice) >= PStart THEN
                MySL = min(close,PositionPrice + PSaved)
                PSaved = PSaved * Multiplier
            ENDIF
        ELSIF ShortOnMarket THEN
            IF (PositionPrice - close) >= PStart THEN
                MySL = max(close,PositionPrice - PSaved)
                PSaved = PSaved * Multiplier
            ENDIF
        ENDIF
    ELSE
        // check if another Step has been triggered
        IF LongOnMarket THEN
            IF (close - MySL) >= PStep THEN
                MySL = min(close,MySL + PSaved)
                PSaved = PSaved * Multiplier
            ENDIF
        ELSIF ShortOnMarket THEN
            IF (MySL - close) >= PStep THEN
                MySL = max(close,MySL - PSaved)
                PSaved = PSaved * Multiplier
            ENDIF
        ENDIF
    ENDIF

    // place Pending STOP orders
    IF MySL > 0 THEN
        IF (MySL = close) OR (abs(MySL - close) < Distance) THEN
            //exit immediately in case MySL has reached
            // the current price or there's not enough DISTANCE
            SELL AT MARKET
            EXITSHORT AT MARKET
        ELSE
            SELL AT MySL STOP
            EXITSHORT AT MySL STOP
        ENDIF
    ENDIF
ENDIF

// graphonprice PositionPrice coloured(0,0,0,255) AS "Entry"
graphonprice MySL coloured(0,128,0,155) AS "Trailing Stop"
IF LongOnMarket THEN
    graphonprice PositionPrice - SL coloured(255,0,0,255) AS "Stop Loss"
ELSE
    graphonprice PositionPrice + SL coloured(255,0,0,255) AS "Stop Loss"
ENDIF
graph PCent coloured(0,0,0,255)
graph PStart coloured(0,0,255,255)
graph PStep coloured(0,128,0,155)
graph PSaved coloured(255,0,0,255)
graph positionperf * positionprice / pipsize AS "Gain"

Explanation of the code:

  • The code starts by calculating a 100-period moving average of the close price. If the market is not entered, it checks for a crossover to either buy or sell short.
  • Initial stop loss is set at 2% of the close price when a new position is opened.
  • When a new trade is detected, it initializes variables for a dynamic trailing stop mechanism, including the target profit, initial trigger level for the trailing stop, step size for trailing, and the increment multiplier for each step.
  • The trailing stop logic checks if the profit from the position has reached the start level to activate the trailing stop. It then adjusts the stop loss dynamically as the price moves favorably, using a multiplier to increase the saved profit at each step.
  • If the trailing stop is close enough to the current price or within a specified distance, the position is closed; otherwise, a stop order is placed at the calculated trailing stop level.
  • Graphical representations on the price chart indicate the entry price, trailing stop, and stop loss levels.

Related Post

Check out this related content for more information:

https://www.prorealcode.com/topic/breakeeven-trailing-profit/page/5/#post-181123

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