Join & EARN

FOREX ALGOS { }

Loops (Iteration Constructs)

Programming structures that repeat a block of code multiple times. Common loop types include forwhile, and do-while. They are useful in trading bots for scanning historical bars, updating indicators, or continuously checking conditions. GeeksforGeeks defines a loop (e.g. while loop) as an “entry-controlled structure that repeatedly executes a block of code as long as a specified condition is true”.

  • Definition: A forwhile, or do-while loop iterates over data. For example, looping through bars to compute an indicator or backtest logic.

  • Context: In a live EA, loops are often used in tick or bar events. For example, iterating through orders:

    for(int i = OrdersTotal()-1; i >= 0; i--)
    {
    if (OrderSelect(i, SELECT_BY_POS) && OrderType() == OP_BUY)
    OrderClose(OrderTicket(), OrderLots(), Bid, 5);
    }
  • Example:

    // cAlgo example: loop over 100 previous bars to find a pattern
    for(int i = Bars.Count - 100; i < Bars.Count; i++)
    {
    if (Bars.HighPrices[i] > Bars.HighPrices[i-1] && Bars.LowPrices[i] > Bars.LowPrices[i-1])
    Print("Higher high at bar ", i);
    }
    // NinjaScript (C#) for loop:
    for(int i = 1; i < Bars.Count; i++)
    {
    if (Close[i] > SMA(20)[i])
    count++;
    }