Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 26

Looping for Repetition and Iteration

Recommended resources

Hello! Welcome to your next lesson in the "Python Fundamentals for Algorithmic Trading" module.

In the last lesson, we gave our code the ability to make decisions using if, elif, and else statements. This allowed us to check a market condition and execute a specific action, like identifying whether a price was in a premium or discount zone.

However, trading involves analyzing not just one moment in time, but a whole sequence of price data. Today's lesson is about making our code do the heavy lifting. We will focus on the learning outcome: Use loops (for and while) to repeat tasks and iterate over data. Loops are the key to automating repetitive analysis, whether it's scanning thousands of historical candles or running a trading bot that continuously checks the market.

The for Loop: Processing Each Item in a Sequence

The most common type of repetition in data analysis is iterating through a collection of items, like a list of prices or a series of candlesticks. The for loop is designed for exactly this. Its logic is simple: "For each item in this collection, perform this action."

To understand the core mechanics, let's watch a visual explanation.

Python Loops (Visually Explained) | For, While, Break, Continue, Else

The video 'Python Loops (Visually Explained)' offers a clear, animated breakdown of how for loops work. We'll start with the fundamentals of their structure and how to iterate over sequences.

Watch from the beginning to 15:52. Pay close attention to the syntax (for item in sequence:), how the loop variable works, and the use of the range() function to generate number sequences.

Now, let's apply this to a trading context. Imagine you have a list of closing prices for the last five 15-minute candles and you want to check if any of them broke a key resistance level.

Open your Jupyter Notebook or Python environment and run this code:

resistance_level = 1.0750
recent_closes = [1.0745, 1.0748, 1.0752, 1.0751, 1.0749]
breakout_found = False # A flag to track if a breakout happened

print(f"Checking for a breakout above {resistance_level}...")

# This is our for loop. In each iteration, 'price' will hold one value from the list.
for price in recent_closes:
    print(f"Current candle close: {price}") # See the loop in action
    if price > resistance_level:
        print(f"   -> Breakout detected at {price}!")
        breakout_found = True

# This code runs after the loop has finished
if breakout_found:
    print("A breakout occurred within the recent candles.")
else:
    print("No breakout occurred. The level held.")

This is the power of combining the if statement from our last lesson with a for loop. We're no longer checking a single price; we're systematically analyzing a whole series of them.

In a real trading bot, you won't just have a simple list of prices. You'll likely have more detailed information for each candle. The following video shows a practical example of iterating through a list of candle data, where each "item" is a dictionary containing the open, high, low, and close prices.

How to Build a Trading Bot in Python | Full Algorithmic Trading Tutorial

This clip from 'How to Build a Trading Bot in Python' shows a for loop being used in a real-world script. Notice how the code iterates through a list called candles and extracts specific price data from each one.

Watch from 05:55 to 07:12. This demonstrates how to process more complex data structures, which is exactly what we'll be doing with market data.


The while Loop: Repeating Until a Condition Changes

Sometimes, you don't know how many times you need to loop. You just want to repeat an action until a certain condition is met. This is where the while loop comes in. It says: "While this condition is true, keep running this block of code."

This is perfect for situations like:

  • Waiting for the price to enter a specific ICT Killzone.
  • Holding a position until the price hits a take-profit or stop-loss level.
  • Running a trading bot continuously.

Let's watch another segment from the visual explanation video to understand while loops.

Python Loops (Visually Explained) | For, While, Break, Continue, Else

This part of the video explains the while loop. It highlights the three crucial components: initialization, the condition, and the update. It also introduces the danger of an infinite loop.

Watch from 01:16:21 to 01:27:49. Focus on how a while loop is different from a for loop and why the update step is so important.

A common pattern in algorithmic trading is to have a bot that runs forever, constantly checking the market. This is often done with a while True loop, which is a loop that never ends on its own.

Python While Loop Examples
This image shows a few examples of `while` loops, including a basic counter and one that uses a `break` statement to exit, a concept we'll explore next.

Let's see this "always-on" pattern in the context of our trading bot example.

How to Build a Trading Bot in Python | Full Algorithmic Trading Tutorial

Here, the developer needs the bot to run continuously. Watch how a while loop is used to make the program constantly check the time and look for new trade signals.

Watch from 20:17 to 24:10. You don't need to understand every line of code, but focus on the overall structure: the while loop that keeps the bot alive and the if statements inside that decide when to act.


Controlling the Flow: break and continue

Sometimes you need more control over your loops. Python gives us two commands to do this: break and continue.

  • break: Immediately terminates the loop. The code inside the loop will not run again, and the program will continue with the code after the loop.
  • continue: Skips the rest of the current iteration and immediately starts the next one.

Let's see how these are used in practice.

Python Loops (Visually Explained) | For, While, Break, Continue, Else

This final clip from the visual guide explains break and continue. See how break provides an 'emergency exit' and continue allows you to skip specific items.

Watch from 23:21 to 36:50. This section is a bit longer but provides a very clear, animated explanation of these crucial control statements.

Here's an ICT-based example. Imagine we're looping through historical candles to find the first time price swept below a sell-side liquidity (SSL) level.

sell_side_liquidity = 1.2500
# A list of dictionaries, where each represents a candle's data
historical_candles = [
    {'high': 1.2550, 'low': 1.2520},
    {'high': 1.2530, 'low': 1.2510},
    {'high': 1.2515, 'low': 1.2495}, # Liquidity is swept here
    {'high': 1.2505, 'low': 1.2480}  # This candle also sweeps it, but we want the first
]

for candle in historical_candles:
    print(f"Analyzing candle with low at {candle['low']}")
    if candle['low'] < sell_side_liquidity:
        print(f"   -> Sell-side liquidity at {sell_side_liquidity} was taken!")
        break # We found it, no need to check the rest. Exit the loop.

print("Analysis complete.")

Without break, the loop would have continued and printed the message for the last candle as well. break makes our code more efficient by stopping as soon as the goal is achieved.

Test your understanding!

You have a list of recent candles. You want to calculate the total range of all candles that are not dojis (where open equals close).

candles = [
    {'open': 1.10, 'close': 1.15, 'high': 1.16, 'low': 1.09}, # Range = 0.07
    {'open': 1.15, 'close': 1.15, 'high': 1.16, 'low': 1.14}, # Doji, should be skipped
    {'open': 1.15, 'close': 1.12, 'high': 1.15, 'low': 1.11}, # Range = 0.04
]
total_range = 0.0

Which statement should you use inside the loop to properly skip the doji candle?

  1. if candle['open'] == candle['close']: break
  2. if candle['open'] == candle['close']: pass
  3. if candle['open'] != candle['close']: continue
  4. if candle['open'] == candle['close']: continue
Show answer

The correct answer is 4: if candle['open'] == candle['close']: continue.

This logic checks if the candle is a doji. If it is, continue tells the loop to immediately skip to the next candle, ignoring the range calculation for the current one. break would stop the loop entirely. pass does nothing. The third option has the logic reversed.

Here's the full solution:

total_range = 0.0
for candle in candles:
    if candle['open'] == candle['close']:
        continue # Skip this iteration
    
    candle_range = candle['high'] - candle['low']
    total_range += candle_range # Adds the candle_range to the total

# Using round() to handle potential floating point inaccuracies
print(f"Total range of non-doji candles: {round(total_range, 2)}")

Conclusion

Excellent work! You've just unlocked the ability to automate repetitive tasks, which is the heart and soul of algorithmic trading and analysis.

Key Takeaways:

  • for loops are for iterating over a known sequence of items (e.g., a list of candles).
  • while loops are for repeating an action until a condition is no longer true (e.g., running a bot continuously).
  • Infinite Loops are a risk with while loops; always ensure your condition will eventually become false or that you have a break statement.
  • break lets you exit a loop early.
  • continue lets you skip the current iteration and move to the next.

Preview for the Next Lesson:

Our scripts are getting more complex. We have logic for making decisions (if) and for repeating actions (loops). What if we want to reuse a piece of logic, like "find a Fair Value Gap"? Copying and pasting code is inefficient and prone to errors.

In the next lesson, we will learn about functions. Functions allow us to package our code into named, reusable blocks, making our trading scripts cleaner, more organized, and much more powerful.