Amibroker - From Backtest to Trading - Going Live

Going Into Production 

So you have a system in Amibroker that you backtested and you are happy with. You now want to go "into production".
How do you get your signals? How do you keep track of open orders, position sizes, ranking rules, etc. It's not as easy as it may seem.

Explore or Scan?

If you try to run scans or explorations you will get Buy/Sell signals but how many? If you have 500 symbols and you trade the top 10 and your size varies with each stock's ATR, you will have to rank the first 10 and compute, atr's and position sizes and bla..bla..bla.. Do that day in day out... You will make a mistake.

Just Backtest!

In every Backtested system there are assumptions. Position Sizing, Ranking rules, skipping signals or not, etc. One way to keep track of all those things is to let Amibroker do it for you.

The following example assumes 
a. You use no stops
b You trade End Of Day at tommorow's open or tommorow's close.

Here are the steps.
1. Go to Amibroker and backtest your formula as usual. Check everything is ok, Commisions, Initial Equity, etc... Check that your backtested equity curve is what it should be.

2.Open the Backtester Setting.

3. In the Portfolio Tab, check the "Add artificial future bar" box.

** If you are trading ETF's you might want to set "Limit trade size as % of entry bar volume" to 0.

4. Under Report select "Detailed  Log".

5. From to Dates: Start today or a month ago depending on wether you are starting from 0 or synching with the current state of your system** (i.e. it is a long term system that holds Gold for 3 years now).
End day can be sometime in the far future: 1/1/2020

6. Check your margin if you are trading stocks. Max should be 50 (i.e.2x leverage) or higher if your broker allows for that. If you want no leverage set it to 100.

6a. Run the backtest. You should see a list. The last item should be for tommorow's trade.

Here you have the orders ready for you to follow. The Position sizing rules and ranking are done for you. All you have to do is synch to the system (the first time) and then follow it every day (or week or month depending on your system).

Automating it

7. Save the .apx file that incorporates all your setting.
While the Analysis Window is selected and you are happy with all the settings go to Amibroker menu, and select File--->Save As.  A window will ask you where to save the file. Choose the folder where your AFL system formula is (or any other folder you want). Give it a name (My_System_1_Live) and save it as .apx, the default. Now you should have a My_System_1_Live.apx file that is all you need to backtest this strategy.

8. Write a Jscript.
a. Create a new NotePad test document
b. Paste this code and save it not as txt but as .js. Replace the file locations with your own.

//-------Code adapted form Thomaz's code

var WshShell= new ActiveXObject("Wscript.Shell");
AB = new ActiveXObject( "Broker.Application" ); // creates AmiBroker object
// opens previously saved analysis project file
    NewA = AB.AnalysisDocs.Open("C:\\Program Files\\AmiBroker\\Formulas\\My_System_1_Live.apx " );
    // NewA represents the instance of New Analysis document/window
    if ( NewA )
         NewA.Run( 2 ); // start backtest asynchronously
         while ( NewA.IsBusy ) WScript.Sleep( 500 ); // check IsBusy every 0.5 second
        NewA.Export( "C:\\Users\\UserMe\\Desktop\\LiveSystems\\ My_System_1_Live .csv" );
         NewA.Close(); // close new Analysis
     WshShell.Popup ("NewA problem", 3,"Active X problem",0);
catch ( err )

   //Email_Event(" failed to run","Exception: " + err.message);
     WshShell.Popup ("Active X problem"+"Exception: " + err.message, 3,"Active X problem",0);
//end code

For example save it as "Run_Backtest_Sys_1.js
Saving it as a ".js" make it an executable JScript under windows.

9. Double clicking on it will run run it. It will launch Amibroker, open the .apx file you specified, backtest your system and export a report at the location you also specify.

10. Open the .csv file. You should see the backtester's results. The last lines should be tommorow's trades.

11. (Oprional) Parse the .csv file.
If you are good at jScript or VBscript you can write a script that will go to tommorow's entries and parse them into arrays. You can then export clean csv's or e-mail yourself the signals or drive a virtual system at Collective 2 or email your broker.

What about Stops?  
Using the Custom Backtester Object.

There's many ways to do teh same thing. Here's teh code for retrieving tommorow's trades (and stops or other variables) using Amibroker's Custom Backtester.

//-One way to get tommorow's signals - 
//Make sure "Add artificial bar for tommorow", under Backtest Settings-->Portfolio Tab is checked to //get tommorow's trade
///////////////Put your system HERE/////////////////////
/////////////////////End System ///////////////////

////////////Variable that you need to report/////////////
StaticVarSet(Name()+"SL",(stoploss));//place the stoploss inside a staticvar array. Include Name!

////////////////////////////Code for custom report///////////
//Make sure "Add artificial bar for tommorow", under Backtest Settings-->Portfolio Tab is checked to //get tommorow's trade
idx = BarIndex();
d = Day();
m = Month();
y = Year();

SetCustomBacktestProc( "" );
if ( Status( "action" ) == actionPortfolio )
    bo = GetBacktesterObject();
    for ( bar = 0; bar < BarCount; bar++ )
        bo.ProcessTradeSignals( bar );
        CurEquity = bo.Equity;
//if bar is the last bar on the chart set Date
     if(bar==BarCount-1)  Datestr= "\n" + "\n" + d[bar] + "/" + m[bar] + "/" + y[bar] ;

        for ( openpos = bo.GetFirstOpenPos(); openpos; openpos = bo.GetNextOpenPos() )
SL=LastValue(Nz(StaticVarGet(Openpos.Symbol()+"SL"))); // Get the stop loss from the static array
if(Openpos.IsLong()) action="Buy"; else action="Sell";

              if(bar==BarCount-1)  //only continue if we are at the last bar (i.e tommorow's trade)
report= action+"  "+Openpos.Symbol()+ "  "+ openpos.Shares()+" shares"+" Set Stop Loss @: "+ SL+"\n" ;

PopupWindow(datestr+" \n "+report,"Your Trades",10);
Say(report+" and please remember to enjoy the rest of your day", purge = True) ;
//AlertIf( True, "EMAIL", datestr+" \n "+report, 1 );


    bo.PostProcess(); // Finalize backtester

Labels: , , , , , , , , ,