7.4 — Position Manager — Automatic Monitoring System
Position Manager — Automatic Monitoring System
Assalam-o-Alaikum, future trading wizards!
Welcome to Module 7. Ab tak hum ne strategy banayi, Kelly Criterion se risk manage karna seekha. Lekin strategy execute karne ke baad kya? Usay khula chhor dein? Bilkul nahi. This lesson is the most critical part of your bot's brain. It's the difference between a professional system and a toy project.
COURSE: Pakistan Ka Pehla Professional Trading Bot Course
MODULE 7: Risk Management — Kelly Criterion Aur Position Sizing
LESSON 7.4: Position Manager — Your Automatic Monitoring System
Chalo shuru kartay hain.
Ek baat zehen mein daal lo: market kabhi soti nahi hai. Tum so jao ge, kaam pe jao ge, shaadi pe jao ge. But your open positions are always at risk. The Position Manager is your 24/7 bodyguard. Tumhara kaam hai strategy banana, iska kaam hai tumhare paison ki hifazat karna, har 30 minute.
Position Manager Kya Hai? The Big Picture
Socho tumne KSE-100 mein ek position li hai using your theta_sniper.py strategy. Tumhara analysis kehta hai ke market upar jaegi. Great. Lekin raat 3 baje State Bank ne interest rate change kar diya. Tum so rahe ho, aur tumhari position -20% neeche chali gayi. Subah uth ke dekhoge to dil ka daura paray ga.
The Position Manager prevents this.
Yeh ek simple sa loop hai jo scanner.py har 30 minute pe run karta hai. Yeh tumhari database se saari 'open' positions uthata hai aur ek-ek kar ke check karta hai:
- Kya position achanak se loss mein jaa rahi hai? (Stop-Loss)
- Kya profit target hit ho gaya hai? (Take-Profit)
- Kya market mein koi aisi khabar aayi hai jis se risk barh gaya hai? (AI Analysis)
- Kya humein thora sa profit book kar lena chahiye? (Momentum Exit)
Yeh textbook theory nahi hai, yeh production code ka logic hai. Let's dive into the code that runs our entire Polymarket Oracle bot's defense.
The Heart of the System: run_position_manager
Yeh function hamare scanner.py ka core component hai. Isko db.py se saari open positions milti hain aur yeh un pe action leta hai.
Dekho, seedhi baat hai. Code ko samjho.
# --- Required Imports and Dummy Functions for a Runnable Example ---
import time
import random
# Dummy database of positions. In production, this comes from db.py
POSITIONS_DB = [
{
"id": 1, "market_id": "market-1", "strategy": "theta_sniper",
"question": "Will Pakistan win the next T20 against India?",
"entry_price": 60.0, "shares": 100, "status": "open",
"initial_value_pkr": 6000,
"thesis": "Pakistan's bowling lineup is strong, and Indian batting has shown weakness."
},
{
"id": 2, "market_id": "market-2", "strategy": "vol_harvester",
"question": "Will the KSE-100 Index close above 80,000 points by end of month?",
"entry_price": 45.0, "shares": 200, "status": "open",
"initial_value_pkr": 9000,
"thesis": "Positive economic indicators suggest a bullish trend for the short term."
},
{
"id": 3, "market_id": "market-3", "strategy": "theta_sniper",
"question": "Will oil prices be above $90 by Friday?",
"entry_price": 70.0, "shares": 50, "status": "closed", # This should be ignored
"initial_value_pkr": 3500,
"thesis": "OPEC meeting is likely to result in production cuts."
}
]
# Dummy market data fetcher. In production, this calls an API.
MARKET_PRICES = {
"market-1": 52.0, # Price has dropped -> potential stop loss
"market-2": 51.0, # Price has increased -> potential take profit
}
def fetch_market_by_id(market_id):
"""Simulates fetching market data."""
if market_id in MARKET_PRICES:
return {"id": market_id, "price": MARKET_PRICES[market_id]}
return None
def get_market_price(market):
"""Simulates getting a clean price from market object."""
return market['price']
def check_exit_triggers(pos, current_price):
"""
Simulates checking for various exit triggers.
In production, this is a complex function, possibly using ai/haiku.py for quick analysis.
"""
triggers = []
entry_price = pos['entry_price']
profit_percent = ((current_price - entry_price) / entry_price) * 100
# 1. Hard Stop-Loss
HARD_STOP_LOSS_PERCENT = -15.0
if profit_percent <= HARD_STOP_LOSS_PERCENT:
triggers.append({
"type": "hard_stop",
"reason": f"Profit at {profit_percent:.1f}%, breached SL of {HARD_STOP_LOSS_PERCENT}%",
"urgency": "critical"
})
# 2. AI-based trigger (simulated)
# Let's pretend for the KSE market, some negative news came out
if pos['market_id'] == 'market-2' and random.random() > 0.5:
triggers.append({
"type": "ai_alert",
"reason": "Haiku detected negative sentiment in news about a new tax policy.",
"urgency": "high"
})
return triggers
def sonnet_decide_exit(pos, current_price, trigger):
"""
Simulates the advanced AI making a final decision.
In production, this calls ai/sonnet.py via ai/gemini.py.
"""
print(f' [AI-SONNET] Analyzing "{pos["question"][:30]}..."')
print(f' [AI-SONNET] Entry: {pos["entry_price"]:.1f}, Current: {current_price:.1f}')
print(f' [AI-SONNET] Initial Thesis: {pos["thesis"]}')
print(f' [AI-SONNET] Trigger Reason: {trigger["reason"]}')
# Simple logic for simulation: if the trigger is 'high' or 'critical', we decide to sell.
if trigger['urgency'] in ('high', 'critical'):
print(f' [AI-SONNET] DECISION: Exit position. The new information invalidates our initial thesis.')
return {"decision": "SELL", "confidence": 0.95}
else:
print(f' [AI-SONNET] DECISION: Hold. The event is low impact.')
return {"decision": "HOLD", "confidence": 0.80}
# --- The ACTUAL Lesson Code ---
def run_position_manager(positions):
"""Check all open positions for exit triggers."""
print(f'\n[PM] Running Position Manager. Checking {len(positions)} total positions...')
open_positions = [p for p in positions if p['status'] == 'open']
print(f'[PM] Found {len(open_positions)} open positions to monitor.')
for pos in open_positions:
# Get fresh price
print(f' -> Checking Position ID {pos["id"]}: "{pos["question"][:40]}..."')
market = fetch_market_by_id(pos['market_id'])
# Automatic position monitoring ensures no trade is left unmanaged
Position managers are critical for 24/7 bot operations without human supervision.
---
## 📺 Recommended Videos & Resources
- **[Real-Time Position Monitoring](https://www.youtube.com/results?search_query=position+monitoring+system+trading+bot)** — Live tracking
- Type: YouTube
- Link description: Search "real-time position monitoring trading"
- **[Automated Alerts & Notifications](https://www.youtube.com/results?search_query=trading+bot+alerts+notifications+discord)** — Real-time notifications
- Type: YouTube
- Link description: Search "Discord/Slack alerts for trading bots"
- **[Heartbeat Monitoring](https://en.wikipedia.org/wiki/Heartbeat_(computing))** — System health checks
- Type: Wikipedia
- Link description: Learn monitoring patterns for robustness
- **[Trade Journal Systems](https://www.youtube.com/results?search_query=trade+journal+system+automated)** — Recording trades
- Type: YouTube
- Link description: Search "trade journaling automated systems"
- **[Health Monitoring for Always-On Systems](https://www.youtube.com/results?search_query=health+monitoring+always+on+systems)** — Keepalive checks
- Type: YouTube
- Link description: Search "health monitoring for always-on services"
---
## 🎯 Mini-Challenge
**5-Minute Practical Task:** Create a position monitor that: (1) Checks all open positions every 30 seconds, (2) Triggers take profit if P&L > 20%, (3) Triggers stop loss if P&L < -10%, (4) Logs all actions. Test with 5 sample positions and verify monitoring works correctly.
---
## 🖼️ Visual Reference
📊 Position Manager Loop (Runs Every 30s) ┌─────────────────────────┐ │ Timer Tick (every 30s) │ └────────────┬────────────┘ │ ▼ ┌─────────────────────────┐ │ Fetch Open Positions │ │ From Database │ └────────────┬────────────┘ │ ▼ ┌────────────────────┐ │ For each position: │ └────┬───────────────┘ │ ▼ ┌────────────────────┐ │ Get Current Price │ │ from API │ └────┬───────────────┘ │ ▼ ┌────────────────────┐ │ Calculate P&L │ └────┬───────────────┘ │ ┌────┼────┬─────┐ │ │ │ │ ▼ ▼ ▼ ▼ [TP] [SL] [HOLD] [ERR] (exit) (exit) (watch) (log)
---
Lesson Summary
Quiz: [Module 7 Lesson 7.4]
4 questions to test your understanding. Score 60% or higher to pass.