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.
.txt, .csv, or .json files."a" mode to append without overwriting.with statementwith open(...) as f — auto-closes the file even if an error occurs.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")
--- 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
"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.
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.
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']:,}")
JSON string:
{
"symbol": "NIFTY25JUNFUT",
"side": "BUY",
"entry": 22300,
"exit": 22480,
"lots": 2,
"pnl": 18000
}
Loaded symbol: NIFTY25JUNFUT
P&L: ₹18,000Store 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.
{
"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
}
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']}")
✅ Config loaded: config.json Symbol : NIFTY25JUNFUT Max Risk : ₹5,000 per trade RR Ratio : 1:2
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.
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:+,}")
💾 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
json.dumps(data, indent=2) do?with open(file) as f: instead of f = open(file)?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.
json.dump(cfg, f, indent=2) to save, json.load(f) to read.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.
max(trades, key=lambda t: t["pnl"]) for best trade.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.
json.dump(self.__dict__, f) saves all instance attributes.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