6.4 — Balance Tracking Aur Portfolio Overview
Balance Tracking Aur Portfolio Overview
Bismillah. Chalo bachon, course ke ek aur important lesson mein khushamdeed.
COURSE: Pakistan Ka Pehla Professional Trading Bot Course
MODULE 6: Execution Engine — Automatically Orders Place Karna
LESSON 6.4: Balance Tracking Aur Portfolio Overview
Assalam-o-Alaikum! Umeed hai sab aag laga rahay ho. Pichlay lessons mein humne execution.py ka basic structure set kiya tha. Ab waqt hai usko aqal denay ka. Bot ko sirf order place karna nahi aana chahiye; usko yeh bhi pata hona chahiye ke "bhai, jaib mein paisay kitnay hain?"
Agar aapka bot andhadhund orders place karta raha, to woh uss dost jaisa hai jo har cheez pe "scene on hai" bol deta hai, aur end mein bill aapko bharna parta hai. Aaj hum apne bot ko aisi harkaton se bachayenge. We will teach it financial discipline.
Kyun Zaroori Hai Yeh Sab? (The Hook)
Simple si baat hai. Paisa kahan se aa raha hai aur kahan ja raha hai, agar yeh nahi pata, toh trading nahi, juaa khel rahay ho. Acha bot wo nahi jo 100 trades le, acha bot wo hai jo profitable trades le aur capital ko smartly manage karay. $30 ke account pe agar tum 15 positions khol ke baith gaye, toh har position mein $2 lage hongay. Itna kum capital spread karoge toh fees hi tumhara profit kha jayegi. This lesson is about building the brain of your bot that manages the money.
Concept 1: Deployed Capital vs. Free Capital
Yeh sab se bunyadi (fundamental) concept hai.
- Total Capital: Yeh woh total raqam hai jo aapne bot ko di hai. For example, $30. Yeh hum
ORACLE_CAPITALenvironment variable mein set karte hain. - Deployed Capital: Yeh woh paisa hai jo already market mein laga hua hai. Yani, aapki open positions ki total cost. Agar aapne 5 YES shares khareeday hain $3 ke, toh aapka deployed capital $3 hai.
- Free/Available Capital: Yeh woh paisa hai jo bot abhi mazeed trades ke liye istemal kar sakta hai.
Total Capital - Deployed Capital = Free Capital.
Apne bot ke execution.py ko koi bhi trade lene se pehle yeh check karna LAZMI hai.
The Heart of Our Portfolio: get_portfolio_summary
Yeh function hamare bot ka "accountant" hai.
import os
def get_portfolio_summary(positions):
"""
Portfolio ka complete overview. Yeh function batata hai kitna paisa
laga hua hai, kitna baaki hai, aur reserve kitna hai.
Args:
positions (list): A list of position dictionaries from our database.
Returns:
dict: A summary of the portfolio.
"""
total_capital = float(os.environ.get('ORACLE_CAPITAL', '30'))
# Sirf 'open' positions count hongi
deployed = sum(p['cost_eur'] for p in positions if p['status'] == 'open')
# 5% hamesha side pe rakho — emergency fund
reserve = total_capital * 0.05
available = max(0, total_capital - deployed - reserve)
# Har strategy ne kitna paisa lagaya hai
by_strategy = {}
for p in positions:
if p['status'] != 'open':
continue
s = p['strategy']
if s not in by_strategy:
by_strategy[s] = {'count': 0, 'deployed': 0}
by_strategy[s]['count'] += 1
by_strategy[s]['deployed'] += p['cost_eur']
return {
'total_capital': total_capital,
'deployed': round(deployed, 2),
'available': round(available, 2),
'reserve': round(reserve, 2),
'open_positions': len([p for p in positions if p['status'] == 'open']),
'by_strategy': by_strategy
}
# --- Example Usage ---
mock_positions_from_db = [
{'strategy': 'theta_sniper', 'cost_eur': 5.50, 'status': 'open'},
{'strategy': 'geo_scout', 'cost_eur': 4.25, 'status': 'open'},
{'strategy': 'theta_sniper', 'cost_eur': 8.00, 'status': 'open'},
{'strategy': 'theta_sniper', 'cost_eur': 3.10, 'status': 'closed'}, # nahi count hogi
{'strategy': 'ai_momentum', 'cost_eur': 6.75, 'status': 'open'}
]
summary = get_portfolio_summary(mock_positions_from_db)
import json
print(json.dumps(summary, indent=2))
Expected Output:
{
"total_capital": 30.0,
"deployed": 24.5,
"available": 4.0,
"reserve": 1.5,
"open_positions": 4,
"by_strategy": {
"theta_sniper": {"count": 2, "deployed": 13.5},
"geo_scout": {"count": 1, "deployed": 4.25},
"ai_momentum": {"count": 1, "deployed": 6.75}
}
}
Code ka Breakdown:
total_capital:os.environ.get()seORACLE_CAPITALvariable uthata hai. Professional tareeqa — code mein hardcode nahi karna.deployed: List comprehension. Sirfstatus == 'open'wali positions ka sum.reserve: Total capital ka 5%. Simple line, important rule.available:total - deployed - reserve.max(0, ...)floating point errors se bachata hai.by_strategy: Dictionary mein har strategy ki count aur deployed amount track hoti hai.
Concept 2: Reserve Management - The 5% Rule
Cricket mein jaise aakhri overs ke liye best bowler ko bacha ke rakhte ho, waise hi trading mein thora capital hamesha reserve mein rakhna chahiye.
Kyun?
- Market Crashes & Opportunities: Market kabhi kabhi achanak crash karti hai. Woh "once in a blue moon" opportunity hoti hai jahan aap saste mein maal utha sakte ho. Agar aapka saara capital deployed hai, toh sirf dekhte reh jao ge.
- Fees & Slippage: Exchanges fees leti hain. Kabhi kabhi aap jis price pe order place karte ho, woh uss price pe fill nahi hota (isko slippage kehte hain). Reserve in chotay motay extra kharchon ko cover karta hai.
- Psychological Safety: Jab aapko pata hota hai ke aap 100% all-in nahi ho, toh behtar فیصلے (decisions) lete ho. Aap panic nahi karte.
CAPITAL ALLOCATION RULES
┌──────────────────────────────────────────────────┐
│ TOTAL CAPITAL: $100 (example) │
│ │
│ Maximum deployed: $95 (95%) │
│ Always reserve: $5 (5%) │
│ │
│ Of deployed capital: │
│ Single strategy max: 40% = $40 │
│ Single position max: 10% = $10 │
│ │
│ EXAMPLE PORTFOLIO STATE: │
│ theta_sniper: $35 (35%) — within limit │
│ geo_scout: $25 (25%) — within limit │
│ ai_momentum: $25 (25%) — within limit │
│ reserve: $5 (5%) — locked │
│ available: $10 (10%) — ready to deploy │
└──────────────────────────────────────────────────┘
Concept 3: Real-Time Balance Check Before Every Trade
Har trade execute karne se pehle, bot yeh check karega:
def can_open_position(strategy: str, intended_cost: float, positions: list) -> dict:
"""
Pre-trade check: Kya hum yeh position le sakte hain?
"""
summary = get_portfolio_summary(positions)
# Check 1: Kya available capital hai?
if intended_cost > summary['available']:
return {
'allowed': False,
'reason': f"Insufficient capital: need ${intended_cost:.2f}, have ${summary['available']:.2f}"
}
# Check 2: Kya strategy limit exceed nahi ho rahi?
total_capital = summary['total_capital']
MAX_STRATEGY_PCT = 0.40 # 40% max per strategy
strategy_deployed = summary['by_strategy'].get(strategy, {}).get('deployed', 0)
if (strategy_deployed + intended_cost) > (total_capital * MAX_STRATEGY_PCT):
return {
'allowed': False,
'reason': f"Strategy '{strategy}' would exceed 40% allocation limit"
}
return {
'allowed': True,
'available_after': round(summary['available'] - intended_cost, 2)
}
Pakistan Case Study: Usman's Over-Leverage Disaster
Background: Usman from Faisalabad started with $50 (PKR 14,000) and was excited by early wins. He disabled the available capital check from his bot — "I want maximum exposure," he said.
What happened: He opened 12 simultaneous positions totaling $48 (96% of capital). Three PSL match markets and four SBP macro markets all had news events on the same day. Six positions went against him simultaneously.
Financial impact:
- Opened: 12 positions × ~$4 average = $48 deployed
- Lost: 6 positions × $4 average = $24 (48% of capital)
- Ending balance: $26
With the portfolio summary check in place:
- Max deployment would have been $45 (95% cap)
- Single strategy cap would have limited PSL positions to $20 (40%)
- Estimated protected balance: $38 (vs. actual $26)
Usman's lesson: "Mujhe laga zyada positions = zyada profit. Asal mein zyada positions = zyada correlated losses. Portfolio summary check mera missing safety belt tha."
Practice Lab
Exercise 1: Run the get_portfolio_summary() function with mock data: create 8 fictional positions across 3 strategies with a mix of open/closed statuses and varying costs. Print the summary and verify: (a) closed positions are not counted in deployed, (b) reserve is correctly 5% of total capital, (c) available never goes negative.
Exercise 2: Build the can_open_position() function and test it with 3 scenarios: (a) you have plenty of available capital, (b) you've reached the available capital limit, (c) one strategy is at 38% but adding a new $5 position would push it to 43%. Verify the function correctly allows (a) and blocks (b) and (c).
Exercise 3: Add a get_strategy_performance() function to your portfolio module that calculates, for each strategy: total positions taken, total cost deployed, total P&L on closed positions, win rate percentage. This gives you the foundation for the performance dashboard in Module 8.
Key Takeaways
- Portfolio tracking is not optional — a bot without capital awareness is gambling, not trading. The
get_portfolio_summary()function is the brain your bot needs before every trade decision. - The 5% reserve rule sounds small but matters at scale: reserves prevent forced selling during temporary drawdowns and preserve psychological discipline.
ORACLE_CAPITALin your.envfile means you can scale your capital without changing code — just update one variable and the bot recalculates all limits automatically.- The
by_strategybreakdown is your early warning system — if theta_sniper is consuming 70% of deployed capital, you're over-concentrated and one bad market wipes your progress. - Defensive coding (
max(0, ...)for available capital, null checks for empty position lists) prevents production crashes that lose real money in live trading scenarios. - In Pakistani market context: PSL markets and SBP markets are highly correlated — limit total exposure to Pakistan-specific themes to prevent simultaneous multi-position losses on a single domestic event.
Lesson Summary
Quiz: [Module 6 Lesson 6.4]
4 questions to test your understanding. Score 60% or higher to pass.