View All Positions with P&L
Copy
from polyhush import PolyhushClient
client = PolyhushClient(api_key="your-api-key")
# Get detailed position info
positions = client.get_position_details()
if not positions:
print("No open positions")
else:
total_value = 0
total_pnl = 0
print("═" * 60)
print("PORTFOLIO POSITIONS")
print("═" * 60)
for pos in positions:
total_value += pos['market_value']
total_pnl += pos['unrealized_pnl']
# P&L indicator
if pos['unrealized_pnl'] >= 0:
indicator = "📈"
pnl_color = "+"
else:
indicator = "📉"
pnl_color = ""
print(f"\n{indicator} {pos['market_question'][:50]}...")
print(f" Position: {pos['size']} {pos['outcome_name']} shares")
print(f" Entry: ${pos['average_price']:.4f}")
print(f" Current: ${pos['current_price']:.4f}")
print(f" P&L: {pnl_color}${pos['unrealized_pnl']:.2f} ({pnl_color}{pos['unrealized_pnl_pct']:.1f}%)")
print(f" Value: ${pos['market_value']:.2f}")
print("\n" + "═" * 60)
print(f"TOTAL VALUE: ${total_value:.2f}")
print(f"TOTAL P&L: ${total_pnl:+.2f}")
print("═" * 60)
Filter Winning and Losing Positions
Copy
positions = client.get_position_details()
winners = [p for p in positions if p['unrealized_pnl'] > 0]
losers = [p for p in positions if p['unrealized_pnl'] < 0]
flat = [p for p in positions if p['unrealized_pnl'] == 0]
print(f"🟢 Winning positions: {len(winners)}")
for p in winners:
print(f" +${p['unrealized_pnl']:.2f} - {p['market_question'][:40]}...")
print(f"\n🔴 Losing positions: {len(losers)}")
for p in losers:
print(f" ${p['unrealized_pnl']:.2f} - {p['market_question'][:40]}...")
print(f"\n⚪ Flat positions: {len(flat)}")
Close a Position
Copy
def close_position(client, token_id):
"""Completely close a position at market price"""
# Get position details
positions = client.get_position_details()
position = next((p for p in positions if p['token_id'] == token_id), None)
if not position:
print("Position not found")
return None
available = position['available_to_sell']
if available <= 0:
print("No shares available to sell (may be reserved for orders)")
return None
print(f"Closing position: {available} shares")
print(f"Current price: ${position['current_price']:.4f}")
print(f"Unrealized P&L: ${position['unrealized_pnl']:.2f}")
# Market sell all available shares
result = client.market_sell(token_id=token_id, shares=available)
print(f"\n✅ Position closed: {result['order_id']}")
return result
# Usage
close_position(client, "your-token-id")
Take Profit / Stop Loss
Copy
def manage_position(client, token_id, take_profit_pct=20, stop_loss_pct=10):
"""Auto-close position at profit/loss thresholds"""
positions = client.get_position_details()
position = next((p for p in positions if p['token_id'] == token_id), None)
if not position:
return "NO_POSITION"
pnl_pct = position['unrealized_pnl_pct']
if pnl_pct >= take_profit_pct:
print(f"🎯 Take profit triggered at {pnl_pct:.1f}%")
client.market_sell(token_id=token_id, shares=position['available_to_sell'])
return "TAKE_PROFIT"
elif pnl_pct <= -stop_loss_pct:
print(f"🛑 Stop loss triggered at {pnl_pct:.1f}%")
client.market_sell(token_id=token_id, shares=position['available_to_sell'])
return "STOP_LOSS"
return "HOLDING"
# Usage in a loop
import time
while True:
status = manage_position(client, "your-token-id")
if status in ["TAKE_PROFIT", "STOP_LOSS", "NO_POSITION"]:
break
time.sleep(60)
Portfolio Rebalancing
Copy
def rebalance_portfolio(client, target_allocations):
"""
Rebalance portfolio to target allocations.
target_allocations: dict of token_id -> target percentage (0-100)
"""
# Get current state
balance = client.get_balance()
positions = client.get_position_details()
total_value = balance['balance'] + sum(p['market_value'] for p in positions)
print(f"Total portfolio value: ${total_value:.2f}")
# Calculate current allocations
current = {}
for pos in positions:
current[pos['token_id']] = (pos['market_value'] / total_value) * 100
# Calculate required trades
for token_id, target_pct in target_allocations.items():
current_pct = current.get(token_id, 0)
diff_pct = target_pct - current_pct
diff_value = (diff_pct / 100) * total_value
print(f"\n{token_id[:10]}...")
print(f" Current: {current_pct:.1f}% → Target: {target_pct:.1f}%")
if abs(diff_value) < 5: # Skip small adjustments
print(f" Skip (diff ${diff_value:.2f} too small)")
continue
if diff_value > 0:
print(f" BUY ${diff_value:.2f}")
client.market_buy(token_id=token_id, usdc_amount=diff_value)
else:
print(f" SELL ${-diff_value:.2f}")
client.market_sell(token_id=token_id, usdc_amount=-diff_value)
# Usage
rebalance_portfolio(client, {
"token_id_1": 40, # 40% allocation
"token_id_2": 30, # 30% allocation
"token_id_3": 30, # 30% allocation
})
Position Alerts
Copy
def check_position_alerts(client, alerts):
"""
Check positions against alert conditions.
alerts: list of dicts with token_id, condition, threshold
"""
positions = client.get_position_details()
triggered = []
for alert in alerts:
pos = next((p for p in positions if p['token_id'] == alert['token_id']), None)
if not pos:
continue
value = pos[alert['field']]
condition = alert['condition']
threshold = alert['threshold']
if condition == 'above' and value > threshold:
triggered.append({
'alert': alert,
'position': pos,
'message': f"{alert['field']} ({value:.2f}) above {threshold}"
})
elif condition == 'below' and value < threshold:
triggered.append({
'alert': alert,
'position': pos,
'message': f"{alert['field']} ({value:.2f}) below {threshold}"
})
return triggered
# Usage
alerts = [
{'token_id': 'abc', 'field': 'current_price', 'condition': 'above', 'threshold': 0.80},
{'token_id': 'abc', 'field': 'unrealized_pnl_pct', 'condition': 'below', 'threshold': -15},
{'token_id': 'xyz', 'field': 'current_price', 'condition': 'below', 'threshold': 0.20},
]
triggered = check_position_alerts(client, alerts)
for alert in triggered:
print(f"🚨 ALERT: {alert['message']}")