ProRealCode - Trading & Coding with ProRealTime™
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
Scusa Roberto, non avevo letto tutto il post precedente. La mia domanda è simile ad una già fatta, non intendevo duplicare il post.
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ò.
Non importa, grazie, gentilissimo.
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
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.
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
//***************************************
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
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
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!
Grazie Roberto,
te ne sarei grato, prenditi il tempo necessario, aspetto.
Buona giornata
Migliorare una strategia con trades simulati
This topic contains 10 replies,
has 2 voices, and was last updated by Simon
2 years, 11 months ago.
| Forum: | Supporto ProOrder |
| Language: | Italian |
| Started: | 01/06/2023 |
| Status: | Active |
| Attachments: | 2 files |
The information collected on this form is stored in a computer file by ProRealCode to create and access your ProRealCode profile. This data is kept in a secure database for the duration of the member's membership. They will be kept as long as you use our services and will be automatically deleted after 3 years of inactivity. Your personal data is used to create your private profile on ProRealCode. This data is maintained by SAS ProRealCode, 407 rue Freycinet, 59151 Arleux, France. If you subscribe to our newsletters, your email address is provided to our service provider "MailChimp" located in the United States, with whom we have signed a confidentiality agreement. This company is also compliant with the EU/Swiss Privacy Shield, and the GDPR. For any request for correction or deletion concerning your data, you can directly contact the ProRealCode team by email at privacy@prorealcode.com If you would like to lodge a complaint regarding the use of your personal data, you can contact your data protection supervisory authority.