backpackgo

package module
v0.0.0-...-85933a5 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 13, 2025 License: MIT Imports: 20 Imported by: 0

README

backpack-go

A Go SDK for Backpack Exchange, API Docs: backpack API docs

Support Backpack API version: 2025-04-22

  • ✅ Public REST API
  • ✅ Authenticated APIs Example
  • ✅ Public Websocket API
  • ✅ Authenticated Websocket API

Installation

To use this SDK in your Go project, you can add it as a dependency with:

go get -u github.com/UnipayFI/backpack-go

Usage

Initialize the REST client
package main

import (
	backpackgo "github.com/UnipayFI/backpack-go"
	"github.com/UnipayFI/backpack-go/rest"
)

func main() {
	// Create a client with default settings
	client := backpackgo.NewRESTClient()

	// Or create a client with custom settings
	// support:
	// - WithAPIToken(apiKey, apiSecret string)
	// - WithBaseURL(baseURL string)
	// - WithWindows(windows time.Duration)
	// - WithTimeout(timeout time.Duration)
	// - WithRetry(retry int)
	// - WithProxy(proxy string)
	clientWithAuth := backpackgo.NewRESTClient(
		rest.WithAPIToken("YOUR_API_KEY", "YOUR_API_SECRET"),
	)

	// Now you can use the client to call APIs
}
Public REST APIs Example
// Get market data
markets, err := client.GetMarkets()
if err != nil {
    // Handle error
}
fmt.Printf("Markets count: %d\n", len(markets))

// Get ticker for a specific symbol
ticker, err := client.GetTicker("BTC_USDC")
if err != nil {
    // Handle error
}
fmt.Printf("%s price: %v\n", ticker.Symbol, ticker.FirstPrice)

// Get klines (candlestick) data
endTime := time.Now()
startTime := endTime.Add(-24 * time.Hour) // Last 24 hours
klines, err := client.GetKlines("BTC_USDC", options.KLineInterval1h, startTime, endTime)
if err != nil {
    // Handle error
}
Authenticated REST APIs Example
// Get account information (requires authentication)
account, err := clientWithAuth.GetAccount()
if err != nil {
    // Handle error
}
fmt.Printf("Account: %+v\n", account)

// also support:
// - ExecuteMarketOrder(symbol, side, quantity)
// - ExecuteLimitOrder(symbol, side, price, quantity)
// - ExecuteConditionalLimitOrder(symbol, side, triggerPrice, price, quantity)
order, err := clientWithAuth.ExecuteLimitOrder(
    "BTC_USDC",
    options.Buy,
    0.001, // quantity
    50000, // price
)
if err != nil {
    // Handle error
}
fmt.Printf("Order placed: %+v\n", order)

// Get open orders
symbol := "BTC_USDC"
marketType := options.Spot
orders, err := clientWithAuth.GetOrders(&symbol, &marketType)
if err != nil {
    // Handle error
}
fmt.Printf("Open orders: %d\n", len(orders))
Initialize the Websocket client
package main

import (
    "fmt"
    
    "github.com/UnipayFI/backpack-go"
)

func main() {
    // Create a client with default settings
    client := backpackgo.NewRESTClient()
    
    // Or create a client with custom settings
    // support:
    // - WithAPIToken(apiKey, apiSecret string)
    // - WithBaseURL(baseURL string)
    // - WithWindows(windows time.Duration)
    // - WithProxy(proxy string)
    clientWithAuth := backpackgo.NewRESTClient(
        rest.WithAPIToken("YOUR_API_KEY", "YOUR_API_SECRET"),
        rest.WithTimeout(10 * time.Second),
    )
    
    // Now you can use the client to call APIs
}
Websocket APIs Example
err = client.SubscribeTrade(symbol, func(trade *models.TradeUpdate) {
    fmt.Println(tade)
})
if err != nil {
    fmt.Errorf("subscribe trade faild: %+v", err)
}

_ = client.Unsubscribe(fmt.Sprintf("trade.%s", symbol+"_PERP"))

// should With API_KEY & API_SECRET
err = client.SubscribeOrderUpdate(func(order *models.OrderUpdate) {
    fmt.Println(order)
})
Advanced: Custom Request
Custom REST Request

You can make custom REST requests with your own defined structures if you need to access endpoints that are not covered by the SDK or if you want more control over the request/response handling:

// Define your custom response structure
type Order struct {
    ID        string  `json:"id"`
    Price     float64 `json:"price"`
    Quantity  float64 `json:"quantity"`
    Timestamp int64   `json:"timestamp"`
    // Add any other fields you need
}

// Make a GET request with custom path and response type
customOrderPath := "/api/v1/custom_order"
params := map[string]string{"param1": "value1", "param2": "value2"}
response, err := backpackgo.Request[*Order](client, "GET", customOrderPath, params)
if err != nil {
    // Handle error
}
fmt.Printf("Custom response: %+v\n", response)

// Make a POST request with custom path and payload
postPayload := map[string]any{
    "key1": "value1",
    "key2": 42,
}
postResponse, err := backpackgo.Request[*CustomResponse](client, "POST", customPath, postPayload)
if err != nil {
    // Handle error
}
Custom WebSocket Request

For WebSocket, you can subscribe to custom stream or handle custom message formats:

// Define your custom message structure
type CustomWSMessage struct {
    EventType string  `json:"e"`
    Symbol    string  `json:"s"`
    Value     float64 `json:"v"`
    // Add any other fields you need
}

// Subscribe to a custom stream with your handler
customStream := "custom.stream.name"
err = client.SubscribePublicStream(customStream, new(CustomWSMessage), func(msg *CustomWSMessage) {
    fmt.Printf("Received custom message: %+v\n", msg)
})
if err != nil {
    fmt.Errorf("subscribe custom stream failed: %+v", err)
}

// For authenticated streams
err = client.SubscribePrivateStream(customStream, new(CustomWSMessage), func(msg *CustomWSMessage) {
    fmt.Printf("Received custom auth message: %+v\n", msg)
})

This flexibility allows you to work with new API endpoints or custom implementations without waiting for SDK updates.

License

feeeei/backpack-go is released under the MIT License.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrInvalidAPIKeyOrSecret = errors.New("invalid API key or secret")
)

Functions

func Request

func Request(api *BackpackREST, method, path string, params map[string]any, headers ...map[string]string) (*resty.Response, error)

func RequestWithAuth

func RequestWithAuth(api *BackpackREST, method, url string, instruction string, params map[string]any) (resp *resty.Response, err error)

func Response

func Response[T any](response *resty.Response, e error) (result T, err error)

func SubscribePrivateStream

func SubscribePrivateStream[T any](client *BackpackWebsocket, stream string, newable models.Newable, handler func(T)) error

func SubscribePublicStream

func SubscribePublicStream[T any](client *BackpackWebsocket, stream string, newable models.Newable, handler func(T)) error

Types

type BackpackError

type BackpackError struct {
	Code    string `json:"code"`
	Message string `json:"message"`
}

func (*BackpackError) Error

func (e *BackpackError) Error() string

type BackpackREST

type BackpackREST struct {
	BaseURL   string
	APIKey    string
	APISecret string
	Windows   time.Duration
	// contains filtered or unexported fields
}

func NewRESTClient

func NewRESTClient(options ...rest.Options) *BackpackREST

func (*BackpackREST) CancelOrderByClientID

func (b *BackpackREST) CancelOrderByClientID(symbol string, clientID uint32) (*models.Order, error)

func (*BackpackREST) CancelOrderByOrderID

func (b *BackpackREST) CancelOrderByOrderID(symbol string, orderID string) (*models.Order, error)

func (*BackpackREST) CancelOrders

func (b *BackpackREST) CancelOrders(symbol string, marketType ...options.OrderType) ([]*models.Order, error)

func (*BackpackREST) ExecuteBorrowLend

func (b *BackpackREST) ExecuteBorrowLend(asset string, side options.BorrowLendSide, quantity float64) error

func (*BackpackREST) ExecuteConditionalLimitOrder

func (b *BackpackREST) ExecuteConditionalLimitOrder(symbol string, side options.Side, triggerPrice float64, price float64, quantity float64, opts ...options.OrderOptionFn) (*models.Order, error)

ExecuteConditionalLimitOrder executes a conditional limit order (stop limit order) symbol: Trading pair (e.g. "BTC_USDC") side: Bid/Buy or Ask/Sell triggerPrice: The price at which the limit order will be triggered price: The limit price after trigger quantity: The amount to trade opts: Optional parameters like clientId, timeInForce etc.

func (*BackpackREST) ExecuteLimitOrder

func (b *BackpackREST) ExecuteLimitOrder(symbol string, side options.Side, price float64, quantity float64, opts ...options.OrderOptionFn) (*models.Order, error)

ExecuteLimitOrder executes a limit order symbol: Trading pair (e.g. "BTC_USDC") side: Bid/Buy or Ask/Sell price: The limit price quantity: The amount to trade opts: Optional parameters like clientId, timeInForce etc.

func (*BackpackREST) ExecuteMarketOrder

func (b *BackpackREST) ExecuteMarketOrder(symbol string, side options.Side, quantity float64, opts ...options.OrderOptionFn) (*models.Order, error)

ExecuteMarketOrder executes a market order symbol: Trading pair (e.g. "BTC_USDC") side: Bid/Buy or Ask/Sell quantity: The amount to trade opts: Optional parameters like clientId, timeInForce etc.

func (*BackpackREST) GetAccount

func (b *BackpackREST) GetAccount() (*models.Account, error)

func (*BackpackREST) GetAccountCollateral

func (b *BackpackREST) GetAccountCollateral() (*models.Collateral, error)

func (*BackpackREST) GetAccountMaxBorrow

func (b *BackpackREST) GetAccountMaxBorrow(asset string) (*models.AccountBorrowLimit, error)

func (*BackpackREST) GetAccountMaxOrder

func (b *BackpackREST) GetAccountMaxOrder(symbol string, side options.Side, args ...options.AccountOrderLimitOptions) (*models.AccountOrderLimit, error)

func (*BackpackREST) GetAccountMaxWithdrawal

func (b *BackpackREST) GetAccountMaxWithdrawal(asset string, args ...options.AccountWithdrawalLimitOptions) (*models.AccountWithdrawalLimit, error)

func (*BackpackREST) GetBalance

func (b *BackpackREST) GetBalance() (map[string]*models.AssetBalance, error)

func (*BackpackREST) GetBorrowLendHistory

func (b *BackpackREST) GetBorrowLendHistory(options ...options.BorrowHistoryOptions) ([]*models.BorrowLendHistory, error)

func (*BackpackREST) GetBorrowLendMarkets

func (b *BackpackREST) GetBorrowLendMarkets() ([]*models.BorrowLendMarket, error)

func (*BackpackREST) GetBorrowLendMarketsHistory

func (b *BackpackREST) GetBorrowLendMarketsHistory(interval options.BorrowLendMarketHistoryInterval, symbol ...string) ([]*models.BorrowLendMarketHistory, error)

symbol is optional, ex USDT、USDC、SOL...

func (*BackpackREST) GetBorrowLendPositions

func (b *BackpackREST) GetBorrowLendPositions() ([]*models.BorrowLend, error)

func (*BackpackREST) GetBorrowPositionsHistory

func (b *BackpackREST) GetBorrowPositionsHistory(options ...options.BorrowPostionHistoryOptions) ([]*models.BorrowPositionHistory, error)

func (*BackpackREST) GetDepositAddress

func (b *BackpackREST) GetDepositAddress(blockchain string) (*models.DepositAddress, error)

func (*BackpackREST) GetDeposits

func (b *BackpackREST) GetDeposits(filter ...options.DateFilter) ([]*models.Deposit, error)

func (*BackpackREST) GetDepth

func (b *BackpackREST) GetDepth(symbol string) (*models.Depth, error)

func (*BackpackREST) GetFillHistory

func (b *BackpackREST) GetFillHistory(options ...options.FillHistoryOptions) ([]*models.FillHistory, error)

func (*BackpackREST) GetFundingHistory

func (b *BackpackREST) GetFundingHistory(options ...options.FundingHistoryOptions) ([]*models.FundingHistory, error)

func (*BackpackREST) GetFundingRates

func (b *BackpackREST) GetFundingRates(symbol string) (*models.PageHeaders, []*models.FundingRate, error)

func (*BackpackREST) GetInterestHistory

func (b *BackpackREST) GetInterestHistory(options ...options.InterestHistoryOptions) ([]*models.InterestHistory, error)

func (*BackpackREST) GetKlines

func (b *BackpackREST) GetKlines(symbol string, interval options.KLineInterval, startTime time.Time, endTime ...time.Time) ([]*models.Kline, error)

endTime is optional

func (*BackpackREST) GetMarkPrices

func (b *BackpackREST) GetMarkPrices(symbol ...string) ([]*models.MarkPrice, error)

symbol is optional

func (*BackpackREST) GetMarket

func (b *BackpackREST) GetMarket(symbol string) (*models.Market, error)

func (*BackpackREST) GetMarketAssets

func (b *BackpackREST) GetMarketAssets() ([]*models.MarketAssets, error)

func (*BackpackREST) GetMarketCollateral

func (b *BackpackREST) GetMarketCollateral() ([]*models.MarketCollateral, error)

func (*BackpackREST) GetMarkets

func (b *BackpackREST) GetMarkets() ([]*models.Market, error)

func (*BackpackREST) GetOpenInterest

func (b *BackpackREST) GetOpenInterest(symbol ...string) ([]*models.OpenInterest, error)

func (*BackpackREST) GetOrderByClientID

func (b *BackpackREST) GetOrderByClientID(symbol string, clientID int) (*models.Order, error)

func (*BackpackREST) GetOrderByOrderID

func (b *BackpackREST) GetOrderByOrderID(symbol, orderID string) (*models.Order, error)

func (*BackpackREST) GetOrders

func (b *BackpackREST) GetOrders(symbol *string, marketType *options.MarketType) ([]*models.Order, error)

symbol is optional marketType is optional

func (*BackpackREST) GetOrdersHistory

func (b *BackpackREST) GetOrdersHistory(options ...options.OrderHistoryOptions) ([]*models.OrderHistory, error)

func (*BackpackREST) GetPnlHistory

func (b *BackpackREST) GetPnlHistory(options ...options.PnlHistoryOptions) ([]*models.PnlHistory, error)

func (*BackpackREST) GetPositions

func (b *BackpackREST) GetPositions() ([]*models.Position, error)

func (*BackpackREST) GetSettlementHistory

func (b *BackpackREST) GetSettlementHistory(options ...options.SettlementHistoryOptions) ([]*models.SettlementHistory, error)

func (*BackpackREST) GetStatus

func (b *BackpackREST) GetStatus() (*models.Status, error)

func (*BackpackREST) GetTicker

func (b *BackpackREST) GetTicker(symbol string, interval ...options.TickerInterval) (*models.Ticker, error)

interval is optional

func (*BackpackREST) GetTickers

func (b *BackpackREST) GetTickers(interval ...options.TickerInterval) ([]*models.Ticker, error)

interval is optional

func (*BackpackREST) GetTime

func (b *BackpackREST) GetTime() (*time.Time, error)

func (*BackpackREST) GetTrades

func (b *BackpackREST) GetTrades(symbol string, limitoffset ...options.LimitOffset) ([]*models.Trade, error)

limitoffset is optional

func (*BackpackREST) GetTradesHistory

func (b *BackpackREST) GetTradesHistory(symbol string, limit ...int) ([]*models.Trade, error)

func (*BackpackREST) GetWithdrawals

func (b *BackpackREST) GetWithdrawals(filter ...options.DateFilter) ([]*models.Withdrawal, error)

func (*BackpackREST) Ping

func (b *BackpackREST) Ping() error

func (*BackpackREST) RequestForQuote

func (b *BackpackREST) RequestForQuote(rfqId string, bidPrice, askPrice float64, clientID *int) (*models.Quote, error)

func (*BackpackREST) RequestWithdrawal

func (b *BackpackREST) RequestWithdrawal(asset string, quantity float64, address, blockchain string, options ...options.WithdrawalOptions) (*models.Withdrawal, error)

func (*BackpackREST) UpdateAccount

func (b *BackpackREST) UpdateAccount(account *models.AccountUpdateble) error

type BackpackWebsocket

type BackpackWebsocket struct {
	BaseURL   string
	APIKey    string
	APISecret string
	Windows   time.Duration
	// contains filtered or unexported fields
}

func NewBackpackWebsocket

func NewBackpackWebsocket(options ...ops.Options) (*BackpackWebsocket, error)

func (*BackpackWebsocket) Subscribe200msDepth

func (client *BackpackWebsocket) Subscribe200msDepth(symbol string, handler func(*models.DepthUpdate)) error

func (*BackpackWebsocket) SubscribeBookTicker

func (client *BackpackWebsocket) SubscribeBookTicker(symbol string, handler func(*models.BookTickerUpdate)) error

func (*BackpackWebsocket) SubscribeDepth

func (client *BackpackWebsocket) SubscribeDepth(symbol string, handler func(*models.DepthUpdate)) error

func (*BackpackWebsocket) SubscribeKLine

func (client *BackpackWebsocket) SubscribeKLine(interval options.KLineInterval, symbol string, handler func(*models.KLineUpdate)) error

func (*BackpackWebsocket) SubscribeLiquidation

func (client *BackpackWebsocket) SubscribeLiquidation(symbol string, handler func(*models.LiquidationUpdate)) error

func (*BackpackWebsocket) SubscribeMarkPrice

func (client *BackpackWebsocket) SubscribeMarkPrice(symbol string, handler func(*models.MarkPriceUpdate)) error

func (*BackpackWebsocket) SubscribeOpenInterest

func (client *BackpackWebsocket) SubscribeOpenInterest(symbol string, handler func(*models.OpenInterestUpdate)) error

func (*BackpackWebsocket) SubscribeOrderUpdate

func (client *BackpackWebsocket) SubscribeOrderUpdate(handler func(*models.OrderUpdate)) error

func (*BackpackWebsocket) SubscribeOrderUpdateWithSymbol

func (client *BackpackWebsocket) SubscribeOrderUpdateWithSymbol(symbol string, handler func(*models.OrderUpdate)) error

func (*BackpackWebsocket) SubscribePositionUpdate

func (client *BackpackWebsocket) SubscribePositionUpdate(handler func(*models.PositionUpdate)) error

func (*BackpackWebsocket) SubscribePositionUpdateWithSymbol

func (client *BackpackWebsocket) SubscribePositionUpdateWithSymbol(symbol string, handler func(*models.PositionUpdate)) error

func (*BackpackWebsocket) SubscribeRFQUpdate

func (client *BackpackWebsocket) SubscribeRFQUpdate(handler func(*models.RFQUpdate)) error

func (*BackpackWebsocket) SubscribeRFQUpdateWithSymbol

func (client *BackpackWebsocket) SubscribeRFQUpdateWithSymbol(symbol string, handler func(*models.RFQUpdate)) error

func (*BackpackWebsocket) SubscribeTicker

func (client *BackpackWebsocket) SubscribeTicker(symbol string, handler func(*models.TickerUpdate)) error

func (*BackpackWebsocket) SubscribeTrade

func (client *BackpackWebsocket) SubscribeTrade(symbol string, handler func(*models.TradeUpdate)) error

func (*BackpackWebsocket) Unsubscribe

func (client *BackpackWebsocket) Unsubscribe(stream string) error

type Message

type Message struct {
	Stream string                  `json:"stream"`
	Data   encodingjson.RawMessage `json:"data"`
}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL