Skip to main content

Place a Limit Buy Order

Place an order that sits on the order book until filled or cancelled.
from polyhush import PolyhushClient, PolyhushAPIError

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

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

# Place a limit order to buy 10 shares at $0.55
try:
    result = client.buy(
        token_id="your-token-id",
        shares=10,
        price=0.55,
        order_type="GTC"  # Good Till Cancelled
    )
    
    print(f"✅ Order placed: {result['order_id']}")
    print(f"   Status: {result['status']}")
    print(f"   Latency: {result['latency_ms']}ms")
    
    if result.get('warning'):
        print(f"   ⚠️ Warning: {result['warning']}")
        
except PolyhushAPIError as e:
    print(f"❌ Order failed: {e.message}")

Place a Market Order

Execute immediately at current market prices.
# Market buy - spend a specific USDC amount
result = client.market_buy(
    token_id="your-token-id",
    usdc_amount=50  # Spend $50 at market price
)
print(f"Bought shares: {result['order_id']}")

# Or buy a specific number of shares
result = client.market_buy(
    token_id="your-token-id",
    shares=100
)

# Market sell - sell shares at market price
result = client.market_sell(
    token_id="your-token-id",
    shares=50
)
print(f"Sold shares: {result['order_id']}")

Fill Or Kill Order

All-or-nothing execution - useful when you need exactly N shares.
# Must fill completely or cancel
result = client.buy(
    token_id="your-token-id",
    shares=100,
    price=0.55,
    order_type="FOK"  # Fill Or Kill
)

if result['status'] == 'FILLED':
    print("Got all 100 shares!")
else:
    print("Couldn't fill - no position taken")

Monitor and Cancel Orders

# Get all open orders
open_orders = client.get_orders(status="PLACED")
print(f"You have {len(open_orders)} open orders")

for order in open_orders:
    print(f"  {order['side']} {order['shares']} @ ${order['price']:.2f}")
    print(f"  Filled: {order['filled_shares']}/{order['shares']}")

# Cancel a specific order
result = client.cancel_order(order_id="ord_abc123")
print(f"Cancelled: {result['message']}")
if result.get('refund_amount'):
    print(f"Refunded: ${result['refund_amount']:.2f}")

# Cancel all open orders
result = client.cancel_all_orders()
print(f"Cancelled {result['cancelled']} orders")
print(f"Total refund: ${result['total_refund']:.2f}")

Trading Bot Template

A simple bot that places orders based on price thresholds.
from polyhush import PolyhushClient, PolyhushAPIError
import time

def simple_trading_bot():
    client = PolyhushClient()
    
    TOKEN_ID = "your-token-id"
    BUY_THRESHOLD = 0.40   # Buy when price falls below
    SELL_THRESHOLD = 0.60  # Sell when price rises above
    POSITION_SIZE = 10     # Shares per trade
    
    while True:
        try:
            # Get current price
            ticker = client.get_ticker(TOKEN_ID)
            price = ticker['midpoint']
            print(f"Current price: ${price:.4f}")
            
            # Get current position
            positions = client.get_positions()
            position = next(
                (p for p in positions if p['token_id'] == TOKEN_ID), 
                None
            )
            current_size = position['size'] if position else 0
            
            # Trading logic
            if price < BUY_THRESHOLD:
                print(f"Price below ${BUY_THRESHOLD} - buying...")
                client.buy(
                    token_id=TOKEN_ID,
                    shares=POSITION_SIZE,
                    price=price + 0.01,  # Slightly above market
                    order_type="GTC"
                )
                
            elif price > SELL_THRESHOLD and current_size > 0:
                print(f"Price above ${SELL_THRESHOLD} - selling...")
                client.sell(
                    token_id=TOKEN_ID,
                    shares=min(POSITION_SIZE, current_size),
                    price=price - 0.01,  # Slightly below market
                    order_type="GTC"
                )
            
            time.sleep(60)  # Check every minute
            
        except PolyhushAPIError as e:
            print(f"Error: {e.message}")
            time.sleep(60)

if __name__ == "__main__":
    simple_trading_bot()

Dollar-Cost Averaging

Automatically invest a fixed amount at regular intervals.
from polyhush import PolyhushClient
import schedule
import time

def dca_buy():
    """Buy $10 worth of shares at market price"""
    client = PolyhushClient()
    
    try:
        result = client.market_buy(
            token_id="your-token-id",
            usdc_amount=10  # $10 per interval
        )
        print(f"DCA buy executed: {result['order_id']}")
    except Exception as e:
        print(f"DCA buy failed: {e}")

# Schedule daily buys at 9 AM
schedule.every().day.at("09:00").do(dca_buy)

while True:
    schedule.run_pending()
    time.sleep(60)

Order Book Analysis Before Trading

def smart_order(client, token_id, side, shares):
    """Place an order with spread awareness"""
    
    # Get current prices
    ticker = client.get_ticker(token_id)
    spread = ticker['best_ask'] - ticker['best_bid']
    spread_pct = (spread / ticker['midpoint']) * 100
    
    print(f"Spread: ${spread:.4f} ({spread_pct:.2f}%)")
    
    if spread_pct > 5:
        # Wide spread - use limit order
        print("Wide spread detected - using limit order")
        if side == "BUY":
            # Place bid slightly above current best bid
            price = ticker['best_bid'] + 0.01
            return client.buy(token_id=token_id, shares=shares, price=price)
        else:
            # Place ask slightly below current best ask
            price = ticker['best_ask'] - 0.01
            return client.sell(token_id=token_id, shares=shares, price=price)
    else:
        # Tight spread - market order is fine
        print("Tight spread - using market order")
        if side == "BUY":
            return client.market_buy(token_id=token_id, shares=shares)
        else:
            return client.market_sell(token_id=token_id, shares=shares)