bitmex

package module
v0.1.3 Latest Latest
Warning

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

Go to latest
Published: May 19, 2024 License: MIT Imports: 24 Imported by: 0

README

bitmex-api

A Go wrapper to the BitMEX API

Example
package main

import (
	"fmt"
	"github.com/t2o2/bitmex-api"
	"github.com/t2o2/bitmex-api/swagger"
	"log"
)

func main() {
    b := bitmex.New(nil,
        bitmex.HostTestnet, "8K2Oi0bnRRZ7GK4UJnY-38oj", "9EmGvk8mKX5nWa11y1KyPPGn78Lv2ZEiLx3TH0YasE_oE06y", true)
	subscribeInfos := []bitmex.SubscribeInfo{
		{Op: bitmex.BitmexWSOrderBookL2, Param: "XBTUSD"},
		{Op: bitmex.BitmexWSOrder, Param: "XBTUSD"},
		{Op: bitmex.BitmexWSPosition, Param: "XBTUSD"},
		{Op: bitmex.BitmexWSMargin, Param: "XBTUSD"},
	}
	err := b.Subscribe(subscribeInfos)
	if err != nil {
		log.Fatal(err)
	}

	b.On(bitmex.BitmexWSOrderBookL2, func(m bitmex.OrderBookDataL2, symbol string) {
		ob := m.OrderBook()
		fmt.Printf("\rOrderbook Asks: %#v Bids: %#v                            ", ob.Asks[0], ob.Bids[0])
	}).On(bitmex.BitmexWSOrder, func(m []*swagger.Order, action string) {
		fmt.Printf("Order action=%v orders=%#v\n", action, m)
	}).On(bitmex.BitmexWSPosition, func(m []*swagger.Position, action string) {
		fmt.Printf("Position action=%v positions=%#v\n", action, m)
	}).On(bitmex.BitmexWSMargin, func(m []*swagger.Margin, action string) {
		fmt.Printf("Wallet action=%v margins=%#v\n", action, m)
	})

	b.StartWS()

	// Get orderbook by rest api
	b.GetOrderBook(10, "XBTUSD")
	// Place a limit buy order
	b.PlaceOrder(bitmex.SIDE_BUY, bitmex.ORD_TYPE_LIMIT, 0, 6000.0, 1000, "", "", "XBTUSD")
	b.GetOrders("XBTUSD")
	b.GetOrder("{OrderID}", "XBTUSD")
	b.AmendOrder("{OrderID}", 6000.5)
	b.CancelOrder("{OrderID}")
	b.CancelAllOrders("XBTUSD")
	b.GetPosition("XBTUSD")
	b.GetMargin()

	forever := make(chan bool)
	<-forever
}

Documentation

Index

Constants

View Source
const (
	HostReal    = "www.bitmex.com"
	HostTestnet = "testnet.bitmex.com"
)
View Source
const (
	// 委托的方向
	SIDE_BUY  = "Buy"
	SIDE_SELL = "Sell"

	// 委托的类型
	ORD_TYPE_MARKET                         = "Market"          // 市价
	ORD_TYPE_LIMIT                          = "Limit"           // 限价
	ORD_TYPE_STOP                           = "Stop"            // 市价止损
	ORD_TYPE_STOP_LIMIT                     = "StopLimit"       // 限价止损
	ORD_TYPE_MARKET_IF_TOUCHED              = "MarketIfTouched" // 市价止盈
	ORD_TYPE_LIMIT_IF_TOUCHED               = "LimitIfTouched"  // 限价止盈
	ORD_TYPE_MARKET_WITH_LEFT_OVER_AS_LIMIT = "MarketWithLeftOverAsLimit"

	// 委托的状态
	OS_NEW              = "New"
	OS_PARTIALLY_FILLED = "PartiallyFilled"
	OS_FILLED           = "Filled"
	OS_CANCELED         = "Canceled"
	OS_REJECTED         = "Rejected"
)
View Source
const (
	// Bitmex websocket op
	BitmexWSAnnouncement        = "announcement"        // 网站公告
	BitmexWSChat                = "chat"                // Trollbox 聊天室
	BitmexWSConnected           = "connected"           // 已连接用户/机器人的统计数据
	BitmexWSFunding             = "funding"             // 永续产品的资金费率更新 每个资金时段发送(通常是 8 小时)
	BitmexWSInstrument          = "instrument"          // 产品更新,包括交易量以及报价
	BitmexWSInsurance           = "insurance"           // 每日保险基金的更新
	BitmexWSLiquidation         = "liquidation"         // 进入委托列表的强平委托
	BitmexWSOrderBookL2_25      = "orderBookL2_25"      // 前 25 层的 Level 2 委托列表
	BitmexWSOrderBookL2         = "orderBookL2"         // 完整的 level 2 委托列表
	BitmexWSOrderBook10         = "orderBook10"         // 前 10 层的委托列表,用传统的完整委托列表推送
	BitmexWSPublicNotifications = "publicNotifications" // 全系统的告示(用于段时间的消息)
	BitmexWSQuote               = "quote"               // 最高层的委托列表
	BitmexWSQuoteBin1m          = "quoteBin1m"          // 每分钟报价数据
	BitmexWSQuoteBin5m          = "quoteBin5m"          // 每 5 分钟报价数据
	BitmexWSQuoteBin1h          = "quoteBin1h"          // 每小时报价数据
	BitmexWSQuoteBin1d          = "quoteBin1d"          // 每天报价数据
	BitmexWSSettlement          = "settlement"          // 结算信息
	BitmexWSTrade               = "trade"               // 实时交易
	BitmexWSTradeBin1m          = "tradeBin1m"          // 每分钟交易数据
	BitmexWSTradeBin5m          = "tradeBin5m"          // 每 5 分钟交易数据
	BitmexWSTradeBin1h          = "tradeBin1h"          // 每小时交易数据
	BitmexWSTradeBin1d          = "tradeBin1d"          // 每天交易数据

	// Bitmex websocket private op
	BitmexWSAffiliate            = "affiliate"            // 邀请人状态,已邀请用户及分红比率
	BitmexWSExecution            = "execution"            // 个别成交,可能是多个成交
	BitmexWSOrder                = "order"                // 你委托的更新
	BitmexWSMargin               = "margin"               // 你账户的余额和保证金要求的更新
	BitmexWSPosition             = "position"             // 你仓位的更新
	BitmexWSPrivateNotifications = "privateNotifications" // 个人的通知,现时并未使用
	BitmexWSTransact             = "transact"             // 资金提存更新
	BitmexWSWallet               = "wallet"               // 比特币余额更新及总提款存款

)

Variables

View Source
var (
	NotFound = errors.New("not found")
)

Functions

func GetClient

func GetClient(ctx context.Context) *swagger.APIClient

func GetConfiguration

func GetConfiguration(ctx context.Context) *swagger.Configuration

func MakeContext

func MakeContext(key string, secret string, host string, timeout int64) context.Context

Types

type BitMEX

type BitMEX struct {
	Key    string
	Secret string
	// contains filtered or unexported fields
}

BitMEX describes the API

func New

func New(httpClient *http.Client, host string, key string, secret string, debugMode bool) *BitMEX

New allows the use of the public or private and websocket api

func (*BitMEX) AmendOrder

func (b *BitMEX) AmendOrder(oid string, price float64) (order swagger.Order, err error)

func (*BitMEX) AmendOrder2

func (b *BitMEX) AmendOrder2(orderID string, origClOrdID string, clOrdID string, simpleOrderQty float64, orderQty float32, simpleLeavesQty float64, leavesQty float32, price float64, stopPx float64, pegOffsetValue float64, text string) (order swagger.Order, err error)

func (*BitMEX) CancelAllOrders

func (b *BitMEX) CancelAllOrders(symbol string) (orders []swagger.Order, err error)

func (*BitMEX) CancelOrder

func (b *BitMEX) CancelOrder(oid string) (order swagger.Order, err error)

func (*BitMEX) CloseOrder

func (b *BitMEX) CloseOrder(side string, ordType string, price float64, orderQty int32, postOnly bool, timeInForce string, symbol string) (order swagger.Order, err error)

func (*BitMEX) CloseWS

func (b *BitMEX) CloseWS()

CloseWS closes the websocket connection

func (*BitMEX) ConfirmWithdrawal

func (b *BitMEX) ConfirmWithdrawal(token string) (trans swagger.Transaction, err error)

func (*BitMEX) Emit

func (b *BitMEX) Emit(event interface{}, arguments ...interface{}) *emission.Emitter

Emit emits an event

func (*BitMEX) GetBucketed

func (b *BitMEX) GetBucketed(symbol string, binSize string, partial bool, filter string, columns string, count float32, start float32, reverse bool, startTime time.Time, endTime time.Time) (o []swagger.TradeBin, err error)

func (*BitMEX) GetInstrument

func (b *BitMEX) GetInstrument(symbol string, count int, reverse bool) (result []swagger.Instrument, err error)

func (*BitMEX) GetMargin

func (b *BitMEX) GetMargin(ccy string) (margin swagger.Margin, err error)

func (*BitMEX) GetOrder

func (b *BitMEX) GetOrder(oid string, symbol string) (order swagger.Order, err error)

func (*BitMEX) GetOrderBook

func (b *BitMEX) GetOrderBook(depth int, symbol string) (ob OrderBook, err error)

func (*BitMEX) GetOrderByClOrdID

func (b *BitMEX) GetOrderByClOrdID(clOrdID string, symbol string) (order swagger.Order, err error)

func (*BitMEX) GetOrders

func (b *BitMEX) GetOrders(symbol string) (orders []swagger.Order, err error)

func (*BitMEX) GetOrdersRaw

func (b *BitMEX) GetOrdersRaw(symbol string, filter string) (orders []swagger.Order, err error)

func (*BitMEX) GetPosition

func (b *BitMEX) GetPosition(symbol string) (position swagger.Position, err error)

func (*BitMEX) GetPositions

func (b *BitMEX) GetPositions(symbol string) (positions []swagger.Position, err error)

func (*BitMEX) GetPositionsRaw

func (b *BitMEX) GetPositionsRaw(filter string, columns string, count int32) (positions []swagger.Position, err error)

func (*BitMEX) GetRateLimit

func (b *BitMEX) GetRateLimit() RateLimit

func (*BitMEX) GetRateLimitPublic

func (b *BitMEX) GetRateLimitPublic() RateLimit

func (*BitMEX) GetTradeHistoryAfter added in v0.1.2

func (b *BitMEX) GetTradeHistoryAfter(symbol string, startTime time.Time) ([]swagger.Execution, error)

func (*BitMEX) GetTradeHistoryByCount added in v0.1.2

func (b *BitMEX) GetTradeHistoryByCount(symbol string, count int) (trades []swagger.Execution, err error)

func (*BitMEX) GetVersion

func (b *BitMEX) GetVersion() (version Version, time time.Duration, err error)

func (*BitMEX) GetWallet

func (b *BitMEX) GetWallet() (wallet swagger.Wallet, err error)

func (*BitMEX) NewOrder

func (b *BitMEX) NewOrder(side string, ordType string, price float64, orderQty int32, postOnly bool, timeInForce string, symbol string) (order swagger.Order, err error)

func (*BitMEX) Off

func (b *BitMEX) Off(event interface{}, listener interface{}) *emission.Emitter

Off removes a listener for an event

func (*BitMEX) On

func (b *BitMEX) On(event interface{}, listener interface{}) *emission.Emitter

On adds a listener to a specific event

func (*BitMEX) PlaceOrder

func (b *BitMEX) PlaceOrder(side string, ordType string, stopPx float64, price float64, orderQty int32, timeInForce string, execInst string, symbol string) (order swagger.Order, err error)

PlaceOrder 放置委托单 execInst: MarkPrice = 标记价格 IndexPrice = 指数价格 LastPrice = 最新成交 ParticipateDoNotInitiate = 被动委托

func (*BitMEX) PlaceOrder2

func (b *BitMEX) PlaceOrder2(side string, ordType string, stopPx float64, price float64, orderQty int32,
	displayQty int32, timeInForce string, execInst string, symbol string, clOrdID string, text string) (order swagger.Order, err error)

PlaceOrder 放置委托单 side: Buy/Sell ordType: = Limit/Stop/StopLimit/MarketIfTouched/LimitIfTouched/MarketWithLeftOverAsLimit stopPx: 止损止盈触发价 price: 委托价 orderQty: 委托数量 displayQty: 默认传: -1 execInst: MarkPrice = 标记价格 IndexPrice = 指数价格 LastPrice = 最新成交 ParticipateDoNotInitiate = 被动委托

func (*BitMEX) PositionUpdateLeverage

func (b *BitMEX) PositionUpdateLeverage(leverage float64, symbol string) (position swagger.Position, err error)

func (*BitMEX) RequestWithdrawal

func (b *BitMEX) RequestWithdrawal(currency string, amount float32, address string, otpToken string, fee float64) (trans swagger.Transaction, err error)

func (*BitMEX) SetHttpProxy

func (b *BitMEX) SetHttpProxy(proxyURL string) error

SetHttpProxy proxyURL: http://127.0.0.1:1080

func (*BitMEX) SetProxy

func (b *BitMEX) SetProxy(socks5Proxy string) error

SetProxy proxyURL: 127.0.0.1:1080

func (*BitMEX) StartWS

func (b *BitMEX) StartWS()

StartWS opens the websocket connection, and waits for message events

func (*BitMEX) Subscribe

func (b *BitMEX) Subscribe(subscribeTypes []SubscribeInfo) error

type Item

type Item struct {
	Amount float64 `json:"amount"`
	Price  float64 `json:"price"`
}

Item stores the amount and price values

type OrderBook

type OrderBook struct {
	Bids      []Item    `json:"bids"`
	Asks      []Item    `json:"asks"`
	Timestamp time.Time `json:"timestamp"`
}

func (*OrderBook) Ask

func (ob *OrderBook) Ask() float64

func (*OrderBook) Bid

func (ob *OrderBook) Bid() float64

func (*OrderBook) Valid

func (ob *OrderBook) Valid() bool

type OrderBook10

type OrderBook10 struct {
	Bids      [][]float64 `json:"bids"`
	Asks      [][]float64 `json:"asks"`
	Timestamp time.Time   `json:"timestamp"`
	Symbol    string      `json:"symbol"`
}

OrderBook10 contains order book 10

type OrderBookData

type OrderBookData []*OrderBookL2

type OrderBookDataL2

type OrderBookDataL2 struct {
	RawData   []OrderBookL2
	Timestamp time.Time
}

func (*OrderBookDataL2) OrderBook

func (o *OrderBookDataL2) OrderBook() (ob OrderBook)

type OrderBookL2

type OrderBookL2 struct {
	ID     int64   `json:"id"`
	Price  float64 `json:"price"`
	Side   string  `json:"side"`
	Size   int64   `json:"size"`
	Symbol string  `json:"symbol"`
}

OrderBookL2 contains order book l2

func (*OrderBookL2) Key

func (o *OrderBookL2) Key() string

type OrderBookLocal

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

func NewOrderBookLocal

func NewOrderBookLocal() *OrderBookLocal

func (*OrderBookLocal) GetOrderbook

func (o *OrderBookLocal) GetOrderbook() (ob OrderBook)

func (*OrderBookLocal) GetOrderbookL2

func (o *OrderBookLocal) GetOrderbookL2() (ob OrderBookDataL2)

func (*OrderBookLocal) LoadSnapshot

func (o *OrderBookLocal) LoadSnapshot(newOrderbook []*OrderBookL2) error

func (*OrderBookLocal) Update

func (o *OrderBookLocal) Update(orderbook []*OrderBookL2, action string)

type RateLimit

type RateLimit struct {
	Limit     int64
	Remaining int64
	Reset     int64
}

type Response

type Response struct {
	Success   bool        `json:"success,omitempty"`
	Subscribe string      `json:"subscribe,omitempty"`
	Request   interface{} `json:"request,omitempty"`
	Table     string      `json:"table,omitempty"`
	Action    string      `json:"action,omitempty"`
	Data      interface{} `json:"data,omitempty"`
}

type SubscribeInfo

type SubscribeInfo struct {
	Op    string
	Param string
}

type Version

type Version struct {
	Name      string `json:"name"`
	Version   string `json:"version"`
	Timestamp int64  `json:"timestamp"`
}

{"name":"BitMEX API","version":"1.2.0","timestamp":1554709447283}

type WSCmd

type WSCmd struct {
	Command string        `json:"op"`
	Args    []interface{} `json:"args"`
}

Directories

Path Synopsis
Package recws provides websocket client based on gorilla/websocket that will automatically reconnect if the connection is dropped.
Package recws provides websocket client based on gorilla/websocket that will automatically reconnect if the connection is dropped.

Jump to

Keyboard shortcuts

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