A complete Swift SDK for the Hyperliquid decentralized exchange.
Current Version: v1.6.0 π―
- π Complete Trading API: Place orders, cancel orders, manage positions
- π Real-time Market Data: Prices, order books, trade history
- π° Account Management: Portfolio tracking, balance queries, user state
- πΈ Transfer Operations: USD, spot tokens, sub-accounts, vault transfers
- π§ Advanced Features: Multi-sig, token delegation, bridge operations
- π EIP-712 Signing: Secure transaction signing with Ethereum standards
- β‘οΈ Type Safety: Full Swift type system with Codable support
- π― Async/Await: Modern Swift concurrency support
- π Multi-Environment: Testnet and Mainnet support
- π‘οΈ Enterprise Grade: Production-ready cryptography and error handling
- π οΈ Development Tools: Makefile, SwiftLint, SwiftFormat for code quality
- Trading
- Limit/Market orders, Modify, Cancel, Schedule cancel
- Bulk orders and Batch modify orders
- Cancel by client order ID, Cancel all orders
- Market Data & Queries
- All mids, L2 order book, Candle snapshot
- Meta, MetaAndAssetCtxs, SpotMeta, SpotMetaAndAssetCtxs
- User/Spot state, Open/Frontend open orders, User fills (+by time)
- Funding history, User funding history, User fees
- Query order by oid/cloid, Referral state
- Perp dex list, Multiβsig signers, Perp deploy auction status
- Subβaccounts query (raw JSON)
- Account Management
- Update leverage, Update isolated margin, Set referrer
- Sub Accounts
- Create sub account
- Transfer Operations
- USD class transfer, USD transfer, Spot transfer
- Sub account transfer, Vault USD transfer, Send asset
- Sub account spot transfer, Approve agent
- Advanced Features
- Token delegate, Withdraw from bridge
- Approve builder fee, Convert to multi-sig user
- Multi-sig operations, Use big blocks
- Realβtime
- WebSocket subscriptions
- Development Tools
- Makefile with common commands
- SwiftLint configuration
- SwiftFormat configuration
- Constants for easy customization
- Error types (ClientError, ServerError, NetworkError)
- Market making strategy example
- Map
querySubAccounts
β strong models (with nested UserState) - More examples and docs for new APIs
- TPSL helpers and risk utilities
- CI matrix expansion (macOS versions, optional Linux build-only)
- Transfer/withdraw operations kept off by default for mobile safety (optβin discussion)
Add to your Package.swift
:
dependencies: [
.package(url: "https://github.com/0xboji/hyperliquid-swift-sdk.git", from: "1.0.0")
]
import HyperliquidSwift
// Initialize client
let client = try HyperliquidClient(
privateKeyHex: "your_private_key_here",
environment: .testnet
)
// Get market data
let prices = try await client.getAllMids()
print("BTC Price: \(prices["BTC"] ?? 0)")
// Place a limit order
let response = try await client.limitBuy(
coin: "ETH",
sz: Decimal(0.1),
px: Decimal(3000.0),
reduceOnly: false
)
# Build the package
make build
# Run tests
make test
# Run linting
make lint
# Format code
make format
# Clean build artifacts
make clean
# Install dependencies
make install
# Generate documentation
make docs
# Run all examples
make examples
# Run security checks
make security
The SDK includes:
- SwiftLint: Code linting with custom rules
- SwiftFormat: Automatic code formatting
- Constants: Easy customization points
- Error Types: Comprehensive error handling
// Get all market prices
let prices = try await client.getAllMids()
// Get exchange metadata
let meta = try await client.getMeta()
// Get metadata with asset contexts
let metaAndCtxs = try await client.getMetaAndAssetCtxs()
// Get spot market metadata
let spotMeta = try await client.getSpotMeta()
// Get spot metadata with asset contexts
let spotMetaAndCtxs = try await client.getSpotMetaAndAssetCtxs()
// Get user state
let userState = try await client.getUserState()
// Place limit buy order
let buyResponse = try await client.limitBuy(
coin: "ETH",
sz: Decimal(0.1),
px: Decimal(3000.0),
reduceOnly: false
)
// Place limit sell order
let sellResponse = try await client.limitSell(
coin: "ETH",
sz: Decimal(0.1),
px: Decimal(3500.0),
reduceOnly: false
)
// Place market orders
let marketBuy = try await client.marketBuy(coin: "ETH", sz: Decimal(0.1))
let marketSell = try await client.marketSell(coin: "BTC", sz: Decimal(0.01))
// Cancel single order
let cancelResponse = try await client.cancelOrder(coin: "ETH", oid: 12345)
// Cancel all orders for a coin
let cancelAllETH = try await client.cancelAllOrders(coin: "ETH")
// Cancel all orders across all coins
let cancelAll = try await client.cancelAllOrders()
// Modify existing order
let modifyResponse = try await client.modifyOrder(
oid: 12345,
coin: "ETH",
newPrice: Decimal(3200.0),
newSize: Decimal(0.05)
)
// Get open orders
let openOrders = try await client.getOpenOrders()
// Get enhanced frontend open orders (with trigger conditions)
let frontendOrders = try await client.getFrontendOpenOrders(address: userAddress)
// Get user fills
let fills = try await client.getUserFills()
// Get user fills by time range
let recentFills = try await client.getUserFillsByTime(
startTime: Date().addingTimeInterval(-86400), // 24 hours ago
endTime: Date()
)
// Get user fees and trading volume
let userFees = try await client.getUserFees(address: userAddress)
// Get user funding history
let fundingHistory = try await client.getUserFunding(
user: userAddress,
startTime: Int(Date().addingTimeInterval(-86400).timeIntervalSince1970 * 1000),
endTime: Int(Date().timeIntervalSince1970 * 1000)
)
// Get funding rate history for a specific coin
let btcFunding = try await client.getFundingHistory(
coin: "BTC",
startTime: Int(Date().addingTimeInterval(-86400).timeIntervalSince1970 * 1000)
)
// Query referral state
let referralState = try await client.queryReferralState(user: userAddress)
// Query sub accounts
let subAccounts = try await client.querySubAccounts(user: userAddress)
// Transfer USDC between spot and perp wallets
let spotToPerp = try await client.usdClassTransfer(amount: Decimal(100.0), toPerp: true)
let perpToSpot = try await client.usdClassTransfer(amount: Decimal(100.0), toPerp: false)
// Transfer USDC to another address
let usdTransfer = try await client.usdTransfer(
amount: Decimal(50.0),
destination: "0x742d35Cc6634C0532925a3b8D4C9db96c4b4Db45"
)
// Transfer spot tokens
let spotTransfer = try await client.spotTransfer(
amount: Decimal(10.0),
destination: "0x742d35Cc6634C0532925a3b8D4C9db96c4b4Db45",
token: "PURR:0xc4bf3f870c0e9465323c0b6ed28096c2"
)
// Transfer to/from sub account
let subAccountDeposit = try await client.subAccountTransfer(
subAccountUser: "0x742d35Cc6634C0532925a3b8D4C9db96c4b4Db45",
isDeposit: true,
usd: Decimal(25.0)
)
// Vault USD transfer (institutional trading)
let vaultDeposit = try await client.vaultUsdTransfer(
vaultAddress: "0xa15099a30bbf2e68942d6f4c43d70d04faeab0a0",
isDeposit: true,
usd: 5_000_000 // $5 in micro-USD
)
// Token delegation to validator
let delegate = try await client.tokenDelegate(
validator: "0x742d35Cc6634C0532925a3b8D4C9db96c4b4Db45",
wei: 1000000000000000000, // 1 token in wei
isUndelegate: false
)
// Withdraw from bridge
let withdraw = try await client.withdrawFromBridge(
amount: Decimal(10.0),
destination: "0x742d35Cc6634C0532925a3b8D4C9db96c4b4Db45"
)
// Convert to multi-signature user
let convertToMultiSig = try await client.convertToMultiSigUser(
authorizedUsers: [
"0x742d35Cc6634C0532925a3b8D4C9db96c4b4Db45",
"0xa15099a30bbf2e68942d6f4c43d70d04faeab0a0"
],
threshold: 2
)
// Enable big blocks for better performance
let bigBlocks = try await client.useBigBlocks(enable: true)
// Send asset between DEXs
let assetTransfer = try await client.sendAsset(
destination: "0x742d35Cc6634C0532925a3b8D4C9db96c4b4Db45",
sourceDex: "",
destinationDex: "spot",
token: "USDC",
amount: Decimal(10.0)
)
// Sub account spot transfer
let subSpotTransfer = try await client.subAccountSpotTransfer(
subAccountUser: "0x742d35Cc6634C0532925a3b8D4C9db96c4b4Db45",
isDeposit: true,
token: "USDC",
amount: Decimal(5.0)
)
// Approve agent for automated trading
let agentApproval = try await client.approveAgent(
agentAddress: "0x742d35Cc6634C0532925a3b8D4C9db96c4b4Db45",
agentName: "TradingBot"
)
Run the included examples:
# Market data and account queries
swift run BasicUsage
# Basic trading tutorial
swift run TradingExample
# Advanced trading operations (market orders, cancel all, modify)
swift run AdvancedTradingExample
# Market making strategy (similar to Python SDK's basic_adding.py)
swift run MarketMakingExample
# New Info API methods (fees, funding, referrals, sub accounts)
swift run NewMethodsExample
# Transfer operations (USD, spot tokens, sub accounts)
swift run TransferExample
# Multi-signature operations
swift run ConvertToMultiSigExample
swift run MultiSigOrderExample
# Builder fees and routing
swift run BuilderFeeExample
# Performance optimization
swift run UseBigBlocksExample
# TPSL (Take Profit/Stop Loss) orders
swift run TPSLOrdersExample
# Bulk cancellation and order expiration
swift run BulkCancelExample
# Validator management operations
swift run ValidatorManagementExample
# Token and asset deployment
swift run DeploymentExample
# Agent wallet management
swift run AgentManagementExample
# Advanced deployment operations
swift run AdvancedDeploymentExample
# Advanced spot token operations
swift run AdvancedSpotOperationsExample
- Core Trading: Basic usage, advanced trading, market orders, TPSL orders
- Market Making: Automated liquidity provision strategy
- Account Management: Leverage, margin, referrals, sub-accounts
- Transfer Operations: USD, spot tokens, sub-accounts, vault transfers
- Advanced Features: Multi-sig, builder fees, big blocks, token delegation
- Order Management: Bulk cancellation, order expiration, advanced cancellation
- Validator Operations: Validator registration, profile management, signer operations
- Deployment Operations: Spot token and perpetual asset deployment, genesis operations
- Agent Management: Agent wallet creation and approval for automated trading
- Real-time Data: WebSocket subscriptions and market data streaming
Each example corresponds to similar functionality in the Python SDK examples, ensuring consistency across implementations.
- β Development Tools: Added Makefile, SwiftLint, SwiftFormat
- β Constants: Added Constants.swift for easy customization
- β Error Types: Added ClientError, ServerError, NetworkError
- β Market Making: Added MarketMakingExample (similar to Python SDK's basic_adding.py)
- β Code Quality: Comprehensive linting and formatting rules
- β Documentation: Updated README with development tools section
- β
Freeze Operations:
spotDeployEnableFreezePrivilege
,spotDeployFreezeUser
,spotDeployRevokeFreezePrivilege
- β
Hyperliquidity:
spotDeployRegisterHyperliquidity
for automated market making - β
Fee Management:
spotDeploySetDeployerTradingFeeShare
for revenue sharing - β Advanced Example: AdvancedSpotOperationsExample with compliance features
- β 105% Coverage: Now exceeds Python SDK baseline (105/100 methods)
- β Compliance Ready: Complete regulatory and freeze management tools
- π― MILESTONE: First SDK to exceed Python SDK feature coverage
- β
Agent Management:
approveAgent
for automated trading wallet creation - β
Advanced Deployment:
spotDeployGenesis
,spotDeployRegisterSpot
,spotDeployUserGenesis
- β
Oracle Management:
perpDeploySetOracle
for perpetual price feeds - β Complete Examples: AgentManagementExample and AdvancedDeploymentExample
- β 100% Feature Parity: All 100/100 methods implemented
- β Production Complete: Full compatibility with Python SDK
- π― MILESTONE: First mobile SDK with complete Hyperliquid API coverage
- β
Validator Management:
changeValidatorProfile
for validator configuration updates - β
Signer Operations:
cSignerUnjailSelf
andcSignerJailSelf
for network participation - β
Spot Deployment:
spotDeployRegisterToken
for new token registration - β
Perpetual Deployment:
perpDeployRegisterAsset
for new asset registration - β New Examples: ValidatorManagementExample and DeploymentExample
- β 98% Feature Parity: 95/97 methods implemented
- β Infrastructure Ready: Complete validator and deployment support
- β
TPSL Orders:
stopLossOrder
andtakeProfitOrder
for automated risk management - β
Bulk Cancellation:
bulkCancelByCloid
for efficient order management - β
Order Expiration:
setExpiresAfter
for automated order lifecycle - β
Validator Operations:
registerValidator
andunregisterValidator
- β New Examples: TPSLOrdersExample and BulkCancelExample
- β 96% Feature Parity: 88/92 methods implemented
- β Enhanced Testing: Comprehensive test coverage for all new methods
- β Multi-signature user conversion and operations
- β Builder fee approval and routing
- β Big blocks configuration
- β Token delegation and bridge operations
- β Complete trading operations (limit, market, cancel, modify)
- β Transfer operations and account management
- β Real-time WebSocket support
- β Comprehensive market data queries
The SDK includes comprehensive tests covering all functionality:
# Run all tests
swift test
# Build only (faster verification)
swift build
# Run specific test suites
swift test --filter NewMethodsTests
swift test --filter HyperliquidClientTests
- Method Signatures: Verify all methods exist with correct signatures
- Parameter Validation: Test parameter handling and validation
- Error Handling: Ensure proper error propagation
- Integration Tests: Test real API interactions (when configured)
- Mock Tests: Unit tests with mocked responses
The test suite ensures compatibility with the Python SDK and validates all newly implemented methods.
π Hyperliquid Swift SDK - Basic Usage Examples
==================================================
π Market Summary
=================
Active Markets: 1441
π Account Summary
==================
Address: 0x1234...7890
Account Value: $8.199509
Total Margin Used: $0
Positions: 0
Open Orders: 0
Create Examples/config.json
:
{
"private_key": "your_private_key_hex",
"environment": "testnet"
}
- iOS 13.0+ / macOS 10.15+
- Swift 5.5+
- Xcode 13.0+
- secp256k1.swift - Elliptic curve cryptography
- CryptoSwift - Cryptographic functions
HyperliquidSwift/
βββ Models/ # Data models and types
βββ Services/ # Core services
β βββ CryptoService.swift # EIP-712 signing
β βββ HTTPClient.swift # Network layer
β βββ TradingService.swift # Trading operations
βββ Utils/ # Utilities and helpers
β βββ Constants.swift # Global constants
β βββ ErrorTypes.swift # Error handling
β βββ Validation.swift # Input validation
βββ HyperliquidClient.swift # Main client interface
- EIP-712 compliant transaction signing
- secp256k1 elliptic curve cryptography
- Keccak256 hashing for Ethereum compatibility
- Private key never leaves your application
swift test
MIT License - see LICENSE file for details.
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature
) - Commit your changes (
git commit -m 'Add amazing feature'
) - Push to the branch (
git push origin feature/amazing-feature
) - Open a Pull Request
- π Documentation
- π Issues
- π¬ Discussions
Built with β€οΈ for the Hyperliquid community.
Ready to trade on Hyperliquid with Swift? Let's go! π