Australian (ASX) Stock Market Forum

Amibroker FAQ

I have been running a backtest which has a filter for EMA. I have had assistance with this backtest about a month ago.

The code currently is:

Code:
MaxPositions = 4;
SetOption("MaxOpenPositions", MaxPositions  );
SetOption("WorstRankHeld", MaxPositions + 2 );
SetPositionSize( 100 / MaxPositions, spsPercentOfEquity ); 

// trade on next day open
BuyPrice = Open;
SetTradeDelays( 1, 1, 1, 1 );


SetBacktestMode( backtestRotational );


SetForeign( "XAO" );
FastMALength = Optimize("FMA",62,30,70,2);
SlowMALength = Optimize("SMA",182,180,200,2);


Filter1 =  EMA( C, FastMALength ) > EMA( C, SlowMALength );
RestorePriceArrays();


//This is the additional filter I have introduced to try and filter out low volume stocks
VolA = Volume * C;
MAVol = MA( VolA, 15 );
Filter = Filter1 AND MAVol > 350000;


// offsetting by large positive number 
// makes sure that our score is always positive and we don't enter short trades
PositionScore = Iif( Filter, 10000 - ROC( C, 252 ), 0 );



StaticVarSet( Name() + "Score", 10000 - ROC( C, 252 ) );

SetCustomBacktestProc("");
if ( Status( "action" ) == actionPortfolio )
{
    bo = GetBacktesterObject();
    bo.backtest( 1 );

    // closed trades
    for ( trade = bo.GetFirstTrade(); trade; trade = bo.GetNextTrade() )
    {   // two additional columns
        trade.addcustomMetric( "Score@entry", Lookup( StaticVarget( trade.symbol + "Score" ), trade.EntryDateTime ) );
        trade.addcustomMetric( "Score@exit", Lookup( StaticVarget( trade.symbol + "Score" ), trade.ExitDateTime ) );
    }
    
    // open trades
    for ( trade = bo.GetFirstOpenPos(); trade; trade = bo.GetNextOpenPos() )
    {   // two additional columns
        trade.addcustomMetric( "Score@entry", Lookup( StaticVarget( trade.symbol + "Score" ), trade.EntryDateTime ) );
        trade.addcustomMetric( "Score@exit", Lookup( StaticVarget( trade.symbol + "Score" ), trade.ExitDateTime ) );
    }

    bo.listTrades();
}

The issue I am having is the EMA 62 is below EMA 182 on "XAO" and has been throughout December. The backtest has however entered into trades for 1 or two days, firstly entering 3 trades on 1 December [closing 2 December] and then entering another trade on 8 December before closing the next day.

Very strange - I note that both sets of trades have occurred on the Monday... possibly a coincidence, but....

Does anyone have an idea where this is messing up...

In the Automatic Analysis settings window under the "general" tab is the option to "pad and align all data to reference symbol". Tick this box and enter XAO as the reference symbol.
 
Hello,

Auto-Trading --- you either love it or hate it. Well, I want to go there. I have not been able to find anyone that offers the needed software for connecting AB to IB. Might any of the posters here know where to direct my attention?

FWIW, my existing code produces all of the orders and position sizes, etc.....just need the next step.

TIA,
RutheezKey
 
Hello,

Auto-Trading --- you either love it or hate it. Well, I want to go there. I have not been able to find anyone that offers the needed software for connecting AB to IB. Might any of the posters here know where to direct my attention?

FWIW, my existing code produces all of the orders and position sizes, etc.....just need the next step.

TIA,
RutheezKey

AmiBroker themselves offer it. Just look for IBcontroller by AmiBroker. It's for discretionary and auto trading with AB.
There is also a link to the source codes of IBcontroller at the AmiBroker devlog
 
Hi Trash,
Thanks! I'll study the material, but it appears this will require more coding than I was hoping for. Perhaps it will not be as tough as I suspect ---- plus, I might actually enjoy the experience. I always look for the easy way out first. ;-)
 
The AmiBroker Users Knowledge Base also has some information, advice, and code related to autotrading:

http://www.amibroker.org/userkb/2007/06/19/introduction-to-real-time-automated-trading/

There have not been posts to the forum from either of the two major contributors to that information -- Al Venosa or Herman van den Bergen -- in several years. Rumor has it that they each bought a tropical island and have retired.

Best,
Howard
 
Anyone know how to do the following:

If i have price pane and two indicator panes on a sheet, how can I draw a vertical line through the three panes (that stays there)? i.e. from top of sheet to bottom of sheet.
 
any one know of a formula which integrates hhv with the condition that prices hold above the close of hhv for x amount of days?

Also as a sell signal, is there a command to sell x percentage under the close of the new hhv set on a specific date?

Thanks
 
Anyone know how to do the following:

If i have price pane and two indicator panes on a sheet, how can I draw a vertical line through the three panes (that stays there)? i.e. from top of sheet to bottom of sheet.

Use static variables and mouse and/or keyboard functions and gfx or plot. If code is finished it will draw 3 lines in three panes at the same time and same position if you click on price chart, for example.
 
Use static variables and mouse and/or keyboard functions and gfx or plot. If code is finished it will draw 3 lines in three panes at the same time and same position if you click on price chart, for example.

Thanks for the reply trash.

I am not quite sophisticated enough with Amibroker to fully understand your answer but will see what I can learn.

Do you know if it is possible to modify a drawing tool. For example would it be possible to modify the vertical line tool to change it from just acting on the pane to instead act on the sheet?
 
Thanks for the reply trash.

I am not quite sophisticated enough with Amibroker to fully understand your answer but will see what I can learn.

Do you know if it is possible to modify a drawing tool. For example would it be possible to modify the vertical line tool to change it from just acting on the pane to instead act on the sheet?

Yes, you can store the studyID to staticvarset using study() function. then you call that study in other chart pane via staticvarget. In addition in that other pane(s) of same sheet you would have to add additional plot code to plot that receiving study (vertical line study being save to static variable)) from master pane (i.e. price chart pane).

It just sounds complicated but it isn't.

BTW the selector line is shown on all chart panes already if you click on a bar. Why do you wanna have an additional vertical line?
 
Yes, you can store the studyID to staticvarset using study() function. then you call that study in other chart pane via staticvarget. In addition in that other pane(s) of same sheet you would have to add additional plot code to plot that receiving study (vertical line study being save to static variable)) from master pane (i.e. price chart pane).

It just sounds complicated but it isn't.

BTW the selector line is shown on all chart panes already if you click on a bar. Why do you wanna have an additional vertical line?

Hi trash

Thanks for the ideas and help. I'll try and get my head around your info in the new year.

I want the line to be permanent (or until I decide to delete it).
 
Hi folks, I'm back with more questions. I've been learning more about trading and coding in Amibroker.
I've put together some code based on:
  • 10 week moving average of index greater than previous week
  • Stock closing at new 20 week high
  • 20 week rate of change > 30
That part of it seemed to work ok until I started adding a trailing stop loss.
The stop loss is supposed to be based on a 40% decline from a stock's highest point unless the index is in decline (based on 10 previous 10 week's trend) in which case it moves up to a 10% decline.

All calculations are done weekly as a close of trading Friday.

When I run this as a scan, it's giving my Buy signals where the stocks don't seem to be meeting the ROC hurdle. It seemed to work ok until I added the trailing stop loss code.

Clearly I've done something(s) wrong and I'm pulling my hair out.

Would you mind having a look at the code and letting me know what I've done wrong. I recognise that the AFL language can be a handful to learn but I'm determined to learn how to do this.

I'm also looking to add a volume filter to the code. What would be appropriate for the All Ords?

Thanks folks. Here's the code.

Code:
SetOption ( "maxopenpositions", mp = 20 );

index = "XAO";   // replace with your index symbol
SetForeign ( index );
{
    TimeFrameSet ( inWeekly );
    {


        Average =   MA ( C, 10 );
        buysignal =  average > Ref ( average, - 1 );
        buysignal1 =  average > Ref ( average, - 1 );      // Buy Condition #1
        uptrend = close > average;

		RestorePriceArrays();

        periodHigh = HHV ( Close, 20 );
         WeeklyClose = close;
        chg =  ROC ( Close, 20 )  ;
        buysignal2 = Close >  Ref ( periodhigh, -1 );   // Buy Condition #2
		buysignal3 = chg > 30 ;               // Buy Condition #3
		buysignal4= uptrend;
        endofweek = 1;
        
    }

    TimeFrameRestore ();
    
    buysignal = TimeFrameExpand ( buysignal , inWeekly, expandpoint );
	uptrend =   TimeFrameExpand ( uptrend , inWeekly );
	endofweek = TimeFrameExpand ( endofweek , inWeekly, expandpoint ) ;
	firstdayofweek = Ref ( endofweek, -1 );


}


Buy= buysignal1 AND buysignal2 AND buysignal3;



//Trailing Stop Information

Buy = Sell = Short = Cover = 0;
position = ExitTrade = EnterTrade = 0;
stopArray = Null ;
TrailingDistance  = IIf ( uptrend , 40 , 10 ) / 100 * Close;

//*************************************
pricecolor = colorDefault;

dow = DayOfWeek();
dt = DateTime();
dtsignal = "";

for ( i = 0 ; i < BarCount ; i ++ )
{
    if ( ExitTrade )
    {
         if ( firstdayofweek [i] )  // exit on monday
        {
            Sell [i] = 1;
            SellPrice [i] = Open[i] ;
            position = 0;
            ExitTrade = 0 ;
        }


    }

    if ( position )
    {
        if ( endofweek [i] )
        {
            if ( WeeklyClose [i ] < stop )
            {
                ExitTrade  = 1;
                pricecolor[i] = colorred;
                dtsignal = DateTimeToStr ( dt[i] );
            }


        }

        if ( ExitTrade == 0 )
        {
            stop = max ( stop , Close [i] - TrailingDistance [i] ) ;     // adjust stop
        }
    }

    if ( EnterTrade )
    {
        if ( firstdayofweek [i] )
        {
            Buy [i] = 1;
            BuyPrice[i] = Open[i];
            stop =  buyprice [i] * ( 1 - 49 / 100 ) ;  // initial stop
            position = 1;
            EnterTrade = 0;
        }


    }

    if ( !position )
    {

        if ( buysignal [i] )
        {
            //printf ( "\n" + dow[i] );
            EnterTrade = 1;
            pricecolor[i] = colorBrightGreen;

            dtsignal = DateTimeToStr ( dt[i] );
        }
    }


    if ( position )
        StopArray [i] = stop ;
}
//*****************************************

Plot ( C, "", colorDefault , stylebar );
shape = Buy *shapeUpArrow;
//Plot ( stopArray, "", colorRed , stylestaircase );
PlotShapes( shape, IIf( Buy, colorGreen, colorRed ), 0, IIf( Buy, Low, High ) );
//PlotShapes (Buy,colorGreen, 0 , Low);
//PlotShapes ( sell  shapedownArrow, colorred, 0 , high );
ribbonColor =  IIf( uptrend , colorGreen, colorRed );
Plot( 2, "", ribbonColor , styleOwnScale | styleArea | styleNoLabel, -0.5, 100 );



GraphXSpace = 10 ;
SetChartOptions( 0 , chartShowDates | chartShowArrows );
 
Hello,

Does anyone know how to access the properties of a study through AFL? I would like to draw a bunch of trend lines and then get their start date & price and end date & price exported to a .txt file.

This thread demonstrates how to access a hand-drawn trend line but there doesn't seem to be any way of directly getting the start and end date & price.
 
Hello,

Does anyone know how to access the properties of a study through AFL? I would like to draw a bunch of trend lines and then get their start date & price and end date & price exported to a .txt file.

This thread demonstrates how to access a hand-drawn trend line but there doesn't seem to be any way of directly getting the start and end date & price.

I found the answer to this on the amibroker KB, although it seems like you are restricted to 6 lines at any one time as there are only 6 possible study IDs. Is there anyway around this?

EDIT: Scratch that. You can make up your own 2-digit ID. If you use the alphabet you can have 676 study IDs e.g. aa, ab, ac, ad etc..
 
Another question if its possible. When running an exploration and you have a filter for average volume done say for example > 1Mill and <4M average, how do you set that filter to only be relavent when the trade signal was given. For example a HHV was triggered 15 years ago. Currently stocks which are currently trading in my filter range might not have been 15 years ago but they are showing up in my exploration list.

Anyway to weed them out?
 
I only explore for prospects in the most recent times to buy now or soon. No point exploring for prospects 15 years ago. :D
 
Haha wysi, I just wanted to test a hypothesis and since I dont have the code for that function yet I thought id manually scan through past price actions.

The funny thing was I set a hhv for atleast above 3 years or so of data and I set raw entry point arrows to be shown on the graph. But for some reason some hhv values didnt even have arrows to indocate an entry position. I put some conditions for price and liquidity but I have alot to learn yet.
 
Top