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()

Custom Base URL

client = PolyhushClient(
    api_key="your-api-key",
    base_url="https://api.polyhush.com"
)

API Reference

Balance & Account

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

Positions

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.0.tar.gz (8.3 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.0-py3-none-any.whl (8.3 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: polyhush-0.1.0.tar.gz
  • Upload date:
  • Size: 8.3 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.0.tar.gz
Algorithm Hash digest
SHA256 0b31cb7e27fb637d47081664b6d696759c64f5dd236c22d8bcfe31f6b629eff0
MD5 f74d85dbe843f18eac98ae9962f2f749
BLAKE2b-256 ce1eec13b37a87a4c66eeb5ecf32d3fbfb7e3bac97af479cecdfbb0ccb541e74

See more details on using hashes here.

File details

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

File metadata

  • Download URL: polyhush-0.1.0-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.0-py3-none-any.whl
Algorithm Hash digest
SHA256 e72138241cd7b2bac87087a9d22ffd4e06c0871d1f04e1f250246c434535c714
MD5 3eee4dff1055b6ad12845b783c3d7aac
BLAKE2b-256 b871022ecadc3646ea68ccd6735a0dfd59cdf5ac274073afadc015d002676965

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