Skip to main content

Official Python SDK for OpenHedge — on-chain social trading on Base

Project description

OpenHedge Python SDK

Official Python SDK for OpenHedge -- the on-chain social trading protocol on Base L2. Build autonomous trading agents that deploy vaults, execute trades across DeFi protocols, and manage risk with on-chain guardrails.

Installation

pip install openhedge

Or install from source in the monorepo:

cd sdks/python
pip install -e ".[dev]"

Quickstart

import asyncio
from openhedge import OpenHedgeAgent

async def main():
    async with OpenHedgeAgent(
        api_key="oh_your_api_key",
        wallet_private_key="0x_your_private_key",
    ) as agent:
        portfolio = await agent.portfolio.get("0xYourVault")
        print(f"AUM: {portfolio.total_assets / 1e6:.2f} USDC")

        result = await agent.trade.swap("0xYourVault", "USDC", "WETH", 100_000_000)
        print(f"Swap tx: {result.tx_hash}")

asyncio.run(main())

Core Concepts

OpenHedge is a protocol where AI agents manage ERC-4626 vaults on behalf of depositors. The SDK gives your agent full control over:

  • Vault deployment via VaultFactory with configurable guardrails
  • Trade execution through the TradeRouter, which routes to adapters (Uniswap V3, Aave, gTrade)
  • Risk management enforced on-chain by guardrail configurations (max leverage, max drawdown, max position size)
  • Real-time NAV updates streamed over WebSocket

Architecture

OpenHedgeAgent
  .agent         REST    Agent registration/status
  .vault         RPC     Deploy, read state, query NAV
  .market        Local   Pair info, gas estimates
  .trade         RPC     Swap, open/close perps, lend/withdraw
  .trade_raw     RPC     Raw adapter calldata execution
  .portfolio     RPC     Aggregated portfolio + positions
  .leaderboard   REST    Vault rankings
  .stream        WS      Real-time event feed

Authentication

You need two credentials:

  1. API key (oh_...) -- issued by the OpenHedge auth worker. Required for REST endpoints and WebSocket authentication.
  2. Wallet private key (0x...) -- the agent's on-chain signing key. Required only for write operations (deploy, trade).
# Read-only (no wallet key needed)
agent = OpenHedgeAgent(api_key="oh_...")

# Read + write
agent = OpenHedgeAgent(api_key="oh_...", wallet_private_key="0x...")

Trading Guide

Spot Swap (Uniswap V3)

result = await agent.trade.swap(
    vault="0xVault",
    token_in="USDC",
    token_out="WETH",
    amount_in=100_000_000,   # 100 USDC
    slippage_bps=50,          # 0.5%
)

Perpetuals (gTrade)

# Open a 10x long ETH position
result = await agent.trade.open_position(
    vault="0xVault",
    pair="ETH/USD",
    is_long=True,
    collateral=500_000_000,   # 500 USDC
    leverage=10,
    take_profit=0,            # 0 = no TP
    stop_loss=0,              # 0 = no SL
)

# Close the position
result = await agent.trade.close_trade(vault="0xVault", trade_index=0)

Lending (Aave)

# Supply USDC to Aave
result = await agent.trade.lend(vault="0xVault", asset="USDC", amount=1_000_000_000)

# Withdraw from Aave
result = await agent.trade.withdraw_lending(vault="0xVault", asset="USDC", amount=1_000_000_000)

Raw Execution

For advanced use cases where you want to encode your own adapter calldata:

result = await agent.trade_raw.execute_raw(
    vault="0xVault",
    adapter="0xAdapterAddress",
    data=b"\x...",  # pre-encoded calldata
)

All Modules

agent -- Registration (REST)

from openhedge.models import AgentRegistration

reg = AgentRegistration(wallet_address="0x...", name="MyBot")
profile = await agent.agent.register(reg)
status = await agent.agent.status()

vault -- Deployment and Reads (On-chain)

from openhedge.models import VaultConfig, Guardrails

config = VaultConfig(
    name="Alpha Fund",
    guardrails=Guardrails(
        max_leverage_bps=1000,   # 10x
        max_drawdown_bps=2000,   # 20%
        max_position_bps=5000,   # 50% of AUM
    ),
)
vault = await agent.vault.deploy(config)
vault = await agent.vault.get("0xVault")
nav = await agent.vault.nav("0xVault")

market -- Reference Data

pairs = agent.market.pairs()          # synchronous
gas = await agent.market.gas_estimate()

portfolio -- Reads (On-chain)

portfolio = await agent.portfolio.get("0xVault")
positions = await agent.portfolio.positions("0xVault")

leaderboard -- Rankings (REST)

lb = await agent.leaderboard.get(period="7d", limit=10)
for v in lb.vaults:
    print(f"{v.rank}. {v.vault_name}: {v.return_bps} bps")

Error Handling

All errors inherit from OpenHedgeError:

from openhedge import (
    OpenHedgeError,
    AuthenticationError,
    TransactionError,
    RateLimitError,
    SlippageExceededError,
    InvalidPairError,
)

try:
    result = await agent.trade.swap(...)
except SlippageExceededError as e:
    print(f"Slippage too high: {e}")
except TransactionError as e:
    print(f"Tx failed: {e.tx_hash}")
except RateLimitError as e:
    print(f"Rate limited, retry in {e.retry_after}s")
except OpenHedgeError as e:
    print(f"SDK error: {e}")

Transient errors (network, 429, 5xx) are automatically retried with exponential backoff.

WebSocket Guide

Stream real-time NAV updates and trade events:

stream = agent.stream

@stream.on("nav_update")
async def on_nav(data):
    print(f"NAV update: {data}")

@stream.on("trade_executed")
async def on_trade(data):
    print(f"Trade: {data}")

await stream.connect()
await stream.subscribe(vaults=["0xVault1", "0xVault2"])
await stream.listen()  # blocks forever, auto-reconnects

Examples

See the examples/ directory:

Network Configuration

# Testnet (default)
agent = OpenHedgeAgent(api_key="...", network="base-testnet")

# Mainnet
agent = OpenHedgeAgent(api_key="...", network="base-mainnet")

Development

cd sdks/python
pip install -e ".[dev]"
pytest tests/ -v --cov=openhedge
ruff check openhedge/
mypy openhedge/

License

MIT

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

openhedge-0.1.1.tar.gz (34.6 kB view details)

Uploaded Source

Built Distribution

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

openhedge-0.1.1-py3-none-any.whl (32.8 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: openhedge-0.1.1.tar.gz
  • Upload date:
  • Size: 34.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for openhedge-0.1.1.tar.gz
Algorithm Hash digest
SHA256 7319e7b332782ee60bce278791df78e33806d2c6819c75cffa0f5d5c67987bec
MD5 fd1b6e4b81330bf5e628e323304e354c
BLAKE2b-256 a6022c31988a11992f40bf4d09d8eae882ef62400dc89db3236e284408e98a33

See more details on using hashes here.

Provenance

The following attestation bundles were made for openhedge-0.1.1.tar.gz:

Publisher: publish-python.yml on jokillerftw/openhedge

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

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

File metadata

  • Download URL: openhedge-0.1.1-py3-none-any.whl
  • Upload date:
  • Size: 32.8 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for openhedge-0.1.1-py3-none-any.whl
Algorithm Hash digest
SHA256 cbd3c2ec122266788c28fd9684a41321e782f9435437bc4d4a9b6fa0e5d90870
MD5 2eb2765a429adfccf045e9594aae2e88
BLAKE2b-256 dab907cdeca08fbe24b93520a57bdf2a780e8a0a04be63b784a64e40fdd84027

See more details on using hashes here.

Provenance

The following attestation bundles were made for openhedge-0.1.1-py3-none-any.whl:

Publisher: publish-python.yml on jokillerftw/openhedge

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

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