I want to exit all trades if the average profit for all the open positions in a
portfolio exceeds a specified value. At the end of this message is the code I
have come up with, I do not think it is working correctly. The reason I am
suspect is that the number of trades I see that show "10" as the reason for
exit is only about 1% of all the trades taken. I'd expect the portfolio stop to
be triggered more like 40% of the time. I am new to the custom backtester and
could really use some help. Thanks!
EnableRotationalTrading();
Maxp = 3;
PositionScore = 1000 - MA( (C/Ref(C,-1)-1),3);
PositionSize = -(100/Maxp);
SetOption("WorstRankHeld", Maxp+2);
SetOption("MaxOpenPositions", Maxp);
SetOption("MaxOpenlong", Maxp);
SetOption("MaxOpenshort", Maxp);
SetOption("UseCustomBacktestProc", True );
if( Status("action") == actionPortfolio )
{
bo = GetBacktesterObject();
bo.PreProcess(); // Initialize backtester
for(bar=0; bar < BarCount; bar++)
{
bo.ProcessTradeSignals( bar );
SumProfitPer= 0; //reset on every bar
NumTrades = 0;
for( pos = bo.GetFirstOpenPos(); pos; pos = bo.GetNextOpenPos() )//iterate
through all open positions for current bar
{
SumProfitPer = SumProfitPer + pos.GetPercentProfit(); //sum
open profit percent for positions
NumTrades++; // count open trades
}
Avp = (SumProfitPer / NumTrades); //average portfolio profit
for( posi = bo.GetFirstOpenPos(); posi; posi = bo.GetNextOpenPos() )
//iterate through open positions again
{
price = posi.GetPrice( bar, "c" );
if( Avp >= 1.5 AND NumTrades=Maxp ) // if average profit crosses amount
exit all open trades at bar close
{
bo.exittrade( bar, posi.Symbol,price,10); //10 is just the tag so we know
this stop was triggered
}
}
}
bo.PostProcess(); // Finalize backtester
}