Implementing a Trailing Stop Strategy Based on Candle Highs in ProBuilder

18 Aug 2019
0 comment
0 attachment

This code snippet demonstrates how to implement a trailing stop strategy based on candle highs using the ProBuilder programming language. The strategy includes conditions for entering trades, managing monthly losses, and dynamically adjusting stop levels based on price movements.


DEFPARAM CUMULATEORDERS = false
PositionSize=1

//=== Max Monthly Loss ===
ONCE MyProfit = 0
ONCE TradeON = 1

IF Month <> Month[1] THEN
    MyProfit = STRATEGYPROFIT //store profits/losses at the beginning of each month
    TradeON = 1 //enable trading each new month
ENDIF

IF (STRATEGYPROFIT - MyProfit) < -3500 THEN
    TradeON = 0 //disable trading when losing > 200 currency units
ENDIF

//=== Entry Filter ===
//Filter 1
indicator1=average[75,7]
indicator2=average[125,7]
indicator3=average[150,7]
F1 = indicator1>indicator2
F2 = indicator2>indicator3

//=== Entry Criteria ===
//Entry Criteria 1
entrylen = 5
LowVol = round(volume[4])
E1 = volume < LowVol
bullish = close>lowest[entrylen](low)

IF E1 AND bullish AND F1 AND F2 AND opendayofweek <> 3 AND opendayofweek <> 4 AND opendayofweek <> 0 AND opendayofweek <> 6 AND TradeON THEN
    BUY PositionSize CONTRACTS AT MARKET
    SET STOP %LOSS 1
    set target %profit 2
ENDIF

// trailingstopRTS=1
IF trailingstopRTS then
    IF Not OnMarket THEN
        PriceDistance = 10 * PipSize //PriceDistance from price as required by the broker
        StopDistance = 30 * PipSize //Distance from HIGH
        SellPrice = close - StopDistance //The first bar StopDistance is from CLOSE
    ELSE
        SellPrice = max(SellPrice,high - StopDistance)
        IF abs(close - SellPrice) > PriceDistance THEN
            IF close >= SellPrice THEN
                SELL AT SellPrice STOP
            ELSE
                SELL AT SellPrice LIMIT
            ENDIF
        ELSE
            SELL AT Market
        ENDIF
    ENDIF
ENDIF

// graphonprice
SellPrice coloured(0,128,0,150)

Explanation of the Code:

  • Initial Setup: Disables cumulating orders and sets initial conditions for monthly profit tracking and trading activation.
  • Monthly Loss Management: At the start of each month, the strategy resets the profit calculation and re-enables trading. It disables trading if the loss exceeds a specified threshold within the month.
  • Entry Filters and Criteria: Defines multiple moving averages as filters and checks for low volume and bullish conditions. It also ensures trades are not executed on certain days of the week.
  • Trade Execution: If all conditions are met, a buy order is placed with predefined stop loss and profit targets.
  • Trailing Stop Logic: Implements a trailing stop mechanism where the stop price is adjusted based on the highest price reached since entry. The stop adjusts only if the price moves favorably and exceeds a specified distance from the current price.
  • Visualization: The trailing stop price is visualized on the price chart for better tracking.

Related Post

Check out this related content for more information:

https://www.prorealcode.com/topic/robertogozzi-trail-stops-trailing/#post-178202

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