Installation
Copy
Ask AI
pip install requests cryptography
Complete SDK
Copy
Ask AI
import os
import time
import base64
import requests
from cryptography.hazmat.primitives.asymmetric import ed25519
class PolymarketAccountSDK:
"""SDK for Polymarket US Account API"""
def __init__(self, api_key_id, private_key_base64):
"""
Initialize the SDK
Args:
api_key_id: Your API key ID from developer portal
private_key_base64: Your base64-encoded Ed25519 private key (64 bytes)
"""
self.api_key_id = api_key_id
self.base_url = "https://api.polymarket.us"
# Parse Ed25519 private key
private_key_bytes = base64.b64decode(private_key_base64)
self.private_key = ed25519.Ed25519PrivateKey.from_private_bytes(
private_key_bytes[:32]
)
def _sign_request(self, method, path):
"""Generate Ed25519 signature for request"""
timestamp = str(int(time.time() * 1000))
message = f"{timestamp}{method}{path}"
signature = self.private_key.sign(message.encode('utf-8'))
signature_base64 = base64.b64encode(signature).decode('utf-8')
return {
"X-PM-Access-Key": self.api_key_id,
"X-PM-Timestamp": timestamp,
"X-PM-Signature": signature_base64
}
def get_balances(self):
"""
Get account balances and financial summary
Returns:
dict: Complete balance information including:
- currentBalance: Fiat currency balance
- buyingPower: Available capital for trading
- assetNotional: Total value of securities
- assetAvailable: Available collateral from securities
- pendingCredit: Pending credits
- openOrders: Value locked in open orders
- unsettledFunds: Funds not yet available
- marginRequirement: Required margin for positions
- pendingWithdrawals: Active withdrawal requests
"""
path = "/v1/account/balances"
headers = self._sign_request("GET", path)
response = requests.get(
f"{self.base_url}{path}",
headers=headers
)
response.raise_for_status()
return response.json()
def get_buying_power(self):
"""
Get available buying power
Returns:
float: Buying power available for trading
"""
balances = self.get_balances()
return float(balances.get("balance", {}).get("buyingPower", 0))
def get_current_balance(self):
"""
Get current fiat balance (not including securities)
Returns:
float: Current fiat balance
"""
balances = self.get_balances()
return float(balances.get("balance", {}).get("currentBalance", 0))
def get_total_portfolio_value(self):
"""
Calculate total portfolio value
Returns:
dict: Portfolio breakdown
"""
balances = self.get_balances().get("balance", {})
current_balance = float(balances.get("currentBalance", 0))
asset_notional = float(balances.get("assetNotional", 0))
return {
"fiatBalance": current_balance,
"assetValue": asset_notional,
"totalValue": current_balance + asset_notional,
"currency": balances.get("currency", "USD")
}
def can_place_order(self, estimated_cost):
"""
Check if there's sufficient buying power for an order
Args:
estimated_cost: Estimated cost of the order
Returns:
tuple: (bool, float) - Whether order can be placed and available buying power
"""
buying_power = self.get_buying_power()
can_place = buying_power >= estimated_cost
return can_place, buying_power
def get_margin_info(self):
"""
Get margin requirement details
Returns:
dict: Margin information
"""
balances = self.get_balances().get("balance", {})
return {
"marginRequirement": float(balances.get("marginRequirement", 0)),
"buyingPower": float(balances.get("buyingPower", 0)),
"assetAvailable": float(balances.get("assetAvailable", 0))
}
def get_pending_withdrawals(self):
"""
Get list of pending withdrawals
Returns:
list: Pending withdrawal requests
"""
balances = self.get_balances().get("balance", {})
return balances.get("pendingWithdrawals", [])
# Example usage
if __name__ == "__main__":
# Load credentials from environment
api_key_id = os.environ.get("POLYMARKET_API_KEY")
private_key = os.environ.get("POLYMARKET_PRIVATE_KEY")
# Initialize SDK
sdk = PolymarketAccountSDK(api_key_id, private_key)
# Example 1: Get complete balance information
balances = sdk.get_balances()
balance = balances.get("balance", {})
print("Account Balances:")
print(f" Current Balance: \${balance.get('currentBalance')}")
print(f" Buying Power: \${balance.get('buyingPower')}")
print(f" Asset Value: \${balance.get('assetNotional')}")
print(f" Open Orders: \${balance.get('openOrders')}")
print(f" Margin Requirement: \${balance.get('marginRequirement')}")
# Example 2: Get buying power
buying_power = sdk.get_buying_power()
print(f"\nAvailable Buying Power: \${buying_power}")
# Example 3: Get current fiat balance
fiat_balance = sdk.get_current_balance()
print(f"Current Fiat Balance: \${fiat_balance}")
# Example 4: Get total portfolio value
portfolio = sdk.get_total_portfolio_value()
print(f"\nPortfolio Value:")
print(f" Fiat: \${portfolio['fiatBalance']}")
print(f" Assets: \${portfolio['assetValue']}")
print(f" Total: \${portfolio['totalValue']} {portfolio['currency']}")
# Example 5: Check if can place order
estimated_cost = 100.50
can_place, available = sdk.can_place_order(estimated_cost)
if can_place:
print(f"\n✓ Can place order for \${estimated_cost}")
print(f" Remaining after: \${available - estimated_cost:.2f}")
else:
print(f"\n✗ Insufficient buying power for \${estimated_cost}")
print(f" Available: \${available:.2f}")
print(f" Needed: \${estimated_cost - available:.2f} more")
# Example 6: Get margin information
margin_info = sdk.get_margin_info()
print(f"\nMargin Information:")
print(f" Requirement: \${margin_info['marginRequirement']}")
print(f" Buying Power: \${margin_info['buyingPower']}")
print(f" Available Collateral: \${margin_info['assetAvailable']}")
# Example 7: Check pending withdrawals
pending = sdk.get_pending_withdrawals()
if pending:
print(f"\nPending Withdrawals: {len(pending)}")
for withdrawal in pending:
print(f" ID: {withdrawal.get('id')}")
print(f" Amount: \${withdrawal.get('balance')}")
print(f" Status: {'Acknowledged' if withdrawal.get('acknowledged') else 'Pending'}")
else:
print("\nNo pending withdrawals")
Balance Fields
| Field | Description |
|---|---|
currentBalance | Fiat currency balance (not including securities) |
buyingPower | Available capital for trading |
assetNotional | Total value of all securities |
assetAvailable | Available collateral from securities |
pendingCredit | Pending credits to account |
openOrders | Value locked in open orders |
unsettledFunds | Funds not yet available to trade |
marginRequirement | Required margin for positions |
pendingWithdrawals | Active withdrawal requests |
balanceReservation | Reserved balance |
Understanding Buying Power
Buying power is calculated as:Copy
Ask AI
Buying Power = Current Balance
+ Asset Available
- Open Orders
- Margin Requirement
- Unsettled Funds
- Balance Reservations
Monitoring Account Health
Copy
Ask AI
def check_account_health(sdk):
"""Check if account is healthy for trading"""
balances = sdk.get_balances().get("balance", {})
buying_power = float(balances.get("buyingPower", 0))
margin_req = float(balances.get("marginRequirement", 0))
current_balance = float(balances.get("currentBalance", 0))
# Check if buying power is positive
if buying_power <= 0:
print("⚠️ Warning: No buying power available")
return False
# Check margin usage
if current_balance > 0:
margin_usage = (margin_req / current_balance) * 100
print(f"Margin usage: {margin_usage:.1f}%")
if margin_usage > 80:
print("⚠️ Warning: High margin usage")
print("✓ Account healthy for trading")
return True
check_account_health(sdk)
Error Handling
Copy
Ask AI
try:
balances = sdk.get_balances()
except requests.exceptions.HTTPError as e:
if e.response.status_code == 401:
print("Authentication failed - check your API key")
else:
print(f"Error: {e.response.text}")