Without loops, checking 50 stocks would require 50 separate if blocks.
A loop lets you repeat a block of code — once per stock, once per candle,
or until a condition changes. Python has two loop types: for (fixed iterations)
and while (condition-based).
for loopwhile loopbreak & continuebreak exits the loop early. continue skips to the next iteration.range()range(5) gives 0,1,2,3,4. Very useful with for.for LoopA for loop steps through each item in a collection. In trading, you use it to process every stock in a watchlist or every candle in an OHLC dataset.
# Scan a NSE watchlist watchlist = ["RELIANCE", "TCS", "INFY", "HDFCBANK", "ICICIBANK"] for stock in watchlist: print(f"Checking signal for: {stock}") # range() — iterate 5 times print("\n--- Candle index ---") for i in range(5): print(f"Candle #{i}") # enumerate() — index + value print("\n--- With index ---") for idx, stock in enumerate(watchlist): print(f"{idx+1}. {stock}")
Checking signal for: RELIANCE Checking signal for: TCS Checking signal for: INFY Checking signal for: HDFCBANK Checking signal for: ICICIBANK --- Candle index --- Candle #0 Candle #1 Candle #2 Candle #3 Candle #4 --- With index --- 1. RELIANCE 2. TCS 3. INFY 4. HDFCBANK 5. ICICIBANK
Combine the for loop with if/else to build a real watchlist scanner that checks every stock against its VWAP and generates signals.
# Watchlist Scanner — LTP vs VWAP stocks = [ {"name": "RELIANCE", "ltp": 2945, "vwap": 2880}, {"name": "TCS", "ltp": 3820, "vwap": 3890}, {"name": "INFY", "ltp": 1480, "vwap": 1480}, {"name": "HDFCBANK", "ltp": 1565, "vwap": 1520}, {"name": "WIPRO", "ltp": 460, "vwap": 472}, ] print(f"{'STOCK':12} {'LTP':>8} {'VWAP':>8} {'SIGNAL':>10}") print("-" * 42) for s in stocks: if s["ltp"] > s["vwap"]: signal = "✅ BUY" elif s["ltp"] < s["vwap"]: signal = "🔴 SELL" else: signal = "⏸ HOLD" print(f"{s['name']:12} {s['ltp']:>8} {s['vwap']:>8} {signal:>10}")
STOCK LTP VWAP SIGNAL ------------------------------------------ RELIANCE 2945 2880 ✅ BUY TCS 3820 3890 🔴 SELL INFY 1480 1480 ⏸ HOLD HDFCBANK 1565 1520 ✅ BUY WIPRO 460 472 🔴 SELL
break immediately exits the loop — useful when you find the first BUY signal and don't need to scan further.
continue skips the rest of the current iteration — useful to ignore stocks with zero volume.
prices = [22100, 22050, 22380, 22450, 22310] vwap = 22300 # break — stop at first price above VWAP print("--- First VWAP cross ---") for i, price in enumerate(prices): if price > vwap: print(f"VWAP cross at index {i}, price ₹{price}") break print(f" Index {i}: ₹{price} — below VWAP") # continue — skip zero-volume ticks volumes = [1200, 0, 3400, 0, 2100] print("\n--- Skip zero volume ---") for i, vol in enumerate(volumes): if vol == 0: continue # skip this tick print(f"Tick {i}: volume = {vol}")
--- First VWAP cross --- Index 0: ₹22100 — below VWAP Index 1: ₹22050 — below VWAP VWAP cross at index 2, price ₹22380 --- Skip zero volume --- Tick 0: volume = 1200 Tick 2: volume = 3400 Tick 4: volume = 2100
while Loop
The while loop keeps running as long as a condition is True.
In live trading systems, the main event loop is a while True that
checks for signals every second until market close.
# Simulated tick monitor — while loop import random ltp = 22300 target = 22500 stop_loss = 22100 ticks = 0 print("Starting tick monitor...") while stop_loss < ltp < target: # Simulate price movement ltp += random.randint(-30, 40) ticks += 1 print(f" Tick {ticks:02d}: LTP = ₹{ltp}") if ticks >= 8: # safety cap for demo break if ltp >= target: print(f"\n🎯 Target ₹{target} hit! Exiting trade.") elif ltp <= stop_loss: print(f"\n🛑 Stop Loss ₹{stop_loss} hit! Exiting trade.") else: print(f"\n⏱ Demo cap reached. LTP: ₹{ltp}")
while True loop without a break or exit condition will run forever and crash your system. Always include a break condition (e.g., market hours check or kill switch).
OHLC data is a list of candles. Loop over it to find patterns, calculate highs/lows, or detect specific candle formations like bullish engulfing.
# NIFTY 5-min candles [open, high, low, close] candles = [ [22300, 22380, 22270, 22360], [22360, 22400, 22320, 22340], [22340, 22450, 22330, 22440], [22440, 22480, 22390, 22410], [22410, 22510, 22400, 22500], ] session_high = 0 session_low = 999999 bullish = 0 bearish = 0 for i, c in enumerate(candles): o, h, l, close = c session_high = max(session_high, h) session_low = min(session_low, l) candle_type = "🟢 Bull" if close > o else "🔴 Bear" if close > o: bullish += 1 else: bearish += 1 print(f"Candle {i+1}: O={o} H={h} L={l} C={close} {candle_type}") print(f"\nSession High : ₹{session_high}") print(f"Session Low : ₹{session_low}") print(f"Bullish/Bearish: {bullish}/{bearish}")
Candle 1: O=22300 H=22380 L=22270 C=22360 🟢 Bull Candle 2: O=22360 H=22400 L=22320 C=22340 🔴 Bear Candle 3: O=22340 H=22450 L=22330 C=22440 🟢 Bull Candle 4: O=22440 H=22480 L=22390 C=22410 🔴 Bear Candle 5: O=22410 H=22510 L=22400 C=22500 🟢 Bull Session High : ₹22510 Session Low : ₹22270 Bullish/Bearish: 3/2
Python's list comprehension creates a new list by running a loop in a single line. Ideal for filtering stocks, normalising price data, or extracting close prices from candles.
prices = [22300, 22360, 22440, 22410, 22500] # Extract close prices from candles candles = [[22300,22380,22270,22360], [22360,22400,22320,22340], [22340,22450,22330,22440]] closes = [c[3] for c in candles] print("Close prices:", closes) # Filter stocks above VWAP (2880) ltps = {"RELIANCE":2945, "TCS":3820, "INFY":1480, "WIPRO":460} vwaps = {"RELIANCE":2880, "TCS":3890, "INFY":1460, "WIPRO":472} buy_list = [sym for sym in ltps if ltps[sym] > vwaps[sym]] print("BUY candidates:", buy_list) # Percentage change from entry entry = 22300 pct_changes = [round((p - entry) / entry * 100, 2) for p in prices] print("% Changes:", pct_changes)
Close prices: [22360, 22340, 22440] BUY candidates: ['RELIANCE', 'INFY'] % Changes: [0.0, 0.27, 0.63, 0.49, 0.9]
for loops for large datasets — important when processing thousands of ticks per second.
[c[3] for c in candles] produce?while True loop without a break or exit condition will:closes = [22360, 22340, 22440, 22410, 22500], use a for loop
to calculate the total and average close price. Print both results.
total = 0 before the loop, then divide by len(closes).volumes = {"RELIANCE": 1500000, "TCS": 980000, "INFY": 1200000, "WIPRO": 750000}.
max_vol = 0 and top_stock = "" variable inside the loop.current_streak and max_streak variables. Reset current_streak on a bearish candle.