Skip to content

Commit

Permalink
Update
Browse files Browse the repository at this point in the history
  • Loading branch information
f0cii committed Jan 25, 2022
1 parent cef6670 commit e3735cd
Show file tree
Hide file tree
Showing 5 changed files with 264 additions and 20 deletions.
31 changes: 27 additions & 4 deletions examples/rest/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,36 @@ package main
import (
"github.com/frankrap/bybit-api/rest"
"log"
"net/http"
"net/url"
)

// HttpProxy = "http://127.0.0.1:6152"
// SocksProxy = "socks5://127.0.0.1:6153"
func newClient(proxyURL string) *http.Client {
if proxyURL == "" {
return nil
}
proxy := func(_ *http.Request) (*url.URL, error) {
return url.Parse(proxyURL)
}

httpTransport := &http.Transport{
Proxy: proxy,
}

httpClient := &http.Client{
Transport: httpTransport,
}
return httpClient
}

func main() {
//baseURL := "https://api.bybit.com/" // 主网络
baseURL := "https://api-testnet.bybit.com/" // 测试网络
b := rest.New(nil,
baseURL, "YIxOY2RhFkylPudq96", "Bg9G2oFOb3aaIMguD3FOvOJJVBycaoXqXNcI", true)
client := newClient("socks5://127.0.0.1:1080")
b := rest.New(client,
baseURL, "rwEwhfC6mDFYIGfcyb", "yfNJSzGapfFwbJyvguAyVXLJSIOCIegBg42Z", true)

// 获取持仓
_, _, positions, err := b.GetPositions()
Expand All @@ -24,8 +47,8 @@ func main() {
symbol := "BTCUSD"
side := "Buy"
orderType := "Limit"
qty := 30
price := 7000.0
qty := 10
price := 35000.0
timeInForce := "GoodTillCancel"
_, _, order, err := b.CreateOrder(side, orderType, price, qty, timeInForce, 0, 0, false, false, "", symbol)
if err != nil {
Expand Down
72 changes: 62 additions & 10 deletions rest/api_linear.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,16 @@ func (b *ByBit) LinearGetKLine(symbol string, interval string, from int64, limit
return
}

// GetOrders
func (b *ByBit) LinearGetOrders(symbol string, orderStatus string, limit int, page int) (query string, resp []byte, result OrderListResponsePaginated, err error) {
// LinearGetOrders GetOrders
// orderStatus:
// Created - order has been accepted by the system but not yet put through the matching engine
// Rejected - order has been triggered but failed to be placed (e.g. due to insufficient margin)
// New - order has been placed successfully
// PartiallyFilled
// Filled
// Cancelled
// PendingCancel - matching engine has received the cancelation request but it may not be canceled successfully
func (b *ByBit) LinearGetOrders(symbol string, orderStatus string, limit int, page int) (query string, resp []byte, result OrderListResponseResultPaginated, err error) {
var cResult OrderListResponsePaginated
if limit == 0 {
limit = 20
Expand All @@ -44,7 +52,7 @@ func (b *ByBit) LinearGetOrders(symbol string, orderStatus string, limit int, pa
err = fmt.Errorf("%v body: [%v]", cResult.RetMsg, string(resp))
return
}
result = cResult
result = cResult.Result
return
}

Expand All @@ -65,7 +73,10 @@ func (b *ByBit) LinearGetActiveOrders(symbol string) (query string, resp []byte,
return
}

// CreateOrder
// LinearCreateOrder CreateOrder
// side: Buy/Sell
// orderType: Limit/Market
// timeInForce: GoodTillCancel/ImmediateOrCancel/FillOrKill/PostOnly
func (b *ByBit) LinearCreateOrder(side string, orderType string, price float64,
qty float64, timeInForce string, takeProfit float64, stopLoss float64, reduceOnly bool,
closeOnTrigger bool, orderLinkID string, symbol string) (query string, resp []byte, result Order, err error) {
Expand Down Expand Up @@ -98,6 +109,7 @@ func (b *ByBit) LinearCreateOrder(side string, orderType string, price float64,
err = fmt.Errorf("%v body: [%v]", cResult.RetMsg, string(resp))
return
}
// {"ret_code":0,"ret_msg":"OK","ext_code":"","ext_info":"","result":{"order_id":"6f771a91-0f4e-4c01-973d-b58e6390ece0","user_id":443679,"symbol":"BTCUSDT","side":"Buy","order_type":"Limit","price":37927.5,"qty":1,"time_in_force":"GoodTillCancel","order_status":"Created","last_exec_price":0,"cum_exec_qty":0,"cum_exec_value":0,"cum_exec_fee":0,"reduce_only":false,"close_on_trigger":false,"order_link_id":"","created_time":"2022-01-25T02:06:25Z","updated_time":"2022-01-25T02:06:25Z","take_profit":0,"stop_loss":0,"tp_trigger_by":"UNKNOWN","sl_trigger_by":"UNKNOWN","position_idx":1},"time_now":"1643076385.967696","rate_limit_status":99,"rate_limit_reset_ms":1643076385963,"rate_limit":100}
result = cResult.Result
return
}
Expand Down Expand Up @@ -126,14 +138,19 @@ func (b *ByBit) LinearReplaceOrder(symbol string, orderID string, qty float64, p
return
}

// CancelOrder
func (b *ByBit) LinearCancelOrder(orderID string, symbol string) (query string, resp []byte, result Order, err error) {
// LinearCancelOrder
// orderID: Order ID. Required if not passing order_link_id
// orderLinkId: Unique user-set order ID. Required if not passing order_id
func (b *ByBit) LinearCancelOrder(orderID string, orderLinkId string, symbol string) (query string, resp []byte, result Order, err error) {
var cResult OrderResponse
params := map[string]interface{}{}
params["symbol"] = symbol
if orderID != "" {
params["order_id"] = orderID
}
if orderLinkId != "" {
params["order_link_id"] = orderLinkId
}
query, resp, err = b.SignedRequest(http.MethodPost, "private/linear/order/cancel", params, &cResult)
if err != nil {
return
Expand All @@ -142,12 +159,12 @@ func (b *ByBit) LinearCancelOrder(orderID string, symbol string) (query string,
err = fmt.Errorf("%v body: [%v]", cResult.RetMsg, string(resp))
return
}

// {"ret_code":0,"ret_msg":"OK","ext_code":"","ext_info":"","result":{"order_id":"d328974d-bfe8-484f-a0e9-30159bc78aaf"},"time_now":"1643077335.069762","rate_limit_status":99,"rate_limit_reset_ms":1643077335056,"rate_limit":100}
result = cResult.Result
return
}

// CancelAllOrder
// LinearCancelAllOrder
func (b *ByBit) LinearCancelAllOrder(symbol string) (query string, resp []byte, result []string, err error) {
var cResult ResultStringArrayResponse
params := map[string]interface{}{}
Expand All @@ -165,7 +182,7 @@ func (b *ByBit) LinearCancelAllOrder(symbol string) (query string, resp []byte,
return
}

// GetStopOrders
// LinearGetStopOrders
func (b *ByBit) LinearGetStopOrders(symbol string, stopOrderStatus string, limit int, page int) (query string, resp []byte, result StopOrderListResponseResult, err error) {
var cResult StopOrderListResponse
if limit == 0 {
Expand All @@ -190,7 +207,7 @@ func (b *ByBit) LinearGetStopOrders(symbol string, stopOrderStatus string, limit
return
}

// GetActiveStopOrders
// LinearGetActiveStopOrders
func (b *ByBit) LinearGetActiveStopOrders(symbol string) (query string, resp []byte, result StopOrderArrayResponse, err error) {
var cResult StopOrderArrayResponse
params := map[string]interface{}{}
Expand Down Expand Up @@ -300,3 +317,38 @@ func (b *ByBit) LinearCancelAllStopOrders(symbol string) (query string, resp []b
result = cResult.Result
return
}

// LinearGetPositions
func (b *ByBit) LinearGetPositions() (query string, resp []byte, result []LinearPositionData, err error) {
var r LinearPositionDataArrayResponse
params := map[string]interface{}{}
query, resp, err = b.SignedRequest(http.MethodGet, "private/linear/position/list", params, &r)
if err != nil {
return
}
if r.RetCode != 0 {
err = fmt.Errorf("%v body: [%v]", r.RetMsg, string(resp))
return
}
result = r.Result
return
}

// LinearGetPosition
func (b *ByBit) LinearGetPosition(symbol string) (query string, resp []byte, result []LinearPosition, err error) {
var r LinearPositionArrayResponse
params := map[string]interface{}{}
if symbol != "" {
params["symbol"] = symbol
}
query, resp, err = b.SignedRequest(http.MethodGet, "private/linear/position/list", params, &r)
if err != nil {
return
}
if r.RetCode != 0 {
err = fmt.Errorf("%v body: [%v]", r.RetMsg, string(resp))
return
}
result = r.Result
return
}
102 changes: 102 additions & 0 deletions rest/api_linear_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
package rest

import (
"testing"
"time"
)

func TestLinear_GetOrderBook(t *testing.T) {
b := newByBit()
_, _, ob, err := b.GetOrderBook("BTCUSDT")
if err != nil {
t.Error(err)
return
}
for _, v := range ob.Asks {
t.Logf("Ask: %#v", v)
}
for _, v := range ob.Bids {
t.Logf("Bid: %#v", v)
}
t.Logf("%v", ob.Time)
}

func TestByBit_LinearGetKLine(t *testing.T) {
b := newByBit()
from := time.Now().Add(-1 * time.Hour).Unix()
_, _, ohlcs, err := b.LinearGetKLine("BTCUSDT", "1", from, 10)
if err != nil {
t.Error(err)
return
}
for _, v := range ohlcs {
t.Logf("%#v", v)
}
}

func TestByBit_LinearCreateOrder(t *testing.T) {
b := newByBit()
_, _, order, err := b.LinearCreateOrder("Buy", "Limit", 35000, 1, "GoodTillCancel", 0,
0, false, false, "", "BTCUSDT")
if err != nil {
t.Error(err)
return
}
t.Logf("%#v", order)
}

func TestByBit_LinearGetOrders(t *testing.T) {
b := newByBit()
_, _, orders, err := b.LinearGetOrders("BTCUSDT", "Created,New", 10, 0)
if err != nil {
t.Error(err)
return
}
t.Logf("%#v", orders.Data)
}

func TestByBit_LinearCancelOrder(t *testing.T) {
b := newByBit()
_, _, ret, err := b.LinearCancelOrder("d328974d-bfe8-484f-a0e9-30159bc78aaf", "", "BTCUSDT")
if err != nil {
t.Error(err)
return
}
t.Logf("%#v", ret)
}

func TestByBit_LinearCancelAllOrder(t *testing.T) {
b := newByBit()
_, _, ret, err := b.LinearCancelAllOrder("BTCUSDT")
if err != nil {
t.Error(err)
return
}
t.Logf("%#v", ret)
}

func TestByBit_LinearGetPositions(t *testing.T) {
b := newByBit()
_, _, ret, err := b.LinearGetPositions() // BTCUSDT
if err != nil {
t.Error(err)
return
}
// t.Logf("%#v", ret)
for _, v := range ret {
if !v.IsValid || v.Data.Size == 0 {
continue
}
t.Logf("%#v", v)
}
}

func TestByBit_LinearGetPosition(t *testing.T) {
b := newByBit()
_, _, ret, err := b.LinearGetPosition("BTCUSDT")
if err != nil {
t.Error(err)
return
}
t.Logf("%#v", ret)
}
36 changes: 30 additions & 6 deletions rest/api_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,42 @@ package rest
import (
"github.com/stretchr/testify/assert"
"log"
"net/http"
"net/url"
"testing"
"time"
)

// https://t.me/Bybitapi

// HttpProxy = "http://127.0.0.1:6152"
// SocksProxy = "socks5://127.0.0.1:6153"
func newClient(proxyURL string) *http.Client {
if proxyURL == "" {
return nil
}
proxy := func(_ *http.Request) (*url.URL, error) {
return url.Parse(proxyURL)
}

httpTransport := &http.Transport{
Proxy: proxy,
}

httpClient := &http.Client{
Transport: httpTransport,
}
return httpClient
}

func newByBit() *ByBit {
//baseURL := "https://api.bybit.com/"
//baseURL := "https://api-testnet.bybit.com/"
baseURL := "https://api.bytick.com/"
apiKey := "6IASD6KDBdunn5qLpT"
secretKey := "nXjZMUiB3aMiPaQ9EUKYFloYNd0zM39RjRWF"
b := New(nil, baseURL, apiKey, secretKey, true)
baseURL := "https://api-testnet.bybit.com/"
//baseURL := "https://api.bytick.com/"
apiKey := "rwEwhfC6mDFYIGfcyb"
secretKey := "yfNJSzGapfFwbJyvguAyVXLJSIOCIegBg42Z"
client := newClient("socks5://127.0.0.1:1080")
b := New(client, baseURL, apiKey, secretKey, true)
err := b.SetCorrectServerTime()
if err != nil {
log.Printf("%v", err)
Expand Down Expand Up @@ -84,7 +107,8 @@ func TestByBit_GetSymbols(t *testing.T) {

func TestByBit_GetWalletBalance(t *testing.T) {
b := newByBit()
_, _, balance, err := b.GetWalletBalance("BTC")
//_, _, balance, err := b.GetWalletBalance("BTC")
_, _, balance, err := b.GetWalletBalance("USDT")
if err != nil {
t.Error(err)
return
Expand Down
Loading

0 comments on commit e3735cd

Please sign in to comment.