Amibroker. Learning to program loops. :)

so, let's take the simplest system and try to program it. If you do this without cycles, then everything is elementary, для первоклассников. But there are problems with the feet. If we test a stock portfolio, then as found out earlier, if a stop is triggered for any of the positions in the portfolio, then a new position on other shares is opened at the opening of the same session, if there was a signal to enter before this session. I.e, peeping into the future. More details were here
http://jc-trader.livejournal.com/433905.html
To avoid this, advised to write loops. What will we do.

Hypothetical system with arbitrary conditions, on daily timeframes — for example:

Entrance
1) stock ликвидная, dollar volume over 10 000 000 Dollars
2) closing price is more than MA(200)
3) closing price is less than MA(20)
If all three conditions are true, place a limit order to open a long position for the next session at the LOW price of the last day.

Exit (one by foot and one by condition)
1) a protective stop is placed on the next bar after the bar for opening a position at a distance of 1ATR from the price of opening a position.
2) if the closing price is higher than MA(20), close the position at the opening of the next session.

Writing Cyclic Code, тестируем, And…… we don't get what we want, but something incomprehensible. Something is wrong:

—————————————————————————————
SetFormulaName("zzz");

SetPositionSize( 20, spsPercentOfEquity );
SetOption("MaxOpenPositions", 5 ); 
SetOption("InitialEquity", 100000 );
SetTradeDelays(0,0,0,0);
SetOption( "UsePrevBarEquityForPosSizing", 1 );
RoundLotSize = 1;
ATRr = 1 * Ref(ATR(20), -1);
CLevel = MA(Close, 20);
SetupBuy = MA(  Volume , 20 ) * MA( Close, 20) > 10000000     
                   AND Close > MA(Close, 200)
                   AND Close < CLevel;  
HV40 = round(StDev(log(C/Ref(C,-1)),40)*100*sqrt(252));
PositionScore = HV40;
position = 0;
Sell = BarIndex() == BarCount-1;
/////////////////////////////////////////////////////////
for(i = 201; i < BarCount – 1; i++) 
   if(position!=1) 
      { 
         if(SetupBuy[i-1]  AND Low[i] < Low[i-1])
            { 
               Buy[i] = SetupBuy[i-1];
               BuyPrice[i] = Min(Low[i-1], Open[i]); 
               position = 1; 
               pricebuy = BuyPrice[i]; 
             } 
      } 
   else
      { 
         Buy[i] = 0; 
         if(Low[i] <= pricebuy – ATRr[i]) 
            {    
               Sell[i] = 1; 
               SellPrice[i] = Min(pricebuy – ATRr[i], Open[i]);   
               position=0; 
            } 
         else
            {    
               if(Close[i-1] > CLevel[i-1]) 
                  { 
                     Sell[i ]= 1;  
                     position = 0;
                  } 
            } 
      } 
}
  Overview of Polymetal: major producer of precious metals
Scroll to Top