DocsCode Examples
Back to Documentation

Code Examples

Ready-to-use code snippets for common trading operations.

Basic Trading Bot

A simple Python bot that monitors price and places orders:

import requests
import time

API_KEY = "pe_your_api_key"
BASE_URL = "https://api.paperx.co"

def get_price(coin: str) -> float:
    """Get current mid price for a coin"""
    resp = requests.post(
        f"{BASE_URL}/v1/exchanges/hyperliquid/info",
        headers={"X-API-Key": API_KEY},
        json={"type": "allMids"}
    )
    return float(resp.json()[coin])

def place_order(asset: int, is_buy: bool, price: str, size: str):
    """Place a limit order"""
    resp = requests.post(
        f"{BASE_URL}/v1/exchanges/hyperliquid/exchange",
        headers={"X-API-Key": API_KEY},
        json={
            "action": {
                "type": "order",
                "orders": [{
                    "a": asset,
                    "b": is_buy,
                    "p": price,
                    "s": size,
                    "r": False,
                    "t": {"limit": {"tif": "Gtc"}}
                }]
            }
        }
    )
    return resp.json()

def get_position(coin: str):
    """Get current position for a coin"""
    resp = requests.post(
        f"{BASE_URL}/v1/exchanges/hyperliquid/info",
        headers={"X-API-Key": API_KEY},
        json={"type": "clearinghouseState"}
    )
    state = resp.json()
    for pos in state.get("assetPositions", []):
        if pos["position"]["coin"] == coin:
            return pos["position"]
    return None

# Simple strategy: Buy when price drops 1%
start_price = get_price("BTC")
print("Starting price: $" + str(start_price))

while True:
    price_now = get_price("BTC")
    change = (price_now - start_price) / start_price
    
    if change <= -0.01:  # Price dropped 1%
        print("Price dropped to $" + str(price_now) + ", placing buy order")
        result = place_order(0, True, str(price_now), "0.01")
        print("Order result: " + str(result))
        start_price = price_now  # Reset entry
    
    time.sleep(10)  # Check every 10 seconds

Grid Trading Strategy

Place multiple orders at different price levels:

import requests

API_KEY = "pe_your_api_key"
BASE_URL = "https://api.paperx.co"

def create_grid(
    asset: int,
    center_price: float,
    grid_size: int = 5,
    spacing_percent: float = 0.5,
    order_size: str = "0.01"
):
    """Create a grid of buy and sell orders"""
    orders = []
    
    for i in range(1, grid_size + 1):
        # Buy orders below center
        buy_price = center_price * (1 - spacing_percent * i / 100)
        orders.append({
            "a": asset,
            "b": True,
            "p": f"{buy_price:.2f}",
            "s": order_size,
            "r": False,
            "t": {"limit": {"tif": "Gtc"}}
        })
        
        # Sell orders above center
        sell_price = center_price * (1 + spacing_percent * i / 100)
        orders.append({
            "a": asset,
            "b": False,
            "p": f"{sell_price:.2f}",
            "s": order_size,
            "r": False,
            "t": {"limit": {"tif": "Gtc"}}
        })
    
    # Place all orders
    resp = requests.post(
        f"{BASE_URL}/v1/exchanges/hyperliquid/exchange",
        headers={"X-API-Key": API_KEY},
        json={"action": {"type": "order", "orders": orders}}
    )
    return resp.json()

# Get current BTC price
resp = requests.post(
    f"{BASE_URL}/v1/exchanges/hyperliquid/info",
    headers={"X-API-Key": API_KEY},
    json={"type": "allMids"}
)
btc_price = float(resp.json()["BTC"])

# Create grid around current price
result = create_grid(
    asset=0,  # BTC
    center_price=btc_price,
    grid_size=5,
    spacing_percent=0.5,
    order_size="0.01"
)
print(f"Grid created: {result}")

Stop Loss & Take Profit

Place a position with automatic TP/SL orders:

import requests

API_KEY = "pe_your_api_key"
BASE_URL = "https://api.paperx.co"

def place_with_tpsl(
    asset: int,
    is_buy: bool,
    entry_price: float,
    size: str,
    tp_percent: float = 2.0,
    sl_percent: float = 1.0
):
    """Place entry order with TP and SL"""
    
    # Calculate TP/SL prices
    if is_buy:
        tp_price = entry_price * (1 + tp_percent / 100)
        sl_price = entry_price * (1 - sl_percent / 100)
    else:
        tp_price = entry_price * (1 - tp_percent / 100)
        sl_price = entry_price * (1 + sl_percent / 100)
    
    # Place entry order (IOC for immediate fill)
    entry_resp = requests.post(
        f"{BASE_URL}/v1/exchanges/hyperliquid/exchange",
        headers={"X-API-Key": API_KEY},
        json={
            "action": {
                "type": "order",
                "orders": [{
                    "a": asset,
                    "b": is_buy,
                    "p": str(entry_price * 1.01 if is_buy else entry_price * 0.99),
                    "s": size,
                    "r": False,
                    "t": {"limit": {"tif": "Ioc"}}
                }]
            }
        }
    )
    
    if "filled" not in str(entry_resp.json()):
        return {"error": "Entry order not filled"}
    
    # Place Take Profit
    tp_resp = requests.post(
        f"{BASE_URL}/v1/exchanges/hyperliquid/exchange",
        headers={"X-API-Key": API_KEY},
        json={
            "action": {
                "type": "order",
                "orders": [{
                    "a": asset,
                    "b": not is_buy,  # Opposite side
                    "p": f"{tp_price:.2f}",
                    "s": size,
                    "r": True,  # Reduce only
                    "t": {
                        "trigger": {
                            "triggerPx": f"{tp_price:.2f}",
                            "isMarket": True,
                            "tpsl": "tp"
                        }
                    }
                }]
            }
        }
    )
    
    # Place Stop Loss
    sl_resp = requests.post(
        f"{BASE_URL}/v1/exchanges/hyperliquid/exchange",
        headers={"X-API-Key": API_KEY},
        json={
            "action": {
                "type": "order",
                "orders": [{
                    "a": asset,
                    "b": not is_buy,
                    "p": f"{sl_price:.2f}",
                    "s": size,
                    "r": True,
                    "t": {
                        "trigger": {
                            "triggerPx": f"{sl_price:.2f}",
                            "isMarket": True,
                            "tpsl": "sl"
                        }
                    }
                }]
            }
        }
    )
    
    return {
        "entry": entry_resp.json(),
        "take_profit": tp_resp.json(),
        "stop_loss": sl_resp.json()
    }

# Example: Long BTC with 2% TP and 1% SL
result = place_with_tpsl(
    asset=0,
    is_buy=True,
    entry_price=87000,
    size="0.01",
    tp_percent=2.0,
    sl_percent=1.0
)
print(result)

Portfolio Tracker

Monitor your positions and PnL in real-time:

import requests
import time
from datetime import datetime

API_KEY = "pe_your_api_key"
BASE_URL = "https://api.paperx.co"

def get_portfolio():
    """Get current portfolio state"""
    resp = requests.post(
        f"{BASE_URL}/v1/exchanges/hyperliquid/info",
        headers={"X-API-Key": API_KEY},
        json={"type": "clearinghouseState"}
    )
    return resp.json()

def print_portfolio(state):
    """Pretty print portfolio"""
    print("\n" + "=" * 50)
    print("Portfolio Update - " + datetime.now().strftime('%H:%M:%S'))
    print("=" * 50)
    
    margin = state["marginSummary"]
    acct_val = float(margin['accountValue'])
    margin_used = float(margin['totalMarginUsed'])
    withdrawable = float(state['withdrawable'])
    print("Account Value: $" + "{:,.2f}".format(acct_val))
    print("Total Margin:  $" + "{:,.2f}".format(margin_used))
    print("Withdrawable:  $" + "{:,.2f}".format(withdrawable))
    
    positions = state.get("assetPositions", [])
    if positions:
        print("\nPositions:")
        print("-" * 50)
        for pos in positions:
            p = pos["position"]
            pnl = float(p.get("unrealizedPnl", 0))
            pnl_sign = "+" if pnl >= 0 else ""
            coin = p['coin']
            size = float(p['szi'])
            entry = float(p['entryPx'])
            print("  " + coin + " | Size: " + str(size) + " | Entry: $" + str(entry) + " | PnL: " + pnl_sign + "$" + str(pnl))
    else:
        print("\nNo open positions")

# Monitor portfolio
print("Starting portfolio tracker (Ctrl+C to stop)")
while True:
    try:
        state = get_portfolio()
        print_portfolio(state)
        time.sleep(30)  # Update every 30 seconds
    except KeyboardInterrupt:
        print("\nStopped")
        break

Leverage Management

Update leverage before placing trades:

import requests

API_KEY = "pe_your_api_key"
BASE_URL = "https://api.paperx.co"

def set_leverage(asset: int, leverage: int, is_cross: bool = True):
    """Set leverage for an asset"""
    resp = requests.post(
        f"{BASE_URL}/v1/exchanges/hyperliquid/exchange",
        headers={"X-API-Key": API_KEY},
        json={
            "action": {
                "type": "updateLeverage",
                "asset": asset,
                "leverage": leverage,
                "isCross": is_cross
            }
        }
    )
    return resp.json()

# Set BTC to 20x cross margin
result = set_leverage(asset=0, leverage=20, is_cross=True)
print(f"Leverage updated: {result}")

# Set ETH to 10x isolated margin
result = set_leverage(asset=1, leverage=10, is_cross=False)
print(f"Leverage updated: {result}")