Custom backtester AFL code to trade only on first x signals where signal is generated
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Custom Backtester to Trade only on First x Symbols | |
Coded by ChokS | |
https://howutrade.in | |
The 'MaxOpenPositions' setting is used to limit the number of open positions at any point of time. | |
Example: | |
Say you are backtesting 100 symbols and set 'MaxOpenPositions' to 5, | |
This will limit the number of open positions to 5 at any point of time, but once a position is closed, new signal will be taken, | |
means trades may be taken for more than 5 symbols | |
This code will not limit trades, it limits just symbols. | |
But what if you want to just trade only on the first 5 symbols where the signal is generated. | |
Below Code will do that, | |
Reference: https://forum.amibroker.com/ | |
*/ | |
_SECTION_BEGIN("BACKTEST"); | |
MaxSymbols = Param("Max Symbols", 5, 1, 200, 1); | |
BarDate = DateNum(); //To Check First Bar of the Day | |
PositionCount = 0; //Used to hold positions count for the current day | |
PositionList = ""; //Used to hold positions list for the current day | |
SetCustomBacktestProc(""); | |
if (Status("action") == actionPortfolio) { | |
bo = GetBacktesterObject(); | |
bo.PreProcess(); | |
for (i = 1; i < BarCount; i++) //Loop through all bars | |
{ | |
//reset positions count and list on first bar | |
if (i == 1 OR(BarDate[i] != BarDate[i - 1])) { | |
PositionCount = 0; | |
PositionList = ""; | |
} | |
for (sig = bo.GetFirstSignal(i); sig; sig = bo.GetNextSignal(i)) { | |
//Apply the logic on EntrySignals | |
if (sig.IsEntry) { | |
Sym = "[" + sig.Symbol + "]"; //Get Symbol of the Signal | |
//We will take the signal on any of the below conditions | |
//Position Count lesser than Max Symbols we set OR | |
//The Signal symbol is already present in our Position List | |
CanTrade = (PositionCount < MaxSymbols OR StrFind(PositionList, Sym) > 0); | |
if (CanTrade) { | |
//update running positions | |
//only once | |
if (StrFind(PositionList, Sym) < 1) { | |
PositionCount = PositionCount + 1; | |
LastList = PositionList; | |
PositionList = LastList + Sym; | |
} | |
} else { | |
sig.Price = -1; //No Trade | |
} | |
} | |
} | |
bo.ProcessTradeSignals(i); | |
} | |
bo.PostProcess(); | |
} | |
_SECTION_END(); |