/* Your original formula here */
buy = cross( macd(), signal() );
sell = cross( signal(), macd() );

/*
** The code below should be
** appended to your original 
** system formula
**
** JScript open position counting 
** (requires AmiBroker 3.6 or higher)
** Written by Tomasz Janeczko
*/

EnableScript("jscript");

days = day();
months = month();
years = year();

<%
days = AFL("days").toArray();
months = AFL("months").toArray();
years = AFL("years").toArray();
buy = AFL("buy").toArray();
sell = AFL("sell").toArray();

// get the access to AmiBroker's application object
oAB = new ActiveXObject("Broker.Application");

// we add artificial "_openposcount" stock that we will use to store
// the cross-market statistics information
comp = oAB.Stocks.Add("_openposcount");

intrade = 0;
for( i = 0; i < days.length; i++ )
{
   // we add the quotation to the artificial stock that we will use
   // to store the information about the cross-market statistics
   qt = comp.Quotations.Add( years[ i ]  + "-" + months[ i ] + "-" + days[ i ] );

    // check if no trade is open and there is a buy signal then open long trade 
    if( intrade == 0 && buy[ i ] ) intrade = 1;
    
    qt.Volume += intrade; // we use Volume field to count number of open trades each day

    // check if there is an open trade and there is a sell signal then close long trade 
    if( intrade == 1 && sell[ i ] ) intrade = 0;
}

%>


