Skip to main content

Python SDK for Polyhush private trading API

Project description

Polyhush

PyPI version Python 3.8+ License: MIT

Polyhush is a Python SDK for trading on prediction markets through the Polyhush API. It provides a simple, Pythonic interface for placing orders, managing positions, and tracking your portfolio.

Features

  • Simple Trading Interface – Buy and sell with intuitive methods
  • Real-time Position Tracking – Monitor positions with P&L information
  • Automatic Settlements – Winnings credited automatically when markets resolve
  • Order Syncing – Keep order status in sync with the exchange
  • Multiple Order Types – Support for limit orders (GTC), fill-or-kill (FOK), and market orders (FAK)

Installation

pip install polyhush

Or with Poetry:

poetry add polyhush

Quick Start

from polyhush import PolyhushClient

# Initialize the client
client = PolyhushClient(api_key="your-api-key")

# Check your balance
balance = client.get_balance()
print(f"Available: ${balance['available_balance']:.2f}")

# Place a limit buy order
result = client.buy(
    token_id="your-token-id",
    shares=10,
    price=0.55
)
print(f"Order placed: {result['order_id']}")

Configuration

API Key

You can provide your API key in two ways:

# Option 1: Pass directly
client = PolyhushClient(api_key="your-api-key")

# Option 2: Environment variable
# Set POLYHUSH_API_KEY in your environment
client = PolyhushClient()

API Reference

Get Balance

# Basic balance info
balance = client.get_balance()
# Returns: balance, available_balance, reserved_balance

# Full portfolio summary
summary = client.get_balance(include_summary=True)
# Also returns: total_position_value, total_value, open_orders_count, positions_count

Get Positions

# Basic positions
positions = client.get_positions()

# Detailed with P&L
positions = client.get_positions(detailed=True)
for pos in positions:
    print(f"{pos['market_question']}: {pos['unrealized_pnl_pct']:.1f}%")

Get CLOB Balance

# Get actual on-chain balance for a token
clob = client.get_clob_balance(token_id="...")
print(f"CLOB balance: {clob['clob_balance']} shares")

Orders

Buy Orders

# Limit order: buy 100 shares at $0.45
client.buy(token_id="...", shares=100, price=0.45)

# Market order: spend $50 at market price
client.buy(token_id="...", usdc_amount=50, order_type="FAK")

# Market order: buy 100 shares at market price
client.buy(token_id="...", shares=100, order_type="FAK")

Sell Orders

# Limit order: sell 100 shares at $0.55
client.sell(token_id="...", shares=100, price=0.55)

# Market order: sell 50 shares at market price
client.sell(token_id="...", shares=50, order_type="FAK")

# Market order: sell $100 worth at market price
client.sell(token_id="...", usdc_amount=100, order_type="FAK")

Cancel Orders

# Cancel a specific order
client.cancel_orders(order_id="abc123")

# Cancel ALL open orders
result = client.cancel_orders()
print(f"Cancelled {result['cancelled']} orders, refunded ${result['total_refund']}")

Sync Orders

# Sync a specific order
client.sync_orders(order_id="abc123")

# Sync all pending orders
result = client.sync_orders()
print(f"Synced {result['synced']} of {result['total']} orders")

Market Data

Get Ticker

ticker = client.get_ticker(token_id="...")
print(f"Last price: ${ticker['last_price']}")
print(f"Bid: ${ticker['best_bid']} / Ask: ${ticker['best_ask']}")

Order Types

Polyhush supports three order types:

Type Name Description
GTC Good Till Cancelled Limit order that sits on the order book until filled or cancelled
FOK Fill Or Kill Must be fully filled immediately or the entire order is cancelled
FAK Fill And Kill Market order that fills immediately; any unfilled portion is cancelled
# Using order type constants
from polyhush import PolyhushClient

client = PolyhushClient(api_key="...")

# These are equivalent
client.buy(token_id="...", shares=10, price=0.50, order_type="GTC")
client.buy(token_id="...", shares=10, price=0.50, order_type=client.GTC)

Error Handling

The SDK raises PolyhushAPIError for API errors:

from polyhush import PolyhushClient, PolyhushAPIError

client = PolyhushClient(api_key="your-api-key")

try:
    result = client.buy(token_id="...", shares=100, price=0.50)
except PolyhushAPIError as e:
    print(f"Error: {e.message}")
    print(f"Status code: {e.status_code}")
    print(f"Response: {e.response}")

Environment Variables

Variable Description
POLYHUSH_API_KEY Your Polyhush API key

Examples

Basic Trading Bot

from polyhush import PolyhushClient, PolyhushAPIError
import time

client = PolyhushClient()

def simple_trading_loop(token_id: str):
    while True:
        try:
            # Get current price
            ticker = client.get_ticker(token_id)
            mid = ticker['midpoint']
            
            # Place limit orders around midpoint
            client.buy(token_id, shares=10, price=round(mid - 0.02, 2))
            client.sell(token_id, shares=10, price=round(mid + 0.02, 2))
            
            # Wait and sync
            time.sleep(60)
            client.sync_orders()
            
        except PolyhushAPIError as e:
            print(f"Error: {e.message}")
            time.sleep(10)

Position Monitor

from polyhush import PolyhushClient

client = PolyhushClient()

def show_portfolio():
    # Get balance with summary
    summary = client.get_balance(include_summary=True)
    print(f"Total Value: ${summary['total_value']:.2f}")
    print(f"   Cash: ${summary['available_balance']:.2f}")
    print(f"   Positions: ${summary['total_position_value']:.2f}")
    print()
    
    # Show detailed positions
    positions = client.get_positions(detailed=True)
    for pos in positions:
        pnl = pos['unrealized_pnl']
        pnl_pct = pos['unrealized_pnl_pct']
        print(f"{pos['market_question'][:50]}...")
        print(f"   {pos['size']} shares @ ${pos['average_price']:.2f}")
        print(f"   P&L: ${pnl:.2f} ({pnl_pct:+.1f}%)")
        print()

show_portfolio()

Documentation

For complete documentation, visit docs.polyhush.com

Requirements

  • Python 3.8+
  • requests >= 2.28.0

License

MIT License - see LICENSE for details.

Support

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

polyhush-0.1.1.tar.gz (8.2 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

polyhush-0.1.1-py3-none-any.whl (8.3 kB view details)

Uploaded Python 3

File details

Details for the file polyhush-0.1.1.tar.gz.

File metadata

  • Download URL: polyhush-0.1.1.tar.gz
  • Upload date:
  • Size: 8.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.11.4

File hashes

Hashes for polyhush-0.1.1.tar.gz
Algorithm Hash digest
SHA256 648c8ec3b3ed313c521cf5cec9a06dc3d3dd43e31e6d373db54b65e291d204f8
MD5 225c3e22da86167e2ac79ac05ecbd501
BLAKE2b-256 455cf4b8f17d4f3ff40aee69dba1d3844601dc329ba4f666d5049a94a52b78be

See more details on using hashes here.

File details

Details for the file polyhush-0.1.1-py3-none-any.whl.

File metadata

  • Download URL: polyhush-0.1.1-py3-none-any.whl
  • Upload date:
  • Size: 8.3 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.11.4

File hashes

Hashes for polyhush-0.1.1-py3-none-any.whl
Algorithm Hash digest
SHA256 f0bee725094fd2c39bbebc7e526c1fcacfe24a6fab378734bfc77350d666f95b
MD5 777639eab30f5925d7154b99b7365938
BLAKE2b-256 70f7915870cd288c662ffccd78799ad0dc859f39f0bd40f0e25a3ac63b6f01ea

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page