I'm new to AFL and I'm stuck on how to properly get the stats of the global portfolio to make decisions in the current backtest, based on what's happening globally. I tried using the GetBacktesterObject() without success, likely because of my ignorance of course.
Buy = Cond1 AND losing_trades_in_row < 5
Is it possible to do that? For example, is there a counter of the current losing trades in a row number?
It depends if you want to do that on portfolio level (so 5 losses in a row but not only on same symbol but possibly on DIFFERENT symbols, so two loses on MSFT followed by say three loses on AAPL - where ordering of trades is directed by EXIT date), or on individual symbol level.
If you want to do that on portfolio level then you need custom backtester
SetCustomBacktestProc("");
Buy = Cross( C, MA(C,10 ) );
Sell = Cross( MA(C, 10 ), C );
if (Status("action") == actionPortfolio)
{
bo = GetBacktesterObject(); // Get backtester object
bo.PreProcess(); // Do pre-processing (always required)
for (i = 0; i < BarCount; i++) // Loop through all bars
{
consLoss = 0;
prevProfit = 0;
for( trade = bo.GetFirstTrade(); trade; trade = bo.GetNextTrade() )
{
if( consLoss < 5 )
{
profit = trade.GetProfit();
if( profit >= 0 ) consLoss = 0;
else
{
if( prevProfit >= 0 ) consLoss = 1;
else consLoss++;
}
prevProfit = profit;
}
}
for (sig = bo.GetFirstSignal( i ); sig; sig = bo.GetNextSignal( i ) )
{
// do your custom signal processing
if( consLoss >= 5 AND sig.IsEntry() ) sig.Price = -1; // SKIP signal
}
bo.ProcessTradeSignals( i ); // Process trades at bar (always required)
}
bo.PostProcess(); // Do post-processing (always required)
}
Thanks a lot for your quick response, @Tomasz! Beautiful!
Yes, and I wanted to do it directed by EXIT date, so if I have 5 losses in a row based on exit dates, I stop trading. Your code is more than enough, I will tweak and play by myself while I do the proper homework and study AFL from A to Z. It seems to me that I started learning and tried to apply something slightly complex for my first strategy.
Once again, Tomasz, thanks a lot for your support!
It is worth noting that I used code snippets to write that. I opened AFL Formula Editor,
chose "CBT Mid Level" from Code Snippets window and I only added those 10 lines that go thru closed trades and check how many of them were losing in a row.
I could also have typed @cbtmid and pressed ENTER and snippet would be inserted without even using a mouse.
Maybe you should also look for a way to make them more visible (for instance avoiding the possibility tyo completely hide them addinf a button in the toolbar) and/or to promote their usage in some way (start page or a as a daily tip like many software do).
And about the snippets shortcuts it would be nice to have a "dynamically" created page that lists all the currently defined shortcuts (btw, at present it seems to me that there is no check for shortcuts duplicates/conflicts - in such cases the top one is always "expanded").