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 pair. Keys must be unique and immutable (strings, numbers).trade["symbol"] is instant regardless of dict size — far faster than searching a list.# 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
NIFTY25JUNFUT 22300 CLOSED P&L: ₹25,000
| Method | What it does | Trading use |
|---|---|---|
.get(key, default) | Safe access — returns default if key missing | Avoid KeyError on missing API fields |
.keys() | All keys as a view | Iterate over all trade attributes |
.values() | All values as a view | Sum all P&L values |
.items() | All (key, value) pairs | Print formatted trade card |
.update(d) | Merge another dict | Update trade with live market data |
.pop(key) | Remove & return key | Close and archive a trade |
key in d | Check if key exists | Verify "exit_price" before calculating P&L |
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']:,}")
SL: 0 symbol : RELIANCE entry : 2880 ltp : 2945 lots : 1 Trade still open — no exit yet Unrealised P&L: ₹20,000
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.
# 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']}")
Max risk per trade : ₹5,000 SL / Target : 150 / 300 pts RR Ratio : 1:2
CONFIG). This signals to other developers (and your future self) that this dict should not be modified at runtime.
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 = [
{"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,}")
# 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,250trade.get("stop_loss", 0) return if "stop_loss" key doesn't exist?print_trade_card(trade) that prints all fields
with labels and calculates unrealised P&L.
.items() to loop, f-strings to format.validate_config(cfg) that checks required keys exist
(symbol, capital, risk_pct, sl_points) and raises a message if any are missing.
key not in cfg inside a loop.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.
positions["NIFTY"]["entry"].Trade class,
a Strategy class, and finally understand how professional algo systems are structured.