This ProBuilder code snippet demonstrates how to manually implement a stop loss mechanism in a trading strategy, which exits a trade based on the closing price of a bar rather than an intraday price hit. This approach can potentially avoid premature exits due to temporary price spikes.
MyStop = 20 * pipsize //20 pips SL
IF Not OnMarket AND MyConditions THEN
BUY 1 CONTRACT AT MARKET
EntryPrice = close
StopLoss = EntryPrice - MyStop
SET TARGET pPROFIT 50
ENDIF
IF LongOnMarket THEN
IF close <= StopLoss THEN
SELL AT MARKET
ENDIF
ENDIF
Explanation of the Code:
- Setting the Stop Loss: The variable MyStop is defined as 20 times the pipsize, which sets the stop loss to 20 pips below the entry price.
- Entry Condition: The IF statement checks if the market position is not already open and other custom conditions (MyConditions) are met. If true, it executes a market order to buy 1 contract.
- Defining Entry and Stop Loss Prices: Upon entering the market, the entry price (EntryPrice) is set to the closing price of the current bar. The stop loss (StopLoss) is then set as the entry price minus MyStop.
- Setting a Profit Target: A profit target is set to 50 pips above the entry price using SET TARGET pPROFIT 50.
- Exit Condition: Another IF statement checks if the position is long and if the closing price of the current bar is less than or equal to the stop loss price. If this condition is met, it triggers a market order to sell, thereby closing the position.
This method ensures that the trade is only exited after a bar closes at or below the stop loss level, potentially allowing for recovery in the price within the duration of the bar and avoiding a stop-out from a brief price dip.