Back
Learning Hub/ Python for Algo Trading/ Lesson 6 Phase 1 of 6
Python for Algo Trading · Phase 1

Dictionaries — Key-Value Data

Every trade has a symbol, entry price, side, and P&L. Dictionaries let you store structured data with named keys instead of index numbers — the natural format for trade objects, config files, and broker API responses.

Lesson 6 of 9 ~40 min Intermediate Trade objects & config
Lesson 6 of 9 — Dictionaries67% complete
LESSON 06 · SECTION 1
What is a Dictionary?
intermediate

A dictionary stores key-value pairs in curly braces. Instead of accessing data by position (trade[0]), you access it by a meaningful key (trade["symbol"]). This is how broker APIs return order data — as JSON dictionaries.

🗝️
Key-Value pairs
Each item is a key: value pair. Keys must be unique and immutable (strings, numbers).
O(1) lookup
Accessing trade["symbol"] is instant regardless of dict size — far faster than searching a list.
🔄
Mutable
Add, update, or delete keys at any time. Live trade state can be updated on every tick.
📦
Nested dicts
Values can be other dicts, lists, or any type — perfect for multi-leg options positions.
dict_basics.pypython
# Trade object as a dictionary
trade = {
    "symbol"     : "NIFTY25JUNFUT",
    "side"       : "BUY",
    "entry_price": 22300,
    "lot_size"   : 50,
    "lots"       : 2,
    "stop_loss"  : 22100,
    "target"     : 22600,
    "status"     : "OPEN",
}

# Access values by key
print(trade["symbol"])          # NIFTY25JUNFUT
print(trade["entry_price"])     # 22300

# Update a value
trade["status"] = "CLOSED"
print(trade["status"])           # CLOSED

# Add a new key
trade["exit_price"] = 22550
trade["pnl"] = (trade["exit_price"] - trade["entry_price"]) * trade["lot_size"] * trade["lots"]
print(f"P&L: ₹{trade['pnl']:,}")  # ₹25,000
Output
NIFTY25JUNFUT
22300
CLOSED
P&L: ₹25,000

Section 2
Dict Methods
MethodWhat it doesTrading use
.get(key, default)Safe access — returns default if key missingAvoid KeyError on missing API fields
.keys()All keys as a viewIterate over all trade attributes
.values()All values as a viewSum all P&L values
.items()All (key, value) pairsPrint formatted trade card
.update(d)Merge another dictUpdate trade with live market data
.pop(key)Remove & return keyClose and archive a trade
key in dCheck if key existsVerify "exit_price" before calculating P&L
dict_methods.pypython
trade = {"symbol":"RELIANCE", "entry":2880, "ltp":2945, "lots":1}

# Safe access — no KeyError if 'sl' missing
sl = trade.get("stop_loss", 0)
print(f"SL: {sl}")          # SL: 0 (default)

# Loop over all fields
for key, val in trade.items():
    print(f"  {key:10}: {val}")

# Check key before using
if "exit_price" not in trade:
    print("Trade still open — no exit yet")

# Update live price
trade.update({"ltp": 2960, "unrealised_pnl": (2960-2880)*250})
print(f"Unrealised P&L: ₹{trade['unrealised_pnl']:,}")
Output
SL: 0
  symbol    : RELIANCE
  entry     : 2880
  ltp       : 2945
  lots      : 1
Trade still open — no exit yet
Unrealised P&L: ₹20,000

Section 3
Config Dictionary

Hard-coding values (lot size, capital, risk) all over your code is dangerous. Store all strategy parameters in a single config dict — one place to change everything.

config.pypython
# Strategy config — single source of truth
CONFIG = {
    "symbol"        : "NIFTY25JUNFUT",
    "exchange"      : "NSE",
    "lot_size"      : 50,
    "capital"       : 500000,
    "risk_pct"      : 1.0,
    "max_trades_day": 5,
    "sl_points"     : 150,
    "tgt_points"    : 300,
    "kill_loss"     : -10000,
    "cutoff_hour"   : 15,
    "timeframe"     : "5min",
}

# Use config values everywhere
max_risk = CONFIG["capital"] * (CONFIG["risk_pct"] / 100)
print(f"Max risk per trade : ₹{max_risk:,.0f}")
print(f"SL / Target        : {CONFIG['sl_points']} / {CONFIG['tgt_points']} pts")
print(f"RR Ratio           : 1:{CONFIG['tgt_points']//CONFIG['sl_points']}")
Output
Max risk per trade : ₹5,000
SL / Target        : 150 / 300 pts
RR Ratio           : 1:2
💡 PRO TIP
Use ALL_CAPS for config/constant dicts (CONFIG). This signals to other developers (and your future self) that this dict should not be modified at runtime.

Section 4
List of Dicts — Trade Log

Combine lists and dicts to build a trade log — a list where each item is a trade dictionary. This is the standard pattern for trade history, order books, and position trackers.

trade_log.pypython
trade_log = [
    {"id":1, "sym":"NIFTY",     "side":"BUY",  "entry":22100, "exit":22450, "lots":2},
    {"id":2, "sym":"BANKNIFTY", "side":"SELL", "entry":48500, "exit":48150, "lots":1},
    {"id":3, "sym":"NIFTY",     "side":"BUY",  "entry":22300, "exit":22180, "lots":2},
]

LOT_SIZES = {"NIFTY": 50, "BANKNIFTY": 15}

print(f"{'#':>3} {'SYM':>10} {'SIDE':>6} {'ENTRY':>8} {'EXIT':>8} {'P&L':>10}")
print("-" * 52)

total_pnl = 0
for t in trade_log:
    ls  = LOT_SIZES[t["sym"]]
    mul = 1 if t["side"] == "BUY" else -1
    pnl = (t["exit"] - t["entry"]) * t["lots"] * ls * mul
    total_pnl += pnl
    emoji = "✅" if pnl > 0 else "❌"
    print(f"{t['id']:>3} {t['sym']:>10} {t['side']:>6} {t['entry']:>8} {t['exit']:>8} {pnl:>+10,} {emoji}")

print("-" * 52)
print(f"{'TOTAL P&L':>44} {total_pnl:>+10,}")
Output
  #        SYM   SIDE    ENTRY     EXIT        P&L
----------------------------------------------------
  1      NIFTY    BUY    22100    22450    +35,000 ✅
  2  BANKNIFTY   SELL    48500    48150     +5,250 ✅
  3      NIFTY    BUY    22300    22180    -12,000 ❌
----------------------------------------------------
                                TOTAL P&L    +28,250

Section 5
Quick Quiz
QUESTION 1 OF 3
What does trade.get("stop_loss", 0) return if "stop_loss" key doesn't exist?
AKeyError
BNone
C0 (the default value)
DFalse
QUESTION 2 OF 3
Which method lets you loop over both keys and values of a dict at the same time?
A.keys()
B.values()
C.items()
D.pairs()
QUESTION 3 OF 3
Why use a CONFIG dict instead of separate variables for strategy settings?
ADicts are always faster than variables
BAll settings in one place — one change updates the whole system
CPython requires configs to be dicts
DOnly dicts can be saved to files

Section 6
Practice Exercises
EXERCISE 1 · EASY
Trade Card Printer
Create a trade dict with keys: symbol, side, entry, ltp, lots, lot_size. Write a function print_trade_card(trade) that prints all fields with labels and calculates unrealised P&L.
Hint: use .items() to loop, f-strings to format.
EXERCISE 2 · MEDIUM
Strategy Config Reader
Create a CONFIG dict for a BANKNIFTY strategy. Write a function validate_config(cfg) that checks required keys exist (symbol, capital, risk_pct, sl_points) and raises a message if any are missing.
Hint: use key not in cfg inside a loop.
EXERCISE 3 · CHALLENGE
Position Tracker
Build a position tracker as a dict of dicts: positions["NIFTY"] = {side, entry, lots}. Write functions to: add_position(sym, ...), update_ltp(sym, ltp), and get_total_pnl(positions). Use LOT_SIZES dict for lot sizes.
Hint: nested dict access: positions["NIFTY"]["entry"].
🚀 UP NEXT — LESSON 7
You can now work with individual trade dicts. But a real trading engine bundles data and behaviour together. Lesson 7: OOP & Classes — build a Trade class, a Strategy class, and finally understand how professional algo systems are structured.
Prev