Portfolio
Access and manage your portfolio including positions, holdings, order book, and trade book through the PyArrow SDK.
Positions
Get your current trading positions across all segments.
from pyarrow_client import ArrowClient
client = ArrowClient(app_id="your_app_id")
# ... authenticate ...
# Get all positions
positions = client.get_positions()
for position in positions:
print(f"Symbol: {position['symbol']}")
print(f"Exchange: {position['exchange']}")
print(f"Quantity: {position['quantity']}")
print(f"Average Price: ₹{position['averagePrice']}")
print(f"P&L: ₹{position['pnl']}")
print("-" * 40)
Position Fields
| Field | Type | Description |
|---|---|---|
symbol |
string | Trading symbol |
exchange |
string | Exchange code (NSE/BSE/NFO/BFO) |
quantity |
string | Net position quantity |
averagePrice |
string | Average entry price |
ltp |
string | Last traded price |
pnl |
string | Profit/Loss |
product |
string | Product type (I/C/M) |
buyQuantity |
string | Buy quantity |
sellQuantity |
string | Sell quantity |
buyValue |
string | Buy value |
sellValue |
string | Sell value |
Example: Position Analysis
def analyze_positions(client):
"""Analyze current positions and calculate total P&L."""
positions = client.get_positions()
if not positions:
print("No open positions")
return
total_pnl = 0
print("=" * 60)
print(f"{'Symbol':<20} {'Qty':>10} {'P&L':>15}")
print("=" * 60)
for pos in positions:
symbol = pos.get('symbol', 'N/A')
qty = pos.get('quantity', '0')
pnl = float(pos.get('pnl', 0))
total_pnl += pnl
pnl_str = f"₹{pnl:,.2f}"
print(f"{symbol:<20} {qty:>10} {pnl_str:>15}")
print("=" * 60)
print(f"{'Total P&L':<31} ₹{total_pnl:>14,.2f}")
return total_pnl
# Usage
total = analyze_positions(client)
Holdings
Get your delivery holdings (stocks held in demat account).
Holdings Structure
# Iterate through holdings
for holding in holdings.get('data', []):
print(f"Symbol: {holding['symbol']}")
print(f"Quantity: {holding['quantity']}")
print(f"Average Price: ₹{holding['averagePrice']}")
print(f"Current Value: ₹{holding['currentValue']}")
print(f"P&L: ₹{holding['pnl']}")
print("-" * 40)
Holdings Fields
| Field | Type | Description |
|---|---|---|
symbol |
string | Stock symbol |
isin |
string | ISIN code |
quantity |
string | Number of shares held |
averagePrice |
string | Average purchase price |
ltp |
string | Last traded price |
currentValue |
string | Current market value |
pnl |
string | Unrealized profit/loss |
pnlPercent |
string | P&L percentage |
Example: Holdings Summary
def holdings_summary(client):
"""Generate holdings portfolio summary."""
holdings = client.get_holdings()
total_invested = 0
total_current = 0
print("\n📊 PORTFOLIO HOLDINGS")
print("=" * 70)
print(f"{'Symbol':<15} {'Qty':>8} {'Avg':>10} {'LTP':>10} {'P&L':>12} {'%':>8}")
print("-" * 70)
for holding in holdings.get('data', []):
symbol = holding.get('symbol', 'N/A')
qty = int(holding.get('quantity', 0))
avg = float(holding.get('averagePrice', 0))
ltp = float(holding.get('ltp', 0))
pnl = float(holding.get('pnl', 0))
pnl_pct = float(holding.get('pnlPercent', 0))
invested = qty * avg
current = qty * ltp
total_invested += invested
total_current += current
print(f"{symbol:<15} {qty:>8} {avg:>10.2f} {ltp:>10.2f} {pnl:>12.2f} {pnl_pct:>7.2f}%")
print("=" * 70)
total_pnl = total_current - total_invested
total_pnl_pct = (total_pnl / total_invested * 100) if total_invested > 0 else 0
print(f"{'Invested:':<35} ₹{total_invested:>12,.2f}")
print(f"{'Current Value:':<35} ₹{total_current:>12,.2f}")
print(f"{'Total P&L:':<35} ₹{total_pnl:>12,.2f} ({total_pnl_pct:.2f}%)")
return {
'invested': total_invested,
'current': total_current,
'pnl': total_pnl,
'pnl_percent': total_pnl_pct
}
# Usage
summary = holdings_summary(client)
Order Book
Access your complete order book for the trading day.
# Get all orders
orders = client.get_order_book()
for order in orders:
print(f"Order ID: {order['id']}")
print(f"Symbol: {order['symbol']} ({order['exchange']})")
print(f"Type: {order['transactionType']} {order['order']}")
print(f"Qty: {order['quantity']} @ ₹{order['price']}")
print(f"Status: {order['orderStatus']}")
print(f"Filled: {order['cumulativeFillQty']}")
print("-" * 40)
Order Book Fields
| Field | Type | Description |
|---|---|---|
id |
string | Order ID |
exchange |
string | Exchange code |
symbol |
string | Trading symbol |
price |
string | Order price |
quantity |
string | Order quantity |
product |
string | Product type |
orderStatus |
string | PENDING/OPEN/COMPLETE/CANCELLED/REJECTED |
transactionType |
string | B (Buy) / S (Sell) |
order |
string | Order type (LMT/MKT/SL-LMT/SL-MKT) |
cumulativeFillQty |
string | Quantity filled so far |
averagePrice |
string | Average execution price |
exchangeOrderID |
string | Exchange order number |
orderTime |
string | Order timestamp |
rejectReason |
string | Rejection reason (if rejected) |
Example: Order Analysis
def order_analysis(client):
"""Analyze today's orders by status."""
orders = client.get_order_book()
status_count = {
'PENDING': 0,
'OPEN': 0,
'COMPLETE': 0,
'CANCELLED': 0,
'REJECTED': 0
}
for order in orders:
status = order.get('orderStatus', 'UNKNOWN')
if status in status_count:
status_count[status] += 1
print("\n📋 ORDER SUMMARY")
print("=" * 30)
for status, count in status_count.items():
emoji = {
'PENDING': '⏳',
'OPEN': '📖',
'COMPLETE': '✅',
'CANCELLED': '❌',
'REJECTED': '🚫'
}.get(status, '•')
print(f"{emoji} {status}: {count}")
print("=" * 30)
print(f"Total Orders: {len(orders)}")
return status_count
# Usage
order_stats = order_analysis(client)
Trade Book
Review all executed trades for the day.
# Get all trades
trades = client.get_trade_book()
for trade in trades:
print(f"Order ID: {trade['id']}")
print(f"Symbol: {trade['symbol']} ({trade['exchange']})")
print(f"Type: {trade['transactionType']}")
print(f"Fill Price: ₹{trade['fillPrice']}")
print(f"Fill Qty: {trade['fillQuantity']}")
print(f"Time: {trade['exchangeUpdateTime']}")
print("-" * 40)
Trade Book Fields
| Field | Type | Description |
|---|---|---|
id |
string | Order ID |
exchange |
string | Exchange code |
symbol |
string | Trading symbol |
quantity |
string | Order quantity |
product |
string | Product type |
transactionType |
string | B (Buy) / S (Sell) |
order |
string | Order type |
fillPrice |
string | Execution price |
fillQuantity |
string | Executed quantity |
fillTime |
string | Execution timestamp |
fillID |
string | Trade/Fill ID |
exchangeOrderID |
string | Exchange order number |
averagePrice |
string | Average price |
Example: Trade Summary
def trade_summary(client):
"""Generate trade summary with buy/sell breakdown."""
trades = client.get_trade_book()
buy_value = 0
sell_value = 0
buy_count = 0
sell_count = 0
print("\n📈 TRADE BOOK")
print("=" * 80)
print(f"{'Time':<20} {'Symbol':<15} {'Type':<6} {'Qty':>8} {'Price':>12} {'Value':>15}")
print("-" * 80)
for trade in trades:
time = trade.get('exchangeUpdateTime', '')[:19]
symbol = trade.get('symbol', 'N/A')
txn_type = 'BUY' if trade.get('transactionType') == 'B' else 'SELL'
qty = int(trade.get('fillQuantity', 0))
price = float(trade.get('fillPrice', 0))
value = qty * price
if trade.get('transactionType') == 'B':
buy_value += value
buy_count += 1
else:
sell_value += value
sell_count += 1
print(f"{time:<20} {symbol:<15} {txn_type:<6} {qty:>8} ₹{price:>11.2f} ₹{value:>14,.2f}")
print("=" * 80)
print(f"\n💰 Buy Trades: {buy_count} | Value: ₹{buy_value:,.2f}")
print(f"💰 Sell Trades: {sell_count} | Value: ₹{sell_value:,.2f}")
print(f"📊 Net Turnover: ₹{buy_value + sell_value:,.2f}")
return {
'buy_value': buy_value,
'sell_value': sell_value,
'total_trades': len(trades)
}
# Usage
summary = trade_summary(client)
User Limits & Funds
Get available margins and trading limits.
# Get user limits
limits = client.get_user_limits()
for limit in limits:
print(f"Segment: {limit.get('segment')}")
print(f"Available Margin: ₹{limit.get('availableMargin')}")
print(f"Used Margin: ₹{limit.get('usedMargin')}")
print(f"Total Margin: ₹{limit.get('totalMargin')}")
print("-" * 40)
User Limits Fields
| Field | Type | Description |
|---|---|---|
segment |
string | Trading segment |
availableMargin |
string | Available funds for trading |
usedMargin |
string | Margin currently in use |
totalMargin |
string | Total margin value |
openingBalance |
string | Opening balance |
payIn |
string | Funds added today |
payOut |
string | Funds withdrawn today |
User Details
Get authenticated user's profile information.
# Get user details
user = client.get_user_details()
print(f"User ID: {user.get('userID')}")
print(f"Name: {user.get('name')}")
print(f"Email: {user.get('email')}")
print(f"Phone: {user.get('phone')}")
print(f"PAN: {user.get('pan')}")
Complete Example
from pyarrow_client import ArrowClient
def portfolio_dashboard(client):
"""Complete portfolio dashboard."""
print("\n" + "=" * 60)
print("📊 PORTFOLIO DASHBOARD")
print("=" * 60)
# User Info
user = client.get_user_details()
print(f"\n👤 Welcome, {user.get('name', 'Trader')}!")
# Funds Summary
limits = client.get_user_limits()
if limits:
total_available = sum(float(l.get('availableMargin', 0)) for l in limits)
print(f"\n💰 Available Margin: ₹{total_available:,.2f}")
# Holdings
holdings = client.get_holdings()
if holdings.get('data'):
print(f"\n📦 Holdings: {len(holdings['data'])} stocks")
# Positions
positions = client.get_positions()
if positions:
total_pnl = sum(float(p.get('pnl', 0)) for p in positions)
print(f"\n📈 Open Positions: {len(positions)}")
print(f" Day P&L: ₹{total_pnl:,.2f}")
else:
print("\n📈 No open positions")
# Orders
orders = client.get_order_book()
open_orders = [o for o in orders if o.get('orderStatus') in ['PENDING', 'OPEN']]
print(f"\n📋 Today's Orders: {len(orders)}")
print(f" Open Orders: {len(open_orders)}")
# Trades
trades = client.get_trade_book()
print(f"\n✅ Trades Executed: {len(trades)}")
print("\n" + "=" * 60)
# Usage
client = ArrowClient(app_id="your_app_id")
# ... authenticate ...
portfolio_dashboard(client)