{"id":1716,"date":"2008-03-16T11:52:08","date_gmt":"2008-03-16T11:52:08","guid":{"rendered":"http:\/\/www.amibroker.org\/userkb\/2008\/03\/16\/amibroker-custom-backtester-interface-2\/"},"modified":"2015-09-30T14:28:03","modified_gmt":"2015-09-30T14:28:03","slug":"amibroker-custom-backtester-interface-2","status":"publish","type":"post","link":"http:\/\/www.amibroker.org\/editable_userkb\/2008\/03\/16\/amibroker-custom-backtester-interface-2\/","title":{"rendered":"AmiBroker Custom Backtester Interface"},"content":{"rendered":"

by Wayne (GP)<\/em><\/p>\n

Introduction<\/strong>\t<\/p>\n

From version 4.67.0, AmiBroker provides a custom backtester interface to allow customising the operation of the backtester’s second phase which processes the trading signals. This allows a range of special situations to be achieved that aren’t natively supported by the backtester. AmiBroker tends to refer to this as the Advanced Portfolio Backtester Interface, but as it seems to be more widely referred to as the Custom Backtester Interface, I will use this latter terminology.<\/p>\n

Due to the object model used by the backtester interface, a higher level of programming knowledge is required than for simple AFL or looping. This document starts by discussing that model, so is aimed at AFL programmers who are already proficient and comfortable with basic AFL use, array indexing, and looping. If you don’t understanding looping, then you almost certainly won’t understand the custom backtester interface.<\/p>\n

The Object Model<\/strong><\/p>\n

The modern programming paradigm is called object-oriented programming, with the system being developed modelled as a set of objects that interact. The custom backtester interface follows that model.<\/p>\n

An object can be thought of as a self-contained black-box that has certain properties and can perform certain functions. Internally it’s a combination of code and variables, where both can be made either private to the internals of the object only or accessible from outside for the benefit of users of the object. The private code and variables are totally hidden from the outside world and are of no interest to users of the object. Only developers working on the object itself care about them. Users of the object are only interested in the code and variables made accessible for their use.<\/p>\n

Any variable made accessible to an object’s user is called a property of the object. For example, the Backtester object has a property (variable) called “Equity”, which is the current value of the portfolio equity during a backtest. Properties can be read and written much the same as any other variable, just by using them in expressions and assigning values to them (although some properties may be read-only). However, the syntax is a little different due to the fact they’re properties of an object, not ordinary variables.<\/p>\n

An object’s code is made accessible to its users by providing a set of functions that can be called in relation to the object. These functions are called methods of the object. They are essentially identical to ordinary functions, but perform operations that are relevant to the purpose of the object. For example, the Backtester object has methods (functions) that perform operations related to backtesting. Methods are called in much the same way as other functions, but again the syntax is a little different due to them being methods of an object rather than ordinary functions.<\/p>\n

The aim of the object model is to view the application as a set of self-contained and reusable objects that can manage their own functionality and provide interfaces for other objects and code to use. Imagine it as being similar to a home entertainment system, where you buy a number of components (objects) like a TV, DVD player, surround-sound system, and karaoke unit (if you’re that way inclined!). Each of those components manages its own functionality and provides you with a set of connectors and cables to join them all together to create the final application: the home entertainment system. The beauty of that arrangement is that each component provides a standard interface (if you’re lucky) that will allow any brands of the other components to be connected, without those components having to know the details of how all the other components work internally, and considerable choice in the structure of the final entertainment system constructed. Similarly, software objects have standard interfaces in the form of methods and properties that allow them to be used and reused in any software.<\/p>\n

Accessing Oject Properties And Methods<\/strong><\/p>\n

To access the properties and methods of an object, you need to know not only the name of the property or method, but also the name of the object. In AmiBroker AFL, you cannot define or create your own objects, only use objects already provided by AmiBroker. AmiBroker help details all its objects, methods, and properties in the section “Advanced portfolio backtester interface”.
\nTo use real AFL examples, the first object detailed in the help is the Backtester object. AmiBroker provides a single Backtester object to perform backtests. To use the Backtester object, you first have to get a copy of it and assign that to your own variable:<\/p>\n

bo <\/span>= <\/span>GetBacktesterObject<\/span>();<\/span><\/pre>\n

The variable “bo” is your own variable, and you can call it whatever you like within the naming rules of AFL. However, to avoid a lot of verbose statements, it’s good to keep it nice and short. Previously you’ve only dealt with variables that are either single numbers, arrays of numbers, or strings. The variable “bo” is none of those, instead being a new type of variable called an object variable. In this case it holds the Backtester object (or really a reference to the Backtester object, but I don’t want to get into the complicated topic of references here). Now that you have the Backtester object in your own variable, you can access its properties and methods.<\/p>\n

The syntax for referencing an object’s property is objectName.objectProperty<\/font>, for example bo.InitialEquity<\/font>,. That can then be used the same as any other variable (assuming it’s not a read-only property, which InitialEquity is not):<\/p>\n

bo<\/span>.<\/span>InitialEquity <\/span>= <\/span>10000<\/span>;\r<\/span>capital <\/span>= <\/span>bo<\/span>.<\/span>InitialEquity<\/span>;\r<\/span>gain <\/span>= (<\/span>capital <\/span>- <\/span>bo<\/span>.<\/span>InitialEquity<\/span>) \/ <\/span>bo<\/span>.<\/span>InitialEquity <\/span>* <\/span>100<\/span>;<\/span><\/pre>\n

From this you can see the advantage of keeping object variable names short. If you called the variable “myBacktesterObject”, then for the last example above you’d end up with:<\/p>\n

gain <\/span>= (<\/span>capital <\/span>- <\/span>myBacktesterObject<\/span>.<\/span>InitialEquity<\/span>) \/ <\/span>myBacktesterObject<\/span>.<\/span>InitialEquity <\/span>* <\/span>100<\/span>;<\/span><\/pre>\n

===============
\nHere I’ve had to reduce the font size just to fit it all on a single line.
\nIf a property is read-only, then you cannot perform any operation that would change its value. So, using the Equity property which is read-only:<\/p>\n

currentEquity <\/span>= <\/span>bo<\/span>.<\/span>Equity<\/span>;    <\/span>\/\/  This is fine<\/span><\/pre>\n

but:<\/p>\n

bo<\/span>.<\/span>Equity <\/span>= <\/span>50000<\/span>;    <\/span>\/\/  This is an error!<\/span><\/pre>\n

The same syntax is used to access the methods of an object. The method name is preceded by the object name with a decimal point: objectName.objectMethod(). Any parameters are passed to the method in the same manner as to ordinary functions: <\/p>\n

objectName<\/span>.<\/span>objectMethod<\/span>(<\/span>parm1<\/span>, <\/span>parm2<\/span>, <\/span>parm3<\/span>).<\/span><\/pre>\n

For example, to call the Backtester object’s AddCustomMetric method and pass the two compulsory parameters Title and Value, a statement like this would be used:<\/p>\n

bo<\/span>.<\/span>AddCustomMetric<\/span>(<\/span>"myMetric"<\/span>, <\/span>1000<\/span>);<\/span><\/pre>\n

AmiBroker help indicates that this method returns a value of type “bool”, which means boolean and thus can only take the values True and False. However, it doesn’t detail what this return value means. A good guess would be that it returns True if the custom metric was successfully added and False if for some reason it failed to be added. However, that’s only a guess, but a common reason for returning boolean values. For some of the other methods that return values of type “long”, it’s more difficult to guess what they might contain.
\nAnother example with a return parameter:<\/p>\n

sig <\/span>= <\/span>bo<\/span>.<\/span>GetFirstSignal<\/span>(<\/span>i<\/span>);<\/span><\/pre>\n

Here the variable “sig” is another object variable, but this time of type Signal rather than Backtester. In other words, it holds a Signal object rather than a Backtester object. Unlike the single Backtester object, AmiBroker can have many different Signal objects created at the same time (one for each trading signal). As a Signal object holds the signal data for a particular symbol at a particular bar, the method needs to know the bar number, which would typically be specified using a loop index variable (‘i’ above) inside a loop:<\/p>\n

<\/span>for (<\/span>i <\/span>= <\/span>0<\/span>; <\/span>i <\/span>< <\/span>BarCount<\/span>; <\/span>i<\/span>++)\r{\r    . . . .\r    <\/span>sig <\/span>= <\/span>bo<\/span>.<\/span>GetFirstSignal<\/span>(<\/span>i<\/span>);\r    . . . .\r}<\/span><\/pre>\n

Once a Signal object has been obtained, its properties and methods can be referenced:<\/p>\n

sig<\/span>.<\/span>PosScore <\/span>= <\/span>0<\/span>;    <\/span>\/\/  Set position score to zero for this bar\r<\/span>if (<\/span>sig<\/span>.<\/span>IsEntry<\/span>())    <\/span>\/\/  If this bar's signal is entry (buy\/short)\r<\/span>{\r    . . . .\r}<\/span><\/pre>\n

Note that the property sig.PosScore is a single number, not an array. While the AFL variable PositionScore is an array, the “sig” object only holds data for a single bar, so the property sig.PosScore is the position score value for that bar only, thus a single number.<\/p>\n

Also note that AmiBroker help is not very clear on some topics. For example, the Signal object only has a few methods that indicate whether the current bar contains an entry, exit, long, or short signal, or has a scale in or out signal. However, it doesn’t indicate how you combine these to get the exact details. For example, how do you tell the difference between a scale-in and a scale-out? Is scaling in to a long position a combination of IsScale, IsEntry, and IsLong, or perhaps just IsScale and IsLong, or neither of those? In some cases you need to use trial and error and see what actually works (learn how to use the DebugView program with _TRACE statements: see Appendix B). Fortunately for this specific example, the Signal object also has a property called Type that indicates exactly what type the signal is.<\/p>\n

Using The Custom Backtester Interface<\/strong><\/p>\n

To use your own custom backtest procedure, you first need to tell AmiBroker that you will be doing so. There are a few ways of doing this:<\/p>\n

    \n
  1. By setting a path to the file holding the procedure in the Automatic Analysis Settings Portfolio page. This procedure will then be used with all backtests, if the “Enable custom backtest procedure” checkbox is checked.\n
  2. By specifying these same two settings in your AFL code using the functions SetOption(“UseCustomBacktestProc”, True) and SetCustomBacktestProc(““). Note that path separators inside strings need to use two backslashes, for example “c:\\\\AmiBroker\\\\Formulas\\\\Custom\\\\Backtests\\\\MyProc.afl”. Although why is not important here, it’s because a single backslash is what’s called an escape character, meaning the character(s) after it can have special meaning rather than just being printable characters, so to actually have a printable backslash, you have to put two in a row.\n
  3. By putting the procedure in the same file as the other AFL code and using the statement SetCustomBacktestProc(“”). This tells AmiBroker that there is a custom backtest procedure but there’s no path for it, because it’s in the current file. This option will be used throughout the rest of this document.\n<\/ol>\n

    The next thing that’s required in all backtest procedures is to ensure the procedure only runs during the second phase of the backtest. That’s achieved with the following conditional statement:<\/p>\n

    <\/span>if (<\/span>Status<\/span>(<\/span>"action"<\/span>) == <\/span>actionPortfolio<\/span>)\r{\r    . . . . \r}<\/span><\/pre>\n

    And finally, before anything else can be done, a copy of the Backtester object is needed:<\/p>\n

    bo <\/span>= <\/span>GetBacktesterObject<\/span>();<\/span><\/pre>\n

    So all custom backtest procedures, where they’re in the same file as the other AFL code, will have a template like this:<\/p>\n

    SetCustomBacktestProc<\/span>(<\/span>""<\/span>);\rif (<\/span>Status<\/span>(<\/span>"action"<\/span>) == <\/span>actionPortfolio<\/span>)\r{\r    <\/span>bo <\/span>= <\/span>GetBacktesterObject<\/span>();\r\r    <\/span>\/\/  Rest of procedure goes here\r\r<\/span>}<\/span><\/pre>\n

    If the backtests were using a procedure in the file:<\/p>\n

    c:\\AmiBroker\\Formulas\\Custom\\Backtests\\MyBacktest.afl<\/p>\n

    then the first line above in your system AFL code would be replaced with:<\/p>\n

    SetOption<\/span>(<\/span>"UseCustomBacktestProc"<\/span>, <\/span>True<\/span>);\r<\/span>SetCustomBacktestProc<\/span>(<\/span>"c:\\\\AmiBroker\\\\Formulas\\\\Custom\\\\Backtests\\\\MyBacktest.afl"<\/span>);<\/span><\/pre>\n

    and the rest of the procedure would be in the specified file. Or, if the same values were specified in the Automatic Analysis settings, the two lines above would not be needed in your AFL code at all, and the procedure would be in the specified file.<\/p>\n

    Custom Backtester Levels<\/strong><\/p>\n

    The AmiBroker custom backtester interface provides three levels of user customisation, simply called high-level, mid-level, and low-level. The high-level approach requires the least programming knowledge, and the low-level approach the most. These levels are just a convenient way of grouping together methods that can and need to be called for a customisation to work, and conversely indicate which methods cannot be called in the same customisation because their functionality conflicts. Some methods can be called at all levels, others only at higher levels, and others only at lower levels. AmiBroker help details which levels each method can be used with. Naturally, the higher the level and the simpler the programming, the less flexibility that’s available.<\/p>\n

    This document will not detail every single method and property available, so the rest of this document should be read in conjunction with the AmiBroker help sections “Advanced portfolio backtester interface” and “Adding custom backtest metrics”.<\/p>\n

    High-Level Interface<\/strong><\/p>\n

    The high-level interface doesn’t allow any customising of the backtest procedure itself. It simply allows custom metrics to be defined for the backtester results display, and trade statistics and metrics to be calculated and examined. A single method call runs the whole backtest in one hit, the same as when the custom backtester interface isn’t used at all.<\/p>\n

    AmiBroker help has an example of using the high level interface to add a custom metric. See the section called “Adding custom backtest metrics”. In essence, the steps are:<\/p>\n

      \n
    1. Start with the custom backtest template above\n
    2. Run the backtest\n
    3. Get the performance statistics or trade details\n
    4. Calculate your new metric\n
    5. Add your new metric to the results display\n<\/ol>\n

      That would look something like this:<\/p>\n

      SetCustomBacktestProc<\/span>(<\/span>""<\/span>);\rif (<\/span>Status<\/span>(<\/span>"action"<\/span>) == <\/span>actionPortfolio<\/span>)\r{\r    <\/span>bo <\/span>= <\/span>GetBacktesterObject<\/span>();    <\/span>\/\/  Get backtester object\r    <\/span>bo<\/span>.<\/span>Backtest<\/span>();    <\/span>\/\/  Run backtests\r    <\/span>stats <\/span>= <\/span>bo<\/span>.<\/span>GetPerformanceStats<\/span>(<\/span>0<\/span>);    <\/span>\/\/  Get Stats object for all trades\r    <\/span>myMetric <\/span>= <<\/span>calculation using stats<\/span>>;    <\/span>\/\/  Calculate new metric\r    <\/span>bo<\/span>.<\/span>AddCustomMetric<\/span>(<\/span>"MyMetric"<\/span>, <\/span>myMetric<\/span>);    <\/span>\/\/  Add metric to display\r<\/span>}<\/span><\/pre>\n

      As well as just using the built-in statistics and metrics, obtained from the Stats object after the backtest has been run, it’s also possible to calculate your metric by examining all the trades using the Trade object. As some positions may still be open at the end of the backtest, you may need to iterate through both the closed trade and open position lists:<\/p>\n

      <\/span>for (<\/span>trade <\/span>= <\/span>bo<\/span>.<\/span>GetFirstTrade<\/span>(); <\/span>trade<\/span>; <\/span>trade <\/span>= <\/span>bo<\/span>.<\/span>GetNextTrade<\/span>())\r{\r    . . . .\r}\rfor (<\/span>trade <\/span>= <\/span>bo<\/span>.<\/span>GetFirstOpenPos<\/span>(); <\/span>trade<\/span>; <\/span>trade <\/span>= <\/span>bo<\/span>.<\/span>GetNextOpenPos<\/span>())\r{\r    . . . .\r}<\/span><\/pre>\n

      In this example, “trade” is an object variable of type Trade, meaning it holds a Trade object. As with the Signal object, AmiBroker can have many Trade objects created at the same time, one for each closed or open trade. The first for loop iterates through the closed trade list, and the second through the open position trade list. The continuation condition “trade” theoretically means while the trade object is not zero, but in fact “trade” will be Null when the end of the list is reached. However, any conditional involving a null value is always false, so this will still work. The five Backtester object methods GetFirstTrade, GetNextTrade, GetFirstOpenPos, GetNextOpenPos, and FindOpenPos all return Null when the end of the list is reached or if no trade or open position is found.<\/p>\n

      The for loops are a little different to normal for loops in that they don’t have a standard loop index variable like ‘i’ that gets incremented at the end of each pass. Instead they call a Backtester object method to get the initial value (the first Trade object) and then another member to get the next value (the next Trade object). So the for loop conditions here are just saying start from the first Trade object, at the end of each pass get the next Trade object, and keep doing that until there are no more Trade objects (ie. “trade” is Null). The loops are iterating through the list of trades, not the bars on a chart. Each Trade object holds the details for a single trade.<\/p>\n

      Putting that code inside the custom backtest template looks like this:<\/p>\n

      SetCustomBacktestProc<\/span>(<\/span>""<\/span>);\rif (<\/span>Status<\/span>(<\/span>"action"<\/span>) == <\/span>actionPortfolio<\/span>)\r{\r    <\/span>bo <\/span>= <\/span>GetBacktesterObject<\/span>();    <\/span>\/\/  Get backtester object\r    <\/span>bo<\/span>.<\/span>Backtest<\/span>();    <\/span>\/\/  Run backtests\r    <\/span>for (<\/span>trade <\/span>= <\/span>bo<\/span>.<\/span>GetFirstTrade<\/span>(); <\/span>trade<\/span>; <\/span>trade <\/span>= <\/span>bo<\/span>.<\/span>GetNextTrade<\/span>())\r    {\r        . . . .    <\/span>\/\/  Use Trade object here\r    <\/span>}\r    for (<\/span>trade <\/span>= <\/span>bo<\/span>.<\/span>GetFirstOpenPos<\/span>(); <\/span>trade<\/span>; <\/span>trade <\/span>= <\/span>bo<\/span>.<\/span>GetNextOpenPos<\/span>())\r    {\r        . . . .    <\/span>\/\/  Use Trade object here\r    <\/span>}\r    <\/span>myMetric <\/span>= <<\/span>some result from Trade object calculations<\/span>>;\r    <\/span>bo<\/span>.<\/span>AddCustomMetric<\/span>(<\/span>"MyMetric"<\/span>, <\/span>myMetric<\/span>);    <\/span>\/\/  Add metric to display\r<\/span>}<\/span><\/pre>\n

      As an example, say we want to calculate the average number of calendar days that winning trades were held for (there’s already a built-in Stats object value for number of bars, but we want number of calendar days). For that we’ll need a function that can calculate the number of calendar days between two dates. Let’s call it “DayCount”, a function that takes two parameters: the entry date and the exit date, both in AmiBroker date\/time format. Since this document is about the custom backtester interface, I don’t want to go into how that function works right now. Let’s just assume it does, but the code for such a function is given in Appendix A if you’re interested. Then, for each trade we’ll need to know:<\/p>\n

        \n
      1. If it was a winning or losing trade\n
      2. The entry date\n
      3. The exit date\n<\/ol>\n

        And to calculate the average, we’ll need a total figure for the number of winning trade days and another total figure for the number of trades. The average is the total number of days winning trades were held divided by the total number of winning trades.
        \nFor the trade details, the Trade object has the following properties:<\/p>\n

          \n
        1. EntryDateTime\tThe entry date & time\n
        2. ExitDateTime\tThe exit date & time
          \nand the following method:<\/p>\n
        3. GetProfit()\tThe profit for the trade\n<\/ol>\n

          Before trying this example, the first time we’ve used this Trade object method, we make the assumption that the profit will be negative for losing trades and positive for winning trades, as AmiBroker help doesn’t clarify that detail (it could be some undefined value for losing trades). If trial and error proves that not to be the case, then we could alternatively try using the Trade object properties EntryPrice, ExitPrice, and IsLong to determine if it was a winning or losing trade. As it turns out upon testing, GetProfit does in fact work as expected.<\/p>\n

          Note that the Trade object also has a property called BarsInTrade, which looks like it could potentially be used instead of the dates, but that only gives the number of bars, not the number of calendar days.
          \nSo, to get the number of calendar days spent in a trade, we call our DayCount function passing the entry and exit dates:
          \nDayCount(trade.EntryDateTime, trade.ExitDateTime);
          \nand to determine if it was a winning trade, where break-even doesn’t count as winning:
          \ntrade.GetProfit() > 0;
          \nThe whole procedure would then be:<\/p>\n

          SetCustomBacktestProc<\/span>(<\/span>""<\/span>);\rif (<\/span>Status<\/span>(<\/span>"action"<\/span>) == <\/span>actionPortfolio<\/span>)\r{\r    <\/span>bo <\/span>= <\/span>GetBacktesterObject<\/span>();    <\/span>\/\/  Get backtester object\r    <\/span>bo<\/span>.<\/span>Backtest<\/span>();    <\/span>\/\/  Run backtests\r    <\/span>totalDays <\/span>= <\/span>0<\/span>;    <\/span>\/\/  Total number of winning days\r    <\/span>totalTrades <\/span>= <\/span>0<\/span>;    <\/span>\/\/  Total number of winning trades\r    <\/span>for (<\/span>trade <\/span>= <\/span>bo<\/span>.<\/span>GetFirstTrade<\/span>(); <\/span>trade<\/span>; <\/span>trade <\/span>= <\/span>bo<\/span>.<\/span>GetNextTrade<\/span>())\r    {    <\/span>\/\/  Loop through all closed trades\r        <\/span>if (<\/span>trade<\/span>.<\/span>GetProfit<\/span>() > <\/span>0<\/span>)    <\/span>\/\/  If this was a winning trade\r        <\/span>{\r            <\/span>totalDays <\/span>= <\/span>totalDays <\/span>+ <\/span>DayCount<\/span>(<\/span>trade<\/span>.<\/span>EntryDateTime<\/span>, <\/span>trade<\/span>.<\/span>ExitDateTime<\/span>);\r            <\/span>totalTrades<\/span>++;  \r        }\r    }    <\/span>\/\/  End of for loop over all trades\r    <\/span>avgWinDays <\/span>= <\/span>totalDays <\/span>\/ <\/span>totalTrades<\/span>;    <\/span>\/\/  Calculate average win days\r    <\/span>bo<\/span>.<\/span>AddCustomMetric<\/span>(<\/span>"AvgWinDays"<\/span>, <\/span>avgWinDays<\/span>);    <\/span>\/\/  Add to results display\r<\/span>}<\/span><\/pre>\n

          Note that we only need to consider closed trades in this example, as counting open positions would not accurately reflect the number of days trades were typically held for. Also, the “totalTrades” variable only counts winning trades, not all trades, since we’re only averaging over winning trades.
          \nWhen a backtest is run with this custom interface and a report generated, our new metric “avgWinDays” will be printed at the bottom of the report:
          \ncbt1.GIF<\/p>\n

          And if we run an optimisation (using a different backtest to above), it will have a column near the right-hand end of the results:<\/p>\n

          cbt2.GIF <\/p>\n

          Note that the reason the “W. Avg Bars Held” column doesn’t seem to agree with the “AvgWinDays” column (ie. the former goes down while the latter goes up) is because the average bars figure includes open positions at the end of the backtest whereas we specifically excluded them.
          \nAs well as overall metrics per backtest, it’s also possible to include individual trade metrics in the backtester results. For this, the metric is added to each Trade object rather than the Backtester object and the trades are listed at the end of the procedure.
          \nFor example, to display the entry position score value against each trade in the backtester results, the following code could be used:<\/p>\n

          SetCustomBacktestProc<\/span>(<\/span>""<\/span>);\rif (<\/span>Status<\/span>(<\/span>"action"<\/span>) == <\/span>actionPortfolio<\/span>)\r{\r    <\/span>bo <\/span>= <\/span>GetBacktesterObject<\/span>();    <\/span>\/\/  Get backtester object\r    <\/span>bo<\/span>.<\/span>Backtest<\/span>(<\/span>True<\/span>);            <\/span>\/\/  Run backtests with no trade listing\r    <\/span>for (<\/span>trade <\/span>= <\/span>bo<\/span>.<\/span>GetFirstTrade<\/span>(); <\/span>trade<\/span>; <\/span>trade <\/span>= <\/span>bo<\/span>.<\/span>GetNextTrade<\/span>())\r        <\/span>trade<\/span>.<\/span>AddCustomMetric<\/span>(<\/span>"Score"<\/span>, <\/span>trade<\/span>.<\/span>Score<\/span>);    <\/span>\/\/  Add closed trade score\r    <\/span>for (<\/span>trade <\/span>= <\/span>bo<\/span>.<\/span>GetFirstOpenPos<\/span>(); <\/span>trade<\/span>; <\/span>trade <\/span>= <\/span>bo<\/span>.<\/span>GetNextOpenPos<\/span>())\r        <\/span>trade<\/span>.<\/span>AddCustomMetric<\/span>(<\/span>"Score"<\/span>, <\/span>trade<\/span>.<\/span>Score<\/span>);    <\/span>\/\/  Add open pos score\r    <\/span>bo<\/span>.<\/span>ListTrades<\/span>();            <\/span>\/\/  Generate trades list\r<\/span>}<\/span><\/pre>\n

          The first for loop iterates through the closed trade list and the second through the open position list to get the entry score value for every trade listed in the results. Note that the bo.BackTest call is passed the value “True” in this case to prevent the list of trades being generated automatically by the backtester. Instead, they’re generated by the subsequent call to the bo.ListTrades method.
          \nAs another example, say we want to list for each winning trade how far above or below the average winning profit it was as a percentage, and similarly for each losing trade, how far above or below the average loss it was as a percentage. For this we need the “WinnersAvgProfit” and “LosersAvgLoss” values from the Stats object, and the profit from the Trade objects for each closed trade (for this example we’ll ignore open positions). Relative loss percentages are displayed as negative numbers.<\/p>\n

          SetCustomBacktestProc<\/span>(<\/span>""<\/span>);\rif (<\/span>Status<\/span>(<\/span>"action"<\/span>) == <\/span>actionPortfolio<\/span>)\r{\r    <\/span>bo <\/span>= <\/span>GetBacktesterObject<\/span>();    <\/span>\/\/  Get backtester object\r    <\/span>bo<\/span>.<\/span>Backtest<\/span>(<\/span>True<\/span>);            <\/span>\/\/  Run backtests with no trade listing\r    <\/span>stat <\/span>= <\/span>bo<\/span>.<\/span>GetPerformanceStats<\/span>(<\/span>0<\/span>);    <\/span>\/\/  Get Stats object for all trades\r    <\/span>winAvgProfit <\/span>= <\/span>stat<\/span>.<\/span>GetValue<\/span>(<\/span>"WinnersAvgProfit"<\/span>);\r    <\/span>loseAvgLoss <\/span>= <\/span>stat<\/span>.<\/span>GetValue<\/span>(<\/span>"LosersAvgLoss"<\/span>);\r    for (<\/span>trade <\/span>= <\/span>bo<\/span>.<\/span>GetFirstTrade<\/span>(); <\/span>trade<\/span>; <\/span>trade <\/span>= <\/span>bo<\/span>.<\/span>GetNextTrade<\/span>())\r    {                    <\/span>\/\/  Loop through all closed trades\r        <\/span>prof <\/span>= <\/span>trade<\/span>.<\/span>GetProfit<\/span>();        <\/span>\/\/  Get trade profit in dollars\r        <\/span>relProf <\/span>= <\/span>0<\/span>;            <\/span>\/\/  This will be profit\/avgProfit as %\r        <\/span>if (<\/span>prof <\/span>> <\/span>0<\/span>)            <\/span>\/\/  If a winner (profit > 0)\r            <\/span>relProf <\/span>= <\/span>prof <\/span>\/ <\/span>winAvgProfit <\/span>* <\/span>100<\/span>;    <\/span>\/\/  Profit relative to average\r        <\/span>else                <\/span>\/\/  Else if a loser (profit <= 0)\r            <\/span>relProf <\/span>= -<\/span>prof <\/span>\/ <\/span>loseAvgLoss <\/span>* <\/span>100<\/span>;    <\/span>\/\/  Loss relative to average\r        <\/span>trade<\/span>.<\/span>AddCustomMetric<\/span>(<\/span>"Rel Avg Profit%"<\/span>, <\/span>relProf<\/span>);    <\/span>\/\/  Add metric\r    <\/span>}                    <\/span>\/\/  End of for loop over all trades\r    <\/span>bo<\/span>.<\/span>ListTrades<\/span>();            <\/span>\/\/  Generate list of trades\r<\/span>}<\/span><\/pre>\n

          Mid-Level Interface<\/strong><\/p>\n

          To be able to modify actual backtest behaviour, the mid-level or low-level interfaces must be used. New metrics can also be calculated at these levels, but since that’s already covered above, this section will only look at what backtest behaviour can be modified at this level. Essentially this means using Signal objects as well as the Backtester object.
          \nWith the mid-level interface, each trading signal at each bar can be examined and the properties of the signals changed, based on the value of other Signal or Backtester object properties, before any trades are executed for that bar. For example, one Backtester object property is “Equity”, which gives the current portfolio equity, and one Signal object property is “PosSize”, the position size specified in the main AFL code, so the mid-level interface can allow, for example, position size to be modified based on current portfolio equity.
          \nThe custom backtester interface template for a mid-level approach, where all the signals at each bar need to be examined, is:<\/p>\n

          SetCustomBacktestProc<\/span>(<\/span>""<\/span>);\rif (<\/span>Status<\/span>(<\/span>"action"<\/span>) == <\/span>actionPortfolio<\/span>) {\r    <\/span>bo <\/span>= <\/span>GetBacktesterObject<\/span>();    <\/span>\/\/  Get backtester object\r    <\/span>bo<\/span>.<\/span>PreProcess<\/span>();    <\/span>\/\/  Do pre-processing (always required)\r    <\/span>for (<\/span>i <\/span>= <\/span>0<\/span>; <\/span>i <\/span>< <\/span>BarCount<\/span>; <\/span>i<\/span>++)    <\/span>\/\/  Loop through all bars\r    <\/span>{\r        for (<\/span>sig <\/span>= <\/span>bo<\/span>.<\/span>GetFirstSignal<\/span>(<\/span>i<\/span>); <\/span>sig<\/span>; <\/span>sig <\/span>= <\/span>bo<\/span>.<\/span>GetNextSignal<\/span>(<\/span>i<\/span>))\r        {    <\/span>\/\/  Loop through all signals at this bar \r                <\/span>. . . .\r        }    <\/span>\/\/  End of for loop over signals at this bar\r        <\/span>bo<\/span>.<\/span>ProcessTradeSignals<\/span>(<\/span>i<\/span>);    <\/span>\/\/  Process trades at bar (always required)\r    <\/span>}    <\/span>\/\/  End of for loop over bars\r    <\/span>bo<\/span>.<\/span>PostProcess<\/span>();    <\/span>\/\/  Do post-processing (always required)\r<\/span>}<\/span><\/pre>\n

          In this example, the variable “sig” is an object variable of type Signal, meaning it holds a Signal object. As with the Trade object in the earlier example, the inner for loop iterates through the list of signals at each bar, not through all bars on a chart. The for loop conditions are effectively saying start from the first Signal object for the current bar, at the end of each pass get the next Signal object for the same bar, and keep doing that until there are no more Signal objects for the bar (ie. “sig” is Null). Each Signal object holds the details of one signal at the current bar (ie. a buy, sell, short, cover or scale indication for one symbol).
          \nThe main differences between the mid-level and high-level approaches are:<\/p>\n

            \n
          1. The Backtester object’s Backtest method is not called.\n
          2. The Backtester object’s ProcessTradeSignals method is called instead at each bar, after examining and possibly modifying some of the Signal object properties and\/or closed or open Trade object properties.\n
          3. A loop is required to iterate through all bars of the chart.\n
          4. A nested loop is required inside that one to iterate through all the signals at each of those bars.\n<\/ol>\n

            If a trading decision needs to be based on some other property of a particular stock, like it’s average daily trading volume for example, then the stock code symbol must be used to obtain that information. This is available in the Signal object’s “Symbol” property. However, since the backtester at this level is not run in the context of a particular symbol, the data must be saved to a composite symbol in the main code (or perhaps a static variable) and referenced in the custom backtest procedure with the Foreign function. For example, in the main AFL code:<\/p>\n

            AddToComposite<\/span>(<\/span>EMA<\/span>(<\/span>Volume<\/span>, <\/span>100<\/span>), <\/span>"~evol_"<\/span>+<\/span>Name<\/span>(), <\/span>"V"<\/span>, <\/span>atcFlagDefaults <\/span>| <\/span>atcFlagEnableInBacktest<\/span>);<\/span><\/pre>\n

            Here the volume EMA array is saved to a separate composite symbol for each stock (ie. each composite consists of just a single stock). For this to work in backtests, the atcFlagEnableInBacktest flag must be used. Then in the custom backtest procedure:<\/p>\n

            evol <\/span>= <\/span>Foreign<\/span>(<\/span>"~evol_"<\/span>+<\/span>sig<\/span>.<\/span>Symbol<\/span>, <\/span>"V"<\/span>);  <\/span>\/\/  Get symbol's volume array\r<\/span>evi <\/span>= <\/span>evol<\/span>[<\/span>i<\/span>];    <\/span>\/\/  Reference a value in the array<\/span><\/pre>\n

            As a real example, to limit the number of shares purchased to a maximum of 10% of the 100 day EMA of the daily volume, and also ensure the position size is no less than $5,000 and no more than $50,000, the following mid-level procedure could be used:<\/p>\n

            SetCustomBacktestProc<\/span>(<\/span>""<\/span>);\rif (<\/span>Status<\/span>(<\/span>"action"<\/span>) == <\/span>actionPortfolio<\/span>)\r{\r    <\/span>bo <\/span>= <\/span>GetBacktesterObject<\/span>();    <\/span>\/\/  Get backtester object\r    <\/span>bo<\/span>.<\/span>PreProcess<\/span>();    <\/span>\/\/  Do pre-processing\r    <\/span>for (<\/span>i <\/span>= <\/span>0<\/span>; <\/span>i <\/span>< <\/span>BarCount<\/span>; <\/span>i<\/span>++)    <\/span>\/\/  Loop through all bars\r    <\/span>{\r        for (<\/span>sig <\/span>= <\/span>bo<\/span>.<\/span>GetFirstSignal<\/span>(<\/span>i<\/span>); <\/span>sig<\/span>; <\/span>sig <\/span>= <\/span>bo<\/span>.<\/span>GetNextSignal<\/span>(<\/span>i<\/span>))\r        {    <\/span>\/\/  Loop through all signals at this bar\r            <\/span>if (<\/span>sig<\/span>.<\/span>IsEntry<\/span>() && <\/span>sig<\/span>.<\/span>IsLong<\/span>())    <\/span>\/\/  If this signal is a long entry (ie. buy)\r            <\/span>{\r                <\/span>evol <\/span>= <\/span>Foreign<\/span>(<\/span>"~evol_"<\/span>+<\/span>sig<\/span>.<\/span>Symbol<\/span>, <\/span>"V"<\/span>);   <\/span>\/\/  Get stock's composite volume array\r                <\/span>psize <\/span>= <\/span>sig<\/span>.<\/span>PosSize<\/span>;    <\/span>\/\/  Get position size specified in AFL code\r                <\/span>if (<\/span>psize <\/span>< <\/span>0<\/span>)    <\/span>\/\/  If it's negative (a percentage of equity)\r                    <\/span>psize <\/span>= (-<\/span>psize<\/span>\/<\/span>100<\/span>) * <\/span>bo<\/span>.<\/span>Equity<\/span>;  <\/span>\/\/  Convert to dollar value using current equity\r                <\/span>scnt <\/span>= <\/span>psize <\/span>\/ <\/span>sig<\/span>.<\/span>Price<\/span>;    <\/span>\/\/  Calculate number of shares for position size\r                <\/span>if (<\/span>scnt <\/span>> <\/span>evol<\/span>[<\/span>i<\/span>] \/ <\/span>10<\/span>)    <\/span>\/\/  If number of shares is > 10% of volume EMA\r                <\/span>{\r                    <\/span>scnt <\/span>= <\/span>evol<\/span>[<\/span>i<\/span>] \/ <\/span>10<\/span>;    <\/span>\/\/  Limit number of shares to 10% of EMA value\r                    <\/span>psize <\/span>= <\/span>scnt <\/span>* <\/span>sig<\/span>.<\/span>Price<\/span>;    <\/span>\/\/  Calculate new position size\r                <\/span>}\r                if (<\/span>psize <\/span>< <\/span>5000<\/span>)    <\/span>\/\/  If position size is less than $5,000\r                    <\/span>psize <\/span>= <\/span>0<\/span>;    <\/span>\/\/  Set to zero so buy signal will be ignored\r                <\/span>else\r               {\r                    if (<\/span>psize <\/span>> <\/span>50000<\/span>)    <\/span>\/\/  If position size is greater than $50,000\r                        <\/span>psize <\/span>= <\/span>50000<\/span>;    <\/span>\/\/  Limit to $50,000\r                <\/span>}\r                <\/span>sig<\/span>.<\/span>PosSize <\/span>= <\/span>psize<\/span>;    <\/span>\/\/  Set modified position size back into object\r            <\/span>}\r        }    <\/span>\/\/  End of for loop over signals at this bar\r        <\/span>bo<\/span>.<\/span>ProcessTradeSignals<\/span>(<\/span>i<\/span>);    <\/span>\/\/  Process trades at this bar\r    <\/span>}    <\/span>\/\/  End of for loop over bars\r    <\/span>bo<\/span>.<\/span>PostProcess<\/span>();    <\/span>\/\/  Do post-processing\r<\/span>}<\/span><\/pre>\n

            In this example, the statement psize = (-psize\/100) * bo.Equity converts the percentage of equity value (which is negative) to its actual dollar value, using the Backtester object’s Equity property. The term -psize\/100 (which doesn’t actually need to be inside brackets) converts the negative percentage to a positive fraction which is then multiplied by the current portfolio equity.
            \nThe statement if (sig.IsEntry() && sig.IsLong()) calls the two Signal object methods IsEntry and IsLong to determine if the current signal is an entry signal and a long signal (ie. a buy signal). Remember that the && operator is equivalent to AND. An alternative would be to check if the Signal object’s Type property was equal to one.
            \nThe array variable “evol” contains the whole EMA array realigned to the number of bars used by the custom backtest procedure. Padded bars don’t matter here as there won’t be any signals for the stock at any of those bars, and we’re only checking the volume on bars where there is a signal. As “evol” is an array, at each bar we’re only interested in the value for the current bar, hence the references to evol[i].
            \nFinally, as detailed in the AmiBroker help, the Signal object’s Price property gives the price for the current signal, so there’s no need to use BuyPrice, SellPrice, etc., and the PosSize property is the signal’s position size value for the current bar. As this is not a read-only property, it can be both read and modified.
            \nAnother example, to prevent scaling in a position that already has $50,000 or more in open position value:<\/p>\n

            SetCustomBacktestProc<\/span>(<\/span>""<\/span>);\rif (<\/span>Status<\/span>(<\/span>"action"<\/span>) == <\/span>actionPortfolio<\/span>)\r{\r    <\/span>bo <\/span>= <\/span>GetBacktesterObject<\/span>();    <\/span>\/\/  Get backtester object\r    <\/span>bo<\/span>.<\/span>PreProcess<\/span>();    <\/span>\/\/  Do pre-processing\r    <\/span>for (<\/span>i <\/span>= <\/span>0<\/span>; <\/span>i <\/span>< <\/span>BarCount<\/span>; <\/span>i<\/span>++)    <\/span>\/\/  Loop through all bars\r    <\/span>{\r        for (<\/span>sig <\/span>= <\/span>bo<\/span>.<\/span>GetFirstSignal<\/span>(<\/span>i<\/span>); <\/span>sig<\/span>; <\/span>sig <\/span>= <\/span>bo<\/span>.<\/span>GetNextSignal<\/span>(<\/span>i<\/span>))\r        {    <\/span>\/\/  Loop through all signals at this bar\r            <\/span>if (<\/span>sig<\/span>.<\/span>Type <\/span>== <\/span>5<\/span>)    <\/span>\/\/  If signal type is scale-in\r            <\/span>{\r                <\/span>trade <\/span>= <\/span>bo<\/span>.<\/span>FindOpenPos<\/span>(<\/span>sig<\/span>.<\/span>Symbol<\/span>);   <\/span>\/\/  Check for open position in stock\r                <\/span>if (<\/span>trade<\/span>)    <\/span>\/\/  Or could use \"if (!IsNull(trade))\"\r                <\/span>{\r                    if (<\/span>trade<\/span>.<\/span>GetPositionValue<\/span>() >= <\/span>50000<\/span>)  <\/span>\/\/  If open position value >= $50,000\r                        <\/span>sig<\/span>.<\/span>PosSize <\/span>= <\/span>0<\/span>;    <\/span>\/\/  Set position size to zero to prevent purchase\r                <\/span>}\r            }\r        }    <\/span>\/\/  End of for loop over signals at this bar\r        <\/span>bo<\/span>.<\/span>ProcessTradeSignals<\/span>(<\/span>i<\/span>);    <\/span>\/\/  Process trades at this bar\r    <\/span>}    <\/span>\/\/  End of for loop over bars\r    <\/span>bo<\/span>.<\/span>PostProcess<\/span>();    <\/span>\/\/  Do post-processing\r<\/span>}<\/span><\/pre>\n

            In this example, as each new scale-in signal is detected, the list of open positions is checked for an open position in the same stock as the new signal. If an open position exists, its current value is obtained, and if that value is $50,000 or more, the position size is set to zero to prevent the scale-in from happening.
            \nThe example combines use of the Backtester object, Signal objects and Trade objects to determine whether or not scale-in of a position should be permitted. Note that the Trade object is returned Null if no open position is found. As any comparison with a null value is always false, provided the test is for the True condition then the IsNull function is not needed: ie. “if (trade)” gives the same result as “if (!IsNull(trade))”. However, if the test is for the negative condition, IsNull is required: ie. “if (!trade)” won’t work (when “trade” is Null it will be treated as False rather than the desired True) and “if (IsNull(trade))” becomes necessary.<\/p>\n

            Low-Level Interface<\/strong><\/p>\n

            The low-level interface provides the most flexibility to control backtester operation. As well as allowing signal properties to be modified, it also allows the entering, exiting, and scaling of trades even if no signal exists.
            \nWith the low-level interface, each trading signal at each bar can be examined, the properties of the signals changed, and trades entered, exited, and scaled. This could be used to implement special stop conditions not provided in the ApplyStop function, or to scale trades based on current portfolio equity or open position value and the like.
            \nThe custom backtester interface template for a low-level approach is:<\/p>\n

            SetCustomBacktestProc<\/span>(<\/span>""<\/span>);\rif (<\/span>Status<\/span>(<\/span>"action"<\/span>) == <\/span>actionPortfolio<\/span>)\r{\r    <\/span>bo <\/span>= <\/span>GetBacktesterObject<\/span>();    <\/span>\/\/  Get backtester object\r    <\/span>bo<\/span>.<\/span>PreProcess<\/span>();    <\/span>\/\/  Do pre-processing\r    <\/span>for (<\/span>i <\/span>= <\/span>0<\/span>; <\/span>i <\/span>< <\/span>BarCount<\/span>; <\/span>i<\/span>++)    <\/span>\/\/  Loop through all bars\r    <\/span>{\r        for (<\/span>sig <\/span>= <\/span>bo<\/span>.<\/span>GetFirstSignal<\/span>(<\/span>i<\/span>); <\/span>sig<\/span>; <\/span>sig <\/span>= <\/span>bo<\/span>.<\/span>GetNextSignal<\/span>(<\/span>i<\/span>))\r        {    <\/span>\/\/  Loop through all signals at this bar\r            <\/span>. . . .\r        }    <\/span>\/\/  End of for loop over signals at this bar\r        <\/span>bo<\/span>.<\/span>HandleStops<\/span>(<\/span>i<\/span>);    <\/span>\/\/  Handle programmed stops at this bar\r        <\/span>bo<\/span>.<\/span>UpdateStats<\/span>(<\/span>i<\/span>, <\/span>1<\/span>);    <\/span>\/\/  Update MAE\/MFE stats for bar\r        <\/span>bo<\/span>.<\/span>UpdateStats<\/span>(<\/span>i<\/span>, <\/span>2<\/span>);    <\/span>\/\/  Update stats at bar's end\r    <\/span>}    <\/span>\/\/  End of for loop over bars\r    <\/span>bo<\/span>.<\/span>PostProcess<\/span>();    <\/span>\/\/  Do post-processing\r<\/span>}<\/span><\/pre>\n

            Note that this template currently has no trades performed in it, as there are a number of options there depending on the system. Typically, inside the signal loop (or possibly the trades loop) there will be a number of tests for various conditions and then trades entered, exited, and scaled accordingly.
            \nThe main differences between the low-level and mid-level approaches are:<\/p>\n

              \n
            1. The Backtester object’s ProcessTradeSignals method is not called.\n
            2. The Backtester object’s EnterTrade, ExitTrade, and ScaleTrade methods are called instead at each bar, after examining and possibly modifying some of the signal properties and\/or closed or open trade properties.\n
            3. The Backtester object’s HandleStops method must be called once per bar to apply any stops programmed in the settings or by the ApplyStop function.\n
            4. The Backtester object’s UpdateStats method must be called at least once for each bar to update values like equity, exposure, MAE\/MFE, etc. The AmiBroker help is a little vague on how the TimeInsideBar parameter works (the values ‘1’ & ‘2’ in the sample above), but it must be called exactly once with that parameter set to two. It should also be called with it set to one to update the MAE\/MFE statistics, but why it would be called with the value set to zero or more than once, I’m not sure.\n<\/ol>\n

              As an example, let’s create a custom backtest procedure that scales in a long position by 50% of its injected capital (ie. excluding profit) whenever its open position profit exceeds its total injected capital, which means it’s sitting on 100% or more profit. The scale-in can be repeated whenever this condition occurs, as immediately after each scale-in, the injected capital will go up by 50%. The system doesn’t do any shorting and no other scaling occurs.<\/p>\n

              The required conditions therefore are:<\/p>\n

                \n
              1. The profit must be greater than the injected capital to scale in.\n
              2. The scale-in position size is equal to half the injected capital.\n
              3. No signal is required to perform the scale-in.\n<\/ol>\n

                The Signal object list is still needed to enter and exit all trades, as there’s no other mechanism to do that, but just the Trade object list is needed for scaling open positions. At each bar, each open long position in the trade open position list must be tested for scaling in, and a scale-in performed if the conditions are met.
                \nThe test for scale-in then looks like this:<\/p>\n

                trade<\/span>.<\/span>GetProfit<\/span>() >= <\/span>trade<\/span>.<\/span>GetEntryValue<\/span>();    <\/span>\/\/  Entry value is injected capital<\/span><\/pre>\n

                The scale-in position size is:<\/p>\n

                scaleSize <\/span>= <\/span>trade<\/span>.<\/span>GetEntryValue<\/span>() \/ <\/span>2<\/span>;    <\/span>\/\/  Half of total injected capital<\/span><\/pre>\n

                And the scale-in method call, using the closing price for scaling, is:<\/p>\n

                bo<\/span>.<\/span>ScaleTrade<\/span>(<\/span>i<\/span>, <\/span>trade<\/span>.<\/span>Symbol<\/span>, <\/span>True<\/span>, <\/span>trade<\/span>.<\/span>GetPrice<\/span>(<\/span>i<\/span>, <\/span>"C"<\/span>), <\/span>scaleSize<\/span>);<\/span><\/pre>\n

                Putting it all into our template gives:<\/p>\n

                SetCustomBacktestProc<\/span>(<\/span>""<\/span>);\rif (<\/span>Status<\/span>(<\/span>"action"<\/span>) == <\/span>actionPortfolio<\/span>)\r{\r    <\/span>bo <\/span>= <\/span>GetBacktesterObject<\/span>();    <\/span>\/\/  Get backtester object\r    <\/span>bo<\/span>.<\/span>PreProcess<\/span>();    <\/span>\/\/  Do pre-processing\r    <\/span>for (<\/span>i <\/span>= <\/span>0<\/span>; <\/span>i <\/span>< <\/span>BarCount<\/span>; <\/span>i<\/span>++)    <\/span>\/\/  Loop through all bars\r    <\/span>{\r        for (<\/span>sig <\/span>= <\/span>bo<\/span>.<\/span>GetFirstSignal<\/span>(<\/span>i<\/span>); <\/span>sig<\/span>; <\/span>sig <\/span>= <\/span>bo<\/span>.<\/span>GetNextSignal<\/span>(<\/span>i<\/span>))\r        {    <\/span>\/\/  Loop through all signals at this bar\r            <\/span>if (<\/span>sig<\/span>.<\/span>IsEntry<\/span>() && <\/span>sig<\/span>.<\/span>IsLong<\/span>())    <\/span>\/\/  Process long entries\r                <\/span>bo<\/span>.<\/span>EnterTrade<\/span>(<\/span>i<\/span>, <\/span>sig<\/span>.<\/span>Symbol<\/span>, <\/span>True<\/span>, <\/span>sig<\/span>.<\/span>Price<\/span>, <\/span>sig<\/span>.<\/span>PosSize<\/span>);\r            else\r            {\r                if (<\/span>sig<\/span>.<\/span>IsExit<\/span>() && <\/span>sig<\/span>.<\/span>IsLong<\/span>())    <\/span>\/\/  Process long exits\r                    <\/span>bo<\/span>.<\/span>ExitTrade<\/span>(<\/span>i<\/span>, <\/span>sig<\/span>.<\/span>Symbol<\/span>, <\/span>sig<\/span>.<\/span>Price<\/span>);\r            }\r        }    <\/span>\/\/  End of for loop over signals at this bar\r        <\/span>bo<\/span>.<\/span>HandleStops<\/span>(<\/span>i<\/span>);    <\/span>\/\/  Handle programmed stops at this bar\r        <\/span>for (<\/span>trade <\/span>= <\/span>bo<\/span>.<\/span>GetFirstOpenPos<\/span>(); <\/span>trade<\/span>; <\/span>trade <\/span>= <\/span>bo<\/span>.<\/span>GetNextOpenPos<\/span>())\r        {    <\/span>\/\/  Loop through all open positions\r            <\/span>if (<\/span>trade<\/span>.<\/span>GetProfit<\/span>() >= <\/span>trade<\/span>.<\/span>GetEntryValue<\/span>())  <\/span>\/\/  If time to scale-in\r            <\/span>{\r                <\/span>scaleSize <\/span>= <\/span>trade<\/span>.<\/span>GetEntryValue<\/span>() \/ <\/span>2<\/span>;    <\/span>\/\/  Scale-in the trade\r                <\/span>bo<\/span>.<\/span>ScaleTrade<\/span>(<\/span>i<\/span>, <\/span>trade<\/span>.<\/span>Symbol<\/span>, <\/span>True<\/span>, <\/span>trade<\/span>.<\/span>GetPrice<\/span>(<\/span>i<\/span>, <\/span>"C"<\/span>), <\/span>scaleSize<\/span>);\r            }\r        }    <\/span>\/\/  End of for loop over trades at this bar\r        <\/span>bo<\/span>.<\/span>UpdateStats<\/span>(<\/span>i<\/span>, <\/span>1<\/span>);    <\/span>\/\/  Update MAE\/MFE stats for bar\r        <\/span>bo<\/span>.<\/span>UpdateStats<\/span>(<\/span>i<\/span>, <\/span>2<\/span>);    <\/span>\/\/  Update stats at bar's end\r    <\/span>}    <\/span>\/\/  End of for loop over bars\r    <\/span>bo<\/span>.<\/span>PostProcess<\/span>();    <\/span>\/\/  Do post-processing\r<\/span>}<\/span><\/pre>\n

                Since we stated that the system doesn’t do any shorting, the tests for sig.IsLong aren’t really necessary.
                \nThe signal for loop processes all entry and exit signals generated by our buy and sell conditions in the main AFL code. As mentioned above, this is necessary since we’re not calling the ProcessTradeSignals method now, as that’s a mid-level method. The trade open position for loop checks for and processes all scaling in. When an exit signal occurs, the whole position is closed.
                \nExtending this example now to include our custom avgWinDays metric from the high-level interface example:<\/p>\n

                SetCustomBacktestProc<\/span>(<\/span>""<\/span>);\rif (<\/span>Status<\/span>(<\/span>"action"<\/span>) == <\/span>actionPortfolio<\/span>)\r{\r    <\/span>bo <\/span>= <\/span>GetBacktesterObject<\/span>();    <\/span>\/\/  Get backtester object\r    <\/span>bo<\/span>.<\/span>PreProcess<\/span>();    <\/span>\/\/  Do pre-processing\r    <\/span>for (<\/span>i <\/span>= <\/span>0<\/span>; <\/span>i <\/span>< <\/span>BarCount<\/span>; <\/span>i<\/span>++)    <\/span>\/\/  Loop through all bars\r    <\/span>{\r        for (<\/span>sig <\/span>= <\/span>bo<\/span>.<\/span>GetFirstSignal<\/span>(<\/span>i<\/span>); <\/span>sig<\/span>; <\/span>sig <\/span>= <\/span>bo<\/span>.<\/span>GetNextSignal<\/span>(<\/span>i<\/span>))\r        {    <\/span>\/\/  Loop through all signals at this bar\r            <\/span>if (<\/span>sig<\/span>.<\/span>IsEntry<\/span>() && <\/span>sig<\/span>.<\/span>IsLong<\/span>())    <\/span>\/\/  Process long entries\r                <\/span>bo<\/span>.<\/span>EnterTrade<\/span>(<\/span>i<\/span>, <\/span>sig<\/span>.<\/span>Symbol<\/span>, <\/span>True<\/span>, <\/span>sig<\/span>.<\/span>Price<\/span>, <\/span>sig<\/span>.<\/span>PosSize<\/span>);\r            else\r            {\r                if (<\/span>sig<\/span>.<\/span>IsExit<\/span>() && <\/span>sig<\/span>.<\/span>IsLong<\/span>())    <\/span>\/\/  Process long exits\r                    <\/span>bo<\/span>.<\/span>ExitTrade<\/span>(<\/span>i<\/span>, <\/span>sig<\/span>.<\/span>Symbol<\/span>, <\/span>sig<\/span>.<\/span>Price<\/span>);\r            }\r        }    <\/span>\/\/  End of for loop over signals at this bar\r        <\/span>bo<\/span>.<\/span>HandleStops<\/span>(<\/span>i<\/span>);    <\/span>\/\/  Handle programmed stops at this bar\r        <\/span>for (<\/span>trade <\/span>= <\/span>bo<\/span>.<\/span>GetFirstOpenPos<\/span>(); <\/span>trade<\/span>; <\/span>trade <\/span>= <\/span>bo<\/span>.<\/span>GetNextOpenPos<\/span>())\r        {    <\/span>\/\/  Loop through all open positions\r            <\/span>if (<\/span>trade<\/span>.<\/span>GetProfit<\/span>() >= <\/span>trade<\/span>.<\/span>GetEntryValue<\/span>())  <\/span>\/\/  If time to scale-in\r            <\/span>{\r                <\/span>scaleSize <\/span>= <\/span>trade<\/span>.<\/span>GetEntryValue<\/span>() \/ <\/span>2<\/span>;    <\/span>\/\/  Scale-in the trade\r                <\/span>bo<\/span>.<\/span>ScaleTrade<\/span>(<\/span>i<\/span>, <\/span>trade<\/span>.<\/span>Symbol<\/span>, <\/span>True<\/span>, <\/span>trade<\/span>.<\/span>GetPrice<\/span>(<\/span>i<\/span>, <\/span>"C"<\/span>), <\/span>scaleSize<\/span>);\r            }\r        }    <\/span>\/\/  End of for loop over trades at this bar\r        <\/span>bo<\/span>.<\/span>UpdateStats<\/span>(<\/span>i<\/span>, <\/span>1<\/span>);    <\/span>\/\/  Update MAE\/MFE stats for bar\r        <\/span>bo<\/span>.<\/span>UpdateStats<\/span>(<\/span>i<\/span>, <\/span>2<\/span>);    <\/span>\/\/  Update stats at bar's end\r    <\/span>}    <\/span>\/\/  End of for loop over bars\r    <\/span>totalDays <\/span>= <\/span>0<\/span>;    <\/span>\/\/  Total number of winning days\r    <\/span>totalTrades <\/span>= <\/span>0<\/span>;    <\/span>\/\/  Total number of winning trades\r    <\/span>for (<\/span>trade <\/span>= <\/span>bo<\/span>.<\/span>GetFirstTrade<\/span>(); <\/span>trade<\/span>; <\/span>trade <\/span>= <\/span>bo<\/span>.<\/span>GetNextTrade<\/span>())\r    {    <\/span>\/\/  Loop through all closed trades (only)\r        <\/span>if (<\/span>trade<\/span>.<\/span>GetProfit<\/span>() > <\/span>0<\/span>)    <\/span>\/\/  If this was a winning trade\r        <\/span>{\r            <\/span>totalDays <\/span>= <\/span>totalDays <\/span>+ <\/span>DayCount<\/span>(<\/span>trade<\/span>.<\/span>EntryDateTime<\/span>, <\/span>trade<\/span>.<\/span>ExitDateTime<\/span>);\r            <\/span>totalTrades<\/span>++;  \r        }\r    }    <\/span>\/\/  End of for loop over all trades\r    <\/span>avgWinDays <\/span>= <\/span>totalDays <\/span>\/ <\/span>totalTrades<\/span>;    <\/span>\/\/  Calculate average win days\r    <\/span>bo<\/span>.<\/span>AddCustomMetric<\/span>(<\/span>"AvgWinDays"<\/span>, <\/span>avgWinDays<\/span>);    <\/span>\/\/  Add to results display\r    <\/span>bo<\/span>.<\/span>PostProcess<\/span>();    <\/span>\/\/  Do post-processing\r<\/span>}<\/span><\/pre>\n

                Note that stops are handled before scale-in checking occurs, as there’s no point scaling in a trade if it’s about to get stopped out on the same bar (although it would be unlikely to satisfy the scale-in condition anyway if it was about to get stopped out).
                \nAlso note that the Trade object method GetEntryValue returns the total amount of injected capital, including all previous scale-in amounts. It’s not possible to get just the amount used in the initial purchase. It would actually be nice here if the Trade object had a few user-defined properties, to allow the user to persist any values they wanted to throughout the life of a trade (although this could also be done with static variables). For example, as mentioned above, the initial purchase amount before any scaling could be remembered, or perhaps the number of times scaling has occurred (your system may want to limit scaling in to a maximum of say three times).
                \nAnother similar example, but this time scaling out a position once it has doubled in value, removing the initial capital invested (approximately):<\/p>\n

                SetCustomBacktestProc<\/span>(<\/span>""<\/span>);\rif (<\/span>Status<\/span>(<\/span>"action"<\/span>) == <\/span>actionPortfolio<\/span>)\r{\r    <\/span>bo <\/span>= <\/span>GetBacktesterObject<\/span>();    <\/span>\/\/  Get backtester object\r    <\/span>bo<\/span>.<\/span>PreProcess<\/span>();    <\/span>\/\/  Do pre-processing\r    <\/span>for (<\/span>i <\/span>= <\/span>0<\/span>; <\/span>i <\/span>< <\/span>BarCount<\/span>; <\/span>i<\/span>++)    <\/span>\/\/  Loop through all bars\r    <\/span>{\r        for (<\/span>sig <\/span>= <\/span>bo<\/span>.<\/span>GetFirstSignal<\/span>(<\/span>i<\/span>); <\/span>sig<\/span>; <\/span>sig <\/span>= <\/span>bo<\/span>.<\/span>GetNextSignal<\/span>(<\/span>i<\/span>))\r        {    <\/span>\/\/  Loop through all signals at this bar\r            <\/span>if (<\/span>sig<\/span>.<\/span>IsEntry<\/span>() && <\/span>sig<\/span>.<\/span>IsLong<\/span>())    <\/span>\/\/  Process long entries\r            <\/span>{\r                <\/span>bo<\/span>.<\/span>EnterTrade<\/span>(<\/span>i<\/span>, <\/span>sig<\/span>.<\/span>Symbol<\/span>, <\/span>True<\/span>, <\/span>sig<\/span>.<\/span>Price<\/span>, <\/span>sig<\/span>.<\/span>PosSize<\/span>);\r                <\/span>trade <\/span>= <\/span>bo<\/span>.<\/span>FindOpenPos<\/span>(<\/span>sig<\/span>.<\/span>Symbol<\/span>);    <\/span>\/\/  Find the trade we just entered\r                <\/span>if (<\/span>trade<\/span>)    <\/span>\/\/  Or \"if (!IsNull(trade))\"\r                    <\/span>trade<\/span>.<\/span>MarginLoan <\/span>= <\/span>0<\/span>;    <\/span>\/\/  On initial buy, zero margin loan property\r            <\/span>}\r            else\r            {\r                if (<\/span>sig<\/span>.<\/span>IsExit<\/span>() && <\/span>sig<\/span>.<\/span>IsLong<\/span>())    <\/span>\/\/  Process long exits\r                    <\/span>bo<\/span>.<\/span>ExitTrade<\/span>(<\/span>i<\/span>, <\/span>sig<\/span>.<\/span>Symbol<\/span>, <\/span>sig<\/span>.<\/span>Price<\/span>);\r            }\r        }    <\/span>\/\/  End of for loop over signals at this bar\r        <\/span>bo<\/span>.<\/span>HandleStops<\/span>(<\/span>i<\/span>);    <\/span>\/\/  Handle programmed stops at this bar\r        <\/span>for (<\/span>trade <\/span>= <\/span>bo<\/span>.<\/span>GetFirstOpenPos<\/span>(); <\/span>trade<\/span>; <\/span>trade <\/span>= <\/span>bo<\/span>.<\/span>GetNextOpenPos<\/span>())\r        {    <\/span>\/\/  Loop through all open positions\r            <\/span>ev <\/span>= <\/span>trade<\/span>.<\/span>GetEntryValue<\/span>();    <\/span>\/\/  Entry value of trade (ie. initial capital)\r            <\/span>if (!<\/span>trade<\/span>.<\/span>MarginLoan <\/span>&& <\/span>trade<\/span>.<\/span>GetProfit<\/span>() >= <\/span>ev<\/span>)   <\/span>\/\/  Only if MarginLoan is zero\r            <\/span>{\r                <\/span>trade<\/span>.<\/span>MarginLoan <\/span>= <\/span>1<\/span>;    <\/span>\/\/  Indicate have scaled out once now\r                <\/span>bo<\/span>.<\/span>ScaleTrade<\/span>(<\/span>i<\/span>, <\/span>trade<\/span>.<\/span>Symbol<\/span>, <\/span>False<\/span>, <\/span>trade<\/span>.<\/span>GetPrice<\/span>(<\/span>i<\/span>, <\/span>"C"<\/span>), <\/span>ev<\/span>);    <\/span>\/\/  Scale out\r            <\/span>}\r        }    <\/span>\/\/  End of for loop over trades at this bar\r        <\/span>bo<\/span>.<\/span>UpdateStats<\/span>(<\/span>i<\/span>, <\/span>1<\/span>);    <\/span>\/\/  Update MAE\/MFE stats for bar\r        <\/span>bo<\/span>.<\/span>UpdateStats<\/span>(<\/span>i<\/span>, <\/span>2<\/span>);    <\/span>\/\/  Update stats at bar's end\r    <\/span>}    <\/span>\/\/  End of for loop over bars\r    <\/span>bo<\/span>.<\/span>PostProcess<\/span>();    <\/span>\/\/  Do post-processing\r<\/span>}<\/span><\/pre>\n

                In this example we only want to do the scale-out once, which introduces a new problem: how do we tell whether we’ve already done it or not? Trial and error shows that the entry value returned by the GetEntryValue method halves if you remove half of the value, so AmiBroker appears to treat a scale-out of half the value as being half profit and half original capital. As mentioned above, we really need a Trade object property here that we can write to with our own information. Since we’re not using margin, we can use the MarginLoan property, which fortunately is not read-only. I tried to use the Score property first, but that turned out to be read-only, despite AmiBroker help not mentioning that fact.
                \nThis example is mostly the same as the previous one, but instead of scaling in, we now scale out. Again, the trigger condition is the profit being greater than the entry value (injected capital), but we need to use a state variable to remember whether or not we’ve already scaled out the position so that we only do it once. As mentioned above, we can’t tell this from the entry value alone. While the MarginLoan property was available and writeable in this case, it would be much better, as already mentioned, if Trade objects had some user-definable properties.
                \nAnd once again as a reminder, since I use C and C++ syntax rather than the syntax defined in AmiBroker help, !trade.MarginLoan is the same as NOT trade.MarginLoan and && is equivalent to AND. The statement !trade.MarginLoan just means if trade.MarginLoan equals zero.<\/p>\n

                Conclusion<\/strong><\/p>\n

                That pretty much covers the use of the custom backtester interface at all three levels. While there are a number of object properties and methods I haven’t mentioned or used, this document is not intended to be a reference manual but rather an introduction to using the interface. There should be enough information here to allow you to figure out the rest for yourself with a bit of trial and error (as I’ve had to use myself while writing this document).<\/p>\n

                Computer programming in any language can be a rewarding, but at times extremely frustrating, experience. After many hours of trying to get your “simple” piece of code working properly, by which time you’re ready to swear on your grandmother’s grave that there has to be a problem with the language interpreter or compiler, almost invariably the problem is in your own code. It could be as simple as a missing semicolon, or as complex as a complete misunderstanding about how something is supposed to work. But as Eric Idle once said, always look on the bright side of life. The good thing about an extremely frustrating problem is that it feels SO good once you finally figure it out!<\/p>\n

                Appendix A – DayCount Function<\/strong><\/p>\n

                The code for the DayCount function used to calculate the number of calendar days between two date\/time values is below. This includes both entry and exit days in the count. It consists of two functions, the DayCount function itself, and a DayInYear function to calculate the current day number in a year for a particular date.
                \nFirstly, the DayInYear function:<\/p>\n

                <\/span>function <\/span>DayInYear<\/span>(<\/span>yday<\/span>, <\/span>ymonth<\/span>, <\/span>yyear<\/span>)\r{\r    <\/span>doy <\/span>= <\/span>yday<\/span>;    <\/span>\/\/  Set number of days to current day\r    <\/span>for (<\/span>i <\/span>= <\/span>1<\/span>; <\/span>i <\/span>< <\/span>ymonth<\/span>; <\/span>i<\/span>++)    <\/span>\/\/  Loop over all months before this one\r    <\/span>{\r        switch (<\/span>i<\/span>)    <\/span>\/\/  Sum number of days in each month\r        <\/span>{\r            case <\/span>1<\/span>:\r            case <\/span>3<\/span>:\r            case <\/span>5<\/span>:\r            case <\/span>7<\/span>:\r            case <\/span>8<\/span>:\r            case <\/span>10<\/span>:\r            case <\/span>12<\/span>:\r                <\/span>doy <\/span>= <\/span>doy <\/span>+ <\/span>31<\/span>; break;    <\/span>\/\/  Months with 31 days\r            <\/span>case <\/span>4<\/span>:\r            case <\/span>6<\/span>:\r            case <\/span>9<\/span>:\r            case <\/span>11<\/span>:\r                <\/span>doy <\/span>= <\/span>doy <\/span>+ <\/span>30<\/span>; break;    <\/span>\/\/  Months with 30 days\r            <\/span>case <\/span>2<\/span>:\r            {\r                <\/span>doy <\/span>= <\/span>doy <\/span>+ <\/span>28<\/span>;    <\/span>\/\/  February non-leap year\r                <\/span>if (!(<\/span>yyear <\/span>% <\/span>4<\/span>) && <\/span>yyear <\/span>!= <\/span>2000<\/span>)\r                    <\/span>doy<\/span>++;    <\/span>\/\/  February leap year\r                <\/span>break;\r            }\r        }\r    }\r    return <\/span>doy<\/span>;    <\/span>\/\/  Return day in year, starting from 1\r<\/span>}<\/span><\/pre>\n

                This gets called by the DayCount function for both the entry and exit days.
                \nNow the DayCount function:<\/p>\n

                <\/span>function <\/span>DayCount<\/span>(<\/span>inDay<\/span>, <\/span>outDay<\/span>)\r{\r    <\/span>in <\/span>= <\/span>DateTimeConvert<\/span>(<\/span>0<\/span>, <\/span>inDay<\/span>);    <\/span>\/\/  Convert entry to DateNum format\r    <\/span>out <\/span>= <\/span>DateTimeConvert<\/span>(<\/span>0<\/span>, <\/span>outDay<\/span>);    <\/span>\/\/  Convert exit date\r\r    <\/span>iyy <\/span>= <\/span>int<\/span>(<\/span>in <\/span>\/ <\/span>10000<\/span>) + <\/span>1900<\/span>;    <\/span>\/\/  Get entry year\r    <\/span>imm <\/span>= <\/span>int<\/span>((<\/span>in <\/span>% <\/span>10000<\/span>) \/ <\/span>100<\/span>);    <\/span>\/\/  Month\r    <\/span>idd <\/span>= <\/span>in <\/span>% <\/span>100<\/span>;    <\/span>\/\/  Day\r    <\/span>doyi <\/span>= <\/span>DayInYear<\/span>(<\/span>idd<\/span>, <\/span>imm<\/span>, <\/span>iyy<\/span>);    <\/span>\/\/  Calculate entry day in year\r\r    <\/span>oyy <\/span>= <\/span>int<\/span>(<\/span>out <\/span>\/ <\/span>10000<\/span>) + <\/span>1900<\/span>;    <\/span>\/\/  Get exit year\r    <\/span>omm <\/span>= <\/span>int<\/span>((<\/span>out <\/span>% <\/span>10000<\/span>) \/ <\/span>100<\/span>);    <\/span>\/\/  Month\r    <\/span>odd <\/span>= <\/span>out <\/span>% <\/span>100<\/span>;    <\/span>\/\/  Day\r    <\/span>doyo <\/span>= <\/span>DayInYear<\/span>(<\/span>odd<\/span>, <\/span>omm<\/span>, <\/span>oyy<\/span>);    <\/span>\/\/  Calculate exit day in year\r\r    <\/span>days <\/span>= <\/span>0<\/span>;    <\/span>\/\/  Initialise days between to zero\r    <\/span>for (<\/span>i <\/span>= <\/span>iyy<\/span>; <\/span>i <\/span>< <\/span>oyy<\/span>; <\/span>i<\/span>++)    <\/span>\/\/  Loop from entry year to < exit year\r    <\/span>{\r        if (!(<\/span>i <\/span>% <\/span>4<\/span>) && <\/span>i <\/span>!= <\/span>2000<\/span>)    <\/span>\/\/  If is a leap year\r            <\/span>days <\/span>= <\/span>days <\/span>+ <\/span>366<\/span>;    <\/span>\/\/  Has 366 days\r        <\/span>else\r            <\/span>days <\/span>= <\/span>days <\/span>+ <\/span>365<\/span>;    <\/span>\/\/  Else has 365 days\r    <\/span>}\r    <\/span>days <\/span>= <\/span>days <\/span>+ <\/span>doyo <\/span>- <\/span>doyi <\/span>+ <\/span>1<\/span>;    <\/span>\/\/  Days\/year plus exit minus entry day\r    \/\/  Plus one to include both dates\r    <\/span>return <\/span>days<\/span>;    <\/span>\/\/  Return total days between dates\r<\/span>}<\/span><\/pre>\n

                Appendix B – Using DebugView<\/strong><\/p>\n

                This appendix discusses the use of the Microsoft SysInternals program DebugView for debugging AFL applications. DebugView can be obtained from the Microsoft website here:
                \nhttp:\/\/www.microsoft.com\/technet\/sysinternals\/Miscellaneous\/DebugView.mspx<\/a>
                \nWhen you run the program, you will get a window like this:<\/p>\n

                cbt3.GIF <\/p>\n

                The display area is where your AFL application can write to using _TRACE statements. Note though, as can be seen above, that your application may not be the only thing sending data to the viewer. DebugView captures all data sent to the viewer from all running applications.
                \nThe main toolbar controls are:<\/p>\n

                cbt4.GIF<\/p>\n

                The Clear Display button is the one you’ll likely use the most while debugging an application. And as with most applications, you can multi-select lines in the output display and use Edit->Copy (Ctrl+C) to copy them to the Clipboard for pasting into another application for further analysis.
                \nUsing The AFL _TRACE Statement
                \nTo output messages to the viewer from your AFL code, including from custom backtest procedures, you use the _TRACE statement:<\/p>\n

                _TRACE<\/span>(<\/span>"Entered 'j' for loop"<\/span>);<\/span><\/pre>\n

                You can concatenate strings simply by “adding” them together:<\/p>\n

                _TRACE<\/span>(<\/span>"Processing symbol " <\/span>+ <\/span>trade<\/span>.<\/span>Symbol<\/span>);<\/span><\/pre>\n

                To include the value of parameters in the message, use the StrFormat function the same as for Plot statements:<\/p>\n

                _TRACE<\/span>(<\/span>StrFormat<\/span>(<\/span>"Buying " <\/span>+ <\/span>sig<\/span>.<\/span>Symbol <\/span>+ <\/span>", price = %1.3f"<\/span>, <\/span>sig<\/span>.<\/span>Price<\/span>));<\/span><\/pre>\n

                A sample trace while testing the first low-level example given in this document:<\/p>\n

                That output was produced by the following code in the custom backtest procedure:<\/p>\n

                isAqp <\/span>= <\/span>trade<\/span>.<\/span>Symbol <\/span>== <\/span>"AQP"<\/span>;\rif (<\/span>isAqp<\/span>)\r    <\/span>_TRACE<\/span>(<\/span>StrFormat<\/span>(<\/span>"Scaling in " <\/span>+ <\/span>trade<\/span>.<\/span>Symbol <\/span>+ <\/span>" at bar %1.0f, entry value = %1.3f"<\/span>, <\/span>i<\/span>, <\/span>trade<\/span>.<\/span>GetEntryValue<\/span>()));\r<\/span>scaleSize <\/span>= <\/span>trade<\/span>.<\/span>GetEntryValue<\/span>() \/ <\/span>2<\/span>;\rif (<\/span>isAqp<\/span>)\r    <\/span>_TRACE<\/span>(<\/span>StrFormat<\/span>(<\/span>"Profit = %1.3f, Value = %1.3f, price = %1.3f, scaleSize = %1.3f"<\/span>, <\/span>trade<\/span>.<\/span>GetProfit<\/span>(), <\/span>trade<\/span>.<\/span>GetPositionValue<\/span>(), <\/span>trade<\/span>.<\/span>GetPrice<\/span>(<\/span>i<\/span>, <\/span>"C"<\/span>), <\/span>scaleSize<\/span>));\r<\/span>bo<\/span>.<\/span>ScaleTrade<\/span>(<\/span>i<\/span>, <\/span>trade<\/span>.<\/span>Symbol<\/span>, <\/span>True<\/span>, <\/span>trade<\/span>.<\/span>GetPrice<\/span>(<\/span>i<\/span>, <\/span>"C"<\/span>), <\/span>scaleSize<\/span>);<\/span><\/pre>\n

                Remember that as newlines are considered white space by the language, one statement can be spread over multiple lines for readability without affecting its operation. The only thing to be aware of is where a single string inside double quotes needs to span multiple lines. White space in a string is treated as exactly what it is, so if you put a line break in the middle of it, you will end up with a line break in your output (this is not true in all languages, but is with AFL as far as tracing goes). Instead, you can split it into two strings and concatenate them:<\/p>\n

                _TRACE<\/span>(<\/span>StrFormat<\/span>(<\/span>"Profit = %1.3f, Value = %1.3f, price = %1.3f, " <\/span>+ <\/span>"scaleSize = %1.3f"<\/span>, <\/span>trade<\/span>.<\/span>GetProfit<\/span>(), <\/span>trade<\/span>.<\/span>GetPositionValue<\/span>(), <\/span>trade<\/span>.<\/span>GetPrice<\/span>(<\/span>i<\/span>, <\/span>"C"<\/span>), <\/span>scaleSize<\/span>));<\/span><\/pre>\n

                In the end though, this is only for readability purposes. As far as the language goes, it doesn’t matter if a single line is 1000 characters long and scrolls off the right-hand end of the screen. It just makes it more difficult to read the line when you’re working on that part of the code.<\/p>\n

                There’s little else that can be said about using DebugView for debugging your AFL code. Debugging is something of an art, and knowing what sort of information to trace at which parts of the code is something you’ll get better at the more you do it. Too little information and you can’t tell what’s happening. Too much and it can be like looking for the proverbial needle in a haystack.<\/p>\n

                Appendix C – Lichello AIM Algorithm<\/strong><\/p>\n

                <\/span>\/*     The AIM algorithm is a monthly long position algorithm that buys as\r        prices fall and sells as prices rise. It maintains a position control\r        amount and then uses a buy safe and sell safe percentage to determine\r        how much to buy or sell each month.\r\r        Each stock is treated separately, with its own amount of allocated\r        funds. This can be split into an initial purchase amount, which\r        becomes the initial position control amount, and a cash component.\r        These are the only funds available for the stock. On the last bar of\r        each month, the algorithm below is followed:\r\r        - Is the current portfolio value higher than the position control?\r        - If so, check if sell any, if not, check if buy any.\r        - If sell, calculate Value*(1-sellSafe)-positionControl. That is\r          the dollar value of sale.\r        - If buy, calculate positionControl-Value*(1+buySafe). That is\r          the dollar value of purchase.\r        - Check if the amount is greater than the minimum trade value.\r        - If sell, check if already maximum cash balance and do vealie if so.\r          Vealie is just add sellValue\/2 to position control. Otherwise sell\r          specified amount as scale-out.\r        - If buy, check if sufficient funds available. If not, reduce\r          purchase to remaining funds value (minus brokerage). If that is\r          still greater than minimum trade, can still buy. Buy calculated\r          value of shares as scale-in. Increase position control by buyValue\/2.\r        - Adjust cash balance of stock to allow for share sale or purchase,\r          including brokerage.\r\r        This implementation adds the following:\r\r        - Buy signal for initial purchase based on relative positions of three\r          EMAs and slope of the longest period one.\r        - After initial purchase, scale-in and scale-out used for all trades.\r        - Maximum loss stop used to sell out position if maximum loss reached.\r        - Buy signals have random score to help with Monte Carlo testing.\r\r        As the only sell signal is the maximum loss stop, once the initial\r        equity has been used up in buying stocks and their cash balances, no\r        more stocks will be bought until one of the purchased ones has been\r        stopped out.\r\r        This routine tracks the stock quantity and cash balance of each\r        stock independantly of the backtester object. It will prevent\r        purchases of new stocks if no cash is available even though the\r        backtester may still show a positive overall cash balance, as the\r        backtester cash balance includes the cash balances of each of the\r        purchased stocks. In other words, the cash part of each stock\r        position is still kept in the backtester's cash balance but is\r        reserved for just that one stock until it gets sold if stopped out.\r\r        The whole AIM algorithm is implemented in the low-level custom\r        backtest procedure. The main AFL code just collects the parameters\r        and passes them as static variables to the custom backtest procedure,\r        and sets up the initial Buy array based on the EMA conditions.\r\r        For more information on the AIM algorithm see the website:\r\r        http:\/\/www.aim-users.com\r\r        and follow the links \"AIM Basics" and \"AIM Improvements\".\r*\/\r\r\/\/===============================================================\r\r\/*      Check if the last bar of a calendar month ....\r\r        Checks if the passed bar is the last bar of a calendar month (which does not necessarily mean the last day of the month). It does this by checking if the next bar is in a different month. As it has to look ahead one bar for that, it cannot check the very last bar, and will\r        always report that bar as not being the last bar of the month.\r\r        \"dn" is the DateNum array\r        \"bar" is the bar to check\r*\/\r\r<\/span>function <\/span>IsEOM<\/span>(<\/span>dn<\/span>, <\/span>bar<\/span>)\r{\r    <\/span>rc <\/span>= <\/span>False<\/span>;\r    if (<\/span>bar <\/span>>= <\/span>0 <\/span>&& <\/span>bar <\/span>< <\/span>BarCount<\/span>-<\/span>1<\/span>)\r    {\r        <\/span>mm <\/span>= <\/span>Int<\/span>((<\/span>dn<\/span>[<\/span>bar<\/span>] % <\/span>10000<\/span>) \/ <\/span>100<\/span>);    <\/span>\/\/  Month of passed bar\r        <\/span>mmn <\/span>= <\/span>Int<\/span>((<\/span>dn<\/span>[<\/span>bar<\/span>+<\/span>1<\/span>] % <\/span>10000<\/span>) \/ <\/span>100<\/span>);    <\/span>\/\/  Month of next bar\r        <\/span>rc <\/span>= <\/span>mmn <\/span>!= <\/span>mm<\/span>;    <\/span>\/\/  End of month if not same\r    <\/span>}\r    return <\/span>rc<\/span>;\r}\r<\/span>SetCustomBacktestProc<\/span>(<\/span>""<\/span>);    <\/span>\/\/  Start of custom backtest procedure\r<\/span>if (<\/span>Status<\/span>(<\/span>"action"<\/span>) == <\/span>actionPortfolio<\/span>)\r{\r    <\/span>bo <\/span>= <\/span>GetBacktesterObject<\/span>();\r    <\/span>bo<\/span>.<\/span>PreProcess<\/span>();\r    <\/span>totalCash <\/span>= <\/span>StaticVarGet<\/span>(<\/span>"totalCashG"<\/span>);    <\/span>\/\/  Get global static variables\r    <\/span>iniPos <\/span>= <\/span>StaticVarGet<\/span>(<\/span>"iniPosG"<\/span>);\r    <\/span>iniCash <\/span>= <\/span>StaticVarGet<\/span>(<\/span>"iniCashG"<\/span>);\r    <\/span>buySafe <\/span>= <\/span>StaticVarGet<\/span>(<\/span>"buySafeG"<\/span>);\r    <\/span>sellSafe <\/span>= <\/span>StaticVarGet<\/span>(<\/span>"sellSafeG"<\/span>);\r    <\/span>minTrade <\/span>= <\/span>StaticVarGet<\/span>(<\/span>"minTradeG"<\/span>);\r    <\/span>maxCash <\/span>= <\/span>StaticVarGet<\/span>(<\/span>"maxCashG"<\/span>);\r    <\/span>maxLoss <\/span>= <\/span>StaticVarGet<\/span>(<\/span>"maxLossG"<\/span>);\r    <\/span>brok <\/span>= <\/span>StaticVarGet<\/span>(<\/span>"brokG"<\/span>);\r    <\/span>monteCarlo <\/span>= <\/span>StaticVarGet<\/span>(<\/span>"monteCarloG"<\/span>);\r    <\/span>dn <\/span>= <\/span>DateNum<\/span>();    <\/span>\/\/  Array for finding end of month\r    <\/span>for (<\/span>i <\/span>= <\/span>0<\/span>; <\/span>i <\/span>< <\/span>BarCount<\/span>-<\/span>1<\/span>; <\/span>i<\/span>++)    <\/span>\/\/  For loop over all bars\r    <\/span>{\r        if (<\/span>IsEOM<\/span>(<\/span>dn<\/span>, <\/span>i<\/span>))    <\/span>\/\/  Scale trades only on last bar of month\r        <\/span>{\r            for (<\/span>trade <\/span>= <\/span>bo<\/span>.<\/span>GetFirstOpenPos<\/span>(); <\/span>trade<\/span>; <\/span>trade <\/span>= <\/span>bo<\/span>.<\/span>GetNextOpenPos<\/span>())\r            {\r                <\/span>qty <\/span>= <\/span>StaticVarGet<\/span>(<\/span>"qty"<\/span>+<\/span>trade<\/span>.<\/span>Symbol<\/span>);    <\/span>\/\/  Current quantity for stock\r                <\/span>poCo <\/span>= <\/span>StaticVarGet<\/span>(<\/span>"poCo"<\/span>+<\/span>trade<\/span>.<\/span>Symbol<\/span>);  <\/span>\/\/  Current position control for stock\r                <\/span>cash <\/span>= <\/span>StaticVarGet<\/span>(<\/span>"cash"<\/span>+<\/span>trade<\/span>.<\/span>Symbol<\/span>);    <\/span>\/\/  Current cash balance for stock\r                <\/span>value <\/span>= <\/span>trade<\/span>.<\/span>Shares<\/span>*<\/span>trade<\/span>.<\/span>GetPrice<\/span>(<\/span>i<\/span>, <\/span>"C"<\/span>);  <\/span>\/\/  Current stock value\r                <\/span>profit <\/span>= <\/span>trade<\/span>.<\/span>GetProfit<\/span>();    <\/span>\/\/  Current trade profit\r                <\/span>bprice <\/span>= <\/span>trade<\/span>.<\/span>GetPrice<\/span>(<\/span>i<\/span>+<\/span>1<\/span>, <\/span>"C"<\/span>);    <\/span>\/\/  Potential buy price (tomorrow's price)\r                <\/span>sprice <\/span>= <\/span>trade<\/span>.<\/span>GetPrice<\/span>(<\/span>i<\/span>+<\/span>1<\/span>, <\/span>"C"<\/span>);    <\/span>\/\/  Potential sell price (tomorrow's price)\r                <\/span>if (<\/span>profit <\/span>\/ (<\/span>iniPos <\/span>+ <\/span>iniCash<\/span>) < -<\/span>maxLoss<\/span>)    <\/span>\/\/  If maximum loss reached\r                <\/span>{\r                    <\/span>bo<\/span>.<\/span>ExitTrade<\/span>(<\/span>i<\/span>, <\/span>trade<\/span>.<\/span>Symbol<\/span>, <\/span>sprice<\/span>, <\/span>1<\/span>);    <\/span>\/\/  Exit trade (stopped out)\r                    <\/span>exitVal <\/span>= <\/span>cash <\/span>+ <\/span>qty<\/span>*<\/span>sprice <\/span>- <\/span>brok<\/span>;    <\/span>\/\/  Cash balance after sale\r                    <\/span>totalCash <\/span>= <\/span>totalCash <\/span>+ <\/span>exitVal<\/span>;    <\/span>\/\/  Update total system cash\r                <\/span>}\r                else\r                {\r                    if (<\/span>value <\/span>> <\/span>poCo<\/span>)    <\/span>\/\/  Increased in value, so look to sell\r                    <\/span>{\r                        <\/span>toSell <\/span>= <\/span>value <\/span>* (<\/span>1 <\/span>- <\/span>sellSafe<\/span>) - <\/span>poCo<\/span>;    <\/span>\/\/  Value to sell\r                        <\/span>sshares <\/span>= <\/span>Int<\/span>(<\/span>toSell <\/span>\/ <\/span>sprice<\/span>);    <\/span>\/\/  Number of shares to sell\r                        <\/span>if (<\/span>sshares <\/span>>= <\/span>qty <\/span>|| <\/span>toSell <\/span>>= <\/span>minTrade<\/span>)  <\/span>\/\/  If more than min or all remaining\r                        <\/span>{\r                            if (<\/span>sshares <\/span>> <\/span>qty<\/span>)    <\/span>\/\/  Can't sell more than have\r                                <\/span>sshares <\/span>= <\/span>qty<\/span>;\r                            <\/span>sval <\/span>= <\/span>sshares <\/span>* <\/span>sprice<\/span>;    <\/span>\/\/  Actual value to sell\r                            <\/span>if (<\/span>cash <\/span>< <\/span>maxCash<\/span>)    <\/span>\/\/  If don't already have max cash\r                            <\/span>{\r                                if (<\/span>cash<\/span>+<\/span>sval <\/span>> <\/span>maxCash<\/span>)    <\/span>\/\/  If sale will give more than max cash\r                                <\/span>{\r                                    <\/span>sval <\/span>= <\/span>maxCash <\/span>- <\/span>cash<\/span>;    <\/span>\/\/  Reduce sale to end with max cash\r                                    <\/span>sshares <\/span>= <\/span>Int<\/span>(<\/span>sval <\/span>\/ <\/span>sprice<\/span>);\r                                    <\/span>sval <\/span>= <\/span>sshares <\/span>* <\/span>sprice<\/span>;\r                                }\r                                <\/span>ishares <\/span>= <\/span>trade<\/span>.<\/span>Shares<\/span>;    <\/span>\/\/  Number of shares have now\r                                <\/span>bo<\/span>.<\/span>ScaleTrade<\/span>(<\/span>i<\/span>, <\/span>trade<\/span>.<\/span>Symbol<\/span>, <\/span>False<\/span>, <\/span>sprice<\/span>, <\/span>sval<\/span>);    <\/span>\/\/  Sell the shares\r                                <\/span>soldShares <\/span>= <\/span>ishares <\/span>- <\/span>trade<\/span>.<\/span>Shares<\/span>;  <\/span>\/\/  Number of shares sold\r                                <\/span>if (<\/span>soldShares <\/span>> <\/span>0<\/span>)    <\/span>\/\/  If actually sold some\r                                <\/span>{\r                                    <\/span>tval <\/span>= <\/span>soldShares <\/span>* <\/span>sprice<\/span>;    <\/span>\/\/  Value of shares sold\r                                    <\/span>StaticVarSet<\/span>(<\/span>"qty"<\/span>+<\/span>trade<\/span>.<\/span>Symbol<\/span>, <\/span>trade<\/span>.<\/span>Shares<\/span>);  <\/span>\/\/ Store remaining qty\r                                    <\/span>StaticVarSet<\/span>(<\/span>"cash"<\/span>+<\/span>trade<\/span>.<\/span>Symbol<\/span>, <\/span>cash<\/span>+<\/span>tval<\/span>-<\/span>brok<\/span>);  <\/span>\/\/  And cash\r                                <\/span>}\r                            }\r                            else    <\/span>\/\/  Have max cash already so do a vealie\r                                <\/span>StaticVarSet<\/span>(<\/span>"poCo"<\/span>+<\/span>trade<\/span>.<\/span>Symbol<\/span>, <\/span>poCo<\/span>+<\/span>toSell<\/span>\/<\/span>2<\/span>);  <\/span>\/\/  The vealie\r                        <\/span>}\r                    }\r                    else    <\/span>\/\/  Decreased in value, so look to buy\r                    <\/span>{\r                        <\/span>toBuy <\/span>= <\/span>poCo <\/span>- <\/span>value <\/span>* (<\/span>1 <\/span>+ <\/span>buySafe<\/span>);    <\/span>\/\/  Value to buy\r                        <\/span>if (<\/span>toBuy <\/span>> <\/span>cash<\/span>-<\/span>brok<\/span>)    <\/span>\/\/  If don't have enough cash\r                            <\/span>toBuy <\/span>= <\/span>cash<\/span>-<\/span>brok<\/span>;    <\/span>\/\/  Reduce buy to remaining cash\r                        <\/span>if (<\/span>toBuy <\/span>>= <\/span>minTrade<\/span>)    <\/span>\/\/  If greater than minimum trade value\r                        <\/span>{\r                            <\/span>bshares <\/span>= <\/span>Int<\/span>(<\/span>toBuy <\/span>\/ <\/span>bprice<\/span>);    <\/span>\/\/  Number of shares to buy\r                            <\/span>bpos <\/span>= <\/span>bshares <\/span>* <\/span>bprice<\/span>;    <\/span>\/\/  Actual value of shares to buy\r                            <\/span>ishares <\/span>= <\/span>trade<\/span>.<\/span>Shares<\/span>;    <\/span>\/\/  Number of shares have now\r                            <\/span>bo<\/span>.<\/span>ScaleTrade<\/span>(<\/span>i<\/span>, <\/span>trade<\/span>.<\/span>Symbol<\/span>, <\/span>True<\/span>, <\/span>bprice<\/span>, <\/span>bpos<\/span>);  <\/span>\/\/  Buy the shares\r                            <\/span>boughtShares <\/span>= <\/span>trade<\/span>.<\/span>Shares <\/span>- <\/span>ishares<\/span>;  <\/span>\/\/  Number of shares bought\r                            <\/span>if (<\/span>boughtShares <\/span>> <\/span>0<\/span>)    <\/span>\/\/  If actually bought some\r                            <\/span>{\r                                <\/span>tval <\/span>= <\/span>boughtShares <\/span>* <\/span>bprice<\/span>;    <\/span>\/\/  Value of shares bought\r                                <\/span>StaticVarSet<\/span>(<\/span>"qty"<\/span>+<\/span>trade<\/span>.<\/span>Symbol<\/span>, <\/span>trade<\/span>.<\/span>Shares<\/span>);  <\/span>\/\/  Store new quantity\r                                <\/span>StaticVarSet<\/span>(<\/span>"poCo"<\/span>+<\/span>trade<\/span>.<\/span>Symbol<\/span>, <\/span>poCo<\/span>+<\/span>tval<\/span>\/<\/span>2<\/span>);  <\/span>\/\/  New pos control\r                                <\/span>StaticVarSet<\/span>(<\/span>"cash"<\/span>+<\/span>trade<\/span>.<\/span>Symbol<\/span>, <\/span>cash<\/span>-<\/span>tval<\/span>-<\/span>brok<\/span>);  <\/span>\/\/  And cash\r                            <\/span>}\r                        }\r                    }\r                }\r            }    <\/span>\/\/  End of for loop over open positions\r        <\/span>}\r        for (<\/span>sig <\/span>= <\/span>bo<\/span>.<\/span>GetFirstSignal<\/span>(<\/span>i<\/span>); <\/span>sig<\/span>; <\/span>sig <\/span>= <\/span>bo<\/span>.<\/span>GetNextSignal<\/span>(<\/span>i<\/span>))    <\/span>\/\/  Check new buys\r        <\/span>{\r            <\/span>doBuy <\/span>= !<\/span>monteCarlo<\/span>;    <\/span>\/\/  See if ignore for Monte Carlo testing\r            <\/span>if (<\/span>monteCarlo<\/span>)\r            {\r                 <\/span>rand <\/span>= <\/span>Random<\/span>();\r                 <\/span>doBuy <\/span>= <\/span>rand<\/span>[<\/span>i<\/span>] >= <\/span>monteCarlo<\/span>;    <\/span>\/\/  \"monteCarlo" is prob of ignoring buy\r            <\/span>}\r                          if (<\/span>doBuy <\/span>&& <\/span>IsNull<\/span>(<\/span>bo<\/span>.<\/span>FindOpenPos<\/span>(<\/span>sig<\/span>.<\/span>Symbol<\/span>)) && <\/span>sig<\/span>.<\/span>IsEntry<\/span>() && <\/span>sig<\/span>.<\/span>IsLong<\/span>() && <\/span>sig<\/span>.<\/span>Price <\/span>> <\/span>0<\/span>)    <\/span>\/\/  Can take initial entry signal for stock\r                          <\/span>{\r                <\/span>icash <\/span>= <\/span>iniPos <\/span>+ <\/span>iniCash<\/span>;    <\/span>\/\/  Initial cash value for stock position\r                <\/span>if (<\/span>totalCash <\/span>< <\/span>icash<\/span>)    <\/span>\/\/  Ignore if not enough portfolio cash\r                    <\/span>break;\r                <\/span>ishares <\/span>= <\/span>Int<\/span>((<\/span>iniPos<\/span>-<\/span>brok<\/span>) \/ <\/span>sig<\/span>.<\/span>Price<\/span>);    <\/span>\/\/  Initial number of shares to buy\r                <\/span>ipos <\/span>= <\/span>ishares <\/span>* <\/span>sig<\/span>.<\/span>Price<\/span>;    <\/span>\/\/  Value of shares to buy\r                <\/span>bo<\/span>.<\/span>EnterTrade<\/span>(<\/span>i<\/span>, <\/span>sig<\/span>.<\/span>Symbol<\/span>, <\/span>True<\/span>, <\/span>sig<\/span>.<\/span>Price<\/span>, <\/span>ipos<\/span>);    <\/span>\/\/  Buy the shares\r                <\/span>trade <\/span>= <\/span>bo<\/span>.<\/span>FindOpenPos<\/span>(<\/span>sig<\/span>.<\/span>Symbol<\/span>);    <\/span>\/\/  Find trade for shares just bought\r                <\/span>if (!<\/span>IsNull<\/span>(<\/span>trade<\/span>))\r                {\r                    <\/span>tval <\/span>= <\/span>trade<\/span>.<\/span>GetEntryValue<\/span>();    <\/span>\/\/  Value of shares\r                    <\/span>tshares <\/span>= <\/span>trade<\/span>.<\/span>Shares<\/span>;    <\/span>\/\/  Number of shares\r                    <\/span>StaticVarSet<\/span>(<\/span>"qty"<\/span>+<\/span>sig<\/span>.<\/span>Symbol<\/span>, <\/span>tshares<\/span>);    <\/span>\/\/  Store number of shares\r                    <\/span>StaticVarSet<\/span>(<\/span>"poCo"<\/span>+<\/span>sig<\/span>.<\/span>Symbol<\/span>, <\/span>tval<\/span>);    <\/span>\/\/  And position control (share value)\r                    <\/span>cash <\/span>= <\/span>iniCash<\/span>+<\/span>iniPos<\/span>-<\/span>tval<\/span>-<\/span>brok<\/span>;    <\/span>\/\/  Stock cash balance after purchase\r                    <\/span>StaticVarSet<\/span>(<\/span>"cash"<\/span>+<\/span>sig<\/span>.<\/span>Symbol<\/span>, <\/span>cash<\/span>);    <\/span>\/\/  Store cash balance for stock\r                    <\/span>totalCash <\/span>= <\/span>totalCash<\/span>-<\/span>iniCash<\/span>-<\/span>iniPos<\/span>;    <\/span>\/\/  Subtract from portfolio cash\r                <\/span>}\r            }\r        }    <\/span>\/\/  End of for loop over buy signals\r        <\/span>bo<\/span>.<\/span>HandleStops<\/span>(<\/span>i<\/span>);    <\/span>\/\/  Shouldn't be any stops\r        <\/span>bo<\/span>.<\/span>UpdateStats<\/span>(<\/span>i<\/span>, <\/span>1<\/span>);\r        <\/span>bo<\/span>.<\/span>UpdateStats<\/span>(<\/span>i<\/span>, <\/span>2<\/span>);    \r    }    <\/span>\/\/  End for loop over bars\r    <\/span>for (<\/span>trade <\/span>= <\/span>bo<\/span>.<\/span>GetFirstOpenPos<\/span>(); <\/span>trade<\/span>; <\/span>trade <\/span>= <\/span>bo<\/span>.<\/span>GetNextOpenPos<\/span>())\r    {    <\/span>\/\/  For all open positions at end of test\r        <\/span>qty <\/span>= <\/span>StaticVarGet<\/span>(<\/span>"qty"<\/span>+<\/span>trade<\/span>.<\/span>Symbol<\/span>);    <\/span>\/\/  Number of shares remaining\r        <\/span>poCo <\/span>= <\/span>StaticVarGet<\/span>(<\/span>"poCo"<\/span>+<\/span>trade<\/span>.<\/span>Symbol<\/span>);    <\/span>\/\/  And position control\r        <\/span>cash <\/span>= <\/span>StaticVarGet<\/span>(<\/span>"cash"<\/span>+<\/span>trade<\/span>.<\/span>Symbol<\/span>);    <\/span>\/\/  And stock cash balance\r        <\/span>trade<\/span>.<\/span>AddCustomMetric<\/span>(<\/span>"Shares"<\/span>, <\/span>qty<\/span>);    <\/span>\/\/  Add as metrics to trade list\r        <\/span>trade<\/span>.<\/span>AddCustomMetric<\/span>(<\/span>"Value"<\/span>, <\/span>qty<\/span>*<\/span>trade<\/span>.<\/span>GetPrice<\/span>(<\/span>BarCount<\/span>-<\/span>1<\/span>, <\/span>"C"<\/span>));\r        <\/span>trade<\/span>.<\/span>AddCustomMetric<\/span>(<\/span>"PosCtrl"<\/span>, <\/span>poCo<\/span>);\r        <\/span>trade<\/span>.<\/span>AddCustomMetric<\/span>(<\/span>"Cash"<\/span>, <\/span>cash<\/span>);\r    }\r    for (<\/span>trade <\/span>= <\/span>bo<\/span>.<\/span>GetFirstTrade<\/span>(); <\/span>trade<\/span>; <\/span>trade <\/span>= <\/span>bo<\/span>.<\/span>GetNextTrade<\/span>())\r    {    <\/span>\/\/  For all closed (stopped out) trades\r        <\/span>poCo <\/span>= <\/span>StaticVarGet<\/span>(<\/span>"poCo"<\/span>+<\/span>trade<\/span>.<\/span>Symbol<\/span>);    <\/span>\/\/  Final position control\r        <\/span>cash <\/span>= <\/span>StaticVarGet<\/span>(<\/span>"cash"<\/span>+<\/span>trade<\/span>.<\/span>Symbol<\/span>);    <\/span>\/\/  And cash balance\r        <\/span>trade<\/span>.<\/span>AddCustomMetric<\/span>(<\/span>"Shares"<\/span>, <\/span>0<\/span>);    <\/span>\/\/  Add as metrics to trade list\r        <\/span>trade<\/span>.<\/span>AddCustomMetric<\/span>(<\/span>"Value"<\/span>, <\/span>0<\/span>);\r        <\/span>trade<\/span>.<\/span>AddCustomMetric<\/span>(<\/span>"PosCtrl"<\/span>, <\/span>poCo<\/span>);\r        <\/span>trade<\/span>.<\/span>AddCustomMetric<\/span>(<\/span>"Cash"<\/span>, <\/span>cash<\/span>);\r    }\r    <\/span>bo<\/span>.<\/span>PostProcess<\/span>();\r}    <\/span>\/\/  End of custom backtest procedure\r\/\/================================================================\r\r\/\/      Start of main AFL code ....\r\r<\/span>totalCash <\/span>= <\/span>Param<\/span>(<\/span>"1. Total Cash (000)?"<\/span>, <\/span>20<\/span>, <\/span>10<\/span>, <\/span>1000<\/span>, <\/span>10<\/span>);    <\/span>\/\/  Get parameters\r<\/span>totalCash <\/span>= <\/span>totalCash <\/span>* <\/span>1000<\/span>;\r<\/span>iniPos <\/span>= <\/span>Param<\/span>(<\/span>"2. Initial Position (000)?"<\/span>, <\/span>10<\/span>, <\/span>0<\/span>, <\/span>100<\/span>, <\/span>1<\/span>);\r<\/span>iniPos <\/span>= <\/span>iniPos <\/span>* <\/span>1000<\/span>;\r<\/span>iniCash <\/span>= <\/span>Param<\/span>(<\/span>"3. Initial Cash (000)?"<\/span>, <\/span>10<\/span>, <\/span>0<\/span>, <\/span>100<\/span>, <\/span>1<\/span>);\r<\/span>iniCash <\/span>= <\/span>iniCash <\/span>* <\/span>1000<\/span>;\r<\/span>buySafe <\/span>= <\/span>Param<\/span>(<\/span>"4. Buy Safe?"<\/span>, <\/span>10<\/span>, <\/span>0<\/span>, <\/span>100<\/span>, <\/span>1<\/span>);\r<\/span>buySafe <\/span>= <\/span>buySafe <\/span>\/ <\/span>100<\/span>;\r<\/span>sellSafe <\/span>= <\/span>Param<\/span>(<\/span>"5. Sell Safe?"<\/span>, <\/span>10<\/span>, <\/span>0<\/span>, <\/span>100<\/span>, <\/span>1<\/span>);\r<\/span>sellSafe <\/span>= <\/span>sellSafe <\/span>\/ <\/span>100<\/span>;\r<\/span>minTrade <\/span>= <\/span>Param<\/span>(<\/span>"6. Minimum Trade?"<\/span>, <\/span>500<\/span>, <\/span>0<\/span>, <\/span>10000<\/span>, <\/span>100<\/span>);\r<\/span>maxCash <\/span>= <\/span>Param<\/span>(<\/span>"7. Maximum Cash (000)?"<\/span>, <\/span>100<\/span>, <\/span>0<\/span>, <\/span>1000<\/span>, <\/span>10<\/span>);\r<\/span>maxCash <\/span>= <\/span>maxCash <\/span>* <\/span>1000<\/span>;\r<\/span>maxLoss <\/span>= <\/span>Param<\/span>(<\/span>"8. Maximum Loss%?"<\/span>, <\/span>20<\/span>, <\/span>0<\/span>, <\/span>100<\/span>, <\/span>1<\/span>);\r<\/span>maxLoss <\/span>= <\/span>maxLoss <\/span>\/ <\/span>100<\/span>;\r<\/span>brok <\/span>= <\/span>Param<\/span>(<\/span>"9. Brokerage?"<\/span>, <\/span>30<\/span>, <\/span>0<\/span>, <\/span>100<\/span>, <\/span>1<\/span>);\r<\/span>monteCarlo <\/span>= <\/span>Param<\/span>(<\/span>"10. Monte Carlo%?"<\/span>, <\/span>0<\/span>, <\/span>0<\/span>, <\/span>100<\/span>, <\/span>1<\/span>);\r<\/span>monteCarlo <\/span>= <\/span>monteCarlo <\/span>\/ <\/span>100<\/span>;\r\rif (<\/span>monteCarlo<\/span>)    <\/span>\/\/  Probability of ignoring buy for Monte Carlo\r    <\/span>Optimize<\/span>(<\/span>"monteCarlo"<\/span>, <\/span>0<\/span>, <\/span>0<\/span>, <\/span>100<\/span>, <\/span>1<\/span>);    <\/span>\/\/  For running Monte Carlo test\r\r<\/span>SetOption<\/span>(<\/span>"InitialEquity"<\/span>, <\/span>totalCash<\/span>);\r<\/span>SetOption<\/span>(<\/span>"CommissionMode"<\/span>, <\/span>2<\/span>);\r<\/span>SetOption<\/span>(<\/span>"CommissionAmount"<\/span>, <\/span>brok<\/span>);\r<\/span>SetTradeDelays<\/span>(<\/span>0<\/span>, <\/span>0<\/span>, <\/span>0<\/span>, <\/span>0<\/span>);\r\r<\/span>StaticVarSet<\/span>(<\/span>"totalCashG"<\/span>, <\/span>totalCash<\/span>);    <\/span>\/\/  Set global static variables\r<\/span>StaticVarSet<\/span>(<\/span>"iniPosG"<\/span>, <\/span>iniPos<\/span>);\r<\/span>StaticVarSet<\/span>(<\/span>"iniCashG"<\/span>, <\/span>iniCash<\/span>);\r<\/span>StaticVarSet<\/span>(<\/span>"buySafeG"<\/span>, <\/span>buySafe<\/span>);\r<\/span>StaticVarSet<\/span>(<\/span>"sellSafeG"<\/span>, <\/span>sellSafe<\/span>);\r<\/span>StaticVarSet<\/span>(<\/span>"minTradeG"<\/span>, <\/span>minTrade<\/span>);\r<\/span>StaticVarSet<\/span>(<\/span>"maxCashG"<\/span>, <\/span>maxCash<\/span>);\r<\/span>StaticVarSet<\/span>(<\/span>"maxLossG"<\/span>, <\/span>maxLoss<\/span>);\r<\/span>StaticVarSet<\/span>(<\/span>"brokG"<\/span>, <\/span>brok<\/span>);\r<\/span>StaticVarSet<\/span>(<\/span>"monteCarloG"<\/span>, <\/span>monteCarlo<\/span>);\r\r<\/span>e1 <\/span>= <\/span>EMA<\/span>(<\/span>Close<\/span>, <\/span>30<\/span>);    <\/span>\/\/  EMA initial buy conditions\r<\/span>e2 <\/span>= <\/span>EMA<\/span>(<\/span>Close<\/span>, <\/span>60<\/span>);\r<\/span>e3 <\/span>= <\/span>EMA<\/span>(<\/span>Close<\/span>, <\/span>180<\/span>);\r<\/span>e3s <\/span>= <\/span>LinRegSlope<\/span>(<\/span>e3<\/span>, <\/span>2<\/span>);\r<\/span>bsig <\/span>= <\/span>e3s <\/span>> <\/span>0 <\/span>&& <\/span>e1 <\/span>> <\/span>e2 <\/span>&& <\/span>e2 <\/span>> <\/span>e3<\/span>;\r\r<\/span>Buy <\/span>= <\/span>bsig<\/span>;\r<\/span>Sell <\/span>= <\/span>False<\/span>;    <\/span>\/\/  Only maximum loss stop to sell\r\r<\/span>PositionSize <\/span>= <\/span>0<\/span>;    <\/span>\/\/  Calculated in custom routine\r<\/span>PositionScore <\/span>= <\/span>Random<\/span>();    <\/span>\/\/  Random position score for backtesting\r<\/span><\/pre>\n

                The default parameters specified here are the AIM standard values, with $10K initial position, $10K cash, and 10% buy and sell safes. For vealies, the maximum cash balance for a stock defaults to $100K. To experiment with this algorithm in the manner it was intended, try it on individual stocks that have had significant swings but no overall trend. Strongly uptrending stocks will give the best results as the parameters approach buy and hold, with initial cash and buy safe of zero, and sell safe of 100%.<\/p>\n

                Note that the code uses trade.Shares*trade.GetPrice(i, “C”) for the current value, not trade.GetPositionValue. That’s because the latter function use’s the previous bar’s closing price to determine the current value, whereas we want the current bar’s price (it’s assumed that buy\/sell tests are made after the close of trading). The actual prices then used are the next bar’s prices, to mimic making the trade the next trading day. Trade delays are set to zero to avoid confusion and conflict.<\/p>\n

                To run this code, copy everything in blue to an AFL file and then run it with the backtester. If you run it over a single stock, set the total cash value to be the sum of the initial position and initial cash values (the default setting), otherwise the backtest report won’t give a realistic result for the percentage return (most of the cash would never have been invested so would have zero gain for that component unless an annual interest rate was set). If running it over a portfolio, set the total cash value to be some multiple of the two initial values to allow that many positions to be entered simultaneously. Running it over a large watchlist of stocks will only pick a few positions, depending on the total cash available, with new positions subsequently only being opened if others are stopped out (note that the maximum loss stop is not part of the AIM algorithm, it’s my own addition).<\/p>\n

                If the backtester results report the trade list, there will only be one entry for each position, no matter how many times it scaled in and out. However, if it got stopped out and the same stock subsequently purchased again, that would show as two trades in the list. To see all the scale in and out trades, run the backtest in Detailed Log mode.<\/p>\n

                At the end of a backtest, the final quantity of shares, their value, the position control, and the cash balance figures are added to the Trade objects as custom metrics (one or two will be the same as existing metrics though). If the trade was closed, the quantity will be zero.
                \nThe parameters include a percentage for Monte Carlo testing. This is the probability of ignoring any particular new buy signal. A value of zero means all buys will be taken, subject to cash availability, while a value of 100 means none will be. The value shouldn’t be set too high otherwise the results might be unrealistic due to a sparsity of trades taken. I’d suggest a value up to 50%, with 25% being what I typically use myself. The less buy signals there are in the Buy array, the lower the value needs to be to avoid giving unrealistic results. To run a Monte Carlo test, set a percentage value and then run an optimisation. The random PositionScore array also helps with Monte Carlo testing.<\/p>\n

                Finally a disclaimer: while I’ve made every attempt to ensure this correctly implements the AIM algorithm as I have specified in the comments and accompanying text, I can’t guarantee that there are no errors or omissions or that this does in fact implement the algorithm correctly. I have presented it here primarily as a more advanced example of a custom backtest procedure, and all use is at your own risk. However, if you do find any errors, please let me know.<\/p>\n","protected":false},"excerpt":{"rendered":"

                by Wayne (GP) Introduction From version 4.67.0, AmiBroker provides a custom backtester interface to allow customising the operation of the backtester’s second phase which processes the trading signals. This allows a range of special situations to be achieved that aren’t natively supported by the backtester. AmiBroker tends to refer to this as the Advanced Portfolio […]<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":[],"categories":[5],"tags":[],"_links":{"self":[{"href":"http:\/\/www.amibroker.org\/editable_userkb\/wp-json\/wp\/v2\/posts\/1716"}],"collection":[{"href":"http:\/\/www.amibroker.org\/editable_userkb\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"http:\/\/www.amibroker.org\/editable_userkb\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"http:\/\/www.amibroker.org\/editable_userkb\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"http:\/\/www.amibroker.org\/editable_userkb\/wp-json\/wp\/v2\/comments?post=1716"}],"version-history":[{"count":3,"href":"http:\/\/www.amibroker.org\/editable_userkb\/wp-json\/wp\/v2\/posts\/1716\/revisions"}],"predecessor-version":[{"id":3503,"href":"http:\/\/www.amibroker.org\/editable_userkb\/wp-json\/wp\/v2\/posts\/1716\/revisions\/3503"}],"wp:attachment":[{"href":"http:\/\/www.amibroker.org\/editable_userkb\/wp-json\/wp\/v2\/media?parent=1716"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"http:\/\/www.amibroker.org\/editable_userkb\/wp-json\/wp\/v2\/categories?post=1716"},{"taxonomy":"post_tag","embeddable":true,"href":"http:\/\/www.amibroker.org\/editable_userkb\/wp-json\/wp\/v2\/tags?post=1716"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}