Giter Club home page Giter Club logo

bybit-api's Introduction

bybit-api

Go library for using the ByBit's Rest & Websocket API

API Doc

Example

Rest api

package main

import (
	"github.com/frankrap/bybit-api/rest"
	"log"
)

func main() {
	//baseURL := "https://api.bybit.com/"	// 主网络
	baseURL := "https://api-testnet.bybit.com/" // 测试网络
	b := rest.New(nil, baseURL, "YIxOY2RhFkylPudq96", "Bg9G2oFOb3aaIMguD3FOvOJJVBycaoXqXNcI")

	// 获取持仓
	positions, err := b.GetPositions()
	if err != nil {
		log.Printf("%v", err)
		return
	}

	log.Printf("positions: %#v", positions)

	// 创建委托
	symbol := "BTCUSD"
	side := "Buy"
	orderType := "Limit"
	qty := 30
	price := 7000.0
	timeInForce := "GoodTillCancel"
	reduceOnly := false
	order, err := b.CreateOrder(side, orderType, price, qty, timeInForce, reduceOnly, symbol)
	if err != nil {
		log.Println(err)
		return
	}
	log.Printf("Create order: %#v", order)

	// 获取委托单
}

Websocket

package main

import (
	"github.com/frankrap/bybit-api/ws"
	"log"
)

func main() {
	cfg := &ws.Configuration{
		Addr:          ws.HostTestnet, // 测试网络
		ApiKey:        "wKuYtkeNdC2PaMKjoy",
		SecretKey:     "5ekcDn3KnKoCRbfvrPImYzVdx7Ri2hhVxkmw",
		AutoReconnect: true, // 断线自动重连
		DebugMode:     true,
	}
	b := ws.New(cfg)

	// 订阅新版25档orderBook
	b.Subscribe(ws.WSOrderBook25L1 + ".BTCUSD")
	// 实时交易
	//b.Subscribe("trade.BTCUSD")
	b.Subscribe(ws.WSTrade) // BTCUSD/ETHUSD/EOSUSD/XRPUSD
	// K线
	b.Subscribe(ws.WSKLine + ".BTCUSD.1m")
	// 每日保险基金更新
	b.Subscribe(ws.WSInsurance)
	// 产品最新行情
	b.Subscribe(ws.WSInstrument + ".BTCUSD")

	// 仓位变化
	b.Subscribe(ws.WSPosition)
	// 委托单成交信息
	b.Subscribe(ws.WSExecution)
	// 委托单的更新
	b.Subscribe(ws.WSOrder)

	b.On(ws.WSOrderBook25L1, handleOrderBook)
	b.On(ws.WSTrade, handleTrade)
	b.On(ws.WSKLine, handleKLine)
	b.On(ws.WSInsurance, handleInsurance)
	b.On(ws.WSInstrument, handleInstrument)

	b.On(ws.WSPosition, handlePosition)
	b.On(ws.WSExecution, handleExecution)
	b.On(ws.WSOrder, handleOrder)

	b.Start()

	forever := make(chan struct{})
	<-forever
}

func handleOrderBook(symbol string, data ws.OrderBook) {
	log.Printf("handleOrderBook %v/%v", symbol, data)
}

func handleTrade(symbol string, data []*ws.Trade) {
	log.Printf("handleTrade %v/%v", symbol, data)
}

func handleKLine(symbol string, data ws.KLine) {
	log.Printf("handleKLine %v/%v", symbol, data)
}

func handleInsurance(currency string, data []*ws.Insurance) {
	log.Printf("handleInsurance %v/%v", currency, data)
}

func handleInstrument(symbol string, data []*ws.Instrument) {
	log.Printf("handleInstrument %v/%v", symbol, data)
}

func handlePosition(data []*ws.Position) {
	log.Printf("handlePosition %v", data)
}

func handleExecution(data []*ws.Execution) {
	log.Printf("handleExecution %v", data)
}

func handleOrder(data []*ws.Order) {
	log.Printf("handleOrder %v", data)
}

bybit-api's People

Contributors

cnspot avatar f0cii avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

bybit-api's Issues

ByBit USDT Perpetual

While trying out crex I noticed I couldn't subscribe to positions on my bybit USDT account. It seems that the endpoint for USDT is different than the inverse one, see: ccxt/ccxt#6827

I get the following error:

2020/07/31 20:25:55 SignedRequest: {"ret_code":10001,"ret_msg":"Param validation for 'symbol' failed on the 'symbol' tag","ext_code":"","ext_info":"","result":null,"time_now":"1596219955.502511","rate_limit_status":119,"rate_limit_reset_ms":1596219955501,"rate_limit":120}

I see in the debug log it doesn't include the /private/linear/position/list as discussed above:

https://api.bybit.com/v2/private/position/list?xxxxx

I tried using the following symbol/market combinations:

market := crx.Market{ Symbol: "BTCUSDT", } ws.SubscribePositions(market, func(positions []*crx.Position) { //log.Printf("%#v", positions) for _, v := range positions { fmt.Println("profit:", v.Profit) fmt.Println("avg price:", v.AvgPrice) fmt.Println("size", v.Size) } })

position, _ := ws.GetPositions("USDT") for _, v := range position { fmt.Println(v) }

I looked around but couldnt find a place to fix this. Can you maybe help me out? Thanks!

Example WS Subscribing to Kline not getting a response?

Thanks for the code to show the connection with the Bybit API.

There is an issue where I don't see the example doing anything with b.Subscribe(ws.WSKLine + ".BTCUSD.1m")

I gather that this should be handled by the function func handleKLine(symbol string, data ws.KLine)

Watching the logs though I don't see it output anything of significance, is there something wrong or does something else trigger this function?

OHLC2 struct

Json cant read OHLC2 struct with types float64 beacuse of Bybit returns numbers with dot.

Rewrote struct, works fine

type OHLC2 struct {
	Symbol   string  `json:"symbol"`
	Interval string  `json:"interval"`
	OpenTime int64   `json:"open_time"`
	Open     float64 `json:"open,string"`
	High     float64 `json:"high,string"`
	Low      float64 `json:"low,string"`
	Close    float64 `json:"close,string"`
	Volume   float64 `json:"volume,string"`
	Turnover float64 `json:"turnover,string"`
}

Getting "readNumberAsString: invalid number" when getting trades from WebSocket

Hello,
I am getting this error when subscribing to trades via websocket:

2022/09/12 19:16:34 BybitWs subscribeHandler
2022/09/12 19:16:35 BybitWs {"topic":"trade.BTCUSDT","data":[{"symbol":"BTCUSDT","tick_direction":"ZeroMinusTick","price":"22230.50","size":0.004,"timestamp":"2022-09-12T17:16:33.000Z","trade_time_ms":"1663002993247","side":"Sell","trade_id":"d6634491-3ffd-537b-8424-e800c5b36f1b","is_block_trade":"false"}]}
2022/09/12 19:16:35 BybitWs []*ws.Trade: ws.Trade.Price: readNumberAsString: invalid number, error found in #10 byte of ...|","price":"22230.50"|..., bigger context ...|BTCUSDT","tick_direction":"ZeroMinusTick","price":"22230.50","size":0.004,"timestamp":"2022-09-12T17|...

This is the code I am using to connect and subscribe to the topic:

cfg := &ws.Configuration{
  Addr:          "wss://stream.bybit.com/realtime_public", 
  ApiKey:        "",
  SecretKey:     "",
  AutoReconnect: true,
  DebugMode:     true,
}
b := ws.New(cfg)
b.Subscribe("trade.BTCUSDT")
b.On(ws.WSTrade, handleTrade)
b.Start()

forever := make(chan struct{})
<-forever

I am not sure if I am doing anything wrong here but it looks like the library for some reason is not able to unmarshal the bybit json to the Trade struct.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.