bybit

package module
v1.4.12 Latest Latest
Warning

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

Go to latest
Published: Aug 29, 2026 License: MIT Imports: 20 Imported by: 0

README

Bybit Golang SDK

Bybit Golang SDK

CI Tests Go vet CodeQL codecov Go Report Card Go Reference Go version License

A small Go client for the Bybit V5 API. It makes it easier to get started with the REST API, demo trading, WebSocket streams, and TradFi instruments without imposing an application architecture on your project.

📚 Looking for the deeper dive? Explore the bybit-go Wiki for guides, endpoint notes, and extended documentation.

Trading involves risk. Test both the integration and your strategy in the demo environment first, use narrowly scoped API-key permissions, and never commit keys to a repository.

Contents

Features

  • REST methods for market data, orders, accounts, and positions;
  • HMAC-SHA256 and RSA-SHA256 signing for REST requests;
  • demo mode plus regional REST and WebSocket endpoints;
  • public and private WebSocket subscriptions;
  • convenience helpers for TradFi instruments (forex, metals, stocks, and indices);
  • standalone working examples in examples/.

Installation

Go 1.21 or later is required.

go get github.com/tigusigalpa/bybit-go
import bybit "github.com/tigusigalpa/bybit-go"

Configuration

Create one client and reuse it for the lifetime of your application. The default HTTP client has a 30-second timeout. You may provide your own *http.Client when you need a proxy, custom transport, observability, or different timeout settings.

ClientConfig field Default Description
APIKey API key for signed endpoints.
APISecret API secret for HMAC signing.
Demo false Routes REST requests to the Bybit demo environment.
Region global Endpoint region: global, nl, tr, kz, ge, or ae. demo also selects the demo REST endpoint.
RecvWindow 5000 Bybit receive window in milliseconds.
Signature hmac Signature algorithm: hmac or rsa.
RSAPrivateKey PEM private key, required when Signature is rsa.
HTTPClient 30 s timeout Optional custom HTTP client.
httpClient := &http.Client{Timeout: 10 * time.Second}
client, err := bybit.NewClient(bybit.ClientConfig{
	APIKey:     os.Getenv("BYBIT_API_KEY"),
	APISecret:  os.Getenv("BYBIT_API_SECRET"),
	Demo:       true,
	RecvWindow: 5_000,
	HTTPClient: httpClient,
})

Demo: true takes precedence over Region. Use demo credentials that belong to the demo environment; do not expect production credentials or balances to work there.

Quick start

Public requests use the same client and do not require an API key.

package main

import (
	"fmt"
	"log"

	bybit "github.com/tigusigalpa/bybit-go"
)

func main() {
	client, err := bybit.NewClient(bybit.ClientConfig{Demo: true})
	if err != nil {
		log.Fatal(err)
	}

	tickers, err := client.GetTickers(map[string]interface{}{
		"category": "linear",
		"symbol":   "BTCUSDT",
	})
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("%+v\n", tickers["result"])
}

For account operations, pass credentials through environment variables:

client, err := bybit.NewClient(bybit.ClientConfig{
	APIKey:    os.Getenv("BYBIT_API_KEY"),
	APISecret: os.Getenv("BYBIT_API_SECRET"),
	Demo:      true,
	Region:    "global", // also: nl, tr, kz, ge, ae
})

REST API

Methods return the decoded Bybit response as map[string]interface{}. This deliberately leaves the full V5 request surface available: pass the exact fields documented by Bybit in the params map.

Market data
orderbook, err := client.GetOrderbook(map[string]interface{}{
	"category": "spot",
	"symbol":   "BTCUSDT",
	"limit":    50,
})

klines, err := client.GetKline(map[string]interface{}{
	"category": "linear",
	"symbol":   "BTCUSDT",
	"interval": "60",
	"limit":    200,
})

trades, err := client.GetRecentTrades(map[string]interface{}{
	"category": "linear",
	"symbol":   "BTCUSDT",
})

Available market helpers include GetServerTime, GetTickers, GetKline, GetOrderbook, GetRPIOrderbook, GetOpenInterest, GetRecentTrades, GetFundingRateHistory, GetHistoricalVolatility, GetInsurance, and GetRiskLimit.

Account and positions
wallet, err := client.GetWalletBalance(map[string]interface{}{
	"accountType": "UNIFIED",
})
positions, err := client.GetPositions(map[string]interface{}{
	"category": "linear",
	"symbol":   "BTCUSDT",
})

The client also provides helpers for account info, transaction logs, open and closed positions, trading stops, margin, leverage, and risk-limit operations. Refer to the official V5 documentation for endpoint-specific required fields and account-mode rules.

Orders and positions

API parameters are passed through directly, so you can use newly added Bybit fields without waiting for an SDK release.

order, err := client.CreateOrder(map[string]interface{}{
	"category":    "linear",
	"symbol":      "BTCUSDT",
	"side":        "Buy",
	"orderType":   "Limit",
	"qty":         "0.001",
	"price":       "30000",
	"timeInForce": "GTC",
})
if err != nil {
	log.Fatal(err)
}
fmt.Println(order)

For a higher-level order helper, PlaceOrder can calculate a derivatives quantity from margin, price, and leverage. Use it only when that calculation matches your instrument's quantity rules; for precise production order sizing, retrieve instrument constraints and submit CreateOrder yourself.

SetLeverage rejects a non-positive leverage value and accepts Buy or Sell when changing one side only. Passing no side changes both buy and sell leverage.

Demo trading

NewDemoClient creates a DemoClient with Demo enabled. It exposes the usual order and account helpers as well as demo-specific operations such as funding requests.

demo, err := bybit.NewDemoClient(bybit.ClientConfig{
	APIKey:    os.Getenv("BYBIT_DEMO_API_KEY"),
	APISecret: os.Getenv("BYBIT_DEMO_API_SECRET"),
})
if err != nil {
	log.Fatal(err)
}

result, err := demo.ApplyForDemoFundsSimple("USDT", "10000")

Errors and response handling

There are two error layers to handle:

  1. Transport, request-construction, HTTP-status, signature, and JSON decoding failures are returned as Go errors.
  2. A Bybit business error, represented by a non-zero retCode, usually arrives with HTTP 200. It is returned in the response map and must be checked by the caller.
response, err := client.CreateOrder(params)
if err != nil {
	var httpErr *bybit.HTTPError
	if errors.As(err, &httpErr) {
		log.Printf("Bybit HTTP failure: status=%d body=%s", httpErr.StatusCode, httpErr.Body)
	}
	log.Fatal(err)
}

if code, ok := response["retCode"].(float64); !ok || code != 0 {
	log.Fatalf("Bybit rejected request: code=%v message=%v", response["retCode"], response["retMsg"])
}

For public calls, an empty API key produces an empty HMAC signature. Bybit may ignore these headers for public endpoints, but authenticated operations require valid credentials. Treat API responses as untrusted input: check types before using nested values from the decoded map.

RSA signatures

For an RSA API key, provide its PEM-encoded private key. Signature: "rsa" requires a private key, and unsupported signature types are rejected when creating the client.

client, err := bybit.NewClient(bybit.ClientConfig{
	APIKey:        os.Getenv("BYBIT_API_KEY"),
	Signature:     "rsa",
	RSAPrivateKey: os.Getenv("BYBIT_RSA_PRIVATE_KEY"),
})

WebSocket

ws := bybit.NewWebSocket(bybit.WebSocketConfig{Demo: true})
defer ws.Close()

ws.OnMessage(func(message map[string]interface{}) {
	fmt.Printf("%+v\n", message)
})

if err := ws.SubscribeTicker("BTCUSDT"); err != nil {
	log.Fatal(err)
}
if err := ws.Listen(); err != nil {
	log.Fatal(err)
}

The package's public WebSocket connects to the spot endpoint. For private streams, set IsPrivate together with APIKey and APISecret; the client authenticates after connecting.

Helper Topic
SubscribeOrderbook("BTCUSDT", 50) orderbook.50.BTCUSDT
SubscribeTrade("BTCUSDT") publicTrade.BTCUSDT
SubscribeTicker("BTCUSDT") tickers.BTCUSDT
SubscribeKline("BTCUSDT", "1") kline.1.BTCUSDT
SubscribePosition, SubscribeOrder, SubscribeExecution, SubscribeWallet Private account topics

Call Unsubscribe with the exact topics when they are no longer needed. Your application owns the connection lifecycle and should reconnect after an error; on reconnect, subscribe again using GetSubscriptions as your source of truth.

TradFi

The package includes lists of popular instruments and focused helper methods:

tickers, err := client.GetTradFiTicker("XAUUSD")
positions, err := client.GetTradFiPositions("XAUUSD")
order, err := client.PlaceTradFiOrder(bybit.TradFiOrderParams{
	Symbol: "XAUUSD", Side: "Buy", OrderType: "Market", Qty: "1",
})

Instrument availability and trading conditions vary by account and region. Call GetTradFiInstruments to retrieve the current list before placing an order.

Examples, testing, and contributing

See the examples directory for basic client, market data, orders, positions, demo trading, TradFi, and WebSocket programs. Examples may make network calls or require credentials, so read their source before running them.

go test ./...
go vet ./...

CI runs these checks on Go 1.21 and the current stable Go release. Pull requests are welcome: please add a test when changing behavior, and never include real API keys or personal data.

The repository's GitHub Actions workflow additionally runs the test suite with Go's race detector. Before opening a pull request, format changed Go files with gofmt and keep go.mod and go.sum tidy.

Documentation and license

Documentation

Index

Constants

View Source
const (
	TradFiCategoryLinear  = "linear"
	TradFiCategoryInverse = "inverse"

	// TradFi asset class prefixes used in Bybit symbol naming
	TradFiAssetForex     = "forex"
	TradFiAssetMetal     = "metal"
	TradFiAssetStock     = "stock"
	TradFiAssetIndex     = "index"
	TradFiAssetCommodity = "commodity"
)

TradFi asset classes available on Bybit

Variables

View Source
var (
	// Metals
	TradFiMetals = []string{
		"XAUUSD",
		"XAGUSD",
		"XPTUSD",
	}

	// Forex majors
	TradFiForexMajors = []string{
		"EURUSD",
		"GBPUSD",
		"USDJPY",
		"USDCHF",
		"AUDUSD",
		"NZDUSD",
		"USDCAD",
	}

	// Forex minors
	TradFiForexMinors = []string{
		"EURGBP",
		"EURJPY",
		"GBPJPY",
		"EURCHF",
		"AUDCAD",
		"AUDNZD",
		"CADJPY",
	}

	// US Stock CFDs
	TradFiUSStocks = []string{
		"AAPLUSDT",
		"AMZNUSDT",
		"TSLAUSDT",
		"GOOGLUSDT",
		"MSFTUSDT",
		"METAUSDT",
		"NVDAUSDT",
		"NFLXUSDT",
	}

	// Major indices
	TradFiIndices = []string{
		"US30USD",
		"US100USD",
		"US500USD",
		"UK100USD",
		"DE40USD",
		"JP225USD",
	}
)

Well-known TradFi symbols traded on Bybit (linear perpetuals)

Functions

func IsTradFiSymbol added in v1.3.14

func IsTradFiSymbol(symbol string) bool

IsTradFiSymbol returns true if the given symbol is likely a TradFi instrument (forex, metals, stock CFD, or index) rather than a crypto perpetual.

Types

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client provides signed REST access to the Bybit V5 API.

func NewClient

func NewClient(config ClientConfig) (*Client, error)

NewClient creates a REST client with the supplied configuration.

func (*Client) AddOrReduceMargin added in v1.1.16

func (c *Client) AddOrReduceMargin(params map[string]interface{}) (map[string]interface{}, error)

AddOrReduceMargin adjusts isolated-position margin using the supplied parameters.

func (*Client) AmendOrder

func (c *Client) AmendOrder(params map[string]interface{}) (map[string]interface{}, error)

AmendOrder updates an existing order using the supplied parameters.

func (*Client) BaseURI

func (c *Client) BaseURI() string

BaseURI returns the REST API base URL selected by the client's demo and region settings.

func (*Client) CancelAllOrders

func (c *Client) CancelAllOrders(params map[string]interface{}) (map[string]interface{}, error)

CancelAllOrders cancels all orders matching the supplied parameters.

func (*Client) CancelOrder

func (c *Client) CancelOrder(params map[string]interface{}) (map[string]interface{}, error)

CancelOrder cancels an order identified by the supplied parameters.

func (*Client) CancelTradFiOrder added in v1.3.14

func (c *Client) CancelTradFiOrder(symbol, orderID, orderLinkID string) (map[string]interface{}, error)

CancelTradFiOrder cancels a specific TradFi order by orderId or orderLinkId.

func (*Client) CloseTradFiPosition added in v1.3.14

func (c *Client) CloseTradFiPosition(symbol, side string, qty string, positionIdx int) (map[string]interface{}, error)

CloseTradFiPosition closes an open TradFi position at market price.

func (*Client) ComputeFee

func (c *Client) ComputeFee(tradeType string, volume float64, level, liquidity string) float64

ComputeFee estimates a fee from the client's built-in fee table.

func (*Client) ConfirmNewRiskLimit added in v1.1.16

func (c *Client) ConfirmNewRiskLimit(params map[string]interface{}) (map[string]interface{}, error)

ConfirmNewRiskLimit confirms a pending maintenance-margin requirement change.

func (*Client) CreateOrder

func (c *Client) CreateOrder(params map[string]interface{}) (map[string]interface{}, error)

CreateOrder submits an order using the supplied Bybit V5 fields.

func (*Client) Endpoint

func (c *Client) Endpoint() string

Endpoint returns the active REST API endpoint.

func (*Client) GetAccountInfo added in v1.1.16

func (c *Client) GetAccountInfo() (map[string]interface{}, error)

GetAccountInfo returns metadata for the authenticated account.

func (*Client) GetAccountInstrumentsInfo added in v1.1.16

func (c *Client) GetAccountInstrumentsInfo(params map[string]interface{}) (map[string]interface{}, error)

GetAccountInstrumentsInfo returns account-specific instrument information.

func (*Client) GetClosedOptionsPositions added in v1.1.16

func (c *Client) GetClosedOptionsPositions(params map[string]interface{}) (map[string]interface{}, error)

GetClosedOptionsPositions returns closed options-position records.

func (*Client) GetClosedPnL added in v1.1.16

func (c *Client) GetClosedPnL(params map[string]interface{}) (map[string]interface{}, error)

GetClosedPnL returns closed profit-and-loss records for the supplied parameters.

func (*Client) GetForexTickers added in v1.3.14

func (c *Client) GetForexTickers() (map[string]interface{}, error)

GetForexTickers returns ticker data for major forex pairs.

func (*Client) GetFundingRateHistory added in v1.1.16

func (c *Client) GetFundingRateHistory(params map[string]interface{}) (map[string]interface{}, error)

GetFundingRateHistory returns funding-rate history for the supplied parameters.

func (*Client) GetHistoricalVolatility added in v1.1.16

func (c *Client) GetHistoricalVolatility(params map[string]interface{}) (map[string]interface{}, error)

GetHistoricalVolatility returns historical volatility data for the supplied parameters.

func (*Client) GetHistoryOrders

func (c *Client) GetHistoryOrders(params map[string]interface{}) (map[string]interface{}, error)

GetHistoryOrders returns historical orders for the supplied parameters.

func (*Client) GetIndexTickers added in v1.3.14

func (c *Client) GetIndexTickers() (map[string]interface{}, error)

GetIndexTickers returns ticker data for major indices.

func (*Client) GetInsurance added in v1.1.16

func (c *Client) GetInsurance(params map[string]interface{}) (map[string]interface{}, error)

GetInsurance returns insurance-pool data for the supplied parameters.

func (*Client) GetKline added in v1.1.16

func (c *Client) GetKline(params map[string]interface{}) (map[string]interface{}, error)

GetKline returns candlestick data for the supplied market parameters.

func (*Client) GetMetalsTickers added in v1.3.14

func (c *Client) GetMetalsTickers() (map[string]interface{}, error)

GetMetalsTickers returns ticker data for gold, silver, and platinum.

func (*Client) GetMovePositionHistory added in v1.1.16

func (c *Client) GetMovePositionHistory(params map[string]interface{}) (map[string]interface{}, error)

GetMovePositionHistory returns position-transfer history for the supplied parameters.

func (*Client) GetOpenInterest added in v1.1.16

func (c *Client) GetOpenInterest(params map[string]interface{}) (map[string]interface{}, error)

GetOpenInterest returns open-interest data for the supplied parameters.

func (*Client) GetOpenOrders

func (c *Client) GetOpenOrders(params map[string]interface{}) (map[string]interface{}, error)

GetOpenOrders returns current open orders for the supplied parameters.

func (*Client) GetOrderbook added in v1.1.16

func (c *Client) GetOrderbook(params map[string]interface{}) (map[string]interface{}, error)

GetOrderbook returns an order book snapshot for the supplied market parameters.

func (*Client) GetPositions

func (c *Client) GetPositions(params map[string]interface{}) (map[string]interface{}, error)

GetPositions returns positions matching the supplied parameters.

func (*Client) GetRPIOrderbook added in v1.1.16

func (c *Client) GetRPIOrderbook(params map[string]interface{}) (map[string]interface{}, error)

GetRPIOrderbook returns an RPI order book snapshot for the supplied parameters.

func (*Client) GetRecentTrades added in v1.1.16

func (c *Client) GetRecentTrades(params map[string]interface{}) (map[string]interface{}, error)

GetRecentTrades returns recent public trades for the supplied parameters.

func (*Client) GetRiskLimit added in v1.1.16

func (c *Client) GetRiskLimit(params map[string]interface{}) (map[string]interface{}, error)

GetRiskLimit returns risk-limit data for the supplied parameters.

func (*Client) GetServerTime

func (c *Client) GetServerTime() (map[string]interface{}, error)

GetServerTime returns the current Bybit server time.

func (*Client) GetStockTickers added in v1.3.14

func (c *Client) GetStockTickers() (map[string]interface{}, error)

GetStockTickers returns ticker data for US stock CFDs.

func (*Client) GetTickers

func (c *Client) GetTickers(params map[string]interface{}) (map[string]interface{}, error)

GetTickers returns ticker data for the supplied market parameters.

func (*Client) GetTradFiFeeRate added in v1.3.14

func (c *Client) GetTradFiFeeRate(symbol string) (map[string]interface{}, error)

GetTradFiFeeRate returns the trading fee rate for TradFi instruments.

func (*Client) GetTradFiInstruments added in v1.3.14

func (c *Client) GetTradFiInstruments(assetClass string) (map[string]interface{}, error)

GetTradFiInstruments returns all available TradFi instruments. Set assetClass to filter by "forex", "metal", "stock", "index", or "" for all.

func (*Client) GetTradFiKline added in v1.3.14

func (c *Client) GetTradFiKline(symbol, interval string, limit int) (map[string]interface{}, error)

GetTradFiKline returns kline/candlestick data for a TradFi symbol. interval: 1, 3, 5, 15, 30, 60, 120, 240, 360, 720, D, W, M

func (*Client) GetTradFiOpenOrders added in v1.3.14

func (c *Client) GetTradFiOpenOrders(symbol string) (map[string]interface{}, error)

GetTradFiOpenOrders returns open orders for TradFi instruments.

func (*Client) GetTradFiOrderbook added in v1.3.14

func (c *Client) GetTradFiOrderbook(symbol string, depth int) (map[string]interface{}, error)

GetTradFiOrderbook returns order book depth for a TradFi symbol. depth: 1, 25, 50, 100, 200

func (*Client) GetTradFiPositions added in v1.3.14

func (c *Client) GetTradFiPositions(symbol string) (map[string]interface{}, error)

GetTradFiPositions returns open TradFi positions for the account. Pass symbol="" to get all TradFi positions.

func (*Client) GetTradFiSwapFee added in v1.3.14

func (c *Client) GetTradFiSwapFee(symbol string) (map[string]interface{}, error)

GetTradFiSwapFee returns the swap (overnight financing) fee info for a TradFi symbol. Swap fees apply when holding TradFi positions past market close.

func (*Client) GetTradFiTicker added in v1.3.14

func (c *Client) GetTradFiTicker(symbol string) (map[string]interface{}, error)

GetTradFiTicker returns ticker data for a single TradFi symbol.

func (*Client) GetTradFiTickers added in v1.3.14

func (c *Client) GetTradFiTickers(symbols []string) (map[string]interface{}, error)

GetTradFiTickers returns ticker data for the given TradFi symbols. Pass nil or empty slice to get tickers for all linear instruments.

func (*Client) GetTradFiTradeHistory added in v1.3.14

func (c *Client) GetTradFiTradeHistory(symbol string, limit int) (map[string]interface{}, error)

GetTradFiTradeHistory returns execution/trade history for TradFi symbols.

func (*Client) GetTransactionLog added in v1.1.16

func (c *Client) GetTransactionLog(params map[string]interface{}) (map[string]interface{}, error)

GetTransactionLog returns account transaction records for the supplied parameters.

func (*Client) GetTransferableAmount added in v1.1.16

func (c *Client) GetTransferableAmount(params map[string]interface{}) (map[string]interface{}, error)

GetTransferableAmount returns the transferable amount for the supplied parameters.

func (*Client) GetWalletBalance

func (c *Client) GetWalletBalance(params map[string]interface{}) (map[string]interface{}, error)

GetWalletBalance returns wallet balances for the supplied account parameters.

func (*Client) MovePosition added in v1.1.16

func (c *Client) MovePosition(params map[string]interface{}) (map[string]interface{}, error)

MovePosition transfers a position using the supplied parameters.

func (*Client) PlaceOrder

func (c *Client) PlaceOrder(params PlaceOrderParams) (map[string]interface{}, error)

PlaceOrder builds and submits an order from the higher-level PlaceOrderParams structure.

func (*Client) PlaceTradFiOrder added in v1.3.14

func (c *Client) PlaceTradFiOrder(p TradFiOrderParams) (map[string]interface{}, error)

PlaceTradFiOrder places an order for a TradFi instrument (forex, metals, stocks, indices).

func (*Client) Request

func (c *Client) Request(method, path string, params map[string]interface{}) (map[string]interface{}, error)

Request performs a signed Bybit REST request and decodes its JSON response.

func (*Client) SetAutoAddMargin added in v1.1.16

func (c *Client) SetAutoAddMargin(params map[string]interface{}) (map[string]interface{}, error)

SetAutoAddMargin enables or disables automatic margin additions.

func (*Client) SetLeverage

func (c *Client) SetLeverage(category, symbol string, leverage float64, side *string) (map[string]interface{}, error)

SetLeverage sets leverage for a symbol and optional Buy or Sell side.

func (*Client) SetTradFiLeverage added in v1.3.14

func (c *Client) SetTradFiLeverage(symbol string, leverage float64) (map[string]interface{}, error)

SetTradFiLeverage sets leverage for a TradFi symbol. TradFi instruments typically support 1x–20x leverage depending on the instrument.

func (*Client) SetTradingStop

func (c *Client) SetTradingStop(params map[string]interface{}) (map[string]interface{}, error)

SetTradingStop configures take-profit, stop-loss, or trailing-stop settings.

func (*Client) SwitchPositionMode

func (c *Client) SwitchPositionMode(params map[string]interface{}) (map[string]interface{}, error)

SwitchPositionMode changes the position mode using the supplied parameters.

type ClientConfig

type ClientConfig struct {
	APIKey        string
	APISecret     string
	Demo          bool
	Region        string
	RecvWindow    int
	Signature     string
	RSAPrivateKey string
	HTTPClient    *http.Client
}

ClientConfig configures a Client instance.

type DemoClient added in v1.1.16

type DemoClient struct {
	*Client
}

DemoClient provides REST helpers for the Bybit demo trading environment.

func NewDemoClient added in v1.1.16

func NewDemoClient(config ClientConfig) (*DemoClient, error)

NewDemoClient creates a client configured for the demo trading environment.

func (*DemoClient) AddOrReduceMargin added in v1.2.23

func (dc *DemoClient) AddOrReduceMargin(params map[string]interface{}) (map[string]interface{}, error)

AddOrReduceMargin adjusts a demo position's margin.

func (*DemoClient) AmendOrder added in v1.2.23

func (dc *DemoClient) AmendOrder(params map[string]interface{}) (map[string]interface{}, error)

AmendOrder updates an existing demo order.

func (*DemoClient) ApplyForDemoFunds added in v1.1.16

func (dc *DemoClient) ApplyForDemoFunds(adjustType int, funds []DemoFundRequest) (map[string]interface{}, error)

ApplyForDemoFunds requests an adjustment to one or more demo account balances.

func (*DemoClient) ApplyForDemoFundsSimple added in v1.2.23

func (dc *DemoClient) ApplyForDemoFundsSimple(coin string, amount string) (map[string]interface{}, error)

ApplyForDemoFundsSimple requests a standard demo-fund adjustment for one coin.

func (*DemoClient) BatchAmendOrder added in v1.2.23

func (dc *DemoClient) BatchAmendOrder(params map[string]interface{}) (map[string]interface{}, error)

BatchAmendOrder updates a batch of demo orders.

func (*DemoClient) BatchCancelOrder added in v1.2.23

func (dc *DemoClient) BatchCancelOrder(params map[string]interface{}) (map[string]interface{}, error)

BatchCancelOrder cancels a batch of demo orders.

func (*DemoClient) BatchPlaceOrder added in v1.2.23

func (dc *DemoClient) BatchPlaceOrder(params map[string]interface{}) (map[string]interface{}, error)

BatchPlaceOrder submits a batch of demo orders.

func (*DemoClient) CancelAllOrders added in v1.2.23

func (dc *DemoClient) CancelAllOrders(params map[string]interface{}) (map[string]interface{}, error)

CancelAllOrders cancels demo orders matching the supplied parameters.

func (*DemoClient) CancelOrder added in v1.2.23

func (dc *DemoClient) CancelOrder(params map[string]interface{}) (map[string]interface{}, error)

CancelOrder cancels a demo order.

func (*DemoClient) CreateDemoAPIKey added in v1.2.23

func (dc *DemoClient) CreateDemoAPIKey(mainnetClient *Client, demoUID string, params map[string]interface{}) (map[string]interface{}, error)

CreateDemoAPIKey creates a demo sub-account API key through a mainnet client.

func (*DemoClient) CreateDemoAccount added in v1.2.23

func (dc *DemoClient) CreateDemoAccount(mainnetClient *Client) (map[string]interface{}, error)

CreateDemoAccount creates a demo member through an authorized mainnet client.

func (*DemoClient) CreateOrder added in v1.2.23

func (dc *DemoClient) CreateOrder(params map[string]interface{}) (map[string]interface{}, error)

CreateOrder submits a demo order using the supplied V5 fields.

func (*DemoClient) DeleteDemoAPIKey added in v1.2.23

func (dc *DemoClient) DeleteDemoAPIKey(mainnetClient *Client, params map[string]interface{}) (map[string]interface{}, error)

DeleteDemoAPIKey removes a demo sub-account API key through a mainnet client.

func (*DemoClient) GetAPIKeyInfo added in v1.2.23

func (dc *DemoClient) GetAPIKeyInfo() (map[string]interface{}, error)

GetAPIKeyInfo returns information about the authenticated demo API key.

func (*DemoClient) GetAccountInfo added in v1.2.23

func (dc *DemoClient) GetAccountInfo() (map[string]interface{}, error)

GetAccountInfo returns metadata for the authenticated demo account.

func (*DemoClient) GetBorrowHistory added in v1.2.23

func (dc *DemoClient) GetBorrowHistory(params map[string]interface{}) (map[string]interface{}, error)

GetBorrowHistory returns demo account borrow history.

func (*DemoClient) GetClosedPnL added in v1.2.23

func (dc *DemoClient) GetClosedPnL(params map[string]interface{}) (map[string]interface{}, error)

GetClosedPnL returns closed PnL records from the demo account.

func (*DemoClient) GetCoinGreeks added in v1.2.23

func (dc *DemoClient) GetCoinGreeks(params map[string]interface{}) (map[string]interface{}, error)

GetCoinGreeks returns option Greeks for the supplied demo-account parameters.

func (*DemoClient) GetCollateralInfo added in v1.2.23

func (dc *DemoClient) GetCollateralInfo(params map[string]interface{}) (map[string]interface{}, error)

GetCollateralInfo returns demo account collateral information.

func (*DemoClient) GetDeliveryRecord added in v1.2.23

func (dc *DemoClient) GetDeliveryRecord(params map[string]interface{}) (map[string]interface{}, error)

GetDeliveryRecord returns demo asset delivery records.

func (*DemoClient) GetOpenOrders added in v1.2.23

func (dc *DemoClient) GetOpenOrders(params map[string]interface{}) (map[string]interface{}, error)

GetOpenOrders returns current demo orders for the supplied parameters.

func (*DemoClient) GetOrderHistory added in v1.2.23

func (dc *DemoClient) GetOrderHistory(params map[string]interface{}) (map[string]interface{}, error)

GetOrderHistory returns historical demo orders for the supplied parameters.

func (*DemoClient) GetPositions added in v1.2.23

func (dc *DemoClient) GetPositions(params map[string]interface{}) (map[string]interface{}, error)

GetPositions returns demo positions for the supplied parameters.

func (*DemoClient) GetSpotMarginStatus added in v1.2.23

func (dc *DemoClient) GetSpotMarginStatus() (map[string]interface{}, error)

GetSpotMarginStatus returns demo spot-margin trading status.

func (*DemoClient) GetTradeHistory added in v1.2.23

func (dc *DemoClient) GetTradeHistory(params map[string]interface{}) (map[string]interface{}, error)

GetTradeHistory returns demo execution history for the supplied parameters.

func (*DemoClient) GetTransactionLog added in v1.2.23

func (dc *DemoClient) GetTransactionLog(params map[string]interface{}) (map[string]interface{}, error)

GetTransactionLog returns demo account transactions.

func (*DemoClient) GetUSDCSettlement added in v1.2.23

func (dc *DemoClient) GetUSDCSettlement(params map[string]interface{}) (map[string]interface{}, error)

GetUSDCSettlement returns demo USDC settlement records.

func (*DemoClient) GetWalletBalance added in v1.2.23

func (dc *DemoClient) GetWalletBalance(params map[string]interface{}) (map[string]interface{}, error)

GetWalletBalance returns demo-account wallet balances and defaults accountType to UNIFIED.

func (*DemoClient) SetAutoAddMargin added in v1.2.23

func (dc *DemoClient) SetAutoAddMargin(params map[string]interface{}) (map[string]interface{}, error)

SetAutoAddMargin configures automatic margin additions for a demo position.

func (*DemoClient) SetCollateralCoin added in v1.2.23

func (dc *DemoClient) SetCollateralCoin(params map[string]interface{}) (map[string]interface{}, error)

SetCollateralCoin updates collateral settings for a demo account.

func (*DemoClient) SetLeverage added in v1.2.23

func (dc *DemoClient) SetLeverage(params map[string]interface{}) (map[string]interface{}, error)

SetLeverage configures demo position leverage using the supplied parameters.

func (*DemoClient) SetMarginMode added in v1.2.23

func (dc *DemoClient) SetMarginMode(params map[string]interface{}) (map[string]interface{}, error)

SetMarginMode changes the demo account margin mode.

func (*DemoClient) SetSpotHedging added in v1.2.23

func (dc *DemoClient) SetSpotHedging(params map[string]interface{}) (map[string]interface{}, error)

SetSpotHedging configures spot hedging for a demo account.

func (*DemoClient) SetSpotMarginLeverage added in v1.2.23

func (dc *DemoClient) SetSpotMarginLeverage(params map[string]interface{}) (map[string]interface{}, error)

SetSpotMarginLeverage sets demo spot-margin leverage.

func (*DemoClient) SetTradingStop added in v1.2.23

func (dc *DemoClient) SetTradingStop(params map[string]interface{}) (map[string]interface{}, error)

SetTradingStop configures demo position stop settings.

func (*DemoClient) SwitchPositionMode added in v1.2.23

func (dc *DemoClient) SwitchPositionMode(params map[string]interface{}) (map[string]interface{}, error)

SwitchPositionMode changes the demo account's position mode.

func (*DemoClient) ToggleMarginTrade added in v1.2.23

func (dc *DemoClient) ToggleMarginTrade(params map[string]interface{}) (map[string]interface{}, error)

ToggleMarginTrade changes spot margin trading mode for a demo account.

func (*DemoClient) UpdateDemoAPIKey added in v1.2.23

func (dc *DemoClient) UpdateDemoAPIKey(mainnetClient *Client, params map[string]interface{}) (map[string]interface{}, error)

UpdateDemoAPIKey updates a demo sub-account API key through a mainnet client.

type DemoFundRequest added in v1.2.23

type DemoFundRequest struct {
	Coin      string `json:"coin"`
	AmountStr string `json:"amountStr"`
}

DemoFundRequest describes a single demo-fund adjustment.

type HTTPError added in v1.4.3

type HTTPError struct {
	StatusCode int
	Status     string
	Body       string
}

HTTPError describes a response that could not be completed at the HTTP layer. A successful Bybit HTTP response can still contain a non-zero retCode; callers receive that API response unchanged and can inspect it according to their flow.

func (*HTTPError) Error added in v1.4.3

func (e *HTTPError) Error() string

type PlaceOrderParams

type PlaceOrderParams struct {
	Type      string
	Symbol    string
	Execution string
	Price     *float64
	Side      *string
	Leverage  *float64
	Size      float64
	SlTp      *SlTpParams
	Extra     map[string]interface{}
}

PlaceOrderParams describes the higher-level order helper input.

type SlTpParams

type SlTpParams struct {
	Type       string
	TakeProfit *float64
	StopLoss   *float64
}

SlTpParams describes optional take-profit and stop-loss settings for PlaceOrder.

type TradFiOrderParams added in v1.3.14

type TradFiOrderParams struct {
	Symbol      string
	Side        string // "Buy" or "Sell"
	OrderType   string // "Market" or "Limit"
	Qty         string // quantity as string
	Price       string // required for Limit orders
	TimeInForce string // "GTC", "IOC", "FOK", "PostOnly"
	TakeProfit  string // optional TP price
	StopLoss    string // optional SL price
	PositionIdx int    // 0=one-way, 1=hedge-long, 2=hedge-short
	ReduceOnly  bool
	OrderLinkID string
}

TradFiOrderParams holds parameters for placing a TradFi order.

type WebSocket

type WebSocket struct {
	// contains filtered or unexported fields
}

WebSocket manages a Bybit WebSocket connection and its subscriptions.

func NewWebSocket

func NewWebSocket(config WebSocketConfig) *WebSocket

NewWebSocket creates a WebSocket client with the supplied configuration.

func (*WebSocket) Close

func (ws *WebSocket) Close() error

Close closes the active WebSocket connection.

func (*WebSocket) Connect

func (ws *WebSocket) Connect() error

Connect establishes the WebSocket connection and authenticates private clients.

func (*WebSocket) GetSubscriptions

func (ws *WebSocket) GetSubscriptions() []string

GetSubscriptions returns a copy of locally tracked subscriptions.

func (*WebSocket) IsConnected

func (ws *WebSocket) IsConnected() bool

IsConnected reports whether the client currently has an active local connection.

func (*WebSocket) Listen

func (ws *WebSocket) Listen() error

Listen reads messages until the connection closes or a read error occurs.

func (*WebSocket) OnMessage

func (ws *WebSocket) OnMessage(callback func(map[string]interface{}))

OnMessage registers the callback invoked for each decoded message or read error.

func (*WebSocket) Ping

func (ws *WebSocket) Ping() error

Ping sends a ping operation to the WebSocket server.

func (*WebSocket) Send

func (ws *WebSocket) Send(message map[string]interface{}) error

Send serializes and sends a WebSocket message, connecting first when necessary.

func (*WebSocket) Subscribe

func (ws *WebSocket) Subscribe(topics []string) error

Subscribe sends a subscription request for the supplied topics.

func (*WebSocket) SubscribeExecution

func (ws *WebSocket) SubscribeExecution() error

SubscribeExecution subscribes to private execution updates.

func (*WebSocket) SubscribeKline

func (ws *WebSocket) SubscribeKline(symbol, interval string) error

SubscribeKline subscribes to candlestick updates for a symbol and interval.

func (*WebSocket) SubscribeOrder

func (ws *WebSocket) SubscribeOrder() error

SubscribeOrder subscribes to private order updates.

func (*WebSocket) SubscribeOrderbook

func (ws *WebSocket) SubscribeOrderbook(symbol string, depth int) error

SubscribeOrderbook subscribes to an order book topic for a symbol and depth.

func (*WebSocket) SubscribePosition

func (ws *WebSocket) SubscribePosition() error

SubscribePosition subscribes to private position updates.

func (*WebSocket) SubscribeTicker

func (ws *WebSocket) SubscribeTicker(symbol string) error

SubscribeTicker subscribes to ticker updates for a symbol.

func (*WebSocket) SubscribeTrade

func (ws *WebSocket) SubscribeTrade(symbol string) error

SubscribeTrade subscribes to public trade updates for a symbol.

func (*WebSocket) SubscribeWallet

func (ws *WebSocket) SubscribeWallet() error

SubscribeWallet subscribes to private wallet updates.

func (*WebSocket) Unsubscribe

func (ws *WebSocket) Unsubscribe(topics []string) error

Unsubscribe sends an unsubscribe request for the supplied topics.

type WebSocketConfig

type WebSocketConfig struct {
	APIKey    string
	APISecret string
	Demo      bool
	Region    string
	IsPrivate bool
}

WebSocketConfig configures a WebSocket client.

Directories

Path Synopsis
examples
account_info command
basic_client command
demo_trading command
market_data command
tradfi command

Jump to

Keyboard shortcuts

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