# PoGPM – Portfolio Manager Implementation Plan
## Overview
Create a Portfolio Manager microservice that monitors and controls PoGUCM (UCB), PoGTrader, and PoGTraderLighter, plus tracks a personal Lighter Exchange manual trading account.
**Port:** 9004
**Location:** D:\PoG\PM
**GitHub:** https://github.com/sirdavidjcoops/PoGPM.git
—
## Services to Monitor
| Service | Port | Purpose |
|———|——|———|
| PoGUCM (UCB) | 9001 | RL Training service |
| PoGTrader | 9002 | HyperLiquid automated trading |
| PoGTraderLighter | 9102 | Lighter Exchange automated trading |
| Personal Lighter | N/A | Manual trading account (direct API) |
—
## UI Layout (Single Page Dashboard)
### Header
– Logo/Title: “PoG Portfolio Manager”
– Service status indicators (green/red dots)
– Connection status for exchanges (Hyperliquid, Lighter)
### Left Panel (280px) – Service Control
– **Service Status Cards** for each service:
– Status indicator (running/stopped)
– Start/Stop/Restart buttons
– Last heartbeat timestamp
– Error count badge
### Main Content Area
#### Section 1: Open Positions (Real-time)
Table with columns:
– Source (Trader/TraderLighter/Personal)
– Strategy
– Symbol
– Direction (Long/Short)
– Size
– Entry Price
– Current Price
– Open PnL ($)
– Open PnL (%)
**Footer:** Total Open PnL | Total Position Count
#### Section 2: Open Orders
Table with columns:
– Source
– Strategy
– Symbol
– Order Type (Limit/Stop/etc)
– Side
– Size
– Price
**Footer:** Total Order Count
#### Section 3: Trade History (Real-time)
Table with columns:
– Source
– Strategy
– Symbol
– Direction
– Size
– Entry → Exit Price
– R:R Ratio
– Close PnL ($)
#### Section 4: Equity Curves (Charts)
**Primary Chart (Full Width, Large):**
– Combined Equity Curve (all accounts)
– Two lines: Realized PnL (solid), Unrealized PnL (dashed overlay)
– Hourly granularity, stored locally
**Secondary Charts Row (3 equal columns):**
1. PoGTrader Equity Curve
2. PoGTraderLighter Equity Curve
3. Personal Lighter Account Curve
### Risk Page (Separate Tab) – MASTER CONTROLLER
Table showing all strategies across all traders/exchanges:
| Column | Description |
|——–|————-|
| Source | Trader / TraderLighter |
| Strategy | Strategy ID |
| Symbol | Trading pair |
| Enabled | Toggle switch |
| Risk Per Trade | Editable % (margin used) |
| Stop Loss ($) | Editable dollar amount |
| Max Drawdown ($) | Kill switch threshold |
| Total PnL | Cumulative strategy PnL |
| Kill Switch | Status + Reset button |
| Actions | Save button |
**Features:**
– Edit risk settings directly – PM pushes changes to Trader/TraderLighter via their APIs
– Enable/disable strategies from PM
– Reset kill switches remotely
– Bulk update capability (apply same settings to multiple strategies)
– Real-time sync with trader services
### Settings Page (Separate Tab)
– API key management for all accounts
– Service paths configuration
– Refresh intervals
—
## Project Structure
plaintext
</div>
<div>D:\PoG\PM/</div>
<div>├── backend/</div>
<div>│ ├── main.py # FastAPI application</div>
<div>│ ├── config.py # Configuration & API keys</div>
<div>│ ├── services/</div>
<div>│ │ ├── service_manager.py # Start/stop/restart services</div>
<div>│ │ ├── ucb_client.py # UCB API client</div>
<div>│ │ ├── trader_client.py # PoGTrader API client</div>
<div>│ │ ├── trader_lighter_client.py # TraderLighter client</div>
<div>│ │ └── lighter_personal.py # Personal Lighter account</div>
<div>│ ├── data/</div>
<div>│ │ ├── aggregator.py # Combine data from all sources</div>
<div>│ │ └── equity_tracker.py # Store/retrieve equity snapshots</div>
<div>│ └── db/</div>
<div>│ ├── database.py # SQLite setup</div>
<div>│ └── models.py # Equity snapshot models</div>
<div>├── frontend/</div>
<div>│ ├── index.html # Single page app</div>
<div>│ └── static/</div>
<div>│ ├── app.js # Application logic</div>
<div>│ └── styles.css # Styling (match UCB)</div>
<div>├── data/</div>
<div>│ └── pm.db # Local SQLite database</div>
<div>├── requirements.txt</div>
<div>├── run.py # Entry point</div>
<div>├── start.bat # Launch script</div>
<div>├── stop.bat # Stop script</div>
<div>├── ClaudeCommonErrors.md</div>
<div>└── BugReport.md</div>
<div>
—
## Backend API Endpoints
### System
–
GET /api/status – PM service status + all service statuses–
GET /api/health – Health check### Service Control
–
GET /api/services – List all services with status–
POST /api/services/{service}/start – Start service–
POST /api/services/{service}/stop – Stop service–
POST /api/services/{service}/restart – Restart service### Aggregated Data
–
GET /api/positions – All open positions (all sources)–
GET /api/orders – All open orders (all sources)–
GET /api/trades?limit=100 – Trade history (all sources)–
GET /api/analytics – Combined analytics### Equity
–
GET /api/equity – All equity snapshots–
GET /api/equity/{source} – Equity for specific source–
POST /api/equity/snapshot – Force snapshot### UCB (PoGUCM) Specific
–
GET /api/ucb/strategies – Loaded strategies–
GET /api/ucb/training – Active training status–
GET /api/ucb/models – Best models–
GET /api/ucb/gpu – GPU usage stats### Risk Management (Master Controller)
–
GET /api/risk/strategies – All strategies from all traders with risk settings–
PUT /api/risk/{source}/{strategy_id}/{symbol} – Update risk settings (pushes to trader)–
POST /api/risk/{source}/{strategy_id}/{symbol}/enable – Enable strategy–
POST /api/risk/{source}/{strategy_id}/{symbol}/disable – Disable strategy–
POST /api/risk/{source}/{strategy_id}/{symbol}/reset-kill-switch – Reset kill switch–
POST /api/risk/bulk-update – Update multiple strategies at once### Settings
–
GET /api/settings – Current settings–
PUT /api/settings – Update settings–
GET /api/settings/keys – API keys (masked)–
PUT /api/settings/keys – Update API keys### WebSocket
–
ws://localhost:9004/ws – Real-time updates—
## Data Fetching Strategy
### From PoGTrader (port 9002)
plaintext
</div>
<div>GET /api/positions → Open positions</div>
<div>GET /api/orders → Open orders</div>
<div>GET /api/trades → Trade history</div>
<div>GET /api/analytics → Stats</div>
<div>GET /api/equity → Equity curve</div>
<div>GET /api/status → Connection status</div>
<div>GET /api/risk/settings → Risk settings for PM</div>
<div>
### From PoGTraderLighter (port 9102)
plaintext
</div>
<div>GET /api/positions → Open positions</div>
<div>GET /api/orders → Open orders</div>
<div>GET /api/trades → Trade history</div>
<div>GET /api/analytics → Stats</div>
<div>GET /api/equity → Equity curve</div>
<div>GET /api/status → Connection status</div>
<div>GET /api/risk/settings → Risk settings for PM</div>
<div>
### From UCB (port 9001)
plaintext
</div>
<div>GET /api/status → GPU, active trainings</div>
<div>GET /api/strategies → Loaded strategies</div>
<div>GET /api/training/sync → Training status</div>
<div>GET /api/stats → Full statistics</div>
<div>GET /api/models → Best models</div>
<div>
### Personal Lighter Account (Direct API)
– Use Lighter SDK with readonly token
– Fetch positions, orders, trade history directly
– Store equity snapshots locally (hourly)
—
## Service Control Implementation
Each service has batch files in their directories:
– UCB:
D:\PoG\UCB\start.bat, stop.bat– Trader:
D:\PoG\Trader\start.bat, stop.bat– TraderLighter:
D:\PoG\TraderLighter\start.bat, stop.batPM will:
1. Check if process is running (by port or PID file)
2. Execute start/stop batch files via subprocess
3. Poll for status confirmation
—
## Equity Tracking
### Local Storage (SQLite)
sql
</div>
<div>CREATE TABLE equity_snapshots (</div>
<div> id INTEGER PRIMARY KEY,</div>
<div> source TEXT, -- 'trader', 'trader_lighter', 'personal', 'combined'</div>
<div> timestamp DATETIME,</div>
<div> equity REAL,</div>
<div> realized_pnl REAL,</div>
<div> unrealized_pnl REAL,</div>
<div> position_count INTEGER</div>
<div>);</div>
<div>
### Snapshot Schedule
– Automatic hourly snapshots
– Manual trigger via API
– Store combined + individual curves
—
## Frontend Implementation
### Technology
– Vanilla JavaScript (match UCB pattern)
– Chart.js for equity curves
– CSS Variables for theming (match UCB)
– WebSocket for real-time updates
### Key Features
1. **Auto-refresh:** Poll services every 5 seconds
2. **Real-time PnL:** WebSocket updates for position changes
3. **Persistent charts:** Equity data stored locally
4. **Service control:** Buttons to start/stop/restart
—
## Implementation Steps
### Phase 1: Project Setup
1. Create directory structure at
D:\PoG\PM2. Create requirements.txt
3. Create config.py with API keys
4. Set up SQLite database
### Phase 2: Modify Trader Services (Master Controller Support)
1. **PoGTrader** (
D:\PoG\Trader\backend\main.py): – Add
GET /api/risk/settings endpoint – Add
PUT /api/risk/settings/bulk endpoint2. **PoGTraderLighter** (
D:\PoG\TraderLighter\backend\main.py): – Add
GET /api/risk/settings endpoint – Add
PUT /api/risk/settings/bulk endpoint### Phase 3: Backend Core
1. Create FastAPI main.py
2. Implement service clients (UCB, Trader, TraderLighter)
3. Implement personal Lighter client
4. Create data aggregator
5. Implement service manager (start/stop/restart)
6. Implement risk controller (proxy to trader services)
### Phase 4: API Endpoints
1. System status endpoints
2. Service control endpoints
3. Aggregated data endpoints
4. Equity endpoints
5. Risk management endpoints (Master Controller)
6. Settings endpoints
7. WebSocket endpoint
### Phase 5: Frontend
1. Create index.html structure (with Risk page tab)
2. Implement styles.css (match UCB)
3. Create app.js with all functionality
4. Implement Chart.js equity curves
5. Implement Risk page with editable table
### Phase 6: Scripts & Documentation
1. Create start.bat
2. Create stop.bat
3. Create ClaudeCommonErrors.md
4. Create BugReport.md
5. Install requirements
### Phase 7: Git & Deploy
1. Initialize git repo
2. Create .gitignore
3. Commit and push to GitHub
—
## Verification Steps
1. **Start PM service:** Run
start.bat, verify port 9004 accessible2. **Check service status:** Verify UCB/Trader/TraderLighter status detection
3. **Test service control:** Start/stop a service, verify it works
4. **View positions:** Confirm positions from all sources appear
5. **View orders:** Confirm orders display correctly
6. **View trades:** Confirm trade history loads
7. **Check equity charts:** Verify all 4 charts render
8. **Test Risk page:**
– Verify all strategies from both traders are listed
– Change risk_per_trade for a strategy, verify it updates in the trader service
– Change stop_loss_dollars, verify it persists
– Toggle enable/disable, verify strategy state changes
– Reset a kill switch, verify it resets
9. **Test settings:** Update an API key, verify it saves
10. **Stop PM service:** Run
stop.bat, verify clean shutdown—
## Critical Files to Create
### PM Service Files
| File | Purpose |
|——|———|
|
backend/main.py | FastAPI app (~700 lines) ||
backend/config.py | Configuration (~100 lines) ||
backend/services/service_manager.py | Process control (~150 lines) ||
backend/services/ucb_client.py | UCB API client (~100 lines) ||
backend/services/trader_client.py | Trader API client (~120 lines) ||
backend/services/trader_lighter_client.py | TraderLighter client (~120 lines) ||
backend/services/lighter_personal.py | Personal account (~150 lines) ||
backend/services/risk_controller.py | Risk management proxy (~100 lines) ||
backend/data/aggregator.py | Data combining (~150 lines) ||
backend/data/equity_tracker.py | Equity snapshots (~100 lines) ||
backend/db/database.py | SQLite setup (~30 lines) ||
backend/db/models.py | SQLAlchemy models (~50 lines) ||
frontend/index.html | HTML template (~500 lines) ||
frontend/static/app.js | JavaScript app (~2000 lines) ||
frontend/static/styles.css | Styling (~1200 lines) ||
run.py | Entry point (~20 lines) ||
requirements.txt | Dependencies ||
start.bat | Launch script ||
stop.bat | Stop script ||
ClaudeCommonErrors.md | Common errors doc ||
BugReport.md | Bug report template |### Files to Modify in Other Services
| File | Changes |
|——|———|
|
D:\PoG\Trader\backend\main.py | Add 2 risk endpoints (~30 lines) ||
D:\PoG\TraderLighter\backend\main.py | Add 2 risk endpoints (~30 lines) |—
## Dependencies (requirements.txt)
plaintext
</div>
<div>fastapi>=0.109.0</div>
<div>uvicorn[standard]>=0.27.0</div>
<div>httpx>=0.26.0</div>
<div>websockets>=12.0</div>
<div>sqlalchemy>=2.0.25</div>
<div>aiosqlite>=0.19.0</div>
<div>pydantic>=2.5.3</div>
<div>python-dotenv>=1.0.0</div>
<div>psutil>=5.9.8</div>
<div># Lighter SDK - Install from GitHub</div>
<div># pip install git+https://github.com/elliottech/lighter-python.git</div>
<div>
—
## Modifications to Trader & TraderLighter Services
PM acts as **Master Controller** – needs additional endpoints in the trader services.
### New Endpoints to Add (Both Services)
#### 1. Get All Risk Settings
**File:**
backend/main.pypython
</div>
<div>@app.get("/api/risk/settings")</div>
<div>async def get_all_risk_settings():</div>
<div> """Get all strategy risk settings for PM."""</div>
<div> if not trade_engine:</div>
<div> raise HTTPException(status_code=503, detail="Engine not ready")</div>
<div> return {</div>
<div> "settings": trade_engine.risk_manager.get_all_settings(),</div>
<div> "strategies": [s.to_dict() for s in trade_engine.get_strategies()]</div>
<div> }</div>
<div>
#### 2. Bulk Update Risk Settings
**File:**
backend/main.pypython
</div>
<div>@app.put("/api/risk/settings/bulk")</div>
<div>async def bulk_update_risk_settings(updates: List[RiskSettingsUpdate]):</div>
<div> """Bulk update risk settings from PM."""</div>
<div> results = []</div>
<div> for update in updates:</div>
<div> try:</div>
<div> await trade_engine.update_strategy_settings(</div>
<div> update.strategy_id, update.symbol,</div>
<div> risk_per_trade=update.risk_per_trade,</div>
<div> stop_loss_dollars=update.stop_loss_dollars,</div>
<div> max_strategy_loss=update.max_strategy_loss</div>
<div> )</div>
<div> results.append({"strategy_id": update.strategy_id, "success": True})</div>
<div> except Exception as e:</div>
<div> results.append({"strategy_id": update.strategy_id, "success": False, "error": str(e)})</div>
<div> return {"results": results}</div>
<div>
### Files to Modify
| Service | File | Changes |
|———|——|———|
| PoGTrader |
backend/main.py | Add /api/risk/settings GET endpoint || PoGTrader |
backend/main.py | Add /api/risk/settings/bulk PUT endpoint || TraderLighter |
backend/main.py | Add /api/risk/settings GET endpoint || TraderLighter |
backend/main.py | Add /api/risk/settings/bulk PUT endpoint |**Existing endpoints already support:**
–
PUT /api/strategies/{strategy_id}/{symbol}/settings – Update individual strategy–
POST /api/strategies/{strategy_id}/{symbol}/enable – Enable strategy–
POST /api/strategies/{strategy_id}/{symbol}/disable – Disable strategy–
POST /api/strategies/{strategy_id}/{symbol}/reset-kill-switch – Reset kill switch—
## Notes
– **PM is Master Controller** – Can modify settings in Trader/TraderLighter via API
– **API keys stored in config.py** – Settings page allows updating
– **Equity snapshots stored locally** – Independent of other services
– **WebSocket for real-time** – Connect to trader services for live updates
– **Risk page provides central control** – All strategy risk management in one place