A list is an ordered, mutable collection of items enclosed in square brackets. Items are accessed by index starting from 0. Lists can hold any type — prices, strings, other lists — and grow/shrink dynamically.
prices[0] is always the first price you added.list[0] = first, list[-1] = last. Negative indexes count from the end.closes = [22300, 22360, 22440, 22410, 22500] watchlist = ["NIFTY", "BANKNIFTY", "RELIANCE", "TCS"] print(closes[0]) # 22300 — first item print(closes[-1]) # 22500 — last item print(len(closes)) # 5 — number of items print(max(closes)) # 22500 — highest close print(min(closes)) # 22300 — lowest close print(sum(closes)) # 112010 — sum
22300 22500 5 22500 22300 112010
Slicing extracts a sub-list using [start:stop:step]. In algo trading, slicing is how you extract the last N candles to calculate a moving average or detect patterns.
closes = [22100, 22200, 22300, 22380, 22440, 22410, 22500] print(closes[2:5]) # [22300, 22380, 22440] — index 2 to 4 print(closes[-3:]) # [22440, 22410, 22500] — last 3 candles print(closes[::2]) # every other candle # 3-period Simple Moving Average on last 3 closes last3 = closes[-3:] sma3 = sum(last3) / len(last3) print(f"SMA(3) = {sma3:.1f}") # 5-period SMA last5 = closes[-5:] sma5 = sum(last5) / len(last5) print(f"SMA(5) = {sma5:.1f}")
[22300, 22380, 22440] [22440, 22410, 22500] [22100, 22300, 22440, 22500] SMA(3) = 22450.0 SMA(5) = 22406.0
| Method | What it does | Trading use |
|---|---|---|
append(x) | Add item to end | Append new tick/candle to buffer |
pop() | Remove & return last item | Remove oldest candle (FIFO buffer) |
remove(x) | Remove first match | Remove exited stock from watchlist |
sort() | Sort in place | Sort stocks by P&L |
reverse() | Reverse in place | Flip candle order oldest→newest |
count(x) | Count occurrences | Count BUY signals in history |
index(x) | Find position | Find where a price level was last seen |
# Rolling 5-candle buffer candle_buffer = [22100, 22200, 22300, 22380, 22440] new_candle = 22500 # Add new, remove oldest candle_buffer.append(new_candle) candle_buffer.pop(0) print("Buffer:", candle_buffer) # Signal history signals = ["BUY", "HOLD", "BUY", "SELL", "BUY", "HOLD"] print("BUY signals:", signals.count("BUY")) # Watchlist management watchlist = ["NIFTY", "BANKNIFTY", "RELIANCE"] watchlist.append("TCS") watchlist.remove("BANKNIFTY") print("Watchlist:", watchlist)
Buffer: [22200, 22300, 22380, 22440, 22500] BUY signals: 3 Watchlist: ['NIFTY', 'RELIANCE', 'TCS']
A 2D list is a list of lists. This is the natural structure for OHLC candle data — each inner list is one candle with [open, high, low, close, volume].
# NIFTY 5-min OHLCV — [open, high, low, close, volume] ohlcv = [ [22300, 22380, 22270, 22360, 125000], [22360, 22400, 22320, 22340, 98000], [22340, 22450, 22330, 22440, 143000], [22440, 22480, 22390, 22410, 112000], [22410, 22510, 22400, 22500, 165000], ] # Extract all close prices closes = [c[3] for c in ohlcv] highs = [c[1] for c in ohlcv] volumes = [c[4] for c in ohlcv] print(f"Closes : {closes}") print(f"Session High: ₹{max(highs)}") print(f"Avg Volume : {sum(volumes)//len(volumes):,}") # Latest candle latest = ohlcv[-1] print(f"\nLatest Candle:") print(f" O={latest[0]} H={latest[1]} L={latest[2]} C={latest[3]}")
Closes : [22360, 22340, 22440, 22410, 22500] Session High: ₹22510 Avg Volume : 128600 Latest Candle: O=22410 H=22510 L=22400 C=22500
Using list slicing, we can compute a rolling Simple Moving Average — the foundation of dozens of trading strategies.
def sma(prices, period): """Simple Moving Average over last N periods""" if len(prices) < period: return None window = prices[-period:] return round(sum(window) / period, 2) closes = [22100, 22200, 22300, 22380, 22440, 22410, 22500, 22480, 22520, 22560] sma5 = sma(closes, 5) sma10 = sma(closes, 10) ltp = closes[-1] print(f"LTP : ₹{ltp}") print(f"SMA5 : ₹{sma5}") print(f"SMA10 : ₹{sma10}") if sma5 > sma10: print("📈 SMA5 > SMA10 — Bullish crossover") else: print("📉 SMA5 < SMA10 — Bearish crossover")
LTP : ₹22560 SMA5 : ₹22494.0 SMA10 : ₹22389.0 📈 SMA5 > SMA10 — Bullish crossover
pandas or numpy for SMA calculations on large datasets. But understanding the list-based version first makes you a better trader-developer — you know what's happening under the hood.
closes = [22100, 22200, 22300], what does closes[-1] return?closes[-3:] return from a 7-item list?closes = [22300, 22360, 22440, 22410, 22500, 22480, 22520],
print the session high, low, average, and range (high - low) using list functions.
max(), min(), sum()/len().None. Test with a
10-candle close list and period=3.
closes[i-period+1:i+1] inside a for loop.[{sym, side, entry, exit, pnl}].
Write functions to: (1) add a trade, (2) get total P&L,
(3) get the best and worst trade by P&L.
max(trades, key=lambda t: t['pnl']) for best trade.trade["symbol"]) instead of index?
Lesson 6: Dictionaries — the data structure that powers trade objects, config files, and API responses.