Backtesting and the ‘correct’ use of stops (Code that is)!!!!

Viewing 13 posts - 1 through 13 (of 13 total)
  • Author
    Posts
  • #247095 quote
    NeoTrader
    Participant
    New
    // ========================================================================
    // 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 Platform
    myATRperiod = 14
    myATRmultiplier = 2.5
    myRiskPercent = 5 // Risk percentage (5%)
    myInitialBalance = 100000 // Starting capital
    myADXThreshold = 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 ENTRY
    myLongSignal = myDIplus CROSSES OVER myDIminus
    myShortSignal = myDIminus CROSSES OVER myDIplus
    
    // ADX trend strength filter
    // ADXStrong: Filter out weak trends to avoid whipsaw trades in choppy markets
    myADXStrong = myADX > myADXThreshold
    
    // Final signals with filter applied
    myLongSignal = myLongSignal AND myADXStrong
    myShortSignal = myShortSignal AND myADXStrong
    
    // === STOP LOSS DISTANCE ===
    myStopLossDistance = myATR * myATRmultiplier
    
    // === RISK MANAGEMENT ===
    // Initialize account balance tracking
    ONCE myCurrentBalance = myInitialBalance
    ONCE myPreviousEquity = myInitialBalance
    ONCE myProfitLoss = 0
    
    // Update account balance based on closed positions
    IF BarsSince(LongOnMarket) = 0 OR BarsSince(ShortOnMarket) = 0 THEN
    // New position opened
    myPreviousEquity = myCurrentBalance
    ENDIF
    
    // If position was closed on previous bar, update the balance
    IF (LongOnMarket[1] AND NOT LongOnMarket) OR (ShortOnMarket[1] AND NOT ShortOnMarket) THEN
    // Calculate profit/loss from the closed position
    IF LongOnMarket[1] THEN
    myProfitLoss = (close[1] - POSITIONPRICE[1]) * COUNTOFPOSITION[1]
    ELSE
    myProfitLoss = (POSITIONPRICE[1] - close[1]) * ABS(COUNTOFPOSITION[1])
    ENDIF
        
    // Update current balance
    myCurrentBalance = myCurrentBalance + myProfitLoss
    ENDIF
    
    // Calculate position size based on risk
    myRiskAmount = myCurrentBalance * (myRiskPercent / 100)
    
    // Calculate position size based on stop loss distance
    IF myStopLossDistance > 0 THEN
    myRiskBasedPositionSize = ROUND(myRiskAmount / myStopLossDistance)
    
    // Ensure minimum position size of 1
    IF myRiskBasedPositionSize < 1 THEN
    myRiskBasedPositionSize = 1
    ENDIF
    ELSE
    myRiskBasedPositionSize = 1
    ENDIF
    
    // === STATE FLAGS ===
    // Initialize these variables only once to maintain state between bars
    ONCE myReverseToLong = 0
    ONCE myReverseToShort = 0
    ONCE myEntryPrice = 0
    ONCE myLongStopLevel = 0
    ONCE myShortStopLevel = 0
    ONCE myExitType = 0  // 0=neutral, +1=opposite signal, -1=stop loss hit
    ONCE myExitPrice = 0  // Price at which exit occurred
    
    
    // === POSITION MANAGEMENT ===
    IF LongOnMarket THEN
    // Store entry price when entering a position
    IF BarsSince(LongOnMarket) = 0 THEN
    myEntryPrice = close
    myLongStopLevel = myEntryPrice - myStopLossDistance
    myExitType = 0
    myExitPrice = 0
        
    // Set stop loss using built-in function
    SET STOP PRICE myLongStopLevel
    ENDIF
    ENDIF
    
    IF ShortOnMarket THEN
    // Store entry price when entering a position
    IF BarsSince(ShortOnMarket) = 0 THEN
    myEntryPrice = close
    myShortStopLevel = myEntryPrice + myStopLossDistance
    myExitType = 0
    myExitPrice = 0
        
    // Set stop loss using built-in function
    SET STOP PRICE myShortStopLevel
    ENDIF
    ENDIF
    
    
    
    
    
    
    
    
    // === ENTRY WHEN FLAT ===
    IF NOT LongOnMarket AND NOT ShortOnMarket THEN
    IF myReverseToLong THEN
    BUY myRiskBasedPositionSize SHARES AT MARKET
    myReverseToLong = 0
    ELSE
    IF myReverseToShort THEN
    SELLSHORT myRiskBasedPositionSize SHARES AT MARKET
    myReverseToShort = 0
    ELSE
    IF myLongSignal THEN
    BUY myRiskBasedPositionSize SHARES AT MARKET
    ELSE
    IF myShortSignal THEN
    SELLSHORT myRiskBasedPositionSize SHARES AT MARKET
    ENDIF
    ENDIF
    ENDIF
    ENDIF
    ENDIF
    
    // === VISUALIZATION ===
    // Show stop levels on price chart
    GraphOnPrice myLongStopLevel coloured("Green")
    GraphOnPrice myShortStopLevel coloured("Red")
    
    // Track exit types in a separate panel
    GRAPH 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.
    NT

    #247098 quote
    JS
    Participant
    Senior

    Hi 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…

    NeoTrader thanked this post
    #247103 quote
    NeoTrader
    Participant
    New
    Hi NT,
    A few comments regarding your code…..
    Hey JS, My my, that sounds like a code mess to untangle… Would you be kind enough to help me, by showing the correction is code form? Is that possible ? With thanks in anticipation, NT
    #247105 quote
    JS
    Participant
    Senior
    Hi 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…

    NeoTrader thanked this post
    #247108 quote
    GraHal
    Participant
    Master
    Also 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.
    NeoTrader thanked this post
    #247111 quote
    NeoTrader
    Participant
    New
    Hi 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
    #247113 quote
    GraHal
    Participant
    Master
    #247114 quote
    JS
    Participant
    Senior

    Article 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/

    NeoTrader and robertogozzi thanked this post
    #247116 quote
    NeoTrader
    Participant
    New
    Is below of any help https://www.prorealcode.com/documentation/ploss-2/
    Hey GraHal, Not sure how ploss is related to the stop loss solution I am looking for… Any ‘stop loss’ links you might know…? Aside, I’ll keep searching, Cheers, NT
    #247122 quote
    NeoTrader
    Participant
    New
    Article about a “trailing stop”… <<< looking for fixed stop loss, not trailing stop 🙂
    https://www.prorealcode.com/blog/learning/kinds-trailing-stop-proorder/ Article about “Breakeven” coding… <<< Can this be used in backtest, it states its for automated trading ?
    https://www.prorealcode.com/blog/learning/breakeven-code-automated-trading-strategy/ Article about using an indicator for the “stop loss”… <<< Digesting this one, lovely, thank you 
    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/  Reviewed said blog, but no specific finds for ‘fixed stop loss’
    I’ll strip out the code, and have a go refactoring the code for a simplistic fixed stop loss. Hopefully, that moves me in the right direction Thanks for the pointers NT.
    #247125 quote
    NeoTrader
    Participant
    New
    Also 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? <<< AI assisted, and the code was also provided by support at PRT. Idea so you can progress … run the code past AI / ChatGPT … you will get suggested fixes in a few seconds.
    Yep. Ive been running the code past several (5 no.) AIM’s for the past few hours… So far, they have made the code worse, even when I provide the explicit probacktest code syntax !!! I have trawled so much of the site, looking for FIXED stop loss backtest code samples, examples…. and so far, I am not seeing any answers on this one…. Aside, I appreciate your involvement GraHal NT
    #247127 quote
    GraHal
    Participant
    Master
    looking for FIXED stop loss backtest code
    What do you mean by above? The link I provided (a few posts above) was for a FIXED stop loss of 50 points. You can optimise the points value or use a % instead of points. I use fixed stop loss in most of my Algos (example below) along with a coded Trailing Stop function. Plenty of coded TS’s on this link … Snippet Link Library
    If buycondition Then 
    buy 1 contract at market
    SET STOP %LOSS A67
    SET TARGET %PROFIT A68
    Endif
    NeoTrader and robertogozzi thanked this post
    #247128 quote
    NeoTrader
    Participant
    New
    What do you mean by above?……
    That is what I get for doing too many things at once…. Indeed GraHal, You link does apply to a ‘fixed stop loss’. I am just setting some time aside to sort this code pickle out. Thank you, for the correction, and making sure I am on the right track. I’ll post my updated code. With thanks NT
    GraHal thanked this post
Viewing 13 posts - 1 through 13 (of 13 total)
  • You must be logged in to reply to this topic.

Backtesting and the ‘correct’ use of stops (Code that is)!!!!


ProOrder: Automated Strategies & Backtesting

New Reply
Author
author-avatar
NeoTrader @neotrader Participant
Summary

This topic contains 12 replies,
has 3 voices, and was last updated by NeoTrader
9 months, 3 weeks ago.

Topic Details
Forum: ProOrder: Automated Strategies & Backtesting
Language: English
Started: 05/14/2025
Status: Active
Attachments: No files
Logo Logo
Loading...