Implementing Breakeven and Partial Position Closure in Trading Strategy

21 May 2020
0 comment
0 attachment

This code snippet demonstrates how to adjust a trading strategy in ProBuilder to move a stop loss to breakeven and partially close a position when a certain percentage of the take profit target is reached. This technique is commonly used in trading to protect gains and manage risk.


defparam cumulateorders=false
// --- settings
amount = 2 //amount of contract/lot/shares to open for each order
takeprofit = 30 //takeprofit in points
stoploss = 60 //stoploss in points
BreakevenAt = 25 //percent achieved of target to move stop to entry (breakeven)
PointsToKeep = 1 //how much pips/points to keep in profit above or below our entry price when the breakeven is activated (beware of spread)
Lot2Close = 1 //amount of contract/lot/shares quantity to close when breakeven occurs
// --- end of settings

upper = BollingerUp[20](close)
lower = BollingerDown[20](close)

//strategy
if high crosses over upper then
  sellshort amount contract at market
endif
if low crosses under lower then
  buy amount contract at market
endif

set target pprofit takeprofit
set stop ploss stoploss

//reset the breakevenLevel when no trade are on market
IF NOT ONMARKET THEN
  breakevenLevel=0
ENDIF

startBreakeven = takeprofit*(BreakevenAt/100)//how much pips/points in gain to activate the breakeven function?

// --- BUY SIDE ---
//test if the price have moved favourably of "startBreakeven" points already
IF LONGONMARKET AND close-tradeprice(1)>=startBreakeven*pipsize THEN
  //calculate the breakevenLevel
  breakevenLevel = tradeprice(1)+PointsToKeep*pipsize
ENDIF

//place the new stop orders on market at breakevenLevel
IF LONGONMARKET AND breakevenLevel>0 THEN
  SELL AT breakevenLevel STOP
  if countoflongshares=amount then
    sell Lot2Close contract at market
  endif
ENDIF

// --- end of BUY SIDE ---

// --- SELL SIDE ---
//test if the price have moved favourably of "startBreakeven" points already
IF SHORTONMARKET AND tradeprice(1)-close>=startBreakeven*pipsize THEN
  //calculate the breakevenLevel
  breakevenLevel = tradeprice(1)-PointsToKeep*pipsize
ENDIF

//place the new stop orders on market at breakevenLevel
IF SHORTONMARKET AND breakevenLevel>0 THEN
  EXITSHORT AT breakevenLevel STOP
  if countofshortshares=amount then
    exitshort Lot2Close contract at market
  endif
ENDIF

// --- end of SELL SIDE ---

This code snippet is structured to handle both buy and sell orders within a trading strategy that uses Bollinger Bands as entry signals. Here’s a breakdown of its functionality:

  • Settings: Initial parameters such as the amount of contracts, take profit, stop loss, and breakeven settings are defined.
  • Entry Conditions: The strategy enters a short position when the high crosses over the upper Bollinger Band and a long position when the low crosses under the lower Bollinger Band.
  • Profit Targets and Stop Losses: These are set based on the initial settings.
  • Breakeven Adjustment: When the price moves favorably by a specified percentage of the take profit target, the stop loss is moved to a breakeven point, adjusted by a small buffer (PointsToKeep) to account for spread or slippage.
  • Partial Closure: Simultaneously, part of the position is closed to lock in profits.

This approach helps in managing ongoing trades by securing profits and reducing risk exposure as the market moves in favor of the open positions.

Related Post

Check out this related content for more information:

https://www.prorealcode.com/topic/bollinger-band-coding-help-please/#post-80959

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