Migliorare una strategia con trades simulati
Forums › ProRealTime forum Italiano › Supporto ProOrder › Migliorare una strategia con trades simulati
- This topic has 10 replies, 2 voices, and was last updated 1 year ago by Simon.
-
-
01/06/2023 at 8:39 AM #206862
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/
How to improve a strategy with simulated trades123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102defparam cumulateorders=false// --- strategy settingstpratio = 2.7stoploss = 65takeprofit = stoploss*tpratio// --- simulated trading settingsequityCurvePeriod = 20 //orders quantity for the equity curve averageactivateSimulatedTrading = 1 //(0= false / 1 =true)//strategiesbuysignal = average[7] crosses over average[21]//rsi[2] crosses over 30if realtrading then //real tradingif not longonmarket and buysignal thenbuy at marketordercount=ordercount+1 //counting the order to know we have sufficient ones to activate the simulation laterendifset target pprofit takeprofitset stop ploss stoplosselsif not realtrading and ordercount>equityCurvePeriod then //fake tradingif not longontrading and buysignal thenopenprice=close //fake order open pricelongontrading=1 //we are now on market//reset MFE & MAE valuesmfe=0mae=0//fake orders countfakeorders=fakeorders+1endifendif//check profit n loss of the fake orderif longontrading=1 thenmfe = max(high-openprice,mfe) //compute the MaxFavorableExcursionmae = min(low-openprice,mae) //compute the MaxAdverseExcursion//profit achievedif mfe>=takeprofit*pointsize then //testing the takeprofitorderPNL=((openprice+takeprofit*pointsize)/openprice)-1longontrading=0 //not on market anymoreendif//shit happens!if mae<=-stoploss*pointsize then //testing the stoplossorderPNL=-(((openprice-stoploss*pointsize)/openprice)-1)longontrading=0 //not on market anymoreendifendif//compute equity curve and its averageif ( (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 notlastcheck = barindexif(not longontrading[1]) then //if it was a real orderorderPNL = positionperf(1) //let's take the real position perf (otherwise the last orderPNL is kept (fake order)endifstrategyPNL = strategyPNL+orderPNL //cumulate the strategy PnL//build a loop to make the equity curve averagecount=0sum=0lastPNL=0for i = 0 to barindex doif strategyPNL[i]<>lastPNL thenlastPNL=strategyPNL[i]count=count+1sum=sum+strategyPNL[i]if count=equityCurvePeriod+1 thensum=sum-lastlast=strategyPNL[i]break//endifendifnextif last<>last[1] thenavg = (sum/equityCurvePeriod)endifif strategyPNL>avg thenrealtrading=1 //activate real trading if the PnL is superior to its averageelserealtrading=0 //or desactivate real tradingendifif ordercount<=equityCurvePeriod or activateSimulatedTrading=0 thenrealtrading=1 //if not enough orders since the beginning or if simulated trading is force to false, we keep on real tradingendifendif//plot the fake orders activationif longontrading thenplotLong = 0.01 //this value might be changed, depending of the strategyelseplotLong = 0endif////plot valuesgraph strategyPNL //plot the cumulated PnLgraph avg coloured(0,0,255) //plot the average of the equity curvegraph plotLong coloured(0,155,0) //plot the fake orders activation01/07/2023 at 11:49 AM #20698601/29/2023 at 1:10 PM #208642Mi scuso per il notevole ritardo 😔, ma non sono riuscito a esaminare il codice. Sarò impegnato nelle prossime 3 settimane, ma subito dopo lo farò.
01/29/2023 at 9:12 PM #20870102/17/2023 at 4:30 PM #209852Finalmente sono riuscito a fare la modifica.
Provalo e fammi sapere.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136// Simulated Tradesx//// https://www.prorealcode.com/blog/learning/how-to-improve-a-strategy-with-simulated-trades-1///defparam cumulateorders=false// --- strategy settingstpratio = 2.7stoploss = 65takeprofit = stoploss*tpratio// --- simulated trading settingsequityCurvePeriod = 20 //orders quantity for the equity curve averageactivateSimulatedTrading = 1 //(0= false / 1 =true)//strategiesbuysignal = average[7] crosses over average[21]//rsi[2] crosses over 30shortsignal = average[7] crosses under average[21]//rsi[2] crosses over 30if realtrading then //real tradingif not longonmarket and buysignal thenbuy at marketordercount=ordercount+1 //counting the order to know we have sufficient ones to activate the simulation laterelsif not shortonmarket and shortsignal thensellshort at marketordercount=ordercount+1 //counting the order to know we have sufficient ones to activate the simulation laterendifset target pprofit takeprofitset stop ploss stoplosselsif not realtrading and ordercount>equityCurvePeriod then //fake tradingif not longontrading and buysignal thenopenprice=close //fake order open pricelongontrading=1 //we are now on marketshortontrading=0 //we are now on market//reset MFE & MAE valuesmfe=0mae=0//fake orders countfakeorders=fakeorders+1elsif not shortontrading and shortsignal thenopenprice=close //fake order open priceshortontrading=1 //we are now on marketlongontrading=0 //we are now on market//reset MFE & MAE valuesmfe=0mae=0//fake orders countfakeorders=fakeorders+1endifendif//check profit n loss of the fake orderif longontrading=1 thenmfe = max(high-openprice,mfe) //compute the MaxFavorableExcursionmae = min(low-openprice,mae) //compute the MaxAdverseExcursion//profit achievedif mfe>=takeprofit*pointsize then //testing the takeprofitorderPNL=((openprice+takeprofit*pointsize)/openprice)-1longontrading=0 //not on market anymoreendif//shit happens!if mae<=-stoploss*pointsize then //testing the stoplossorderPNL=-(((openprice-stoploss*pointsize)/openprice)-1)longontrading=0 //not on market anymoreendifelsif shortontrading=1 thenmfe = max(openprice-low,mfe) //compute the MaxFavorableExcursionmae = min(openprice-high,mae) //compute the MaxAdverseExcursion//profit achievedif mfe>=takeprofit*pointsize then //testing the takeprofitorderPNL=((openprice-takeprofit*pointsize)/openprice)-1shortontrading=0 //not on market anymoreendif//shit happens!if mae<=-stoploss*pointsize then //testing the stoplossorderPNL=-(((openprice+stoploss*pointsize)/openprice)-1)shortontrading=0 //not on market anymoreendifendif//compute equity curve and its averageif ( (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 notlastcheck = barindexif(not longontrading[1] and not shortontrading[1]) then //if it was a real orderorderPNL = positionperf(1) //let's take the real position perf (otherwise the last orderPNL is kept (fake order)endifstrategyPNL = strategyPNL+orderPNL //cumulate the strategy PnL//build a loop to make the equity curve averagecount=0sum=0lastPNL=0for i = 0 to barindex doif strategyPNL[i]<>lastPNL thenlastPNL=strategyPNL[i]count=count+1sum=sum+strategyPNL[i]if count=equityCurvePeriod+1 thensum=sum-lastlast=strategyPNL[i]break//endifendifnextif last<>last[1] thenavg = (sum/equityCurvePeriod)endifif strategyPNL>avg thenrealtrading=1 //activate real trading if the PnL is superior to its averageelserealtrading=0 //or desactivate real tradingendifif ordercount<=equityCurvePeriod or activateSimulatedTrading=0 thenrealtrading=1 //if not enough orders since the beginning or if simulated trading is force to false, we keep on real tradingendifendif//plot the fake orders activationif longontrading thenplotLong = 0.01 //this value might be changed, depending of the strategyplotShort = 0elseplotShort = 0.01 //this value might be changed, depending of the strategyplotLong = 0endif////plot valuesgraph strategyPNL //plot the cumulated PnLgraph avg coloured(0,0,255) //plot the average of the equity curvegraph plotLong coloured(0,155,0) //plot the fake orders activationgraph plotShort coloured(0,155,0) //plot the fake orders activation02/19/2023 at 9:22 AM #209937Grazie 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.
02/19/2023 at 9:28 AM #209938Come trailing stop, mi riferisco alla tua funzione:
Trailing stop function1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556//trailing stop functionIF NOT ONMARKET THENTrailingStart = sp //20 trailing will start @trailinstart points profitTrailingStep = 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 valuenewSL=0ENDIFIF (BarIndex - TradeIndex) >= 0 THEN //0//manage long positionsIF LONGONMARKET THEN//first move (breakeven)IF newSL=0 AND high-TradePrice(1)>=(TrailingStart*PipSize+PointsToKeep*PipSize) THENnewSL = TradePrice(1)+TrailingStep*PipSize+PointsToKeep*PipSizeENDIF//next movesIF newSL>0 AND close-newSL>=TrailingStep*PipSize THENnewSL = newSL+TrailingStep*PipSizeENDIFENDIF//manage short positionsIF SHORTONMARKET THEN//first move (breakeven)IF newSL=0 AND TradePrice(1)-low>=(TrailingStart*PipSize+PointsToKeep*PipSize) THENnewSL = TradePrice(1)-TrailingStep*PipSize+PointsToKeep*PipSizeENDIF//next movesIF newSL>0 AND newSL-close>=TrailingStep*PipSize THENnewSL = newSL-TrailingStep*PipSizeENDIFENDIF//stop order to exit the positionsIF newSL>0 THENIF LongOnMarket THENIF (close + Distance) > newSL THENSELL AT newSL STOPELSIF (close - Distance) < newSL THENSELL AT newSL LIMITELSESELL AT MarketENDIFELSIF ShortOnmarket THENIF (close + Distance) < newSL THENEXITSHORT AT newSL STOPELSIF (close - Distance) > newSL THENEXITSHORT AT newSL LIMITELSEEXITSHORT AT MarketENDIFENDIFENDIFENDIF//***************************************02/23/2023 at 3:43 PM #210286Le 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:
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193// Simulated Tradesx//// https://www.prorealcode.com/blog/learning/how-to-improve-a-strategy-with-simulated-trades-1///defparam cumulateorders=false// --- strategy settingstpratio = 2.7stoploss = 65takeprofit = stoploss*tpratio// --- simulated trading settingsequityCurvePeriod = 20 //orders quantity for the equity curve averageactivateSimulatedTrading = 1 //(0= false / 1 =true)//strategiesbuysignal = average[7] crosses over average[21]//rsi[2] crosses over 30shortsignal = average[7] crosses under average[21]//rsi[2] crosses over 30if realtrading then //real tradingif not longonmarket and buysignal thenbuy at marketordercount=ordercount+1 //counting the order to know we have sufficient ones to activate the simulation laterelsif not shortonmarket and shortsignal thensellshort at marketordercount=ordercount+1 //counting the order to know we have sufficient ones to activate the simulation laterendifset target pprofit takeprofitset stop ploss stoplosselsif not realtrading and ordercount>equityCurvePeriod then //fake tradingif not longontrading and buysignal thenopenprice=close //fake order open pricelongontrading=1 //we are now on marketshortontrading=0 //we are now on market//reset MFE & MAE valuesmfe=0mae=0//fake orders countfakeorders=fakeorders+1elsif not shortontrading and shortsignal thenopenprice=close //fake order open priceshortontrading=1 //we are now on marketlongontrading=0 //we are now on market//reset MFE & MAE valuesmfe=0mae=0//fake orders countfakeorders=fakeorders+1endifendif//check profit n loss of the fake orderif longontrading=1 thenmfe = max(high-openprice,mfe) //compute the MaxFavorableExcursionmae = min(low-openprice,mae) //compute the MaxAdverseExcursion//profit achievedif mfe>=takeprofit*pointsize then //testing the takeprofitorderPNL=((openprice+takeprofit*pointsize)/openprice)-1longontrading=0 //not on market anymoreendif//shit happens!if mae<=-stoploss*pointsize then //testing the stoplossorderPNL=-(((openprice-stoploss*pointsize)/openprice)-1)longontrading=0 //not on market anymoreendifelsif shortontrading=1 thenmfe = max(openprice-low,mfe) //compute the MaxFavorableExcursionmae = min(openprice-high,mae) //compute the MaxAdverseExcursion//profit achievedif mfe>=takeprofit*pointsize then //testing the takeprofitorderPNL=((openprice-takeprofit*pointsize)/openprice)-1shortontrading=0 //not on market anymoreendif//shit happens!if mae<=-stoploss*pointsize then //testing the stoplossorderPNL=-(((openprice+stoploss*pointsize)/openprice)-1)shortontrading=0 //not on market anymoreendifendif//compute equity curve and its averageif ( (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 notlastcheck = barindexif(not longontrading[1] and not shortontrading[1]) then //if it was a real orderorderPNL = positionperf(1) //let's take the real position perf (otherwise the last orderPNL is kept (fake order)endifstrategyPNL = strategyPNL+orderPNL //cumulate the strategy PnL//build a loop to make the equity curve averagecount=0sum=0lastPNL=0for i = 0 to barindex doif strategyPNL[i]<>lastPNL thenlastPNL=strategyPNL[i]count=count+1sum=sum+strategyPNL[i]if count=equityCurvePeriod+1 thensum=sum-lastlast=strategyPNL[i]break//endifendifnextif last<>last[1] thenavg = (sum/equityCurvePeriod)endifif strategyPNL>avg thenrealtrading=1 //activate real trading if the PnL is superior to its averageelserealtrading=0 //or desactivate real tradingendifif ordercount<=equityCurvePeriod or activateSimulatedTrading=0 thenrealtrading=1 //if not enough orders since the beginning or if simulated trading is force to false, we keep on real tradingendifendif//plot the fake orders activationif longontrading thenplotLong = 0.01 //this value might be changed, depending of the strategyplotShort = 0elseplotShort = 0.01 //this value might be changed, depending of the strategyplotLong = 0endif////******************************************************************************//trailing stop functionIF NOT ONMARKET THENTrailingStart = 20//sp //20 trailing will start @trailinstart points profitTrailingStep = 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 valuenewSL=0ENDIFIF (BarIndex - TradeIndex) >= 0 THEN //0//manage long positionsIF LONGONMARKET THEN//first move (breakeven)IF newSL=0 AND high-TradePrice(1)>=(TrailingStart*PipSize+PointsToKeep*PipSize) THENnewSL = TradePrice(1)+TrailingStep*PipSize+PointsToKeep*PipSizeENDIF//next movesIF newSL>0 AND close-newSL>=TrailingStep*PipSize THENnewSL = newSL+TrailingStep*PipSizeENDIFENDIF//manage short positionsIF SHORTONMARKET THEN//first move (breakeven)IF newSL=0 AND TradePrice(1)-low>=(TrailingStart*PipSize+PointsToKeep*PipSize) THENnewSL = TradePrice(1)-TrailingStep*PipSize+PointsToKeep*PipSizeENDIF//next movesIF newSL>0 AND newSL-close>=TrailingStep*PipSize THENnewSL = newSL-TrailingStep*PipSizeENDIFENDIF//stop order to exit the positionsIF newSL>0 THENIF LongOnMarket THENIF (close + Distance) > newSL THENSELL AT newSL STOPELSIF (close - Distance) < newSL THENSELL AT newSL LIMITELSESELL AT MarketENDIFELSIF ShortOnmarket THENIF (close + Distance) < newSL THENEXITSHORT AT newSL STOPELSIF (close - Distance) > newSL THENEXITSHORT AT newSL LIMITELSEEXITSHORT AT MarketENDIFENDIFENDIFENDIF//******************************************************************************//plot valuesgraph strategyPNL //plot the cumulated PnLgraph avg coloured(0,0,255) //plot the average of the equity curvegraph plotLong coloured(0,155,0) //plot the fake orders activationgraph plotShort coloured(0,155,0) //plot the fake orders activation02/23/2023 at 4:05 PM #210290Buongiorno 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
02/23/2023 at 4:24 PM #210299No, 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!
02/23/2023 at 5:13 PM #210313 -
AuthorPosts
Find exclusive trading pro-tools on