Back
Learning Hub/ Python for Algo Trading/ Lesson 9 — Final 🎉 Phase 1 Complete!
Python for Algo Trading · Phase 1 — FINAL LESSON

File I/O & JSON Logs

Your strategy runs, makes decisions, and handles errors. Now make it persistent. Save trade journals to disk, read config files at startup, and build a JSON-based audit trail — the final piece of a production-grade algo trading system.

Lesson 9 of 9 — FINAL ~45 min Intermediate–Advanced Persistent trade journals
Lesson 9 of 9 — File I/O & JSON Logs100% — Phase 1 Complete! 🎉
LESSON 09 · SECTION 1
Why File I/O in Algo Trading?
Phase 1 Final

Without file I/O, everything is lost when your script restarts. A persistent system can load yesterday's trade log, resume from a config file, and write every order to an audit file — exactly what regulators and post-market analysis require.

📄
Reading files
Load config, strategy params, or yesterday's trade log from .txt, .csv, or .json files.
✍️
Writing files
Append each trade, error, or signal to a log file. Use "a" mode to append without overwriting.
📦
JSON
JavaScript Object Notation — structured key-value format. API responses and config files are almost always JSON.
🔐
with statement
Always open files with with open(...) as f — auto-closes the file even if an error occurs.

Section 2
Reading & Writing Text Files
file_io_basics.pypython
import datetime

# Write a trade log entry
def log_trade_txt(filename, entry):
    timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    with open(filename, "a") as f:   # "a" = append
        f.write(f"{timestamp} | {entry}\n")

# Read and display the log
def print_log(filename):
    try:
        with open(filename, "r") as f:  # "r" = read
            lines = f.readlines()
        print(f"--- {filename} ({len(lines)} entries) ---")
        for line in lines:
            print(line.strip())
    except FileNotFoundError:
        print(f"No log file found: {filename}")

log_trade_txt("trade_log.txt", "BUY NIFTY @ 22300 | Lots: 2 | SL: 22150")
log_trade_txt("trade_log.txt", "EXIT NIFTY @ 22480 | P&L: +18000")
print_log("trade_log.txt")
Output
--- trade_log.txt (2 entries) ---
2025-06-15 09:32:11 | BUY NIFTY @ 22300 | Lots: 2 | SL: 22150
2025-06-15 10:18:44 | EXIT NIFTY @ 22480 | P&L: +18000
⚠️ FILE MODES
"r" = read only · "w" = write (overwrites!) · "a" = append · "r+" = read+write. Always use "a" for trade logs — never "w" or you'll overwrite your history.

Section 3
JSON — Structured Data

JSON (JavaScript Object Notation) maps directly to Python dicts and lists. Use it for config files, trade logs with structured fields, and saving/loading strategy state.

json_basics.pypython
import json

# Python dict → JSON string
trade = {
    "symbol": "NIFTY25JUNFUT", "side": "BUY",
    "entry": 22300, "exit": 22480, "lots": 2, "pnl": 18000
}

json_str = json.dumps(trade, indent=2)
print("JSON string:")
print(json_str)

# JSON string → Python dict
loaded = json.loads(json_str)
print(f"\nLoaded symbol: {loaded['symbol']}")
print(f"P&L: ₹{loaded['pnl']:,}")
Output
JSON string:
{
  "symbol": "NIFTY25JUNFUT",
  "side": "BUY",
  "entry": 22300,
  "exit": 22480,
  "lots": 2,
  "pnl": 18000
}

Loaded symbol: NIFTY25JUNFUT
P&L: ₹18,000

Section 4
JSON Config File

Store all strategy parameters in a config.json file. Load it at startup. Change parameters without modifying code — perfect for live trading where you adjust risk without redeploying.

config.jsonjson
{
  "symbol": "NIFTY25JUNFUT",
  "exchange": "NSE",
  "lot_size": 50,
  "capital": 500000,
  "risk_pct": 1.0,
  "sl_points": 150,
  "tgt_points": 300,
  "kill_loss": -10000,
  "max_trades": 5
}
load_config.pypython
import json

def load_config(filepath="config.json"):
    """Load strategy configuration from JSON file."""
    try:
        with open(filepath, "r") as f:
            config = json.load(f)
        print(f"✅ Config loaded: {filepath}")
        return config
    except FileNotFoundError:
        print(f"❌ Config not found: {filepath}")
        return {}

cfg = load_config()
if cfg:
    max_risk = cfg["capital"] * (cfg["risk_pct"] / 100)
    print(f"Symbol   : {cfg['symbol']}")
    print(f"Max Risk : ₹{max_risk:,.0f} per trade")
    print(f"RR Ratio : 1:{cfg['tgt_points']//cfg['sl_points']}")
Output
✅ Config loaded: config.json
Symbol   : NIFTY25JUNFUT
Max Risk : ₹5,000 per trade
RR Ratio : 1:2

Section 5
JSON Trade Journal

The complete trade journal — append each trade as a JSON line (JSONL format), then reload and analyse the full day's history. This is exactly how production trading systems store their audit trail.

trade_journal.pypython
import json, datetime

JOURNAL_FILE = "trade_journal.jsonl"

def save_trade(trade):
    """Append one trade as a JSON line."""
    trade["timestamp"] = datetime.datetime.now().isoformat()
    with open(JOURNAL_FILE, "a") as f:
        f.write(json.dumps(trade) + "\n")
    print(f"💾 Trade saved: {trade['side']} {trade['symbol']} P&L ₹{trade['pnl']:+,}")

def load_journal():
    """Load all trades and compute day stats."""
    trades = []
    try:
        with open(JOURNAL_FILE, "r") as f:
            for line in f:
                trades.append(json.loads(line.strip()))
    except FileNotFoundError:
        return []
    return trades

# Save today's trades
save_trade({"symbol":"NIFTY",  "side":"BUY",  "pnl":18000})
save_trade({"symbol":"BANKNIFTY","side":"SELL", "pnl":5250})
save_trade({"symbol":"NIFTY",  "side":"BUY",  "pnl":-12000})

# Analyse day
trades = load_journal()
total  = sum(t["pnl"] for t in trades)
wins   = [t for t in trades if t["pnl"] > 0]
print(f"\n📊 Day Summary: {len(trades)} trades | "
      f"Wins: {len(wins)} | P&L: ₹{total:+,}")
Output
💾 Trade saved: BUY NIFTY P&L ₹+18,000
💾 Trade saved: SELL BANKNIFTY P&L ₹+5,250
💾 Trade saved: BUY NIFTY P&L ₹-12,000

📊 Day Summary: 3 trades | Wins: 2 | P&L: ₹+11,250
💡 JSONL FORMAT
JSONL (JSON Lines) stores one JSON object per line. It's append-friendly, easy to stream, and can be loaded line-by-line without reading the entire file into memory — perfect for large trade history files.

Section 6
Quick Quiz
QUESTION 1 OF 3
Which file mode should you use to add trades to a log without deleting previous entries?
A"w" (write)
B"a" (append)
C"r" (read)
D"x" (exclusive)
QUESTION 2 OF 3
What does json.dumps(data, indent=2) do?
ASaves the dict directly to a file
BConverts a Python dict to a formatted JSON string
CLoads JSON from a string
DValidates JSON structure
QUESTION 3 OF 3
Why use with open(file) as f: instead of f = open(file)?
AIt opens the file faster
BIt's the only way to read files
CIt automatically closes the file even if an error occurs
DIt prevents other programs from reading the file

Section 7
Practice Exercises
EXERCISE 1 · EASY
Config File Manager
Write save_config(cfg, filename) and load_config(filename). Save a NIFTY strategy config dict as JSON, then reload it and print the risk/reward ratio.
Hint: use json.dump(cfg, f, indent=2) to save, json.load(f) to read.
EXERCISE 2 · MEDIUM
Daily Summary Report
Load all trades from trade_journal.jsonl and write a daily_report.txt with: total trades, wins, losses, best trade, worst trade, and total P&L. Format it nicely with dashes and labels.
Hint: use max(trades, key=lambda t: t["pnl"]) for best trade.
EXERCISE 3 · CHALLENGE
Persistent Strategy State
Build a StateManager class with save(filename) and load(filename) methods that persist daily P&L, trade count, and open positions to JSON. Test it by saving state, modifying it, then loading the original.
Hint: json.dump(self.__dict__, f) saves all instance attributes.

🏆
Phase 1 Complete!

You've mastered all 9 Python fundamentals — every concept used in real algo trading systems. You're now ready for Phase 2: Market Data & APIs.

  • Variables & Data Types
  • If / Else Conditions & Kill Switch Logic
  • Loops — Watchlist Scanner & Candle Analysis
  • Functions — Signal Engine & Risk Calculator
  • Lists — OHLC Arrays & Rolling SMA
  • Dictionaries — Trade Objects & Config
  • OOP — Trade Class & Strategy Inheritance
  • Error Handling — Crash-Proof Order Manager
  • File I/O & JSON — Persistent Trade Journal
🚀 PHASE 2 COMING SOON
Phase 2: Market Data & APIs — Connect to Zerodha KiteConnect, Upstox, or Angel Broking. Fetch live OHLCV data, set up WebSocket tick feeds, and calculate your first real-time technical indicator. This is where Python meets the live market.
Prev