### Initialize and verify the project Source: https://github.com/sonirico/go-hyperliquid/blob/master/README.md Use these commands to clone the repository, install necessary tools, and execute the full CI suite. ```bash # Clone the repository git clone https://github.com/sonirico/go-hyperliquid.git cd go-hyperliquid # Install dependencies and tools make deps install-tools # Run all checks make ci-full # Run tests (excluding examples) make ci-test ``` -------------------------------- ### Install go-hyperliquid Source: https://github.com/sonirico/go-hyperliquid/blob/master/README.md Use 'go get' to add the go-hyperliquid library to your project dependencies. ```bash go get github.com/sonirico/go-hyperliquid ``` -------------------------------- ### Initialize Exchange and Place Limit Order with go-hyperliquid Source: https://github.com/sonirico/go-hyperliquid/blob/master/README.md This example demonstrates initializing the Hyperliquid exchange client using a private key and placing a limit order. It also shows how to subscribe to real-time trade data via WebSocket. Ensure you replace 'your-private-key' with your actual private key. ```go package main import ( "context" "fmt" "log" "github.com/ethereum/go-ethereum/crypto" hyperliquid "github.com/sonirico/go-hyperliquid" ) func main() { // For trading, create an Exchange with your private key privateKey, _ := crypto.HexToECDSA("your-private-key") exchange := hyperliquid.NewExchange( context.Background(), privateKey, hyperliquid.MainnetAPIURL, nil, // Meta will be fetched automatically "vault-address", "account-address", nil, // SpotMeta will be fetched automatically nil, // PerpDexs will be fetched automatically ) // Place a limit order order := hyperliquid.OrderRequest{ Coin: "BTC", IsBuy: true, Size: 0.1, LimitPx: 40000.0, OrderType: hyperliquid.OrderType{ Limit: &hyperliquid.LimitOrderType{ Tif: "Gtc", }, }, } resp, err := exchange.Order(context.Background(), order, nil) if err != nil { log.Fatal(err) } // Subscribe to WebSocket updates ws := hyperliquid.NewWebsocketClient(hyperliquid.MainnetAPIURL) if err := ws.Connect(context.Background()); err != nil { log.Fatal(err) } defer ws.Close() // Subscribe to BTC trades _, err = ws.Subscribe(hyperliquid.Subscription{ Type: "trades", Coin: "BTC", }, func(msg hyperliquid.wsMessage) { fmt.Printf("Trade: %+v\n", msg) }) } ``` -------------------------------- ### Token Staking and Delegation in Go Source: https://context7.com/sonirico/go-hyperliquid/llms.txt Provides examples for checking staking summaries, retrieving delegation details, delegating tokens to a validator, and fetching staking rewards using the Hyperliquid Go SDK. Ensure the address and validator address are correctly specified. ```go package main import ( "context" "fmt" "log" "github.com/ethereum/go-ethereum/crypto" hyperliquid "github.com/sonirico/go-hyperliquid" ) func main() { privateKey, _ := crypto.HexToECDSA("your-private-key") exchange := hyperliquid.NewExchange( context.Background(), privateKey, hyperliquid.MainnetAPIURL, nil, "", "", nil, nil, ) ctx := context.Background() info := exchange.Info() address := "0xYourAddress" // Check staking summary summary, err := info.UserStakingSummary(ctx, address) if err != nil { log.Fatal(err) } fmt.Printf("Staking summary: %+v\n", summary) // Get delegations delegations, err := info.UserStakingDelegations(ctx, address) if err != nil { log.Fatal(err) } for _, d := range delegations { fmt.Printf("Delegation: %+v\n", d) } // Delegate tokens to validator delegateResult, err := exchange.TokenDelegate( ctx, "0xValidatorAddress", 1000000000000000000, // wei amount false, // isUndelegate ) if err != nil { log.Fatal(err) } fmt.Printf("Delegation result: %+v\n", delegateResult) // Get staking rewards rewards, err := info.UserStakingRewards(ctx, address) if err != nil { log.Fatal(err) } for _, r := range rewards { fmt.Printf("Reward: %+v\n", r) } } ``` -------------------------------- ### Initialize Info Client Source: https://context7.com/sonirico/go-hyperliquid/llms.txt Create a read-only client for fetching market data and account information without requiring a private key. ```go package main import ( "context" "fmt" "log" hyperliquid "github.com/sonirico/go-hyperliquid" ) func main() { ctx := context.Background() // Create info client for read-only operations info := hyperliquid.NewInfo( ctx, hyperliquid.MainnetAPIURL, true, // skipWS - skip WebSocket initialization nil, // Meta will be fetched automatically nil, // SpotMeta will be fetched automatically nil, // PerpDexs will be fetched automatically ) // Fetch perpetuals metadata meta, err := info.Meta(ctx) if err != nil { log.Fatal(err) } fmt.Printf("Found %d perpetual markets\n", len(meta.Universe)) // Fetch all mid prices mids, err := info.AllMids(ctx) if err != nil { log.Fatal(err) } fmt.Printf("BTC mid price: %s\n", mids["BTC"]) } ``` -------------------------------- ### Initialize Exchange Client Source: https://context7.com/sonirico/go-hyperliquid/llms.txt Create an authenticated client for trading operations. Requires a private key and supports optional vault or account address configuration. ```go package main import ( "context" "log" "github.com/ethereum/go-ethereum/crypto" hyperliquid "github.com/sonirico/go-hyperliquid" ) func main() { // Load your private key (never hardcode in production) privateKey, err := crypto.HexToECDSA("your-private-key-hex-without-0x") if err != nil { log.Fatal(err) } // Create exchange client for mainnet exchange := hyperliquid.NewExchange( context.Background(), privateKey, hyperliquid.MainnetAPIURL, // or hyperliquid.TestnetAPIURL nil, // Meta will be fetched automatically "", // vault address (optional) "", // account address (optional, uses key address) nil, // SpotMeta will be fetched automatically nil, // PerpDexs will be fetched automatically ) // Exchange is ready for trading operations log.Println("Exchange client initialized") } ``` -------------------------------- ### Create and Manage Vaults in Go Source: https://context7.com/sonirico/go-hyperliquid/llms.txt Demonstrates how to create, deposit to, modify, and distribute profits from a vault using the Hyperliquid Go SDK. Ensure you have your private key and vault address correctly configured. ```go package main import ( "context" "fmt" "log" "github.com/ethereum/go-ethereum/crypto" hyperliquid "github.com/sonirico/go-hyperliquid" ) func main() { privateKey, _ := crypto.HexToECDSA("your-private-key") exchange := hyperliquid.NewExchange( context.Background(), privateKey, hyperliquid.MainnetAPIURL, nil, "", "", nil, nil, ) ctx := context.Background() // Create a vault createResult, err := exchange.CreateVault(ctx, "My Trading Vault", "Algorithmic trading strategy", 10000) if err != nil { log.Fatal(err) } fmt.Printf("Vault created: %+v\n", createResult) vaultAddress := "0xVaultAddress" // Deposit to vault depositResult, err := exchange.VaultUsdTransfer(ctx, vaultAddress, true, 5000) if err != nil { log.Fatal(err) } fmt.Printf("Vault deposit: %+v\n", depositResult) // Modify vault settings modifyResult, err := exchange.VaultModify(ctx, vaultAddress, true, false) if err != nil { log.Fatal(err) } fmt.Printf("Vault modified: %+v\n", modifyResult) // Distribute vault profits distributeResult, err := exchange.VaultDistribute(ctx, vaultAddress, 1000) if err != nil { log.Fatal(err) } fmt.Printf("Vault distribution: %+v\n", distributeResult) } ``` -------------------------------- ### Run project verification commands Source: https://github.com/sonirico/go-hyperliquid/blob/master/CONTRIBUTING.md Execute this command to ensure code generation, linting, and tests pass before pushing changes. ```bash make generate && make check && make test ``` -------------------------------- ### Subscribe to All Mid Prices via WebSocket Source: https://context7.com/sonirico/go-hyperliquid/llms.txt Establishes a WebSocket connection to receive real-time mid price updates for assets. Requires a context with a timeout and a callback function to handle incoming data. ```go package main import ( "context" "fmt" "log" "time" hyperliquid "github.com/sonirico/go-hyperliquid" ) func main() { ws := hyperliquid.NewWebsocketClient(hyperliquid.MainnetAPIURL) ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) defer cancel() if err := ws.Connect(ctx); err != nil { log.Fatal(err) } defer ws.Close() sub, err := ws.AllMids( hyperliquid.AllMidsSubscriptionParams{Dex: nil}, func(mids hyperliquid.AllMids, err error) { if err != nil { log.Printf("Error: %v", err) return } fmt.Printf("BTC: %s, ETH: %s, SOL: %s\n", mids.Mids["BTC"], mids.Mids["ETH"], mids.Mids["SOL"]) }, ) if err != nil { log.Fatal(err) } defer sub.Close() <-ctx.Done() } ``` -------------------------------- ### Approve Trading Agents and Builder Fees in Go Source: https://context7.com/sonirico/go-hyperliquid/llms.txt Shows how to approve a new trading agent and a builder fee using the Hyperliquid Go SDK. The agent approval generates a new private key which must be stored securely. ```go package main import ( "context" "fmt" "log" "github.com/ethereum/go-ethereum/crypto" hyperliquid "github.com/sonirico/go-hyperliquid" ) func main() { privateKey, _ := crypto.HexToECDSA("your-private-key") exchange := hyperliquid.NewExchange( context.Background(), privateKey, hyperliquid.MainnetAPIURL, nil, "", "", nil, nil, ) ctx := context.Background() // Approve a trading agent (generates new agent key) agentName := "My Trading Bot" agentResult, agentPrivateKey, err := exchange.ApproveAgent(ctx, &agentName) if err != nil { log.Fatal(err) } fmt.Printf("Agent approved: %+v\n", agentResult) fmt.Printf("Agent private key (save securely): %s\n", agentPrivateKey) // Approve builder fee builderResult, err := exchange.ApproveBuilderFee(ctx, "0xBuilderAddress", "0.001") if err != nil { log.Fatal(err) } fmt.Printf("Builder fee approved: %+v\n", builderResult) } ``` -------------------------------- ### Manage Leverage and Margin in Go Source: https://context7.com/sonirico/go-hyperliquid/llms.txt Updates leverage settings and adjusts isolated margin for specific positions. Requires a valid private key for exchange authentication. ```go package main import ( "context" "fmt" "log" "github.com/ethereum/go-ethereum/crypto" hyperliquid "github.com/sonirico/go-hyperliquid" ) func main() { privateKey, _ := crypto.HexToECDSA("your-private-key") exchange := hyperliquid.NewExchange( context.Background(), privateKey, hyperliquid.MainnetAPIURL, nil, "", "", nil, nil, ) ctx := context.Background() // Update leverage to 10x cross margin userState, err := exchange.UpdateLeverage(ctx, 10, "BTC", true) if err != nil { log.Fatal(err) } fmt.Printf("Leverage updated. Account value: %s\n", userState.MarginSummary.AccountValue) // Switch to 5x isolated margin userState, err = exchange.UpdateLeverage(ctx, 5, "BTC", false) if err != nil { log.Fatal(err) } fmt.Printf("Switched to isolated margin\n") // Add isolated margin to position (positive = add, negative = remove) userState, err = exchange.UpdateIsolatedMargin(ctx, 100.0, "BTC") if err != nil { log.Fatal(err) } fmt.Printf("Isolated margin updated\n") } ``` -------------------------------- ### Place Stop-Loss and Take-Profit Orders in Go Source: https://context7.com/sonirico/go-hyperliquid/llms.txt Configures trigger orders using CreateOrderRequest to automate exit strategies. Set ReduceOnly to true to ensure the order only closes existing positions. ```go package main import ( "context" "fmt" "log" "github.com/ethereum/go-ethereum/crypto" hyperliquid "github.com/sonirico/go-hyperliquid" ) func main() { privateKey, _ := crypto.HexToECDSA("your-private-key") exchange := hyperliquid.NewExchange( context.Background(), privateKey, hyperliquid.MainnetAPIURL, nil, "", "", nil, nil, ) // Place a stop-loss order stopLossReq := hyperliquid.CreateOrderRequest{ Coin: "SOL", IsBuy: true, // Buy to close short, Sell to close long Size: 1.0, Price: 110.0, // Limit price after trigger ReduceOnly: true, OrderType: hyperliquid.OrderType{ Trigger: &hyperliquid.TriggerOrderType{ TriggerPx: 100.0, // Trigger when price reaches this IsMarket: true, // Execute as market order Tpsl: hyperliquid.StopLoss, }, }, } result, err := exchange.Order(context.Background(), stopLossReq, nil) if err != nil { log.Fatal(err) } fmt.Printf("Stop-loss order: %+v\n", result) // Place a take-profit order takeProfitReq := hyperliquid.CreateOrderRequest{ Coin: "SOL", IsBuy: false, // Sell to take profit on long Size: 1.0, Price: 200.0, ReduceOnly: true, OrderType: hyperliquid.OrderType{ Trigger: &hyperliquid.TriggerOrderType{ TriggerPx: 200.0, IsMarket: true, Tpsl: hyperliquid.TakeProfit, }, }, } tpResult, err := exchange.Order(context.Background(), takeProfitReq, nil) if err != nil { log.Fatal(err) } fmt.Printf("Take-profit order: %+v\n", tpResult) } ``` -------------------------------- ### Place Bulk Orders Source: https://context7.com/sonirico/go-hyperliquid/llms.txt Use the BulkOrders method to submit multiple orders in a single request. Requires a valid private key and exchange initialization. ```go package main import ( "context" "fmt" "log" "github.com/ethereum/go-ethereum/crypto" hyperliquid "github.com/sonirico/go-hyperliquid" ) func main() { privateKey, _ := crypto.HexToECDSA("your-private-key") exchange := hyperliquid.NewExchange( context.Background(), privateKey, hyperliquid.MainnetAPIURL, nil, "", "", nil, nil, ) // Create multiple orders orders := []hyperliquid.CreateOrderRequest{ { Coin: "BTC", IsBuy: true, Size: 0.001, Price: 39000.0, OrderType: hyperliquid.OrderType{ Limit: &hyperliquid.LimitOrderType{Tif: hyperliquid.TifGtc}, }, }, { Coin: "BTC", IsBuy: true, Size: 0.001, Price: 38000.0, OrderType: hyperliquid.OrderType{ Limit: &hyperliquid.LimitOrderType{Tif: hyperliquid.TifGtc}, }, }, { Coin: "ETH", IsBuy: false, Size: 0.01, Price: 3000.0, OrderType: hyperliquid.OrderType{ Limit: &hyperliquid.LimitOrderType{Tif: hyperliquid.TifGtc}, }, }, } result, err := exchange.BulkOrders(context.Background(), orders, nil) if err != nil { log.Fatal(err) } fmt.Printf("Placed %d orders\n", len(result.Data.Statuses)) for i, status := range result.Data.Statuses { if status.Resting != nil { fmt.Printf(" Order %d: OID=%d\n", i, status.Resting.Oid) } } } ``` -------------------------------- ### Fetch Market Data in Go Source: https://context7.com/sonirico/go-hyperliquid/llms.txt Accesses market metadata, real-time mid prices, L2 order book snapshots, and historical candle data. ```go package main import ( "context" "fmt" "log" "time" hyperliquid "github.com/sonirico/go-hyperliquid" ) func main() { ctx := context.Background() info := hyperliquid.NewInfo(ctx, hyperliquid.MainnetAPIURL, true, nil, nil, nil) // Get perpetuals metadata meta, err := info.Meta(ctx) if err != nil { log.Fatal(err) } for _, asset := range meta.Universe { fmt.Printf("Asset: %s, Decimals: %d, MaxLeverage: %d\n", asset.Name, asset.SzDecimals, asset.MaxLeverage) } // Get all mid prices mids, err := info.AllMids(ctx) if err != nil { log.Fatal(err) } fmt.Printf("BTC: %s, ETH: %s\n", mids["BTC"], mids["ETH"]) // Get L2 order book snapshot l2Book, err := info.L2Snapshot(ctx, "BTC") if err != nil { log.Fatal(err) } fmt.Printf("Order book time: %d\n", l2Book.Time) if len(l2Book.Levels) >= 2 { fmt.Printf("Best bid: %+v\n", l2Book.Levels[0][0]) fmt.Printf("Best ask: %+v\n", l2Book.Levels[1][0]) } // Get historical candles endTime := time.Now().UnixMilli() startTime := endTime - (24 * time.Hour).Milliseconds() candles, err := info.CandlesSnapshot(ctx, "BTC", "1h", startTime, endTime) if err != nil { log.Fatal(err) } fmt.Printf("Retrieved %d candles\n", len(candles)) for _, c := range candles[:3] { fmt.Printf(" Open: %s, High: %s, Low: %s, Close: %s\n", c.Open, c.High, c.Low, c.Close) } } ``` -------------------------------- ### Query Historical Data with Go Source: https://context7.com/sonirico/go-hyperliquid/llms.txt Retrieves user fills, funding history, and ledger updates using the Info client. Requires a valid context and API URL. ```go package main import ( "context" "fmt" "log" "time" hyperliquid "github.com/sonirico/go-hyperliquid" ) func main() { ctx := context.Background() info := hyperliquid.NewInfo(ctx, hyperliquid.MainnetAPIURL, true, nil, nil, nil) address := "0xYourAddress" endTime := time.Now().UnixMilli() startTime := endTime - (7 * 24 * time.Hour).Milliseconds() // 7 days ago // Get user fills fills, err := info.UserFillsByTime(ctx, address, startTime, &endTime, nil) if err != nil { log.Fatal(err) } fmt.Printf("Fills in last 7 days: %d\n", len(fills)) for _, fill := range fills[:min(3, len(fills))] { fmt.Printf(" %s %s @ %s, Size: %s, PnL: %s\n", fill.Coin, fill.Side, fill.Px, fill.Sz, fill.ClosedPnl) } // Get funding history for a coin fundingHistory, err := info.FundingHistory(ctx, "BTC", startTime, &endTime) if err != nil { log.Fatal(err) } fmt.Printf("Funding history entries: %d\n", len(fundingHistory)) // Get user funding history userFunding, err := info.UserFundingHistory(ctx, address, startTime, &endTime) if err != nil { log.Fatal(err) } fmt.Printf("User funding entries: %d\n", len(userFunding)) // Get non-funding ledger updates ledgerUpdates, err := info.UserNonFundingLedgerUpdates(ctx, address, startTime, &endTime) if err != nil { log.Fatal(err) } fmt.Printf("Ledger updates: %d\n", len(ledgerUpdates)) } func min(a, b int) int { if a < b { return a } return b } ``` -------------------------------- ### Place Market Orders with Slippage Protection in Go Source: https://context7.com/sonirico/go-hyperliquid/llms.txt Opens and closes market positions using the MarketOpen and MarketClose methods with defined slippage tolerance. Requires a valid ECDSA private key for exchange initialization. ```go package main import ( "context" "fmt" "log" "github.com/ethereum/go-ethereum/crypto" hyperliquid "github.com/sonirico/go-hyperliquid" ) func main() { privateKey, _ := crypto.HexToECDSA("your-private-key") exchange := hyperliquid.NewExchange( context.Background(), privateKey, hyperliquid.MainnetAPIURL, nil, "", "", nil, nil, ) ctx := context.Background() // Open a long position with 1% slippage tolerance result, err := exchange.MarketOpen( ctx, "ETH", // coin true, // isBuy (true = long, false = short) 0.1, // size nil, // price (nil = use mid price) 0.01, // slippage (1%) nil, // client order ID nil, // builder info ) if err != nil { log.Fatal(err) } fmt.Printf("Market order result: %+v\n", result) // Close the position with slippage protection closeResult, err := exchange.MarketClose( ctx, "ETH", // coin nil, // size (nil = close entire position) nil, // price 0.01, // slippage nil, // client order ID nil, // builder info ) if err != nil { log.Fatal(err) } fmt.Printf("Position closed: %+v\n", closeResult) } ``` -------------------------------- ### Configure Debug Mode and HTTP Client in Go Source: https://context7.com/sonirico/go-hyperliquid/llms.txt Enables debug logging and custom HTTP client settings for the Exchange and WebSocket clients. Useful for debugging network issues or setting custom timeouts. ```go package main import ( "context" "log" "net/http" "time" "github.com/ethereum/go-ethereum/crypto" hyperliquid "github.com/sonirico/go-hyperliquid" ) func main() { privateKey, _ := crypto.HexToECDSA("your-private-key") // Custom HTTP client with timeout httpClient := &http.Client{ Timeout: 30 * time.Second, } // Create exchange with debug mode and custom HTTP client exchange := hyperliquid.NewExchange( context.Background(), privateKey, hyperliquid.MainnetAPIURL, nil, "", "", nil, nil, hyperliquid.ExchangeOptDebugMode(), hyperliquid.ExchangeOptClientOptions( hyperliquid.ClientOptHTTPClient(httpClient), ), ) // WebSocket with debug mode and custom read timeout ws := hyperliquid.NewWebsocketClient( hyperliquid.MainnetAPIURL, hyperliquid.WsOptDebugMode(), hyperliquid.WsOptReadTimeout(120*time.Second), ) log.Printf("Debug mode enabled for exchange and websocket") _ = exchange _ = ws } ``` -------------------------------- ### Query Account State and Positions in Go Source: https://context7.com/sonirico/go-hyperliquid/llms.txt Retrieves perpetuals and spot account balances, active positions, and order statuses. Uses the Info client for read-only operations. ```go package main import ( "context" "fmt" "log" hyperliquid "github.com/sonirico/go-hyperliquid" ) func main() { ctx := context.Background() info := hyperliquid.NewInfo(ctx, hyperliquid.MainnetAPIURL, true, nil, nil, nil) address := "0xYourAddress" // Get perpetuals account state userState, err := info.UserState(ctx, address) if err != nil { log.Fatal(err) } fmt.Printf("Account Value: %s\n", userState.MarginSummary.AccountValue) fmt.Printf("Withdrawable: %s\n", userState.Withdrawable) // List positions for _, pos := range userState.AssetPositions { fmt.Printf("Position: %s, Size: %s, Entry: %s, PnL: %s\n", pos.Position.Coin, pos.Position.Szi, pos.Position.EntryPx, pos.Position.UnrealizedPnl) } // Get spot account state spotState, err := info.SpotUserState(ctx, address) if err != nil { log.Fatal(err) } for _, balance := range spotState.Balances { fmt.Printf("Token: %s, Hold: %s, Total: %s\n", balance.Token, balance.Hold, balance.Total) } // Get open orders orders, err := info.OpenOrders(ctx, address) if err != nil { log.Fatal(err) } fmt.Printf("Open orders: %d\n", len(orders)) // Query specific order status orderStatus, err := info.QueryOrderByOid(ctx, address, 12345) if err != nil { log.Fatal(err) } fmt.Printf("Order status: %+v\n", orderStatus) } ``` -------------------------------- ### Execute USD and Spot Transfers Source: https://context7.com/sonirico/go-hyperliquid/llms.txt Performs transfers of USD, spot tokens, and USD class between perp and spot accounts. Requires an initialized exchange client with a valid private key. ```go package main import ( "context" "fmt" "log" "github.com/ethereum/go-ethereum/crypto" hyperliquid "github.com/sonirico/go-hyperliquid" ) func main() { privateKey, _ := crypto.HexToECDSA("your-private-key") exchange := hyperliquid.NewExchange( context.Background(), privateKey, hyperliquid.MainnetAPIURL, nil, "", "", nil, nil, ) ctx := context.Background() // Transfer USD to another address result, err := exchange.UsdTransfer(ctx, 100.0, "0xRecipientAddress") if err != nil { log.Fatal(err) } fmt.Printf("USD Transfer: %+v\n", result) // Transfer spot tokens spotResult, err := exchange.SpotTransfer(ctx, 10.0, "0xRecipientAddress", "USDC") if err != nil { log.Fatal(err) } fmt.Printf("Spot Transfer: %+v\n", spotResult) // Transfer USD class between perp and spot classResult, err := exchange.UsdClassTransfer(ctx, 50.0, true) // true = to perp if err != nil { log.Fatal(err) } fmt.Printf("USD Class Transfer: %+v\n", classResult) } ``` -------------------------------- ### Implement Custom Signers in Go Source: https://context7.com/sonirico/go-hyperliquid/llms.txt Defines custom L1 and UserSigned action signers for hardware wallet or HSM integration. Pass these implementations to the Exchange constructor using functional options. ```go package main import ( "context" "fmt" "log" "github.com/ethereum/go-ethereum/crypto" "github.com/ethereum/go-ethereum/signer/core/apitypes" hyperliquid "github.com/sonirico/go-hyperliquid" ) // CustomL1Signer implements hyperliquid.L1ActionSigner type CustomL1Signer struct { // Add your HSM client or hardware wallet connection here } func (s *CustomL1Signer) SignL1Action( ctx context.Context, action any, vaultAddress string, timestamp int64, expiresAfter *int64, isMainnet bool, ) (hyperliquid.SignatureResult, error) { // Implement your custom signing logic here // For example, delegate to a hardware wallet or HSM return hyperliquid.SignatureResult{}, fmt.Errorf("not implemented") } // CustomUserSignedSigner implements hyperliquid.UserSignedActionSigner type CustomUserSignedSigner struct{} func (s *CustomUserSignedSigner) SignUserSignedAction( ctx context.Context, action map[string]any, payloadTypes []apitypes.Type, primaryType string, isMainnet bool, ) (hyperliquid.SignatureResult, error) { // Implement your custom signing logic here return hyperliquid.SignatureResult{}, fmt.Errorf("not implemented") } func main() { privateKey, _ := crypto.HexToECDSA("your-private-key") // Use custom signers with Exchange exchange := hyperliquid.NewExchange( context.Background(), privateKey, hyperliquid.MainnetAPIURL, nil, "", "", nil, nil, hyperliquid.ExchangeOptL1Signer(&CustomL1Signer{}), hyperliquid.ExchangeOptUserSignedSigner(&CustomUserSignedSigner{}), ) log.Printf("Exchange with custom signers: %+v", exchange) } ``` -------------------------------- ### Subscribe to Real-time BTC Trades Source: https://context7.com/sonirico/go-hyperliquid/llms.txt Connects to the Hyperliquid WebSocket API and subscribes to real-time trade data for Bitcoin (BTC). Handles incoming trades and prints their details. Requires a 60-second context timeout. ```go package main import ( "context" "fmt" "log" "time" hyperliquid "github.com/sonirico/go-hyperliquid" ) func main() { ws := hyperliquid.NewWebsocketClient(hyperliquid.MainnetAPIURL) ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second) defer cancel() if err := ws.Connect(ctx); err != nil { log.Fatal(err) } defer ws.Close() // Subscribe to BTC trades sub, err := ws.Trades( hyperliquid.TradesSubscriptionParams{Coin: "BTC"}, func(trades []hyperliquid.Trade, err error) { if err != nil { log.Printf("Error: %v", err) return } for _, trade := range trades { fmt.Printf("Trade: %s %s @ %s, Size: %s\n", trade.Coin, trade.Side, trade.Px, trade.Sz) } }, ) if err != nil { log.Fatal(err) } defer sub.Close() fmt.Println("Listening for trades...") <-ctx.Done() } ``` -------------------------------- ### Subscribe to Real-time ETH L2 Order Book Updates Source: https://context7.com/sonirico/go-hyperliquid/llms.txt Connects to the Hyperliquid WebSocket API and subscribes to Level 2 order book updates for Ethereum (ETH) with 5 significant figures and no mantissa aggregation. Prints the best bid and ask prices and sizes. Uses a 30-second context timeout. ```go package main import ( "context" "fmt" "log" "time" hyperliquid "github.com/sonirico/go-hyperliquid" ) func main() { ws := hyperliquid.NewWebsocketClient(hyperliquid.MainnetAPIURL) ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) defer cancel() if err := ws.Connect(ctx); err != nil { log.Fatal(err) } defer ws.Close() // Subscribe to ETH L2 book sub, err := ws.L2Book( hyperliquid.L2BookSubscriptionParams{ Coin: "ETH", NSigFigs: 5, // Number of significant figures Mantissa: 0, // Mantissa for aggregation }, func(book hyperliquid.L2Book, err error) { if err != nil { log.Printf("Error: %v", err) return } fmt.Printf("L2 Book Update - Time: %d\n", book.Time) if len(book.Levels) >= 2 && len(book.Levels[0]) > 0 { bid := book.Levels[0][0] ask := book.Levels[1][0] fmt.Printf(" Best Bid: %.2f x %.4f\n", bid.Px, bid.Sz) fmt.Printf(" Best Ask: %.2f x %.4f\n", ask.Px, ask.Sz) } }, ) if err != nil { log.Fatal(err) } defer sub.Close() <-ctx.Done() } ``` -------------------------------- ### Manage Sub-Accounts Source: https://context7.com/sonirico/go-hyperliquid/llms.txt Handles creation, querying, and fund transfers for sub-accounts. Transfers support both USD and spot tokens using deposit/withdrawal flags. ```go package main import ( "context" "fmt" "log" "github.com/ethereum/go-ethereum/crypto" hyperliquid "github.com/sonirico/go-hyperliquid" ) func main() { privateKey, _ := crypto.HexToECDSA("your-private-key") exchange := hyperliquid.NewExchange( context.Background(), privateKey, hyperliquid.MainnetAPIURL, nil, "", "", nil, nil, ) ctx := context.Background() // Create a sub-account createResult, err := exchange.CreateSubAccount(ctx, "Trading Bot 1") if err != nil { log.Fatal(err) } fmt.Printf("Sub-account created: %+v\n", createResult) // Query sub-accounts info := exchange.Info() subAccounts, err := info.QuerySubAccounts(ctx, "0xYourAddress") if err != nil { log.Fatal(err) } for _, sub := range subAccounts { fmt.Printf("Sub-account: %s - %s\n", sub.SubAccountUser, sub.Name) } // Transfer USD to sub-account transferResult, err := exchange.SubAccountTransfer( ctx, "0xSubAccountAddress", true, // isDeposit (true = deposit to sub, false = withdraw) 1000, // USD amount ) if err != nil { log.Fatal(err) } fmt.Printf("Transfer to sub-account: %+v\n", transferResult) // Transfer spot tokens to sub-account spotTransfer, err := exchange.SubAccountSpotTransfer( ctx, "0xSubAccountAddress", true, // isDeposit "USDC", 100.0, ) if err != nil { log.Fatal(err) } fmt.Printf("Spot transfer to sub-account: %+v\n", spotTransfer) } ``` -------------------------------- ### Place Limit Orders Source: https://context7.com/sonirico/go-hyperliquid/llms.txt Submit limit orders using the Exchange client with specified time-in-force options like GTC or IOC. ```go package main import ( "context" "fmt" "log" "github.com/ethereum/go-ethereum/crypto" hyperliquid "github.com/sonirico/go-hyperliquid" ) func main() { privateKey, _ := crypto.HexToECDSA("your-private-key") exchange := hyperliquid.NewExchange( context.Background(), privateKey, hyperliquid.MainnetAPIURL, nil, "", "", nil, nil, ) // Place a limit buy order orderReq := hyperliquid.CreateOrderRequest{ Coin: "BTC", IsBuy: true, Size: 0.001, Price: 40000.0, ReduceOnly: false, OrderType: hyperliquid.OrderType{ Limit: &hyperliquid.LimitOrderType{ Tif: hyperliquid.TifGtc, // Good-Til-Canceled }, }, } result, err := exchange.Order(context.Background(), orderReq, nil) if err != nil { log.Fatal(err) } if result.Resting != nil { fmt.Printf("Order placed: OID=%d, Status=%s\n", result.Resting.Oid, result.Resting.Status) } else if result.Filled != nil { fmt.Printf("Order filled: AvgPx=%s, TotalSz=%s\n", result.Filled.AvgPx, result.Filled.TotalSz) } } ``` -------------------------------- ### Subscribe to Real-time Order Updates Source: https://context7.com/sonirico/go-hyperliquid/llms.txt Connects to the Hyperliquid WebSocket API and subscribes to real-time updates for a specific user's orders. Requires the user's address and prints order details and status. Uses a 300-second context timeout. ```go package main import ( "context" "fmt" "log" "time" hyperliquid "github.com/sonirico/go-hyperliquid" ) func main() { ws := hyperliquid.NewWebsocketClient(hyperliquid.MainnetAPIURL) ctx, cancel := context.WithTimeout(context.Background(), 300*time.Second) defer cancel() if err := ws.Connect(ctx); err != nil { log.Fatal(err) } defer ws.Close() address := "0xYourAddress" // Subscribe to order updates sub, err := ws.OrderUpdates( hyperliquid.OrderUpdatesSubscriptionParams{User: address}, func(orders []hyperliquid.WsOrder, err error) { if err != nil { log.Printf("Error: %v", err) return } for _, order := range orders { fmt.Printf("Order Update: %s %s OID=%d Status=%s\n", order.Order.Coin, order.Order.Side, order.Order.Oid, order.Status) } }, ) if err != nil { log.Fatal(err) } defer sub.Close() <-ctx.Done() } ``` -------------------------------- ### Trigger project release Source: https://github.com/sonirico/go-hyperliquid/blob/master/CONTRIBUTING.md Create and push a new Git tag to initiate the automated release process via GitHub Actions. ```bash git tag -a v1.0.0 -m "Release v1.0.0" git push origin v1.0.0 ``` -------------------------------- ### Subscribe to Real-time BTC Candlestick Data Source: https://context7.com/sonirico/go-hyperliquid/llms.txt Connects to the Hyperliquid WebSocket API and subscribes to 1-minute candlestick (OHLCV) data for Bitcoin (BTC). Prints the open, high, low, close, and volume for each candle. Uses a 120-second context timeout. ```go package main import ( "context" "fmt" "log" "time" hyperliquid "github.com/sonirico/go-hyperliquid" ) func main() { ws := hyperliquid.NewWebsocketClient(hyperliquid.MainnetAPIURL) ctx, cancel := context.WithTimeout(context.Background(), 120*time.Second) defer cancel() if err := ws.Connect(ctx); err != nil { log.Fatal(err) } defer ws.Close() // Subscribe to 1-minute BTC candles sub, err := ws.Candles( hyperliquid.CandlesSubscriptionParams{ Coin: "BTC", Interval: "1m", // 1m, 5m, 15m, 1h, 4h, 1d }, func(candle hyperliquid.Candle, err error) { if err != nil { log.Printf("Error: %v", err) return } fmt.Printf("Candle [%s]: O=%s H=%s L=%s C=%s V=%s\n", candle.Symbol, candle.Open, candle.High, candle.Low, candle.Close, candle.Volume) }, ) if err != nil { log.Fatal(err) } defer sub.Close() <-ctx.Done() } ``` -------------------------------- ### Modify Orders Source: https://context7.com/sonirico/go-hyperliquid/llms.txt Update existing orders by providing a new size or price. Supports both single and bulk modifications. ```go package main import ( "context" "fmt" "log" "github.com/ethereum/go-ethereum/crypto" hyperliquid "github.com/sonirico/go-hyperliquid" ) func main() { privateKey, _ := crypto.HexToECDSA("your-private-key") exchange := hyperliquid.NewExchange( context.Background(), privateKey, hyperliquid.MainnetAPIURL, nil, "", "", nil, nil, ) oid := int64(12345) modifyReq := hyperliquid.ModifyOrderRequest{ Oid: &oid, Order: hyperliquid.CreateOrderRequest{ Coin: "BTC", IsBuy: true, Size: 0.002, // New size Price: 41000.0, // New price OrderType: hyperliquid.OrderType{ Limit: &hyperliquid.LimitOrderType{Tif: hyperliquid.TifGtc}, }, }, } result, err := exchange.ModifyOrder(context.Background(), modifyReq) if err != nil { log.Fatal(err) } fmt.Printf("Modified order: %+v\n", result) // Bulk modify multiple orders modifyRequests := []hyperliquid.ModifyOrderRequest{modifyReq} bulkResult, err := exchange.BulkModifyOrders(context.Background(), modifyRequests) if err != nil { log.Fatal(err) } fmt.Printf("Modified %d orders\n", len(bulkResult)) } ``` -------------------------------- ### Cancel Orders Source: https://context7.com/sonirico/go-hyperliquid/llms.txt Cancel orders using either the order ID, client order ID, or perform a bulk cancellation. ```go package main import ( "context" "fmt" "log" "github.com/ethereum/go-ethereum/crypto" hyperliquid "github.com/sonirico/go-hyperliquid" ) func main() { privateKey, _ := crypto.HexToECDSA("your-private-key") exchange := hyperliquid.NewExchange( context.Background(), privateKey, hyperliquid.MainnetAPIURL, nil, "", "", nil, nil, ) ctx := context.Background() // Cancel by order ID oid := int64(12345) result, err := exchange.Cancel(ctx, "BTC", oid) if err != nil { log.Fatal(err) } fmt.Printf("Cancel result: %+v\n", result) // Cancel by client order ID cloid := "0x06c60000000000000000000000003f5a" cloidResult, err := exchange.CancelByCloid(ctx, "BTC", cloid) if err != nil { log.Fatal(err) } fmt.Printf("Cancel by CLOID result: %+v\n", cloidResult) // Bulk cancel multiple orders cancels := []hyperliquid.CancelOrderRequest{ {Coin: "BTC", OrderID: 12345}, {Coin: "ETH", OrderID: 67890}, } bulkResult, err := exchange.BulkCancel(ctx, cancels) if err != nil { log.Fatal(err) } fmt.Printf("Bulk cancel: %d orders processed\n", len(bulkResult.Data.Statuses)) } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.