Migliorare una strategia con trades simulati

Viewing 11 posts - 1 through 11 (of 11 total)
  • Author
    Posts
  • #206862 quote
    Simon
    Participant
    New

    Buongiorno Roberto,

    ho trovato questo codice di Nicolas che trovo molto interessante ma gestisce solo le posizioni long

    Non riesco ad aggiungere il lato short, potresti cortesemente aggiungere tu la gestione dei segnali short in modo che vengano calcolati nella simulazione?

    Il segnale short potrebbe essere la stessa media usata per il long con incrocio al ribasso.

    Grazie

    Link al post originale:

    https://www.prorealcode.com/blog/learning/how-to-improve-a-strategy-with-simulated-trades-1/

     

    defparam cumulateorders=false
     
    // --- strategy settings 
    tpratio = 2.7
    stoploss = 65
    takeprofit = stoploss*tpratio
     
    // --- simulated trading settings 
    equityCurvePeriod = 20 //orders quantity for the equity curve average
    activateSimulatedTrading = 1 //(0= false / 1 =true)
     
    //strategies
    buysignal = average[7] crosses over average[21]//rsi[2] crosses over 30
     
    if realtrading then //real trading
     if not longonmarket and buysignal then
      buy at market
      ordercount=ordercount+1 //counting the order to know we have sufficient ones to activate the simulation later
     endif
     set target pprofit takeprofit
     set stop ploss stoploss
    elsif not realtrading and ordercount>equityCurvePeriod then //fake trading
     if not longontrading and buysignal then
      openprice=close //fake order open price
      longontrading=1 //we are now on market
      //reset MFE & MAE values
      mfe=0
      mae=0
      //fake orders count
      fakeorders=fakeorders+1
     endif
    endif
     
    //check profit n loss of the fake order
    if longontrading=1 then
     mfe = max(high-openprice,mfe) //compute the MaxFavorableExcursion
     mae = min(low-openprice,mae) //compute the MaxAdverseExcursion 
     //profit achieved
     if mfe>=takeprofit*pointsize then //testing the takeprofit 
      orderPNL=((openprice+takeprofit*pointsize)/openprice)-1
      longontrading=0 //not on market anymore
     endif
     //shit happens!
     if mae<=-stoploss*pointsize then //testing the stoploss
      orderPNL=-(((openprice-stoploss*pointsize)/openprice)-1)
      longontrading=0 //not on market anymore
     endif
    endif
     
    //compute equity curve and its average
    if ( (not onmarket and onmarket[1]) or (tradeindex(1)=tradeindex(2) and tradeindex(1)=barindex[1]) or (not longontrading and longontrading[1]) )  and lastcheck<>barindex then //check if an order has just closed or not
     lastcheck = barindex
     
     if(not longontrading[1]) then //if it was a real order
      orderPNL = positionperf(1) //let's take the real position perf (otherwise the last orderPNL is kept (fake order)
     endif
     
     strategyPNL = strategyPNL+orderPNL //cumulate the strategy PnL
     
     //build a loop to make the equity curve average
     count=0
     sum=0
     lastPNL=0
     for i = 0 to barindex do
      if strategyPNL[i]<>lastPNL then
      lastPNL=strategyPNL[i]
      count=count+1
     
      sum=sum+strategyPNL[i]
       if count=equityCurvePeriod+1 then
        sum=sum-last
        last=strategyPNL[i]
        break
        //
       endif
      endif
     next
     if last<>last[1] then
      avg = (sum/equityCurvePeriod)
     endif
     if strategyPNL>avg then
      realtrading=1 //activate real trading if the PnL is superior to its average
     else
      realtrading=0 //or desactivate real trading 
     endif
     if ordercount<=equityCurvePeriod or activateSimulatedTrading=0 then
      realtrading=1 //if not enough orders since the beginning or if simulated trading is force to false, we keep on real trading 
     endif
    endif
     
    //plot the fake orders activation
    if longontrading then
     plotLong = 0.01 //this value might be changed, depending of the strategy
    else
     plotLong = 0
    endif
    //
     
    //plot values
    graph strategyPNL //plot the cumulated PnL
    graph avg coloured(0,0,255) //plot the average of the equity curve
    graph plotLong coloured(0,155,0) //plot the fake orders activation
    #206986 quote
    Simon
    Participant
    New

    Scusa Roberto, non avevo letto tutto il post precedente.  La mia domanda è simile ad una già fatta, non intendevo duplicare il post.

    #208642 quote
    robertogozzi
    Moderator
    Master

    Mi scuso per il notevole ritardo 😔, ma non sono riuscito a esaminare il codice. Sarò impegnato nelle prossime 3 settimane, ma subito dopo lo farò.

    #208701 quote
    Simon
    Participant
    New

    Non importa, grazie, gentilissimo.

    #209852 quote
    robertogozzi
    Moderator
    Master

    Finalmente sono riuscito a fare la modifica.

    Provalo e fammi sapere.

    // Simulated Tradesx
    //
    // https://www.prorealcode.com/blog/learning/how-to-improve-a-strategy-with-simulated-trades-1/
    //
    defparam cumulateorders=false
    
    // --- strategy settings
    tpratio = 2.7
    stoploss = 65
    takeprofit = stoploss*tpratio
    
    // --- simulated trading settings
    equityCurvePeriod = 20 //orders quantity for the equity curve average
    activateSimulatedTrading = 1 //(0= false / 1 =true)
    
    //strategies
    buysignal = average[7] crosses over average[21]//rsi[2] crosses over 30
    shortsignal = average[7] crosses under average[21]//rsi[2] crosses over 30
    
    if realtrading then //real trading
    if not longonmarket and buysignal then
    buy at market
    ordercount=ordercount+1 //counting the order to know we have sufficient ones to activate the simulation later
    elsif not shortonmarket and shortsignal then
    sellshort at market
    ordercount=ordercount+1 //counting the order to know we have sufficient ones to activate the simulation later
    endif
    set target pprofit takeprofit
    set stop ploss stoploss
    elsif not realtrading and ordercount>equityCurvePeriod then //fake trading
    if not longontrading and buysignal then
    openprice=close //fake order open price
    longontrading=1 //we are now on market
    shortontrading=0 //we are now on market
    //reset MFE & MAE values
    mfe=0
    mae=0
    //fake orders count
    fakeorders=fakeorders+1
    elsif not shortontrading and shortsignal then
    openprice=close //fake order open price
    shortontrading=1 //we are now on market
    longontrading=0 //we are now on market
    //reset MFE & MAE values
    mfe=0
    mae=0
    //fake orders count
    fakeorders=fakeorders+1
    endif
    endif
    
    //check profit n loss of the fake order
    if longontrading=1 then
    mfe = max(high-openprice,mfe) //compute the MaxFavorableExcursion
    mae = min(low-openprice,mae) //compute the MaxAdverseExcursion
    //profit achieved
    if mfe>=takeprofit*pointsize then //testing the takeprofit
    orderPNL=((openprice+takeprofit*pointsize)/openprice)-1
    longontrading=0 //not on market anymore
    endif
    //shit happens!
    if mae<=-stoploss*pointsize then //testing the stoploss
    orderPNL=-(((openprice-stoploss*pointsize)/openprice)-1)
    longontrading=0 //not on market anymore
    endif
    elsif shortontrading=1 then
    mfe = max(openprice-low,mfe) //compute the MaxFavorableExcursion
    mae = min(openprice-high,mae) //compute the MaxAdverseExcursion
    //profit achieved
    if mfe>=takeprofit*pointsize then //testing the takeprofit
    orderPNL=((openprice-takeprofit*pointsize)/openprice)-1
    shortontrading=0 //not on market anymore
    endif
    //shit happens!
    if mae<=-stoploss*pointsize then //testing the stoploss
    orderPNL=-(((openprice+stoploss*pointsize)/openprice)-1)
    shortontrading=0 //not on market anymore
    endif
    endif
    
    //compute equity curve and its average
    if ( (not onmarket and onmarket[1]) or (tradeindex(1)=tradeindex(2) and tradeindex(1)=barindex[1]) or (not longontrading and longontrading[1]) or (not shortontrading and shortontrading[1]) )  and lastcheck<>barindex then //check if an order has just closed or not
    lastcheck = barindex
    
    if(not longontrading[1] and not shortontrading[1]) then //if it was a real order
    orderPNL = positionperf(1) //let's take the real position perf (otherwise the last orderPNL is kept (fake order)
    endif
    
    strategyPNL = strategyPNL+orderPNL //cumulate the strategy PnL
    
    //build a loop to make the equity curve average
    count=0
    sum=0
    lastPNL=0
    for i = 0 to barindex do
    if strategyPNL[i]<>lastPNL then
    lastPNL=strategyPNL[i]
    count=count+1
    
    sum=sum+strategyPNL[i]
    if count=equityCurvePeriod+1 then
    sum=sum-last
    last=strategyPNL[i]
    break
    //
    endif
    endif
    next
    if last<>last[1] then
    avg = (sum/equityCurvePeriod)
    endif
    if strategyPNL>avg then
    realtrading=1 //activate real trading if the PnL is superior to its average
    else
    realtrading=0 //or desactivate real trading
    endif
    if ordercount<=equityCurvePeriod or activateSimulatedTrading=0 then
    realtrading=1 //if not enough orders since the beginning or if simulated trading is force to false, we keep on real trading
    endif
    endif
    
    //plot the fake orders activation
    if longontrading then
    plotLong = 0.01 //this value might be changed, depending of the strategy
    plotShort = 0
    else
    plotShort = 0.01 //this value might be changed, depending of the strategy
    plotLong = 0
    endif
    //
    
    //plot values
    graph strategyPNL //plot the cumulated PnL
    graph avg coloured(0,0,255) //plot the average of the equity curve
    graph plotLong coloured(0,155,0) //plot the fake orders activation
    graph plotShort coloured(0,155,0) //plot the fake orders activation
    #209937 quote
    Simon
    Participant
    New

    Grazie Mille Roberto!

    Sto testando il codice, mi sembra che funzioni correttamente.

    Sarebbe possibile aggiungere una  condizione di uscita per lato long e short e inserire il codice di trailing stop?

    Grazie ancora per il prezioso aiuto e il tuo tempo.

    #209938 quote
    Simon
    Participant
    New

    Come trailing stop, mi riferisco alla tua funzione:

    //trailing stop function
    IF NOT ONMARKET THEN
    TrailingStart = sp  //20 trailing will start @trailinstart points profit
    TrailingStep  = ts   //5  trailing step to move the "stoploss"
    Distance      = pk   //7  pips Distance from caurrent price (if required by the broker)
    PointsToKeep  = 1   //1  pips to be gained when breakeven is set
    //reset the stoploss value
    newSL=0
    ENDIF
    IF (BarIndex - TradeIndex) >= 0 THEN                                 //0
    //manage long positions
    IF LONGONMARKET THEN
    //first move (breakeven)
    IF newSL=0 AND high-TradePrice(1)>=(TrailingStart*PipSize+PointsToKeep*PipSize) THEN
    newSL = TradePrice(1)+TrailingStep*PipSize+PointsToKeep*PipSize
    ENDIF
    //next moves
    IF newSL>0 AND close-newSL>=TrailingStep*PipSize THEN
    newSL = newSL+TrailingStep*PipSize
    ENDIF
    ENDIF
     
    //manage short positions
    IF SHORTONMARKET THEN
    //first move (breakeven)
    IF newSL=0 AND TradePrice(1)-low>=(TrailingStart*PipSize+PointsToKeep*PipSize) THEN
    newSL = TradePrice(1)-TrailingStep*PipSize+PointsToKeep*PipSize
    ENDIF
    //next moves
    IF newSL>0 AND newSL-close>=TrailingStep*PipSize THEN
    newSL = newSL-TrailingStep*PipSize
    ENDIF
    ENDIF
     
    //stop order to exit the positions
    IF newSL>0 THEN
    IF LongOnMarket THEN
    IF (close + Distance) > newSL THEN
    SELL AT newSL STOP
    ELSIF (close - Distance) < newSL THEN
    SELL AT newSL LIMIT
    ELSE
    SELL AT Market
    ENDIF
    ELSIF ShortOnmarket THEN
    IF (close + Distance) < newSL THEN
    EXITSHORT AT newSL STOP
    ELSIF (close - Distance) > newSL THEN
    EXITSHORT AT newSL LIMIT
    ELSE
    EXITSHORT AT Market
    ENDIF
    ENDIF
    ENDIF
    ENDIF
    //***************************************
    #210286 quote
    robertogozzi
    Moderator
    Master

    Le condizioni di uscita cis sono già, lo Stop Loss, il Take Profit e lo Stop & Reverse, oltre al trailing stop. Non ho idea a quali condizioni ti riferisci.

    Per il trailing stop basta aggiungere, alla fine (prima di GRAPH), le righe che hai postato. Questo è il codice completo:

    // Simulated Tradesx
    //
    // https://www.prorealcode.com/blog/learning/how-to-improve-a-strategy-with-simulated-trades-1/
    //
    defparam cumulateorders=false
    
    // --- strategy settings
    tpratio = 2.7
    stoploss = 65
    takeprofit = stoploss*tpratio
    
    // --- simulated trading settings
    equityCurvePeriod = 20 //orders quantity for the equity curve average
    activateSimulatedTrading = 1 //(0= false / 1 =true)
    
    //strategies
    buysignal = average[7] crosses over average[21]//rsi[2] crosses over 30
    shortsignal = average[7] crosses under average[21]//rsi[2] crosses over 30
    
    if realtrading then //real trading
    if not longonmarket and buysignal then
    buy at market
    ordercount=ordercount+1 //counting the order to know we have sufficient ones to activate the simulation later
    elsif not shortonmarket and shortsignal then
    sellshort at market
    ordercount=ordercount+1 //counting the order to know we have sufficient ones to activate the simulation later
    endif
    set target pprofit takeprofit
    set stop ploss stoploss
    elsif not realtrading and ordercount>equityCurvePeriod then //fake trading
    if not longontrading and buysignal then
    openprice=close //fake order open price
    longontrading=1 //we are now on market
    shortontrading=0 //we are now on market
    //reset MFE & MAE values
    mfe=0
    mae=0
    //fake orders count
    fakeorders=fakeorders+1
    elsif not shortontrading and shortsignal then
    openprice=close //fake order open price
    shortontrading=1 //we are now on market
    longontrading=0 //we are now on market
    //reset MFE & MAE values
    mfe=0
    mae=0
    //fake orders count
    fakeorders=fakeorders+1
    endif
    endif
    
    //check profit n loss of the fake order
    if longontrading=1 then
    mfe = max(high-openprice,mfe) //compute the MaxFavorableExcursion
    mae = min(low-openprice,mae) //compute the MaxAdverseExcursion
    //profit achieved
    if mfe>=takeprofit*pointsize then //testing the takeprofit
    orderPNL=((openprice+takeprofit*pointsize)/openprice)-1
    longontrading=0 //not on market anymore
    endif
    //shit happens!
    if mae<=-stoploss*pointsize then //testing the stoploss
    orderPNL=-(((openprice-stoploss*pointsize)/openprice)-1)
    longontrading=0 //not on market anymore
    endif
    elsif shortontrading=1 then
    mfe = max(openprice-low,mfe) //compute the MaxFavorableExcursion
    mae = min(openprice-high,mae) //compute the MaxAdverseExcursion
    //profit achieved
    if mfe>=takeprofit*pointsize then //testing the takeprofit
    orderPNL=((openprice-takeprofit*pointsize)/openprice)-1
    shortontrading=0 //not on market anymore
    endif
    //shit happens!
    if mae<=-stoploss*pointsize then //testing the stoploss
    orderPNL=-(((openprice+stoploss*pointsize)/openprice)-1)
    shortontrading=0 //not on market anymore
    endif
    endif
    
    //compute equity curve and its average
    if ( (not onmarket and onmarket[1]) or (tradeindex(1)=tradeindex(2) and tradeindex(1)=barindex[1]) or (not longontrading and longontrading[1]) or (not shortontrading and shortontrading[1]) )  and lastcheck<>barindex then //check if an order has just closed or not
    lastcheck = barindex
    
    if(not longontrading[1] and not shortontrading[1]) then //if it was a real order
    orderPNL = positionperf(1) //let's take the real position perf (otherwise the last orderPNL is kept (fake order)
    endif
    
    strategyPNL = strategyPNL+orderPNL //cumulate the strategy PnL
    
    //build a loop to make the equity curve average
    count=0
    sum=0
    lastPNL=0
    for i = 0 to barindex do
    if strategyPNL[i]<>lastPNL then
    lastPNL=strategyPNL[i]
    count=count+1
    
    sum=sum+strategyPNL[i]
    if count=equityCurvePeriod+1 then
    sum=sum-last
    last=strategyPNL[i]
    break
    //
    endif
    endif
    next
    if last<>last[1] then
    avg = (sum/equityCurvePeriod)
    endif
    if strategyPNL>avg then
    realtrading=1 //activate real trading if the PnL is superior to its average
    else
    realtrading=0 //or desactivate real trading
    endif
    if ordercount<=equityCurvePeriod or activateSimulatedTrading=0 then
    realtrading=1 //if not enough orders since the beginning or if simulated trading is force to false, we keep on real trading
    endif
    endif
    
    //plot the fake orders activation
    if longontrading then
    plotLong = 0.01 //this value might be changed, depending of the strategy
    plotShort = 0
    else
    plotShort = 0.01 //this value might be changed, depending of the strategy
    plotLong = 0
    endif
    //
    //******************************************************************************
    //trailing stop function
    IF NOT ONMARKET THEN
    TrailingStart = 20//sp  //20 trailing will start @trailinstart points profit
    TrailingStep  = 5 //ts   //5  trailing step to move the "stoploss"
    Distance      = 7 //pk   //7  pips Distance from caurrent price (if required by the broker)
    PointsToKeep  = 1 //1  pips to be gained when breakeven is set
    //reset the stoploss value
    newSL=0
    ENDIF
    IF (BarIndex - TradeIndex) >= 0 THEN                                 //0
    //manage long positions
    IF LONGONMARKET THEN
    //first move (breakeven)
    IF newSL=0 AND high-TradePrice(1)>=(TrailingStart*PipSize+PointsToKeep*PipSize) THEN
    newSL = TradePrice(1)+TrailingStep*PipSize+PointsToKeep*PipSize
    ENDIF
    //next moves
    IF newSL>0 AND close-newSL>=TrailingStep*PipSize THEN
    newSL = newSL+TrailingStep*PipSize
    ENDIF
    ENDIF
     
    //manage short positions
    IF SHORTONMARKET THEN
    //first move (breakeven)
    IF newSL=0 AND TradePrice(1)-low>=(TrailingStart*PipSize+PointsToKeep*PipSize) THEN
    newSL = TradePrice(1)-TrailingStep*PipSize+PointsToKeep*PipSize
    ENDIF
    //next moves
    IF newSL>0 AND newSL-close>=TrailingStep*PipSize THEN
    newSL = newSL-TrailingStep*PipSize
    ENDIF
    ENDIF
     
    //stop order to exit the positions
    IF newSL>0 THEN
    IF LongOnMarket THEN
    IF (close + Distance) > newSL THEN
    SELL AT newSL STOP
    ELSIF (close - Distance) < newSL THEN
    SELL AT newSL LIMIT
    ELSE
    SELL AT Market
    ENDIF
    ELSIF ShortOnmarket THEN
    IF (close + Distance) < newSL THEN
    EXITSHORT AT newSL STOP
    ELSIF (close - Distance) > newSL THEN
    EXITSHORT AT newSL LIMIT
    ELSE
    EXITSHORT AT Market
    ENDIF
    ENDIF
    ENDIF
    ENDIF
    //******************************************************************************
    
    //plot values
    graph strategyPNL //plot the cumulated PnL
    graph avg coloured(0,0,255) //plot the average of the equity curve
    graph plotLong coloured(0,155,0) //plot the fake orders activation
    graph plotShort coloured(0,155,0) //plot the fake orders activation
    #210290 quote
    Simon
    Participant
    New

    Buongiorno Roberto,

    innanzitutto grazie,

    come condizioni di uscita intendevo due aree dove inserire condizioni per   exitlong e exitshort  che se si verificano, escono dal mercato (oltre allo stoploss e stop profit) es. una condizione di ipervenduto / ipercomprato o altro

    Domanda, il codice di trailing stop che hai  inserito in fondo quindi funziona anche negli ordini simulati? Cioè replica le stesse uscite anche quando il ts stà simulando gli ordini?

    Grazie ancora

    #210299 quote
    robertogozzi
    Moderator
    Master

    No, funziona solo con le operazioni reali.

    Per adattarlo anche agli ordini simulati occorre entrare bene nalla logica della simulazione e richiede del tempo.

    Posso fartelo, ma… non troppo velocemente!

    #210313 quote
    Simon
    Participant
    New

    Grazie Roberto,

    te ne sarei grato, prenditi il tempo necessario, aspetto.

    Buona giornata

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

Migliorare una strategia con trades simulati


Supporto ProOrder

New Reply
Author
author-avatar
Simon @simontemp Participant
Summary

This topic contains 10 replies,
has 2 voices, and was last updated by Simon
2 years, 11 months ago.

Topic Details
Forum: Supporto ProOrder
Language: Italian
Started: 01/06/2023
Status: Active
Attachments: 2 files
Logo Logo
Loading...