Division by zero Stopping Trading System

Viewing 10 posts - 1 through 10 (of 10 total)
  • Author
    Posts
  • #139550 quote
    Bard
    Participant
    Master

    Hi, this system code below is causing a “Division by Zero” system stop out issue twice since being launched last week.

    Is anyone able to find the line of code that is causing the problem? It tested fine and well on back test (Wall Street DFB).

    Cheers, much appreciated for any help.

    //-------------------------------------------------------------------------
    //Main code : Bard Renko ML3 pLoss (CLR)(i)
    //Cycle Limit + Resetperiod
    
    //First Fully Working ML3 System
    
    //Long Boxsize  = ValueX  
    //Short Boxsize = ValueY
    //Point Loss    = ValueZ 
    
    //Heuristic = 3. Check 
    //ElsIf HeuristicsAlgo3 = 1 Then -- Check
    //Corrected to Mode3 in ML3 -- Check
    
    //https://www.prorealcode.com/topic/machine-learning-in-proorder/page/3/#post-121130
    //-------------------------------------------------------------------------
    //https://www.prorealcode.com/topic/why-is-backtesting-so-unreliable/#post-110889
    //definition of code parameters
    
    defparam cumulateorders = false // cumulating positions deactivated
    defparam preloadbars    = 1000
    
    //Money Management
    //Capital = 10000 + strategyprofit //Current profit made by the closed trades of the running strategy.
    N = 1//10*Capital/Close //30*Capital/Close //30
    
    //Settings 1 & 2
    
    /////////////////////////////////////////////////////////////
    
    startingvalue   = 50  //50 20 40 5, 100, 10 //boxsize 
    maxvalue        = 250  //250 50 20, 300, 150 //maximum allowed value
    increment       = 20  //10, 5, 20,
    minvalue        = 20  //15, minimum allowed value
    maxincrement    = 10  //20, 5, 10 limit of no of increments either up or down
    reps            = 2   //1 number of trades to use for analysis //2
    ResetPeriod     = 0.5  //0.5 = same as if no Reset system. Specify no of months to reset optimisation
    
    /////////////////////////////////////////////////////////////
    
    startingvalue2  = 50  //50 20 40 5, 100, 10 //boxsize
    maxvalue2       = 250 //250 20, 300, 150 //maximum allowed value
    increment2      = 20  //20, 5 10
    minvalue2       = 20  //20 15, minimum allowed value
    maxincrement2   = 10  //5, 10 limit of no of increments either up or down
    reps2           = 2   //2, 1 number of trades to use for analysis //2
    ResetPeriod2    = 0.5 //0.5 Specify no of months to reset optimisation
    
    /////////////////////////////////////////////////////////////
    
    startingvalue3  = 50   //50, 5, 100, 10 // pLoss
    maxvalue3       = 100  //100 20, 300, 150 //maximum allowed value
    increment3      = 5   //5, 20, 10
    minvalue3       = 5   //5, minimum allowed value
    maxincrement3   = 8   //8, 5, 10 limit of no of increments either up or down
    reps3           = 2    //2, 1 number of trades to use for analysis //2
    ResetPeriod3    = 0.5  //0.5 Specify no of months to reset optimisation
    
    /////////////////////////////////////////////////////////////
    
    HeuristicsCycleLimit = 3
     
    once HeuristicsCycle = 0
    once HeuristicsAlgo1 = 1
    once HeuristicsAlgo2 = 0
    once HeuristicsAlgo3 = 0
     
    If HeuristicsCycle >= HeuristicsCycleLimit Then
    If HeuristicsAlgo1 = 1 Then
    HeuristicsAlgo1 = 0
    HeuristicsAlgo2 = 1
    HeuristicsAlgo3 = 0
     
    ElsIf HeuristicsAlgo2 = 1 Then
    HeuristicsAlgo1 = 0
    HeuristicsAlgo2 = 0
    HeuristicsAlgo3 = 1
     
    ElsIf HeuristicsAlgo3 = 1 Then
    HeuristicsAlgo1 = 1
    HeuristicsAlgo2 = 0
    HeuristicsAlgo3 = 0
    EndIf
     
    HeuristicsCycle = 0
    EndIf
     
    If HeuristicsAlgo1 = 1 Then
    
    //heuristics algorithm 1 start
     
    if (onmarket[1] = 1 and onmarket = 0) or (longonmarket[1] = 1 and longonmarket and countoflongshares < countoflongshares[1]) or (longonmarket[1] = 1 and longonmarket and countoflongshares > countoflongshares[1]) or (shortonmarket[1] = 1 and shortonmarket and countofshortshares < countofshortshares[1]) or (shortonmarket[1] = 1 and shortonmarket and countofshortshares > countofshortshares[1]) or (longonmarket[1] and shortonmarket) or (shortonmarket[1] and longonmarket) then
    optimise = optimise + 1
    endif
    
    once monthinit = month
    once yearinit = year
    If (year = yearinit and month = (monthinit + ResetPeriod)) or (year = (yearinit + 1) and ((12 - monthinit) + month = ResetPeriod)) Then
    ValueX = StartingValue
    WinCountB = 0
    StratAvgB = 0
    BestA = 0
    BestB = 0
    monthinit = month
    yearinit = year
    EndIf
    
    once valuex  = startingvalue
    once pincpos = 1 //positive increment position
    once nincpos = 1 //negative increment position
    once optimise = 0 //initialize heuristicks engine counter (must be incremented at position start or exit)
    once mode1 = 1 //switches between negative and positive increments
    //once wincountb = 3 //initialize best win count
    //graph wincountb coloured (0,0,0) as "wincountb"
    //once stratavgb = 4353 //initialize best avg strategy profit
    //graph stratavgb coloured (0,0,0) as "stratavgb"
     
    if optimise = reps then
    wincounta = 0 //initialize current win count
    stratavga = 0 //initialize current avg strategy profit
    heuristicscycle = heuristicscycle + 1
     
    for i = 1 to reps do
    if positionperf(i) > 0 then
    wincounta = wincounta + 1 //increment current wincount
    endif
    stratavga = stratavga + (((positionperf(i)*countofposition[i]*close)*-1)*-1)
    next
    stratavga = stratavga/reps //calculate current avg strategy profit
    //graph (positionperf(1)*countofposition[1]*Close)*-1 as "posperf1"
    //graph (positionperf(2)*countofposition[2]*Close)*-1 as "posperf2"
    //graph stratavga*-1 as "stratavga"
    //once besta = 300
    //graph besta coloured (0,0,0) as "besta"
    if stratavga >= stratavgb then
    stratavgb = stratavga //update best strategy profit
    besta = valuex
    endif
    //once bestb = 300
    //graph bestb coloured (0,0,0) as "bestb"
    if wincounta >= wincountb then
    wincountb = wincounta //update best win count
    bestb = valuex
    endif
     
    if wincounta > wincountb and stratavga > stratavgb then
    mode1 = 0
    elsif wincounta < wincountb and stratavga < stratavgb and mode1 = 1 then
    valuex = valuex - (increment*nincpos)
    nincpos = nincpos + 1
    mode1 = 2
    elsif wincounta >= wincountb or stratavga >= stratavgb and mode1 = 1 then
    valuex = valuex + (increment*pincpos)
    pincpos = pincpos + 1
    mode1 = 1
    elsif wincounta < wincountb and stratavga < stratavgb and mode1 = 2 then
    valuex = valuex + (increment*pincpos)
    pincpos = pincpos + 1
    mode1 = 1
    elsif wincounta >= wincountb or stratavga >= stratavgb and mode1 = 2 then
    valuex = valuex - (increment*nincpos)
    nincpos = nincpos + 1
    mode1 = 2
    endif
     
    if nincpos > maxincrement or pincpos > maxincrement then
    if besta = bestb then
    valuex = besta
    else
    if reps >= 10 then
    weightedscore = 10
    else
    weightedscore = round((reps/100)*100)
    endif
    valuex = round(((besta*(20-weightedscore)) + (bestb*weightedscore))/20) //lower reps = less weight assigned to win%
    endif
    nincpos = 1
    pincpos = 1
    elsif valuex > maxvalue then
    valuex = maxvalue
    elsif valuex < minvalue then
    valuex = minvalue
    endif
     
    optimise = 0
    endif
     
    // heuristics algorithm 1 end
    
    elsif heuristicsalgo2 = 1 then
    
    // heuristics algorithm 2 start
     
    if (onmarket[1] = 1 and onmarket = 0) or (longonmarket[1] = 1 and longonmarket and countoflongshares < countoflongshares[1]) or (longonmarket[1] = 1 and longonmarket and countoflongshares > countoflongshares[1]) or (shortonmarket[1] = 1 and shortonmarket and countofshortshares < countofshortshares[1]) or (shortonmarket[1] = 1 and shortonmarket and countofshortshares > countofshortshares[1]) or (longonmarket[1] and shortonmarket) or (shortonmarket[1] and longonmarket) then
    optimise2 = optimise2 + 1
    endif
    
    once monthinit2 = month
    once yearinit2 = year
    If (year = yearinit2 and month = (monthinit2 + ResetPeriod2)) or (year = (yearinit2 + 1) and ((12 - monthinit2) + month = ResetPeriod2)) Then
    ValueY = StartingValue2
    WinCountB2 = 0
    StratAvgB2 = 0
    BestA2 = 0
    BestB2 = 0
    monthinit2 = month
    yearinit2 = year
    EndIf
     
    once valuey = startingvalue2
    once pincpos2 = 1 //positive increment2 position
    once nincpos2 = 1 //negative increment2 position
    once optimise2 = 0 //initialize heuristicks engine counter (must be incremented at position start or exit)
    once mode2 = 1 //switches between negative and positive increments
    //once wincountb2 = 3 //initialize best win count
    //graph wincountb2 coloured (0,0,0) as "wincountb2"
    //once stratavgb2 = 4353 //initialize best avg strategy profit
    //graph stratavgb2 coloured (0,0,0) as "stratavgb2"
     
    if optimise2 = reps2 then
    wincounta2 = 0 //initialize current win count
    stratavga2 = 0 //initialize current avg strategy profit
    heuristicscycle = heuristicscycle + 1
     
    for i2 = 1 to reps2 do
    if positionperf(i2) > 0 then
    wincounta2 = wincounta2 + 1 //increment current wincount
    endif
    stratavga2 = stratavga2 + (((positionperf(i2)*countofposition[i2]*close)*-1)*-1)
    next
    stratavga2 = stratavga2/reps2 //calculate current avg strategy profit
    //graph (positionperf(1)*countofposition[1]*Close)*-1 as "posperf1-2"
    //graph (positionperf(2)*countofposition[2]*Close)*-1 as "posperf2-2"
    //graph stratavga2*-1 as "stratavga2"
    //once besta2 = 300
    //graph besta2 coloured (0,0,0) as "besta2"
    if stratavga2 >= stratavgb2 then
    stratavgb2 = stratavga2 //update best strategy profit
    besta2 = valuey
    endif
    //once bestb2 = 300
    //graph bestb2 coloured (0,0,0) as "bestb2"
    if wincounta2 >= wincountb2 then
    wincountb2 = wincounta2 //update best win count
    bestb2 = valuey
    endif
     
    if wincounta2 > wincountb2 and stratavga2 > stratavgb2 then
    mode2 = 0
    elsif wincounta2 < wincountb2 and stratavga2 < stratavgb2 and mode2 = 1 then
    valuey = valuey - (increment2*nincpos2)
    nincpos2 = nincpos2 + 1
    mode2 = 2
    elsif wincounta2 >= wincountb2 or stratavga2 >= stratavgb2 and mode2 = 1 then
    valuey = valuey + (increment2*pincpos2)
    pincpos2 = pincpos2 + 1
    mode2 = 1
    elsif wincounta2 < wincountb2 and stratavga2 < stratavgb2 and mode2 = 2 then
    valuey = valuey + (increment2*pincpos2)
    pincpos2 = pincpos2 + 1
    mode2 = 1
    elsif wincounta2 >= wincountb2 or stratavga2 >= stratavgb2 and mode2 = 2 then
    valuey = valuey - (increment2*nincpos2)
    nincpos2 = nincpos2 + 1
    mode2 = 2
    endif
     
    if nincpos2 > maxincrement2 or pincpos2 > maxincrement2 then
    if besta2 = bestb2 then
    valuey = besta2
    else
    if reps2 >= 10 then
    weightedscore2 = 10
    else
    weightedscore2 = round((reps2/100)*100)
    endif
    valuey = round(((besta2*(20-weightedscore2)) + (bestb2*weightedscore2))/20) //lower reps = less weight assigned to win%
    endif
    nincpos2 = 1
    pincpos2 = 1
    elsif valuey > maxvalue2 then
    valuey = maxvalue2
    elsif valuey < minvalue2 then
    valuey = minvalue2
    endif
     
    optimise2 = 0
    endif
    
    // heuristics algorithm 2 end
    //endif
    
    elsif heuristicsalgo3 = 1 then
    
    // Heuristics Algorithm 3 Start
    
    //If HeuristicsAlgo3 = 1 Then
     
    If (onmarket[1] = 1 and onmarket = 0) or (longonmarket[1] = 1 and longonmarket and countoflongshares < countoflongshares[1]) or (longonmarket[1] = 1 and longonmarket and countoflongshares > countoflongshares[1]) or (shortonmarket[1] = 1 and shortonmarket and countofshortshares < countofshortshares[1]) or (shortonmarket[1] = 1 and shortonmarket and countofshortshares > countofshortshares[1]) or (longonmarket[1] and shortonmarket) or (shortonmarket[1] and longonmarket) Then
    optimise3 = optimise3 + 1
    EndIf
    
    once monthinit3 = month
    once yearinit3 = year
    If (year = yearinit3 and month = (monthinit3 + ResetPeriod3)) or (year = (yearinit3 + 1) and ((12 - monthinit3) + month = ResetPeriod3)) Then
    ValueZ = StartingValue3
    WinCountB3 = 0
    StratAvgB3 = 0
    BestA3 = 0
    BestB3 = 0
    monthinit3 = month
    yearinit3 = year
    EndIf
    
    once ValueZ = StartingValue3 // N = £/Tick
    once PIncPos3 = 1 //Positive increment2 Position
    once NIncPos3 = 1 //Negative increment2 Position
    once optimise3 = 0 //Initialize Heuristicks Engine Counter (Must be Incremented at Position Start or Exit)
    once Mode3 = 1 //Switches between negative and positive increments
    //once WinCountB3 = 3 //Initialize Best Win Count
    //GRAPH WinCountB3 coloured (0,0,0) AS "WinCountB2"
    //once StratAvgB3 = 4353 //Initialize Best Avg St3ategy Profit
    //GRAPH StratAvgB3 coloured (0,0,0) AS "StratAvgB3"
     
    If optimise3 = Reps3 Then
    WinCountA3 = 0 //Initialize current Win Count
    StratAvgA3 = 0 //Initialize current Avg Strategy Profit
    HeuristicsCycle = HeuristicsCycle + 1
     
    For i3 = 1 to Reps3 Do
    If positionperf(i3) > 0 Then
    WinCountA3 = WinCountA3 + 1 //Increment Current WinCount
    EndIf
    StratAvgA3 = StratAvgA3 + (((PositionPerf(i3)*countofposition[i3]*Close)*-1)*-1)
    Next
    StratAvgA3 = StratAvgA3/Reps3 //Calculate Current Avg Strategy Profit
    //Graph (PositionPerf(1)*countofposition[1]*Close)*-1 as "PosPerf1-2"
    //Graph (PositionPerf(2)*countofposition[2]*Close)*-1 as "PosPerf2-2"///////////// 3?
    //Graph StratAvgA3*-1 as "StratAvgA3"
    //once BestA3 = 300
    //GRAPH BestA3 coloured (0,0,0) AS "BestA3"
    
    If StratAvgA3 >= StratAvgB3 Then
    StratAvgB3 = StratAvgA3 //Update Best Strategy Profit
    BestA3 = ValueZ
    EndIf
    //once BestB3 = 300
    //GRAPH BestB3 coloured (0,0,0) AS "BestB3"
    
    If WinCountA3 >= WinCountB3 Then
    WinCountB3 = WinCountA3 //Update Best Win Count
    BestB3 = ValueZ
    EndIf
     
    If WinCountA3 > WinCountB3 and StratAvgA3 > StratAvgB3 Then
    Mode3 = 0 //Strategy is performing well with current variable, do not optimise
    
    ElsIf WinCountA3 < WinCountB3 and StratAvgA3 < StratAvgB3 and Mode3 = 2 Then
    ValueZ = ValueZ + (Increment3*PIncPos3)
    PIncPos3 = PIncPos3 + 1
    Mode3 = 1  //For strategy performing worse Next cycle optimise with positive increments
    
    ElsIf WinCountA3 < WinCountB3 and StratAvgA3 < StratAvgB3 and Mode3 = 1 Then
    ValueZ = ValueZ - (Increment3*NIncPos3)
    NIncPos3 = NIncPos3 + 1
    Mode3 = 2 //For strategy performing worse Next cycle optimise with negative increments
    
    ElsIf WinCountA3 >= WinCountB3 or StratAvgA3 >= StratAvgB3 and Mode3 = 1 Then
    ValueZ = ValueZ + (Increment3*PIncPos3)
    PIncPos3 = PIncPos3 + 1
    Mode3 = 1 //For strategy performing better Next cycle again optimise with positive increments
    
    ElsIf WinCountA3 >= WinCountB3 or StratAvgA3 >= StratAvgB3 and Mode3 = 2 Then
    ValueZ = ValueZ - (Increment3*NIncPos3)
    NIncPos3 = NIncPos3 + 1
    Mode3 = 2 //For strategy performing better Next cycle again optimise with negative increments
    EndIf
     
    If NIncPos3 > MaxIncrement3 or PIncPos > MaxIncrement3 Then
    If BestA3 = BestB3 Then
    ValueZ = BestA3
    Else
    If reps3 >= 10 Then
    WeightedScore3 = 10
    Else
    WeightedScore3 = round((reps3/100)*100)
    EndIf
    
    ValueZ = round(((BestA3*(20-WeightedScore3)) + (BestB3*WeightedScore3))/20) //Lower Reps = Less weight assigned to Win%
    EndIf
    NIncPos3 = 1
    PIncPos3 = 1
    ElsIf ValueZ > MaxValue3 Then
    ValueZ = MaxValue3
    ElsIf ValueZ < MinValue3 Then
    ValueZ = MinValue3
    EndIF
     
    optimise3 = 0
    EndIf
    
    // Heuristics Algorithm 3 End
    
    Endif
     
    
    //
    BoxSizeL = ValueX
    BoxSizeS = ValueY
    
    //
    renkomaxl = round(close / boxsizel) * boxsizel
    renkominl = renkomaxl - boxsizel
    
    renkomaxs = round(close / boxsizes) * boxsizes
    renkomins = renkomaxs - boxsizes
    
    //
    if high > renkomaxl + boxsizel then
    renkomaxl = renkomaxl + boxsizel
    renkominl = renkominl + boxsizel
    endif
    if low < renkomins - boxsizes then
    renkomaxs = renkomaxs - boxsizesoptimisation
    renkomins = renkomins - boxsizes
    endif
    
    
    // Conditions to enter long positions
    Buy N CONTRACT at renkoMaxL + boxSizeL stop
    
    // Conditions to enter short positions
    Sellshort N CONTRACT at renkoMinS - boxSizeS stop
    
    
    //if percentage then
    //set stop %loss 0.5
    //set target %profit 2
    //else
    
    SET STOP pLOSS ValueZ
    SET TARGET PPROFIT 500
    //endif
    
    //
    //graphonprice renkomaxl + boxsizel coloured(0,200,0) as "renkomax"
    //graphonprice renkomins - boxsizes coloured(200,0,0) as "renkomin"
    
    graph ValueX coloured(0,255,0)
    graph ValueY coloured(255,0,0)
    graph ValueZ coloured(0,0,255)
    
    #139552 quote
    GraHal
    Participant
    Master

    What TF are you running?

    The error messages (divide by zero etc) may not always be accurate.

    If you are running on 1 sec TF then maybe the code above occasionally does not fully execute in 1 second and so the divide by zero error code is thrown up?

    Unless I can quickly spot the cause (for divide by zero etc) I generally start the System back up again and think … “life is too short … I’m not going to get frustrated looking for a problem that may not even exist in the code !!??” 🙂

    PS

    Good to see you back … I thought you may have moved on to pastures new! 🙂

    #139560 quote
    Bard
    Participant
    Master

    Hey GraHal, cheers, likewise and thanks for the help, right, it’s a daily TF and it was stopped out within 24 hours of putting it back up after the first stopped out the day before.

    You know when Juanj said (regarding his ML post topic), words to the effect that this was just “the tip of the iceberg,” well, because I had to take time off from sitting at the desk and 50″ trading screen because of an old back injury flare up (compressed nerve), I went and listened to a lot of Kraftwerk, Stranglers and The Undertones and read everything I could on ML. Please read this phd thesis paper, it will blow your mind:

    https://www.researchgate.net/publication/328838338_Automated_Stock_Market_Trading_Using_Machine_Learning

    The pdf download link is in blue, top right.

    I’m learning to use RapidMiner presently but Gabri (Gabriele) is saying that Python is pretty good too. The hardest and critical part of ML is data preparation. I’m using Excel, and have already programmed all the indicators used in the research paper but would like to add more complex indicators like ones by John Ehlers, so I posted an “Excel collaboration” idea in the forums: https://www.prorealcode.com/topic/collaboration-to-code-indicators-into-excel-file/

    I’m also thinking of maybe getting either a Trading View subscription or Interactive Brokers account because they both let you download O/H/L/C/V and indicator values to Excel which you’ll need. The idea is that the you’ll need to de-trend the noise out of the time series and use volatility data too. Luke Rose’s research paper only used generic indicators though but got incredible 30 and 200 day trend prediction results using Random Forests. Then again he was using the Nasdaq stocks which go up generally, I want to see how accurate it is for mean reverting currencies.

    Let me know what you think?

    #140232 quote
    Bard
    Participant
    Master

    Anyone?

    Tried using if positionperf (i)<>0 for lines 124, 226 and 331 but it still got stopped out.

    #140237 quote
    robertogozzi
    Moderator
    Master

    Try GRAPHing

    • optimise
    • optimise2
    • optimise3
    • heuristicscycle

    I didn’t, but at first glance it looks like some of them could be the problem.

    Bard thanked this post
    #140254 quote
    Dow Jones
    Participant
    Veteran

    I made a simple test that shows back test cannot alert your strategy has division zero issue, you can refer to here, https://www.prorealcode.com/topic/proorder-exception-line-number/#post-140253

    On the same post, I also shared my experience to pay attention to the timing when PRT notify you the division zero error, i.e. the date and time, and use it as your input for debugging. In your case, maybe you can graph all the division and pay attention which variable give you zero on the particular timing or nearby timing in case some delay in sending the notification, but at least it narrow down your debugging range.

    Bard thanked this post
    #140281 quote
    KarlBenjamin
    Participant
    Average

    Hi I’m not exactly a pro coder and it may be something to do with the insert PRT code but every time you use “increment” or “maxincrement” it sees the “rem” and turns it into a remark.

    The earliest lines of this is lines 33 and 35.

    I’ve not used anything like that in my codes so not sure if that’s what happens in the real PRT.

    Bard thanked this post
    #140521 quote
    Bard
    Participant
    Master

    Cheers @robertogozzi !
    I’ll take a look this weekend.

    #140529 quote
    Bard
    Participant
    Master

    Thanks @DowJones for taking the time to help identify this division by zero issue and for the link. I’ll be paying more attention to the time when PRT send the system stopped email.

    #199087 quote
    Dollar
    Participant
    New

    The division by zero may occur on lines 412 or 415

    Passing the both lines as remarks as below, you will avoid the division by zero. But the results will be slightly different as you will be in position for longer periods.

    412 //renkomaxl <span class=”crayon-o”>=</span> <span class=”crayon-st”>round</span>(<span class=”crayon-st”>close</span> <span class=”crayon-o”>/</span> boxsizel) <span class=”crayon-o”>*</span> boxsizel

    415 //renkomaxs <span class=”crayon-o”>=</span> <span class=”crayon-st”>round</span>(<span class=”crayon-st”>close</span> <span class=”crayon-o”>/</span> boxsizes) <span class=”crayon-o”>*</span> boxsizes

Viewing 10 posts - 1 through 10 (of 10 total)
  • You must be logged in to reply to this topic.

Division by zero Stopping Trading System


ProOrder: Automated Strategies & Backtesting

New Reply
Author
author-avatar
Bard @brad Participant
Summary

This topic contains 9 replies,
has 6 voices, and was last updated by Dollar
3 years, 7 months ago.

Topic Details
Forum: ProOrder: Automated Strategies & Backtesting
Language: English
Started: 07/18/2020
Status: Active
Attachments: No files
Logo Logo
Loading...