Backtesting and the ‘correct’ use of stops (Code that is)!!!!
Forums › ProRealTime English forum › ProOrder support › Backtesting and the ‘correct’ use of stops (Code that is)!!!!
- This topic has 7 replies, 3 voices, and was last updated 3 minutes ago by
JS.
-
-
05/14/2025 at 11:39 AM #247095Code for review...123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151// ========================================================================// STRATEGY: DMI-ADX Crossover with Stop Loss + Opposite Signal Exit// ========================================================================// BT-DMI-test-V3.0.13.2-VS-AQ// === INPUTS ===myDMIperiod = myDMIperiod // 10 // optimize from 1 to 20 via PRT PlatformmyATRperiod = 14myATRmultiplier = 2.5myRiskPercent = 5 // Risk percentage (5%)myInitialBalance = 100000 // Starting capitalmyADXThreshold = 20 // Minimum ADX value for trend strength confirmation// === INDICATORS ===myDIplus = DIPLUS[myDMIperiod]myDIminus = DIMINUS[myDMIperiod]myADX = ADX[myDMIperiod]myATR = AVERAGETRUERANGE[myATRperiod]// === SIGNALS ===// Basic DMI crossover signals - SAME BAR ENTRYmyLongSignal = myDIplus CROSSES OVER myDIminusmyShortSignal = myDIminus CROSSES OVER myDIplus// ADX trend strength filter// ADXStrong: Filter out weak trends to avoid whipsaw trades in choppy marketsmyADXStrong = myADX > myADXThreshold// Final signals with filter appliedmyLongSignal = myLongSignal AND myADXStrongmyShortSignal = myShortSignal AND myADXStrong// === STOP LOSS DISTANCE ===myStopLossDistance = myATR * myATRmultiplier// === RISK MANAGEMENT ===// Initialize account balance trackingONCE myCurrentBalance = myInitialBalanceONCE myPreviousEquity = myInitialBalanceONCE myProfitLoss = 0// Update account balance based on closed positionsIF BarsSince(LongOnMarket) = 0 OR BarsSince(ShortOnMarket) = 0 THEN// New position openedmyPreviousEquity = myCurrentBalanceENDIF// If position was closed on previous bar, update the balanceIF (LongOnMarket[1] AND NOT LongOnMarket) OR (ShortOnMarket[1] AND NOT ShortOnMarket) THEN// Calculate profit/loss from the closed positionIF LongOnMarket[1] THENmyProfitLoss = (close[1] - POSITIONPRICE[1]) * COUNTOFPOSITION[1]ELSEmyProfitLoss = (POSITIONPRICE[1] - close[1]) * ABS(COUNTOFPOSITION[1])ENDIF// Update current balancemyCurrentBalance = myCurrentBalance + myProfitLossENDIF// Calculate position size based on riskmyRiskAmount = myCurrentBalance * (myRiskPercent / 100)// Calculate position size based on stop loss distanceIF myStopLossDistance > 0 THENmyRiskBasedPositionSize = ROUND(myRiskAmount / myStopLossDistance)// Ensure minimum position size of 1IF myRiskBasedPositionSize < 1 THENmyRiskBasedPositionSize = 1ENDIFELSEmyRiskBasedPositionSize = 1ENDIF// === STATE FLAGS ===// Initialize these variables only once to maintain state between barsONCE myReverseToLong = 0ONCE myReverseToShort = 0ONCE myEntryPrice = 0ONCE myLongStopLevel = 0ONCE myShortStopLevel = 0ONCE myExitType = 0 // 0=neutral, +1=opposite signal, -1=stop loss hitONCE myExitPrice = 0 // Price at which exit occurred// === POSITION MANAGEMENT ===IF LongOnMarket THEN// Store entry price when entering a positionIF BarsSince(LongOnMarket) = 0 THENmyEntryPrice = closemyLongStopLevel = myEntryPrice - myStopLossDistancemyExitType = 0myExitPrice = 0// Set stop loss using built-in functionSET STOP PRICE myLongStopLevelENDIFENDIFIF ShortOnMarket THEN// Store entry price when entering a positionIF BarsSince(ShortOnMarket) = 0 THENmyEntryPrice = closemyShortStopLevel = myEntryPrice + myStopLossDistancemyExitType = 0myExitPrice = 0// Set stop loss using built-in functionSET STOP PRICE myShortStopLevelENDIFENDIF// === ENTRY WHEN FLAT ===IF NOT LongOnMarket AND NOT ShortOnMarket THENIF myReverseToLong THENBUY myRiskBasedPositionSize SHARES AT MARKETmyReverseToLong = 0ELSEIF myReverseToShort THENSELLSHORT myRiskBasedPositionSize SHARES AT MARKETmyReverseToShort = 0ELSEIF myLongSignal THENBUY myRiskBasedPositionSize SHARES AT MARKETELSEIF myShortSignal THENSELLSHORT myRiskBasedPositionSize SHARES AT MARKETENDIFENDIFENDIFENDIFENDIF// === VISUALIZATION ===// Show stop levels on price chartGraphOnPrice myLongStopLevel coloured("Green")GraphOnPrice myShortStopLevel coloured("Red")// Track exit types in a separate panelGRAPH myExitType AS "Exit Type (+1=Signal, 0=Neutral, -1=Stop Loss)"// End
Hiya all coders,
This one has had my head pickled of late!!!
PLEASE NOTE: I only ever use the daily: 1 day / 1 bar.
Background:
—————
To get a backtest benchmark, I use a fixed stop loss.
Once the fixed stop loss backtest has been validated,
I then move to a training stop system.I have found a way to validate the exit type (Separate panel)
1. Stop loss hit SL (-1)
2. Opposite signal triggered OS (+1)
This is working and a good visual for said exit types.
And provides a useful visual of the trade entry system, and its exit.Issue:
——–
Currently, my code is not detecting the stop loss hits, and thus the trade continues!
When the SL is detected, it can be days / bars later.
I also notice that there are occurrences where the trade exit is nowhere near a stop loss level or an opposite signal !I have used both the system code => SET STOP PRICE
And a manual check, ‘high or low’ values of the latest bar.
The opposite signal trigger is working – and for some reason, the OS check is occurring before the SL!!!Subjectively:
—————-
The stop loss SL check should be performed before the opposite signal OS check.
If, during the day, the price has been higher or lower than the SL level, then the SL should be triggered before the next bar / next day.
if no stop loss is triggered, then the OS check should be performed, and if triggered the open trade is closed, and the opposite trade is opened (on the same bar)I hope this explanation makes sense.
I appreciate any code guidance that provides a working solution.
My thanks always.
NT05/14/2025 at 1:12 PM #247098Hi NT,
A few comments regarding your code:-
The logic in the signal definitions is incorrect…
-
Some variables are defined multiple times in different ways…
-
Misuse of “BarsSince”…
-
Certain variables are never reset…
-
myReverseToLong
always remains zero… -
myReverseToShort
always remains zero… - …
1 user thanked author for this post.
05/14/2025 at 1:42 PM #24710305/14/2025 at 2:52 PM #247105Hi NT,
I would like to help you, but this is going to take too much time to get the code right…
Line 22 and 23 you define myLongSignal and myShortSignal but in line 30 and 31 you redefine them…
When you are “Long” then BarsSince(LongOnMarket) is always equal to zero so myPreviousEquity will be redefined repeatedly…
myReverseToLong is reset to zero once but does not change after that…
Same with myReverseToShort…
Maybe better to start with a simpler strategy to understand the PRT logic…
1 user thanked author for this post.
05/14/2025 at 3:15 PM #247108Also myExitType looks like it is always = 0?
Beats me how you can author / amend / add to 148 lines of code Neo … but you can’t debug it?
Idea so you can progress … run the code past AI / ChatGPT … you will get suggested fixes in a few seconds.
05/14/2025 at 3:26 PM #247111Hi NT,
I would like to help you, but this is going to take too much time to get the code right…
Hi JS,
Oh, okay….Can I ask that you send me a link to code, that can send me in the right direction….
For the FIXED stop loss for instance….I ask this, as I am not sure if others may look in on this matter, as you have commented…. or shall I repost requesting more defined code guidance ??
In the meantime, I’ll strip out the stop loss and opposite signal processes, and start again…
My regards
NT
05/14/2025 at 3:40 PM #24711305/14/2025 at 3:55 PM #247114Article about a “trailing stop”…
https://www.prorealcode.com/blog/learning/kinds-trailing-stop-proorder/Article about “Breakeven” coding…
https://www.prorealcode.com/blog/learning/breakeven-code-automated-trading-strategy/Article about using an indicator for the “stop loss”…
https://www.prorealcode.com/blog/learning/moving-stoploss-dynamic-informations-proorder/I recommend checking the “Blog” section, which contains many interesting articles (including videos)…
https://www.prorealcode.com/category/blog/ -
-
AuthorPosts