portfolio
Portfolio management with OpenAlgo - funds, positions, holdings, order book, trade book, margin calculator, and account management
What this skill does
# OpenAlgo Portfolio Management
Manage your trading portfolio using OpenAlgo's unified Python SDK. Access funds, positions, holdings, orders, trades, and margin information.
## Environment Setup
```python
from openalgo import api
client = api(
api_key='your_api_key_here',
host='http://127.0.0.1:5000'
)
```
## Quick Start Scripts
### Portfolio Summary
```bash
python scripts/portfolio.py --summary
```
### View Positions
```bash
python scripts/portfolio.py --positions
```
### View Holdings
```bash
python scripts/portfolio.py --holdings
```
### Calculate Margin
```bash
python scripts/margin.py --symbol NIFTY30JAN2526000CE --exchange NFO --action SELL --quantity 75
```
---
## Core API Methods
### 1. Funds
Get account balance and margin information:
```python
response = client.funds()
```
**Response:**
```json
{
"status": "success",
"data": {
"availablecash": "320.66",
"collateral": "0.00",
"m2mrealized": "3.27",
"m2munrealized": "-7.88",
"utiliseddebits": "679.34"
}
}
```
**Fields Explained:**
- `availablecash`: Cash available for new trades
- `collateral`: Pledged collateral value
- `m2mrealized`: Realized Mark-to-Market P&L
- `m2munrealized`: Unrealized Mark-to-Market P&L
- `utiliseddebits`: Margin utilized for open positions
### 2. Position Book
Get all open positions:
```python
response = client.positionbook()
```
**Response:**
```json
{
"status": "success",
"data": [
{
"symbol": "RELIANCE",
"exchange": "NSE",
"product": "MIS",
"quantity": "10",
"average_price": "1180.50",
"ltp": "1189.90",
"pnl": "94.00"
},
{
"symbol": "SBIN",
"exchange": "NSE",
"product": "MIS",
"quantity": "-5",
"average_price": "770.20",
"ltp": "769.80",
"pnl": "2.00"
}
]
}
```
**Notes:**
- Positive quantity = Long position
- Negative quantity = Short position
- P&L is calculated as (LTP - Avg Price) * Quantity
### 3. Holdings
Get delivery holdings (CNC):
```python
response = client.holdings()
```
**Response:**
```json
{
"status": "success",
"data": {
"holdings": [
{
"symbol": "RELIANCE",
"exchange": "NSE",
"product": "CNC",
"quantity": 10,
"pnl": -149.0,
"pnlpercent": -11.1
},
{
"symbol": "TATASTEEL",
"exchange": "NSE",
"product": "CNC",
"quantity": 5,
"pnl": -15.0,
"pnlpercent": -10.41
}
],
"statistics": {
"totalholdingvalue": 17680.0,
"totalinvvalue": 20010.0,
"totalprofitandloss": -2330.0,
"totalpnlpercentage": -11.65
}
}
}
```
### 4. Order Book
Get all orders for the day:
```python
response = client.orderbook()
```
**Response:**
```json
{
"status": "success",
"data": {
"orders": [
{
"action": "BUY",
"symbol": "RELIANCE",
"exchange": "NSE",
"orderid": "250408000989443",
"product": "MIS",
"quantity": "1",
"price": 1186.0,
"pricetype": "MARKET",
"order_status": "complete",
"trigger_price": 0.0,
"timestamp": "08-Apr-2025 13:58:03"
},
{
"action": "BUY",
"symbol": "YESBANK",
"exchange": "NSE",
"orderid": "250408001002736",
"product": "MIS",
"quantity": "1",
"price": 16.5,
"pricetype": "LIMIT",
"order_status": "open",
"trigger_price": 0.0,
"timestamp": "08-Apr-2025 14:13:45"
}
],
"statistics": {
"total_buy_orders": 2.0,
"total_sell_orders": 0.0,
"total_completed_orders": 1.0,
"total_open_orders": 1.0,
"total_rejected_orders": 0.0
}
}
}
```
**Order Statuses:**
- `complete`: Order executed
- `open`: Order pending
- `cancelled`: Order cancelled
- `rejected`: Order rejected
- `trigger_pending`: SL/SL-M waiting for trigger
### 5. Trade Book
Get all executed trades:
```python
response = client.tradebook()
```
**Response:**
```json
{
"status": "success",
"data": [
{
"action": "BUY",
"symbol": "RELIANCE",
"exchange": "NSE",
"orderid": "250408000989443",
"product": "MIS",
"quantity": 1,
"average_price": 1180.1,
"timestamp": "13:58:03",
"trade_value": 1180.1
}
]
}
```
### 6. Order Status
Get status of a specific order:
```python
response = client.orderstatus(
order_id="250408000989443",
strategy="MyStrategy"
)
```
**Response:**
```json
{
"status": "success",
"data": {
"action": "BUY",
"average_price": 1180.1,
"exchange": "NSE",
"order_status": "complete",
"orderid": "250408000989443",
"price": 0,
"pricetype": "MARKET",
"product": "MIS",
"quantity": "1",
"symbol": "RELIANCE",
"timestamp": "08-Apr-2025 13:58:03",
"trigger_price": 0
}
}
```
### 7. Open Position
Get position for a specific symbol:
```python
response = client.openposition(
strategy="MyStrategy",
symbol="RELIANCE",
exchange="NSE",
product="MIS"
)
```
**Response:**
```json
{
"status": "success",
"quantity": "10"
}
```
---
## Margin Calculator
### Single Position Margin
```python
response = client.margin(positions=[
{
"symbol": "NIFTY30JAN2526000CE",
"exchange": "NFO",
"action": "SELL",
"product": "NRML",
"pricetype": "MARKET",
"quantity": "75"
}
])
```
**Response:**
```json
{
"status": "success",
"data": {
"total_margin_required": 125000.00,
"span_margin": 95000.00,
"exposure_margin": 30000.00
}
}
```
### Multi-Leg Margin (Spread Benefit)
```python
response = client.margin(positions=[
{
"symbol": "NIFTY30JAN2526000CE",
"exchange": "NFO",
"action": "BUY",
"product": "NRML",
"pricetype": "MARKET",
"quantity": "75"
},
{
"symbol": "NIFTY30JAN2526500CE",
"exchange": "NFO",
"action": "SELL",
"product": "NRML",
"pricetype": "MARKET",
"quantity": "75"
}
])
# Spread margin will be lower than naked option margin
```
---
## Account Actions
### Close All Positions
Square off all open positions:
```python
response = client.closeposition(strategy="MyStrategy")
```
**Response:**
```json
{
"status": "success",
"message": "All Open Positions Squared Off"
}
```
### Cancel All Orders
Cancel all pending orders:
```python
response = client.cancelallorder(strategy="MyStrategy")
```
**Response:**
```json
{
"status": "success",
"message": "Canceled 5 orders. Failed to cancel 0 orders.",
"canceled_orders": ["250408001042620", "250408001042667"],
"failed_cancellations": []
}
```
---
## Analyzer Mode
Test strategies without real execution:
### Check Analyzer Status
```python
response = client.analyzerstatus()
```
**Response:**
```json
{
"status": "success",
"data": {
"analyze_mode": true,
"mode": "analyze",
"total_logs": 25
}
}
```
### Toggle Analyzer Mode
```python
# Enable paper trading
response = client.analyzertoggle(mode=True)
# Disable paper trading (live mode)
response = client.analyzertoggle(mode=False)
```
---
## Telegram Alerts
Send trading notifications:
```python
response = client.telegram(
username="your_openalgo_username",
message="NIFTY crossed 26000! Entry triggered."
)
```
**Response:**
```json
{
"status": "success",
"message": "Notification sent successfully"
}
```
---
## Common Patterns
### Daily P&L Summary
```python
def get_daily_pnl():
"""Calculate total daily P&L from positions."""
positions = client.positionbook()
if positions.get('status') != 'success':
return None
total_pnl = 0
for pos in positions.get('data', []):
total_pnl += float(pos.get('pnl', 0))
return total_pnl
pnl = get_daily_pnl()
print(f"Today's P&L: ₹{pnl:,.2f}")
```
### Check Available Margin
```python
def check_margin_available(Related in General
modeling-omnistudio-epc-catalog
IncludedSalesforce Industries CME EPC product-modeling skill for Product2-based catalog creation. Use when creating EPC products, configuring product attributes, building offer bundles with Product Child Items, or reviewing EPC DataPack JSON metadata for product catalog changes. TRIGGER when: user creates or updates Product2 EPC records, AttributeAssignment payloads, AttributeMetadata/AttributeDefaultValues, Offer bundles, or ProductChildItem relationships. DO NOT TRIGGER when: designing OmniScripts/FlexCards/Integration Procedures (use building-omnistudio-omniscript, building-omnistudio-flexcard, or building-omnistudio-integration-procedure), implementing Apex business logic (use generating-apex), or troubleshooting deployment pipelines (use deploying-metadata).
relationship-science-coach
IncludedUse this skill for direct, practical adult relationship coaching: couples conflict, repair, trust, marriage, dating, flirting, attachment patterns, emotional connection, sex, desire differences, eroticism, kink negotiation, affection, love languages, breakups, and long-term passion. Draw on Gottman, EFT and Hold Me Tight, attachment science, modern sex research, Perel, Nagoski, Kerner, Schnarch, Love and Stosny, and flexible love-language tools. Be concrete and low-hedge. Redirect only for imminent danger, abuse, coercive control, minors, non-consent, self-harm, stalking, or medical/legal/psychiatric decisions.
building-sf-integrations
IncludedSalesforce integration architecture and runtime plumbing with 120-point scoring. Use this skill to set up Named Credentials, External Credentials, External Services, REST/SOAP callout patterns, Platform Events, and Change Data Capture. TRIGGER when: user sets up Named Credentials, External Services, REST/SOAP callouts, Platform Events, CDC, or touches .namedCredential-meta.xml files. DO NOT TRIGGER when: Connected App/OAuth config (use configuring-connected-apps), Apex-only logic (use generating-apex), or data import/export (use handling-sf-data).
venue-templates
IncludedAccess comprehensive LaTeX templates, formatting requirements, and submission guidelines for major scientific publication venues (Nature, Science, PLOS, IEEE, ACM), academic conferences (NeurIPS, ICML, CVPR, CHI), research posters, and grant proposals (NSF, NIH, DOE, DARPA). This skill should be used when preparing manuscripts for journal submission, conference papers, research posters, or grant proposals and need venue-specific formatting requirements and templates.
let-fate-decide
IncludedDraws the 12 Houses of the Zodiac Tarot spread to inject entropy into planning when prompts are vague, ambiguous, or casually delegated. Interprets the spread to guide next steps. Use when the user says 'let fate decide', 'YOLO', 'whatever', 'idk', or other nonchalant phrases, makes Yu-Gi-Oh references, or when you are about to arbitrarily pick between multiple reasonable approaches. Prefer over ask-questions-if-underspecified when the user's tone is casual or playful rather than precision-seeking.
net-ops
IncludedCross-platform network troubleshooting (Windows, macOS, Linux) via local or remote shell. Use for: DNS broken, can't resolve hostnames, nslookup/dig works but apps fail, NRPT, WFP, scutil, /etc/resolver, systemd-resolved, /etc/resolv.conf, NetworkManager, VPN DNS leak residue (ProtonVPN/Mullvad/WireGuard/AnyConnect), AV/firewall blocking DNS or DoH, Tailscale DNS interaction, intermittent connectivity, remote diagnostics over SSH.