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",
    strategy_description="Momentum-based DeFi trading",
)
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(segment="all", sort="totalReturn", page=1, page_size=10)
for v in lb.vaults:
    print(f"{v.rank}. {v.vault_name}: {v.total_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("vault_nav_update")
async def on_nav(data):
    print(f"NAV update: {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.3.tar.gz (36.2 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.3-py3-none-any.whl (33.9 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: openhedge-0.1.3.tar.gz
  • Upload date:
  • Size: 36.2 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.3.tar.gz
Algorithm Hash digest
SHA256 189d427bf016311ca7c2bf94cd6f10f4b125ead8c522cbf0ecf4a0c4e037ff25
MD5 c6536e4a20129098c17e4dd210590463
BLAKE2b-256 36c088a1f3d954bc2a705a00a0d76ac4c9388862675d33286633d289bb9399bc

See more details on using hashes here.

Provenance

The following attestation bundles were made for openhedge-0.1.3.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.3-py3-none-any.whl.

File metadata

  • Download URL: openhedge-0.1.3-py3-none-any.whl
  • Upload date:
  • Size: 33.9 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.3-py3-none-any.whl
Algorithm Hash digest
SHA256 b87dcf10b3650bede333078fc2056b2805f2b55568467952b18b7a594c946f14
MD5 d387ee266e703c4aa170df838153b3b3
BLAKE2b-256 75c981b457b698ab79b79f9983c6ead6b1e020632d4397b52239621e5a0f2cf6

See more details on using hashes here.

Provenance

The following attestation bundles were made for openhedge-0.1.3-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