├── .gitignore ├── LICENSE ├── README.md ├── api.go ├── api_test.go ├── events.go ├── example ├── build_linux_amd64.bat └── main.go ├── go.mod ├── go.sum ├── order_test.go ├── orderbook.go ├── recws ├── LICENSE ├── README.md ├── examples │ └── basic.go ├── keepalive.go └── recws.go ├── rest.go ├── rest_test.go ├── swagger ├── access_token.go ├── affiliate.go ├── announcement.go ├── announcement_api.go ├── api_client.go ├── api_key.go ├── api_key_api.go ├── api_response.go ├── auth_util.go ├── chat.go ├── chat_api.go ├── chat_channel.go ├── configuration.go ├── connected_users.go ├── error_error.go ├── execution.go ├── execution_api.go ├── funding.go ├── funding_api.go ├── index_composite.go ├── inline_response_200.go ├── instrument.go ├── instrument_api.go ├── instrument_interval.go ├── insurance.go ├── insurance_api.go ├── leaderboard.go ├── leaderboard_api.go ├── liquidation.go ├── liquidation_api.go ├── margin.go ├── model_error.go ├── notification.go ├── notification_api.go ├── order.go ├── order_api.go ├── order_book.go ├── order_book_api.go ├── order_book_l2.go ├── position.go ├── position_api.go ├── quote.go ├── quote_api.go ├── schema_api.go ├── settlement.go ├── settlement_api.go ├── stats.go ├── stats_api.go ├── stats_history.go ├── stats_usd.go ├── trade.go ├── trade_api.go ├── trade_bin.go ├── transaction.go ├── user.go ├── user_api.go ├── user_commission.go ├── user_preferences.go ├── wallet.go └── x_any.go ├── testdata └── config.yaml.example ├── ws.go └── ws_test.go /.gitignore: -------------------------------------------------------------------------------- 1 | # Binaries for programs and plugins 2 | *.exe 3 | *.exe~ 4 | *.dll 5 | *.so 6 | *.dylib 7 | 8 | # Test binary, build with `go test -c` 9 | *.test 10 | 11 | # Output of the go coverage tool, specifically when used with LiteIDE 12 | *.out 13 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2019 Frankrap 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # bitmex-api 2 | A Go wrapper to the BitMEX API 3 | 4 | ### Example 5 | 6 | ``` 7 | package main 8 | 9 | import ( 10 | "fmt" 11 | "github.com/frankrap/bitmex-api" 12 | "github.com/frankrap/bitmex-api/swagger" 13 | "log" 14 | ) 15 | 16 | func main() { 17 | b := bitmex.New(nil, 18 | bitmex.HostTestnet, "8K2Oi0bnRRZ7GK4UJnY-38oj", "9EmGvk8mKX5nWa11y1KyPPGn78Lv2ZEiLx3TH0YasE_oE06y", true) 19 | subscribeInfos := []bitmex.SubscribeInfo{ 20 | {Op: bitmex.BitmexWSOrderBookL2, Param: "XBTUSD"}, 21 | {Op: bitmex.BitmexWSOrder, Param: "XBTUSD"}, 22 | {Op: bitmex.BitmexWSPosition, Param: "XBTUSD"}, 23 | {Op: bitmex.BitmexWSMargin, Param: "XBTUSD"}, 24 | } 25 | err := b.Subscribe(subscribeInfos) 26 | if err != nil { 27 | log.Fatal(err) 28 | } 29 | 30 | b.On(bitmex.BitmexWSOrderBookL2, func(m bitmex.OrderBookDataL2, symbol string) { 31 | ob := m.OrderBook() 32 | fmt.Printf("\rOrderbook Asks: %#v Bids: %#v ", ob.Asks[0], ob.Bids[0]) 33 | }).On(bitmex.BitmexWSOrder, func(m []*swagger.Order, action string) { 34 | fmt.Printf("Order action=%v orders=%#v\n", action, m) 35 | }).On(bitmex.BitmexWSPosition, func(m []*swagger.Position, action string) { 36 | fmt.Printf("Position action=%v positions=%#v\n", action, m) 37 | }).On(bitmex.BitmexWSMargin, func(m []*swagger.Margin, action string) { 38 | fmt.Printf("Wallet action=%v margins=%#v\n", action, m) 39 | }) 40 | 41 | b.StartWS() 42 | 43 | // Get orderbook by rest api 44 | b.GetOrderBook(10, "XBTUSD") 45 | // Place a limit buy order 46 | b.PlaceOrder(bitmex.SIDE_BUY, bitmex.ORD_TYPE_LIMIT, 0, 6000.0, 1000, "", "", "XBTUSD") 47 | b.GetOrders("XBTUSD") 48 | b.GetOrder("{OrderID}", "XBTUSD") 49 | b.AmendOrder("{OrderID}", 6000.5) 50 | b.CancelOrder("{OrderID}") 51 | b.CancelAllOrders("XBTUSD") 52 | b.GetPosition("XBTUSD") 53 | b.GetMargin() 54 | 55 | forever := make(chan bool) 56 | <-forever 57 | } 58 | ``` -------------------------------------------------------------------------------- /api.go: -------------------------------------------------------------------------------- 1 | package bitmex 2 | 3 | import ( 4 | "context" 5 | "github.com/chuckpreslar/emission" 6 | "github.com/frankrap/bitmex-api/recws" 7 | "golang.org/x/net/proxy" 8 | "log" 9 | "net" 10 | "time" 11 | 12 | //"github.com/recws-org/recws" 13 | "github.com/frankrap/bitmex-api/swagger" 14 | "net/http" 15 | "net/url" 16 | "sync" 17 | ) 18 | 19 | const ( 20 | HostReal = "www.bitmex.com" 21 | HostTestnet = "testnet.bitmex.com" 22 | ) 23 | 24 | type RateLimit struct { 25 | Limit int64 26 | Remaining int64 27 | Reset int64 28 | } 29 | 30 | // BitMEX describes the API 31 | type BitMEX struct { 32 | Key string 33 | Secret string 34 | host string 35 | proxyURL string 36 | debugMode bool 37 | 38 | ctx context.Context 39 | timeout time.Duration 40 | httpClient *http.Client 41 | cfg *swagger.Configuration 42 | client *swagger.APIClient 43 | rateLimitMutexPublic sync.RWMutex 44 | rateLimitMutex sync.RWMutex 45 | rateLimitPublic RateLimit 46 | rateLimit RateLimit 47 | 48 | ws recws.RecConn 49 | emitter *emission.Emitter 50 | subscribeCmd *WSCmd 51 | orderBookLocals map[string]*OrderBookLocal // key: symbol 52 | orderLocals map[string]*swagger.Order // key: OrderID 53 | orderBookLoaded map[string]bool // key: symbol 54 | } 55 | 56 | // New allows the use of the public or private and websocket api 57 | func New(httpClient *http.Client, host string, key string, secret string, debugMode bool) *BitMEX { 58 | b := &BitMEX{} 59 | b.Key = key 60 | b.Secret = secret 61 | b.debugMode = debugMode 62 | b.emitter = emission.NewEmitter() 63 | b.orderBookLocals = make(map[string]*OrderBookLocal) 64 | b.orderLocals = make(map[string]*swagger.Order) 65 | b.orderBookLoaded = make(map[string]bool) 66 | b.ws = recws.RecConn{ 67 | SubscribeHandler: b.subscribeHandler, 68 | } 69 | b.host = host 70 | b.ctx = MakeContext(key, secret, host, 10) 71 | b.timeout = 10 * time.Second 72 | b.cfg = GetConfiguration(b.ctx) 73 | if httpClient == nil { 74 | httpClient = &http.Client{ 75 | Timeout: b.timeout, 76 | } 77 | } 78 | b.httpClient = httpClient 79 | b.cfg.HTTPClient = httpClient 80 | b.client = swagger.NewAPIClient(b.cfg) 81 | return b 82 | } 83 | 84 | // SetHttpProxy proxyURL: http://127.0.0.1:1080 85 | func (b *BitMEX) SetHttpProxy(proxyURL string) error { 86 | proxyURL_, err := url.Parse(proxyURL) 87 | if err != nil { 88 | return err 89 | } 90 | 91 | //adding the proxy settings to the Transport object 92 | transport := &http.Transport{ 93 | Proxy: http.ProxyURL(proxyURL_), 94 | } 95 | 96 | //adding the Transport object to the http Client 97 | client := &http.Client{ 98 | Transport: transport, 99 | Timeout: b.timeout, 100 | } 101 | b.httpClient = client 102 | b.cfg.HTTPClient = client 103 | b.proxyURL = proxyURL 104 | return nil 105 | } 106 | 107 | // SetProxy proxyURL: 127.0.0.1:1080 108 | func (b *BitMEX) SetProxy(socks5Proxy string) error { 109 | // socks5Proxy := "127.0.0.1:1080" 110 | dialer, err := proxy.SOCKS5("tcp", socks5Proxy, nil, proxy.Direct) 111 | if err != nil { 112 | log.Fatal("Error creating dialer, aborting.") 113 | } 114 | 115 | dialFunc := func(ctx context.Context, network, addr string) (net.Conn, error) { 116 | return dialer.Dial(network, addr) 117 | } 118 | 119 | tr := &http.Transport{DialContext: dialFunc} // Dial: dialer.Dial, 120 | client := &http.Client{Transport: tr, Timeout: b.timeout} 121 | 122 | b.httpClient = client 123 | b.cfg.HTTPClient = client 124 | b.proxyURL = "http://" + socks5Proxy 125 | return nil 126 | } 127 | 128 | func (b *BitMEX) GetRateLimit() RateLimit { 129 | b.rateLimitMutex.RLock() 130 | defer b.rateLimitMutex.RUnlock() 131 | return b.rateLimit 132 | } 133 | 134 | func (b *BitMEX) GetRateLimitPublic() RateLimit { 135 | b.rateLimitMutexPublic.RLock() 136 | defer b.rateLimitMutexPublic.RUnlock() 137 | return b.rateLimitPublic 138 | } 139 | 140 | func MakeContext(key string, secret string, host string, timeout int64) context.Context { 141 | return context.WithValue(context.TODO(), swagger.ContextAPIKey, swagger.APIKey{ 142 | Key: key, 143 | Secret: secret, 144 | Host: host, 145 | Timeout: timeout, 146 | }) 147 | } 148 | 149 | func GetConfiguration(ctx context.Context) *swagger.Configuration { 150 | c := ctx.Value(swagger.ContextAPIKey).(swagger.APIKey) 151 | cfg := &swagger.Configuration{ 152 | BasePath: "https://" + c.Host + "/api/v1", 153 | DefaultHeader: make(map[string]string), 154 | UserAgent: "Swagger-Codegen/1.0.0/go", 155 | ExpireTime: 5, //seconds 156 | } 157 | return cfg 158 | } 159 | 160 | func GetClient(ctx context.Context) *swagger.APIClient { 161 | c := ctx.Value(swagger.ContextAPIKey).(swagger.APIKey) 162 | cfg := &swagger.Configuration{ 163 | BasePath: "https://" + c.Host + "/api/v1", 164 | DefaultHeader: make(map[string]string), 165 | UserAgent: "Swagger-Codegen/1.0.0/go", 166 | ExpireTime: 5, //seconds 167 | } 168 | 169 | return swagger.NewAPIClient(cfg) 170 | } 171 | -------------------------------------------------------------------------------- /api_test.go: -------------------------------------------------------------------------------- 1 | package bitmex 2 | 3 | import ( 4 | "github.com/micro/go-micro/config" 5 | "github.com/micro/go-micro/config/source/file" 6 | "testing" 7 | ) 8 | 9 | var ( 10 | _proxyURL string 11 | _testnet bool 12 | _key string 13 | _secret string 14 | _key2 string 15 | _secret2 string 16 | ) 17 | 18 | func loadConfig() { 19 | err := config.Load(file.NewSource(file.WithPath("./testdata/config.yaml"))) 20 | if err != nil { 21 | return 22 | } 23 | cfg := config.Map() 24 | 25 | _proxyURL = cfg["proxy_url"].(string) 26 | _testnet = cfg["testnet"].(bool) 27 | _key = cfg["key"].(string) 28 | _secret = cfg["secret"].(string) 29 | _key2 = cfg["key2"].(string) 30 | _secret2 = cfg["secret2"].(string) 31 | } 32 | 33 | func TestConfig(t *testing.T) { 34 | err := config.Load(file.NewSource(file.WithPath("./testdata/config.yaml"))) 35 | if err != nil { 36 | t.Error(err) 37 | } 38 | cfg := config.Map() 39 | 40 | proxy := cfg["proxy_url"].(string) 41 | testnet := cfg["testnet"].(bool) 42 | key := cfg["key"].(string) 43 | secret := cfg["secret"].(string) 44 | key2 := cfg["key2"].(string) 45 | secret2 := cfg["secret2"].(string) 46 | 47 | t.Log(proxy) 48 | t.Log(testnet) 49 | t.Log(key) 50 | t.Log(secret) 51 | t.Log(key2) 52 | t.Log(secret2) 53 | } 54 | 55 | func newBitmexForTest() *BitMEX { 56 | loadConfig() 57 | var host string 58 | if _testnet { 59 | host = HostTestnet 60 | } else { 61 | host = HostReal 62 | } 63 | bitmex := New(nil, host, _key, _secret, true) 64 | if _proxyURL != "" { 65 | bitmex.SetHttpProxy(_proxyURL) 66 | } 67 | return bitmex 68 | } 69 | 70 | func newBitmexForTest2() *BitMEX { 71 | loadConfig() 72 | var host string 73 | if _testnet { 74 | host = HostTestnet 75 | } else { 76 | host = HostReal 77 | } 78 | bitmex := New(nil, host, _key2, _secret2, true) 79 | if _proxyURL != "" { 80 | bitmex.SetHttpProxy(_proxyURL) 81 | } 82 | return bitmex 83 | } 84 | -------------------------------------------------------------------------------- /events.go: -------------------------------------------------------------------------------- 1 | package bitmex 2 | 3 | import "github.com/chuckpreslar/emission" 4 | 5 | //On adds a listener to a specific event 6 | func (b *BitMEX) On(event interface{}, listener interface{}) *emission.Emitter { 7 | return b.emitter.On(event, listener) 8 | } 9 | 10 | //Emit emits an event 11 | func (b *BitMEX) Emit(event interface{}, arguments ...interface{}) *emission.Emitter { 12 | return b.emitter.Emit(event, arguments...) 13 | } 14 | 15 | //Off removes a listener for an event 16 | func (b *BitMEX) Off(event interface{}, listener interface{}) *emission.Emitter { 17 | return b.emitter.Off(event, listener) 18 | } 19 | -------------------------------------------------------------------------------- /example/build_linux_amd64.bat: -------------------------------------------------------------------------------- 1 | SET CGO_ENABLED=0 2 | SET GOOS=linux 3 | SET GOARCH=amd64 4 | go build -------------------------------------------------------------------------------- /example/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "github.com/frankrap/bitmex-api" 6 | "github.com/frankrap/bitmex-api/swagger" 7 | "log" 8 | ) 9 | 10 | func main() { 11 | b := bitmex.New(nil, 12 | bitmex.HostTestnet, "8K2Oi0bnRRZ7GK4UJnY-38oj", "9EmGvk8mKX5nWa11y1KyPPGn78Lv2ZEiLx3TH0YasE_oE06y", true) 13 | subscribeInfos := []bitmex.SubscribeInfo{ 14 | {Op: bitmex.BitmexWSOrderBookL2, Param: "XBTUSD"}, 15 | {Op: bitmex.BitmexWSTrade, Param: "XBTUSD"}, 16 | {Op: bitmex.BitmexWSOrder, Param: "XBTUSD"}, 17 | {Op: bitmex.BitmexWSPosition, Param: "XBTUSD"}, 18 | {Op: bitmex.BitmexWSMargin, Param: "XBTUSD"}, 19 | } 20 | err := b.Subscribe(subscribeInfos) 21 | if err != nil { 22 | log.Fatal(err) 23 | } 24 | 25 | b.On(bitmex.BitmexWSOrderBookL2, func(m bitmex.OrderBookDataL2, symbol string) { 26 | ob := m.OrderBook() 27 | fmt.Printf("\rOrderbook Asks: %#v Bids: %#v ", ob.Asks[0], ob.Bids[0]) 28 | }).On(bitmex.BitmexWSTrade, func(trades []*swagger.Trade, action string) { 29 | fmt.Printf("Trades %#v action=%v", trades, action) 30 | }).On(bitmex.BitmexWSOrder, func(m []*swagger.Order, action string) { 31 | fmt.Printf("Order action=%v orders=%#v\n", action, m) 32 | }).On(bitmex.BitmexWSPosition, func(m []*swagger.Position, action string) { 33 | fmt.Printf("Position action=%v positions=%#v\n", action, m) 34 | }).On(bitmex.BitmexWSMargin, func(m []*swagger.Margin, action string) { 35 | fmt.Printf("Wallet action=%v margins=%#v\n", action, m) 36 | }) 37 | 38 | b.StartWS() 39 | 40 | // Get orderbook by rest api 41 | b.GetOrderBook(10, "XBTUSD") 42 | // Place a limit buy order 43 | b.PlaceOrder(bitmex.SIDE_BUY, bitmex.ORD_TYPE_LIMIT, 0, 6000.0, 1000, "", "", "XBTUSD") 44 | b.GetOrders("XBTUSD") 45 | b.GetOrder("{OrderID}", "XBTUSD") 46 | b.AmendOrder("{OrderID}", 6000.5) 47 | b.CancelOrder("{OrderID}") 48 | b.CancelAllOrders("XBTUSD") 49 | b.GetPosition("XBTUSD") 50 | b.GetMargin() 51 | 52 | forever := make(chan bool) 53 | <-forever 54 | } 55 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/frankrap/bitmex-api 2 | 3 | go 1.17 4 | 5 | require ( 6 | github.com/chuckpreslar/emission v0.0.0-20170206194824-a7ddd980baf9 7 | github.com/gorilla/websocket v1.4.2 8 | github.com/jpillora/backoff v1.0.0 9 | github.com/micro/go-micro v1.18.0 10 | github.com/pkg/errors v0.9.1 11 | github.com/recws-org/recws v1.2.1 12 | github.com/tidwall/gjson v1.6.0 13 | golang.org/x/net v0.0.0-20200421231249-e086a090c8fd 14 | golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d 15 | ) 16 | 17 | require ( 18 | github.com/BurntSushi/toml v0.3.1 // indirect 19 | github.com/bitly/go-simplejson v0.5.0 // indirect 20 | github.com/fsnotify/fsnotify v1.4.7 // indirect 21 | github.com/ghodss/yaml v1.0.0 // indirect 22 | github.com/golang/protobuf v1.3.2 // indirect 23 | github.com/hashicorp/hcl v1.0.0 // indirect 24 | github.com/imdario/mergo v0.3.8 // indirect 25 | github.com/stretchr/testify v1.5.1 // indirect 26 | github.com/tidwall/match v1.0.1 // indirect 27 | github.com/tidwall/pretty v1.0.0 // indirect 28 | golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd // indirect 29 | google.golang.org/appengine v1.5.0 // indirect 30 | gopkg.in/yaml.v2 v2.2.2 // indirect 31 | ) 32 | -------------------------------------------------------------------------------- /order_test.go: -------------------------------------------------------------------------------- 1 | package bitmex 2 | 3 | import ( 4 | "encoding/json" 5 | "github.com/frankrap/bitmex-api/swagger" 6 | "testing" 7 | ) 8 | 9 | func TestParseOrders(t *testing.T) { 10 | raw := `[{"orderID":"fe492d85-9bd6-4147-c286-c9149163a3be","clOrdID":"","clOrdLinkID":"","account":149029,"symbol":"XBTUSD","side":"Buy","simpleOrderQty":null,"orderQty":20,"price":2100,"displayQty":null,"stopPx":null,"pegOffsetValue":null,"pegPriceType":"","currency":"USD","settlCurrency":"XBt","ordType":"Limit","timeInForce":"GoodTillCancel","execInst":"ParticipateDoNotInitiate","contingencyType":"","exDestination":"XBME","ordStatus":"New","triggered":"","workingIndicator":true,"ordRejReason":"","simpleLeavesQty":null,"leavesQty":20,"simpleCumQty":null,"cumQty":0,"avgPx":null,"multiLegReportingType":"SingleSecurity","text":"open long with bitmex api","transactTime":"2019-04-08T08:53:00.460Z","timestamp":"2019-04-08T08:53:00.460Z"},{"orderID":"f4c8e673-fab9-b41d-51b1-35b064c27e26","clOrdID":"","clOrdLinkID":"","account":149029,"symbol":"XBTUSD","side":"Buy","simpleOrderQty":null,"orderQty":20,"price":2100,"displayQty":null,"stopPx":null,"pegOffsetValue":null,"pegPriceType":"","currency":"USD","settlCurrency":"XBt","ordType":"Limit","timeInForce":"GoodTillCancel","execInst":"ParticipateDoNotInitiate","contingencyType":"","exDestination":"XBME","ordStatus":"New","triggered":"","workingIndicator":true,"ordRejReason":"","simpleLeavesQty":null,"leavesQty":20,"simpleCumQty":null,"cumQty":0,"avgPx":null,"multiLegReportingType":"SingleSecurity","text":"open long with bitmex api","transactTime":"2019-04-08T08:53:22.279Z","timestamp":"2019-04-08T08:53:22.279Z"},{"orderID":"f31997b8-809c-1ce2-20ef-9ce5fba4886c","clOrdID":"","clOrdLinkID":"","account":149029,"symbol":"XBTUSD","side":"Buy","simpleOrderQty":null,"orderQty":30,"price":3600,"displayQty":null,"stopPx":null,"pegOffsetValue":null,"pegPriceType":"","currency":"USD","settlCurrency":"XBt","ordType":"Limit","timeInForce":"GoodTillCancel","execInst":"","contingencyType":"","exDestination":"XBME","ordStatus":"New","triggered":"","workingIndicator":true,"ordRejReason":"","simpleLeavesQty":null,"leavesQty":30,"simpleCumQty":null,"cumQty":0,"avgPx":null,"multiLegReportingType":"SingleSecurity","text":"Submission from testnet.bitmex.com","transactTime":"2019-04-09T08:15:12.704Z","timestamp":"2019-04-09T08:15:12.704Z"}]` 11 | 12 | var orders []*swagger.Order 13 | err := json.Unmarshal([]byte(raw), &orders) 14 | if err != nil { 15 | t.Error(err) 16 | } 17 | 18 | for _, v := range orders { 19 | t.Logf("%v", *v) 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /orderbook.go: -------------------------------------------------------------------------------- 1 | package bitmex 2 | 3 | import ( 4 | "sort" 5 | "strconv" 6 | "sync" 7 | "time" 8 | ) 9 | 10 | // OrderBookL2 contains order book l2 11 | type OrderBookL2 struct { 12 | ID int64 `json:"id"` 13 | Price float64 `json:"price"` 14 | Side string `json:"side"` 15 | Size int64 `json:"size"` 16 | Symbol string `json:"symbol"` 17 | } 18 | 19 | func (o *OrderBookL2) Key() string { 20 | // return fmt.Sprintf("%s-%s-%d", o.Symbol, o.Side, o.ID) 21 | return strconv.FormatInt(o.ID, 10) 22 | } 23 | 24 | type OrderBookData []*OrderBookL2 25 | 26 | type OrderBookDataL2 struct { 27 | RawData []OrderBookL2 28 | Timestamp time.Time 29 | } 30 | 31 | func (o *OrderBookDataL2) OrderBook() (ob OrderBook) { 32 | for _, v := range o.RawData { 33 | switch v.Side { 34 | case "Buy": 35 | ob.Bids = append(ob.Bids, Item{ 36 | Price: v.Price, 37 | Amount: float64(v.Size), 38 | }) 39 | case "Sell": 40 | ob.Asks = append(ob.Asks, Item{ 41 | Price: v.Price, 42 | Amount: float64(v.Size), 43 | }) 44 | } 45 | } 46 | 47 | sort.Slice(ob.Bids, func(i, j int) bool { 48 | return ob.Bids[i].Price > ob.Bids[j].Price 49 | }) 50 | 51 | sort.Slice(ob.Asks, func(i, j int) bool { 52 | return ob.Asks[i].Price < ob.Asks[j].Price 53 | }) 54 | 55 | ob.Timestamp = o.Timestamp 56 | return 57 | } 58 | 59 | // OrderBook10 contains order book 10 60 | type OrderBook10 struct { 61 | Bids [][]float64 `json:"bids"` 62 | Asks [][]float64 `json:"asks"` 63 | Timestamp time.Time `json:"timestamp"` 64 | Symbol string `json:"symbol"` 65 | } 66 | 67 | // Item stores the amount and price values 68 | type Item struct { 69 | Amount float64 `json:"amount"` 70 | Price float64 `json:"price"` 71 | } 72 | 73 | type OrderBook struct { 74 | Bids []Item `json:"bids"` 75 | Asks []Item `json:"asks"` 76 | Timestamp time.Time `json:"timestamp"` 77 | } 78 | 79 | func (ob *OrderBook) Valid() bool { 80 | return len(ob.Bids) > 0 && len(ob.Asks) > 0 81 | } 82 | 83 | func (ob *OrderBook) Bid() float64 { 84 | if len(ob.Bids) < 1 { 85 | return 0.0 86 | } 87 | return ob.Bids[0].Price 88 | } 89 | 90 | func (ob *OrderBook) Ask() float64 { 91 | if len(ob.Asks) < 1 { 92 | return 0.0 93 | } 94 | return ob.Asks[0].Price 95 | } 96 | 97 | type OrderBookLocal struct { 98 | ob map[string]*OrderBookL2 99 | m sync.Mutex 100 | } 101 | 102 | func NewOrderBookLocal() *OrderBookLocal { 103 | o := &OrderBookLocal{ 104 | ob: make(map[string]*OrderBookL2), 105 | } 106 | return o 107 | } 108 | 109 | func (o *OrderBookLocal) GetOrderbookL2() (ob OrderBookDataL2) { 110 | ob.RawData = make([]OrderBookL2, 0, len(o.ob)) 111 | for _, v := range o.ob { 112 | ob.RawData = append(ob.RawData, *v) 113 | } 114 | ob.Timestamp = time.Now() 115 | return 116 | } 117 | 118 | func (o *OrderBookLocal) GetOrderbook() (ob OrderBook) { 119 | //ob.Symbol = "XBTUSD" 120 | for _, v := range o.ob { 121 | switch v.Side { 122 | case "Buy": 123 | ob.Bids = append(ob.Bids, Item{ 124 | Price: v.Price, 125 | Amount: float64(v.Size), 126 | }) 127 | case "Sell": 128 | ob.Asks = append(ob.Asks, Item{ 129 | Price: v.Price, 130 | Amount: float64(v.Size), 131 | }) 132 | } 133 | } 134 | 135 | sort.Slice(ob.Bids, func(i, j int) bool { 136 | return ob.Bids[i].Price > ob.Bids[j].Price 137 | }) 138 | 139 | sort.Slice(ob.Asks, func(i, j int) bool { 140 | return ob.Asks[i].Price < ob.Asks[j].Price 141 | }) 142 | 143 | ob.Timestamp = time.Now() 144 | 145 | return 146 | } 147 | 148 | func (o *OrderBookLocal) LoadSnapshot(newOrderbook []*OrderBookL2) error { 149 | o.m.Lock() 150 | defer o.m.Unlock() 151 | 152 | o.ob = make(map[string]*OrderBookL2) 153 | 154 | for _, v := range newOrderbook { 155 | o.ob[v.Key()] = v 156 | } 157 | 158 | return nil 159 | } 160 | 161 | func (o *OrderBookLocal) Update(orderbook []*OrderBookL2, action string) { 162 | o.m.Lock() 163 | defer o.m.Unlock() 164 | 165 | switch action { 166 | case bitmexActionUpdateData: 167 | for _, elem := range orderbook { 168 | if v, ok := o.ob[elem.Key()]; ok { 169 | // price is same while id is same 170 | // v.Price = elem.Price 171 | v.Size = elem.Size 172 | v.Side = elem.Side 173 | } 174 | } 175 | case bitmexActionDeleteData: 176 | for _, v := range orderbook { 177 | delete(o.ob, v.Key()) 178 | } 179 | case bitmexActionInsertData: 180 | for _, v := range orderbook { 181 | o.ob[v.Key()] = v 182 | } 183 | } 184 | } 185 | -------------------------------------------------------------------------------- /recws/LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2017 Marius Dobre 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /recws/README.md: -------------------------------------------------------------------------------- 1 | # recws 2 | 3 | [![Go Report Card](https://goreportcard.com/badge/github.com/mariuspass/recws)](https://goreportcard.com/report/github.com/mariuspass/recws) 4 | [![GitHub license](https://img.shields.io/github/license/Naereen/StrapDown.js.svg)](https://github.com/Naereen/StrapDown.js/blob/master/LICENSE) 5 | 6 | Reconnecting WebSocket is a websocket client based on [gorilla/websocket](https://github.com/gorilla/websocket) that will automatically reconnect if the connection is dropped. 7 | 8 | ## Basic example 9 | 10 | ```go 11 | package main 12 | 13 | import ( 14 | "context" 15 | "github.com/mariuspass/recws" 16 | "log" 17 | "time" 18 | ) 19 | 20 | func main() { 21 | ctx, cancel := context.WithCancel(context.Background()) 22 | ws := recws.RecConn{} 23 | ws.Dial("wss://echo.websocket.org", nil) 24 | 25 | go func() { 26 | time.Sleep(2 * time.Second) 27 | cancel() 28 | }() 29 | 30 | for { 31 | select { 32 | case <-ctx.Done(): 33 | go ws.Close() 34 | log.Printf("Websocket closed %s", ws.GetURL()) 35 | return 36 | default: 37 | if !ws.IsConnected() { 38 | log.Printf("Websocket disconnected %s", ws.GetURL()) 39 | continue 40 | } 41 | 42 | if err := ws.WriteMessage(1, []byte("Incoming")); err != nil { 43 | log.Printf("Error: WriteMessage %s", ws.GetURL()) 44 | return 45 | } 46 | 47 | _, message, err := ws.ReadMessage() 48 | if err != nil { 49 | log.Printf("Error: ReadMessage %s", ws.GetURL()) 50 | return 51 | } 52 | 53 | log.Printf("Success: %s", message) 54 | } 55 | } 56 | } 57 | ``` 58 | -------------------------------------------------------------------------------- /recws/examples/basic.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "context" 5 | "github.com/recws-org/recws" 6 | "log" 7 | "time" 8 | ) 9 | 10 | func main() { 11 | ctx, cancel := context.WithCancel(context.Background()) 12 | ws := recws.RecConn{} 13 | ws.Dial("wss://echo.websocket.org", nil) 14 | 15 | go func() { 16 | time.Sleep(2 * time.Second) 17 | cancel() 18 | }() 19 | 20 | for { 21 | select { 22 | case <-ctx.Done(): 23 | go ws.Close() 24 | log.Printf("Websocket closed %s", ws.GetURL()) 25 | return 26 | default: 27 | if !ws.IsConnected() { 28 | log.Printf("Websocket disconnected %s", ws.GetURL()) 29 | continue 30 | } 31 | 32 | if err := ws.WriteMessage(1, []byte("Incoming")); err != nil { 33 | log.Printf("Error: WriteMessage %s", ws.GetURL()) 34 | return 35 | } 36 | 37 | _, message, err := ws.ReadMessage() 38 | if err != nil { 39 | log.Printf("Error: ReadMessage %s", ws.GetURL()) 40 | return 41 | } 42 | 43 | log.Printf("Success: %s", message) 44 | } 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /recws/keepalive.go: -------------------------------------------------------------------------------- 1 | package recws 2 | 3 | import ( 4 | "sync" 5 | "time" 6 | ) 7 | 8 | type keepAliveResponse struct { 9 | lastResponse time.Time 10 | sync.RWMutex 11 | } 12 | 13 | func (k *keepAliveResponse) setLastResponse() { 14 | k.Lock() 15 | defer k.Unlock() 16 | 17 | k.lastResponse = time.Now() 18 | } 19 | 20 | func (k *keepAliveResponse) getLastResponse() time.Time { 21 | k.RLock() 22 | defer k.RUnlock() 23 | 24 | return k.lastResponse 25 | } 26 | -------------------------------------------------------------------------------- /recws/recws.go: -------------------------------------------------------------------------------- 1 | // Package recws provides websocket client based on gorilla/websocket 2 | // that will automatically reconnect if the connection is dropped. 3 | package recws 4 | 5 | import ( 6 | "errors" 7 | "log" 8 | "math/rand" 9 | "net/http" 10 | "net/url" 11 | "sync" 12 | "time" 13 | 14 | "github.com/gorilla/websocket" 15 | "github.com/jpillora/backoff" 16 | ) 17 | 18 | // ErrNotConnected is returned when the application read/writes 19 | // a message and the connection is closed 20 | var ErrNotConnected = errors.New("websocket: not connected") 21 | 22 | // The RecConn type represents a Reconnecting WebSocket connection. 23 | type RecConn struct { 24 | // RecIntvlMin specifies the initial reconnecting interval, 25 | // default to 2 seconds 26 | RecIntvlMin time.Duration 27 | // RecIntvlMax specifies the maximum reconnecting interval, 28 | // default to 30 seconds 29 | RecIntvlMax time.Duration 30 | // RecIntvlFactor specifies the rate of increase of the reconnection 31 | // interval, default to 1.5 32 | RecIntvlFactor float64 33 | // HandshakeTimeout specifies the duration for the handshake to complete, 34 | // default to 2 seconds 35 | HandshakeTimeout time.Duration 36 | // NonVerbose suppress connecting/reconnecting messages. 37 | NonVerbose bool 38 | // SubscribeHandler fires after the connection successfully establish. 39 | SubscribeHandler func() error 40 | // KeepAliveTimeout is an interval for sending ping/pong messages 41 | // disabled if 0 42 | KeepAliveTimeout time.Duration 43 | 44 | mu sync.RWMutex 45 | url string 46 | proxyURL string 47 | reqHeader http.Header 48 | httpResp *http.Response 49 | dialErr error 50 | isConnected bool 51 | isClosed bool 52 | dialer *websocket.Dialer 53 | 54 | *websocket.Conn 55 | } 56 | 57 | // CloseAndReconnect will try to reconnect. 58 | func (rc *RecConn) closeAndReconnect() { 59 | rc.Close() 60 | if rc.IsClosed() { 61 | return 62 | } 63 | go rc.connect() 64 | } 65 | 66 | // setIsConnected sets state for isConnected 67 | func (rc *RecConn) setIsConnected(state bool) { 68 | rc.mu.Lock() 69 | defer rc.mu.Unlock() 70 | 71 | rc.isConnected = state 72 | } 73 | 74 | // setIsClosed sets state for isClosed 75 | func (rc *RecConn) setIsClosed(state bool) { 76 | rc.mu.Lock() 77 | defer rc.mu.Unlock() 78 | 79 | rc.isClosed = state 80 | } 81 | 82 | func (rc *RecConn) getConn() *websocket.Conn { 83 | rc.mu.RLock() 84 | defer rc.mu.RUnlock() 85 | 86 | return rc.Conn 87 | } 88 | 89 | // SetProxyURL set connect proxy url 90 | func (rc *RecConn) SetProxyURL(proxyURL string) { 91 | rc.proxyURL = proxyURL 92 | } 93 | 94 | // Close closes the underlying network connection without 95 | // sending or waiting for a close frame. 96 | func (rc *RecConn) Close() { 97 | if rc.getConn() != nil { 98 | rc.mu.Lock() 99 | rc.Conn.Close() 100 | rc.mu.Unlock() 101 | } 102 | 103 | rc.setIsConnected(false) 104 | } 105 | 106 | // CloseWS closes the underlying network connection without 107 | // sending or waiting for a close frame. 108 | func (rc *RecConn) CloseWS() { 109 | rc.setIsClosed(true) 110 | 111 | if rc.getConn() != nil { 112 | rc.mu.Lock() 113 | rc.Conn.Close() 114 | rc.mu.Unlock() 115 | } 116 | 117 | rc.setIsConnected(false) 118 | } 119 | 120 | // ReadMessage is a helper method for getting a reader 121 | // using NextReader and reading from that reader to a buffer. 122 | // 123 | // If the connection is closed ErrNotConnected is returned 124 | func (rc *RecConn) ReadMessage() (messageType int, message []byte, err error) { 125 | err = ErrNotConnected 126 | if rc.IsConnected() { 127 | messageType, message, err = rc.Conn.ReadMessage() 128 | if err != nil { 129 | rc.closeAndReconnect() 130 | } 131 | } 132 | 133 | return 134 | } 135 | 136 | // WriteMessage is a helper method for getting a writer using NextWriter, 137 | // writing the message and closing the writer. 138 | // 139 | // If the connection is closed ErrNotConnected is returned 140 | func (rc *RecConn) WriteMessage(messageType int, data []byte) error { 141 | err := ErrNotConnected 142 | if rc.IsConnected() { 143 | rc.mu.Lock() 144 | err = rc.Conn.WriteMessage(messageType, data) 145 | rc.mu.Unlock() 146 | if err != nil { 147 | rc.closeAndReconnect() 148 | } 149 | } 150 | 151 | return err 152 | } 153 | 154 | // WriteJSON writes the JSON encoding of v to the connection. 155 | // 156 | // See the documentation for encoding/json Marshal for details about the 157 | // conversion of Go values to JSON. 158 | // 159 | // If the connection is closed ErrNotConnected is returned 160 | func (rc *RecConn) WriteJSON(v interface{}) error { 161 | err := ErrNotConnected 162 | if rc.IsConnected() { 163 | rc.mu.Lock() 164 | err = rc.Conn.WriteJSON(v) 165 | rc.mu.Unlock() 166 | if err != nil { 167 | rc.closeAndReconnect() 168 | } 169 | } 170 | 171 | return err 172 | } 173 | 174 | // ReadJSON reads the next JSON-encoded message from the connection and stores 175 | // it in the value pointed to by v. 176 | // 177 | // See the documentation for the encoding/json Unmarshal function for details 178 | // about the conversion of JSON to a Go value. 179 | // 180 | // If the connection is closed ErrNotConnected is returned 181 | func (rc *RecConn) ReadJSON(v interface{}) error { 182 | err := ErrNotConnected 183 | if rc.IsConnected() { 184 | err = rc.Conn.ReadJSON(v) 185 | if err != nil { 186 | rc.closeAndReconnect() 187 | } 188 | } 189 | 190 | return err 191 | } 192 | 193 | func (rc *RecConn) setURL(url string) { 194 | rc.mu.Lock() 195 | defer rc.mu.Unlock() 196 | 197 | rc.url = url 198 | } 199 | 200 | func (rc *RecConn) setReqHeader(reqHeader http.Header) { 201 | rc.mu.Lock() 202 | defer rc.mu.Unlock() 203 | 204 | rc.reqHeader = reqHeader 205 | } 206 | 207 | // parseURL parses current url 208 | func (rc *RecConn) parseURL(urlStr string) (string, error) { 209 | if urlStr == "" { 210 | return "", errors.New("dial: url cannot be empty") 211 | } 212 | 213 | u, err := url.Parse(urlStr) 214 | 215 | if err != nil { 216 | return "", errors.New("url: " + err.Error()) 217 | } 218 | 219 | if u.Scheme != "ws" && u.Scheme != "wss" { 220 | return "", errors.New("url: websocket uris must start with ws or wss scheme") 221 | } 222 | 223 | if u.User != nil { 224 | return "", errors.New("url: user name and password are not allowed in websocket URIs") 225 | } 226 | 227 | return urlStr, nil 228 | } 229 | 230 | func (rc *RecConn) setDefaultRecIntvlMin() { 231 | rc.mu.Lock() 232 | defer rc.mu.Unlock() 233 | 234 | if rc.RecIntvlMin == 0 { 235 | rc.RecIntvlMin = 2 * time.Second 236 | } 237 | } 238 | 239 | func (rc *RecConn) setDefaultRecIntvlMax() { 240 | rc.mu.Lock() 241 | defer rc.mu.Unlock() 242 | 243 | if rc.RecIntvlMax == 0 { 244 | rc.RecIntvlMax = 30 * time.Second 245 | } 246 | } 247 | 248 | func (rc *RecConn) setDefaultRecIntvlFactor() { 249 | rc.mu.Lock() 250 | defer rc.mu.Unlock() 251 | 252 | if rc.RecIntvlFactor == 0 { 253 | rc.RecIntvlFactor = 1.5 254 | } 255 | } 256 | 257 | func (rc *RecConn) setDefaultHandshakeTimeout() { 258 | rc.mu.Lock() 259 | defer rc.mu.Unlock() 260 | 261 | if rc.HandshakeTimeout == 0 { 262 | rc.HandshakeTimeout = 2 * time.Second 263 | } 264 | } 265 | 266 | func (rc *RecConn) setDefaultDialer(handshakeTimeout time.Duration) { 267 | rc.mu.Lock() 268 | defer rc.mu.Unlock() 269 | 270 | rc.dialer = &websocket.Dialer{ 271 | HandshakeTimeout: handshakeTimeout, 272 | } 273 | if rc.proxyURL != "" { 274 | proxyURL_, err := url.Parse(rc.proxyURL) 275 | if err != nil { 276 | return 277 | } 278 | rc.dialer.Proxy = http.ProxyURL(proxyURL_) 279 | } 280 | } 281 | 282 | func (rc *RecConn) getHandshakeTimeout() time.Duration { 283 | rc.mu.RLock() 284 | defer rc.mu.RUnlock() 285 | 286 | return rc.HandshakeTimeout 287 | } 288 | 289 | // Dial creates a new client connection. 290 | // The URL url specifies the host and request URI. Use requestHeader to specify 291 | // the origin (Origin), subprotocols (Sec-WebSocket-Protocol) and cookies 292 | // (Cookie). Use GetHTTPResponse() method for the response.Header to get 293 | // the selected subprotocol (Sec-WebSocket-Protocol) and cookies (Set-Cookie). 294 | func (rc *RecConn) Dial(urlStr string, reqHeader http.Header) { 295 | urlStr, err := rc.parseURL(urlStr) 296 | 297 | if err != nil { 298 | log.Fatalf("Dial: %v", err) 299 | } 300 | 301 | // Config 302 | rc.setURL(urlStr) 303 | rc.setReqHeader(reqHeader) 304 | rc.setDefaultRecIntvlMin() 305 | rc.setDefaultRecIntvlMax() 306 | rc.setDefaultRecIntvlFactor() 307 | rc.setDefaultHandshakeTimeout() 308 | rc.setDefaultDialer(rc.getHandshakeTimeout()) 309 | 310 | // Connect 311 | go rc.connect() 312 | 313 | // wait on first attempt 314 | time.Sleep(rc.getHandshakeTimeout()) 315 | } 316 | 317 | // GetURL returns current connection url 318 | func (rc *RecConn) GetURL() string { 319 | rc.mu.RLock() 320 | defer rc.mu.RUnlock() 321 | 322 | return rc.url 323 | } 324 | 325 | func (rc *RecConn) getNonVerbose() bool { 326 | rc.mu.RLock() 327 | defer rc.mu.RUnlock() 328 | 329 | return rc.NonVerbose 330 | } 331 | 332 | func (rc *RecConn) getBackoff() *backoff.Backoff { 333 | rc.mu.RLock() 334 | defer rc.mu.RUnlock() 335 | 336 | return &backoff.Backoff{ 337 | Min: rc.RecIntvlMin, 338 | Max: rc.RecIntvlMax, 339 | Factor: rc.RecIntvlFactor, 340 | Jitter: true, 341 | } 342 | } 343 | 344 | func (rc *RecConn) hasSubscribeHandler() bool { 345 | rc.mu.RLock() 346 | defer rc.mu.RUnlock() 347 | 348 | return rc.SubscribeHandler != nil 349 | } 350 | 351 | func (rc *RecConn) getKeepAliveTimeout() time.Duration { 352 | rc.mu.RLock() 353 | defer rc.mu.RUnlock() 354 | 355 | return rc.KeepAliveTimeout 356 | } 357 | 358 | func (rc *RecConn) writeControlPingMessage() error { 359 | rc.mu.Lock() 360 | defer rc.mu.Unlock() 361 | 362 | return rc.Conn.WriteControl(websocket.PingMessage, []byte{}, time.Now().Add(10*time.Second)) 363 | } 364 | 365 | func (rc *RecConn) keepAlive() { 366 | var ( 367 | keepAliveResponse = new(keepAliveResponse) 368 | ticker = time.NewTicker(rc.getKeepAliveTimeout()) 369 | ) 370 | 371 | rc.mu.Lock() 372 | rc.Conn.SetPongHandler(func(msg string) error { 373 | keepAliveResponse.setLastResponse() 374 | return nil 375 | }) 376 | rc.mu.Unlock() 377 | 378 | go func() { 379 | defer ticker.Stop() 380 | 381 | for { 382 | rc.writeControlPingMessage() 383 | <-ticker.C 384 | if rc.IsClosed() { 385 | return 386 | } 387 | if time.Now().Sub(keepAliveResponse.getLastResponse()) > rc.getKeepAliveTimeout() { 388 | rc.closeAndReconnect() 389 | return 390 | } 391 | } 392 | }() 393 | } 394 | 395 | func (rc *RecConn) connect() { 396 | b := rc.getBackoff() 397 | rand.Seed(time.Now().UTC().UnixNano()) 398 | 399 | for { 400 | if rc.IsClosed() { 401 | return 402 | } 403 | nextItvl := b.Duration() 404 | wsConn, httpResp, err := rc.dialer.Dial(rc.url, rc.reqHeader) 405 | 406 | rc.mu.Lock() 407 | rc.Conn = wsConn 408 | rc.dialErr = err 409 | rc.isConnected = err == nil 410 | rc.httpResp = httpResp 411 | rc.mu.Unlock() 412 | 413 | if rc.IsClosed() { 414 | return 415 | } 416 | 417 | if err == nil { 418 | if !rc.getNonVerbose() { 419 | log.Printf("Dial: connection was successfully established with %s\n", rc.url) 420 | 421 | if !rc.hasSubscribeHandler() { 422 | return 423 | } 424 | 425 | if err := rc.SubscribeHandler(); err != nil { 426 | log.Fatalf("Dial: connect handler failed with %s", err.Error()) 427 | } 428 | 429 | log.Printf("Dial: connect handler was successfully established with %s\n", rc.url) 430 | 431 | if rc.getKeepAliveTimeout() != 0 { 432 | rc.keepAlive() 433 | } 434 | } 435 | 436 | return 437 | } 438 | 439 | if !rc.getNonVerbose() { 440 | log.Println(err) 441 | log.Println("Dial: will try again in", nextItvl, "seconds.") 442 | } 443 | 444 | time.Sleep(nextItvl) 445 | } 446 | } 447 | 448 | // GetHTTPResponse returns the http response from the handshake. 449 | // Useful when WebSocket handshake fails, 450 | // so that callers can handle redirects, authentication, etc. 451 | func (rc *RecConn) GetHTTPResponse() *http.Response { 452 | rc.mu.RLock() 453 | defer rc.mu.RUnlock() 454 | 455 | return rc.httpResp 456 | } 457 | 458 | // GetDialError returns the last dialer error. 459 | // nil on successful connection. 460 | func (rc *RecConn) GetDialError() error { 461 | rc.mu.RLock() 462 | defer rc.mu.RUnlock() 463 | 464 | return rc.dialErr 465 | } 466 | 467 | // IsConnected returns the WebSocket connection state 468 | func (rc *RecConn) IsConnected() bool { 469 | rc.mu.RLock() 470 | defer rc.mu.RUnlock() 471 | 472 | return rc.isConnected 473 | } 474 | 475 | // IsClosed returns the WebSocket connection state 476 | func (rc *RecConn) IsClosed() bool { 477 | rc.mu.RLock() 478 | defer rc.mu.RUnlock() 479 | 480 | return rc.isClosed 481 | } 482 | -------------------------------------------------------------------------------- /rest_test.go: -------------------------------------------------------------------------------- 1 | package bitmex 2 | 3 | import ( 4 | "math" 5 | "testing" 6 | "time" 7 | ) 8 | 9 | func TestBitMEX_GetVersion(t *testing.T) { 10 | bitmex := newBitmexForTest() 11 | version, _, err := bitmex.GetVersion() 12 | if err != nil { 13 | t.Error(err) 14 | } 15 | 16 | now := time.Now().UnixNano() / 1000000 17 | diff := version.Timestamp - now 18 | 19 | t.Logf("Version time: %v now: %v diff: %v", version.Timestamp, now, diff) 20 | 21 | if math.Abs(float64(diff)) >= 2000 { // 时间差多余2s 22 | t.Error("time error") 23 | } 24 | } 25 | 26 | func TestBitMEX_GetOrderBookL2(t *testing.T) { 27 | bitmex := newBitmexForTest() 28 | orderBookL2, err := bitmex.getOrderBookL2(5, "XBTUSD") 29 | if err != nil { 30 | t.Error(err) 31 | return 32 | } 33 | t.Log(orderBookL2) 34 | rateLimit := bitmex.GetRateLimit() 35 | t.Logf("RateLimit: %v", rateLimit) 36 | } 37 | 38 | func TestBitMEX_GetOrderBook(t *testing.T) { 39 | bitmex := newBitmexForTest() 40 | orderBook, err := bitmex.GetOrderBook(5, "XBTUSD") 41 | if err != nil { 42 | t.Error(err) 43 | return 44 | } 45 | t.Log(orderBook) 46 | } 47 | 48 | func TestBitMEX_GetBucketed(t *testing.T) { 49 | bitmex := newBitmexForTest() 50 | startTime := time.Now().Add(-time.Minute * 8).UTC() 51 | var endTime time.Time 52 | data, err := bitmex.GetBucketed("XBTUSD", "1m", false, "", "", 10, 0, false, startTime, endTime) 53 | if err != nil { 54 | t.Error(err) 55 | return 56 | } 57 | t.Logf("%#v", data) 58 | for _, v := range data { 59 | t.Logf("Timestamp=%v Open=%v High=%v Low=%v Close=%v", v.Timestamp.Local(), v.Open, v.High, v.Low, v.Close) 60 | } 61 | } 62 | 63 | func TestBitMEX_GetOrders(t *testing.T) { 64 | bitmex := newBitmexForTest() 65 | orders, err := bitmex.GetOrders("XBTUSD") 66 | if err != nil { 67 | t.Error(err) 68 | return 69 | } 70 | t.Log(orders) 71 | } 72 | 73 | func TestBitMEX_GetWallet(t *testing.T) { 74 | bitmex := newBitmexForTest() 75 | wallet, err := bitmex.GetWallet() 76 | if err != nil { 77 | t.Error(err) 78 | return 79 | } 80 | // XBt 81 | t.Logf("%#v", wallet) 82 | } 83 | 84 | func TestBitMEX_GetMargin(t *testing.T) { 85 | bitmex := newBitmexForTest() 86 | margin, err := bitmex.GetMargin() 87 | if err != nil { 88 | t.Error(err) 89 | return 90 | } 91 | t.Logf("%#v", margin) 92 | } 93 | 94 | func TestBitMEX_GetPositions(t *testing.T) { 95 | bitmex := newBitmexForTest() 96 | positions, err := bitmex.GetPositions("XBTUSD") 97 | if err != nil { 98 | t.Error(err) 99 | return 100 | } 101 | t.Log(positions) 102 | } 103 | 104 | func TestBitMEX_PositionUpdateLeverage(t *testing.T) { 105 | bitmex := newBitmexForTest() 106 | leverage := 2.0 107 | position, err := bitmex.PositionUpdateLeverage(leverage, "XBTUSD") 108 | if err != nil { 109 | t.Error(err) 110 | return 111 | } 112 | 113 | t.Logf("%#v", position) 114 | 115 | if position.Leverage != leverage { 116 | t.Error("Leverage error") 117 | return 118 | } 119 | } 120 | 121 | func TestBitMEX_NewOrder(t *testing.T) { 122 | bitmex := newBitmexForTest() 123 | price := 3000.0 124 | order, err := bitmex.NewOrder(SIDE_BUY, ORD_TYPE_LIMIT, price, 20, true, "", "XBTUSD") 125 | if err != nil { 126 | // 403 Forbidden 127 | t.Error(err) 128 | return 129 | } 130 | if order.Symbol != "XBTUSD" { 131 | t.Errorf("symbol error [%v]", order.Symbol) 132 | return 133 | } 134 | if order.Price != price { 135 | t.Errorf("price error [%v]", order.Price) 136 | return 137 | } 138 | t.Logf("%#v", order) 139 | } 140 | 141 | func TestBitMEX_CancelOrder(t *testing.T) { 142 | bitmex := newBitmexForTest() 143 | oid := `e4c72847-93f9-0304-d666-5f7d6ceb3ade` 144 | order, err := bitmex.CancelOrder(oid) 145 | if err != nil { 146 | // 400 Bad Request 147 | t.Error(err) 148 | return 149 | } 150 | t.Logf("%#v", order) 151 | } 152 | 153 | func TestBitMEX_CancelAllOrders(t *testing.T) { 154 | bitmex := newBitmexForTest() 155 | orders, err := bitmex.CancelAllOrders("XBTUSD") 156 | if err != nil { 157 | // 400 Bad Request 158 | t.Error(err) 159 | return 160 | } 161 | t.Logf("%#v", orders) 162 | } 163 | 164 | func TestBitMEX_AmendOrder(t *testing.T) { 165 | bitmex := newBitmexForTest() 166 | oid := `a17d25a3-6149-3edf-d196-75cc775beb29` 167 | newPrice := 3001.0 168 | order, err := bitmex.AmendOrder(oid, newPrice) 169 | if err != nil { 170 | t.Error(err) 171 | return 172 | } 173 | if order.Price != newPrice { 174 | t.Error("price error") 175 | return 176 | } 177 | t.Logf("%#v", order) 178 | } 179 | 180 | func TestBitMEX_CloseOrder(t *testing.T) { 181 | bitmex := newBitmexForTest() 182 | price := 6000.0 183 | order, err := bitmex.CloseOrder(SIDE_SELL, ORD_TYPE_LIMIT, price, 20, true, "", "XBTUSD") 184 | if err != nil { 185 | // 403 Forbidden 186 | t.Error(err) 187 | return 188 | } 189 | if order.Symbol != "XBTUSD" { 190 | t.Errorf("symbol error [%v]", order.Symbol) 191 | return 192 | } 193 | if order.Price != price { 194 | t.Errorf("price error [%v]", order.Price) 195 | return 196 | } 197 | t.Logf("%#v", order) 198 | } 199 | 200 | func TestBitMEX_RequestWithdrawal(t *testing.T) { 201 | bitmex := newBitmexForTest2() 202 | currency := "XBt" 203 | amount := float32(1000000.0) 204 | address := "3BMEXT9XuBTSkALWTovH1idLSC2tusjKBT" 205 | optToken := "" 206 | fee := 0.0 207 | // 401 Unauthorized 208 | trans, err := bitmex.RequestWithdrawal(currency, amount, address, optToken, fee) 209 | if err != nil { 210 | t.Error(err) 211 | return 212 | } 213 | t.Logf("%#v", trans) 214 | } 215 | 216 | func TestBitMEX_GetInstrument(t *testing.T) { 217 | bitmex := newBitmexForTest() 218 | i, err := bitmex.GetInstrument("XBTUSD", 1, true) 219 | if err != nil { 220 | t.Error(err) 221 | return 222 | } 223 | t.Logf("%#v", i) 224 | t.Logf("FundingRate: %v", i[0].FundingRate) 225 | } 226 | -------------------------------------------------------------------------------- /swagger/access_token.go: -------------------------------------------------------------------------------- 1 | /* 2 | * BitMEX API 3 | * 4 | * ## REST API for the BitMEX Trading Platform [View Changelog](/app/apiChangelog) #### Getting Started ##### Fetching Data All REST endpoints are documented below. You can try out any query right from this interface. Most table queries accept `count`, `start`, and `reverse` params. Set `reverse=true` to get rows newest-first. Additional documentation regarding filters, timestamps, and authentication is available in [the main API documentation](https://www.bitmex.com/app/restAPI). *All* table data is available via the [Websocket](/app/wsAPI). We highly recommend using the socket if you want to have the quickest possible data without being subject to ratelimits. ##### Return Types By default, all data is returned as JSON. Send `?_format=csv` to get CSV data or `?_format=xml` to get XML data. ##### Trade Data Queries *This is only a small subset of what is available, to get you started.* Fill in the parameters and click the `Try it out!` button to try any of these queries. * [Pricing Data](#!/Quote/Quote_get) * [Trade Data](#!/Trade/Trade_get) * [OrderBook Data](#!/OrderBook/OrderBook_getL2) * [Settlement Data](#!/Settlement/Settlement_get) * [Exchange Statistics](#!/Stats/Stats_history) Every function of the BitMEX.com platform is exposed here and documented. Many more functions are available. ##### Swagger Specification [⇩ Download Swagger JSON](swagger.json) ## All API Endpoints Click to expand a section. 5 | * 6 | * OpenAPI spec version: 1.2.0 7 | * Contact: support@bitmex.com 8 | * Generated by: https://github.com/swagger-api/swagger-codegen.git 9 | */ 10 | 11 | package swagger 12 | 13 | import ( 14 | "time" 15 | ) 16 | 17 | type AccessToken struct { 18 | Id string `json:"id"` 19 | 20 | // time to live in seconds (2 weeks by default) 21 | Ttl float64 `json:"ttl,omitempty"` 22 | 23 | Created time.Time `json:"created,omitempty"` 24 | 25 | UserId float64 `json:"userId,omitempty"` 26 | } 27 | -------------------------------------------------------------------------------- /swagger/affiliate.go: -------------------------------------------------------------------------------- 1 | /* 2 | * BitMEX API 3 | * 4 | * ## REST API for the BitMEX Trading Platform [View Changelog](/app/apiChangelog) #### Getting Started ##### Fetching Data All REST endpoints are documented below. You can try out any query right from this interface. Most table queries accept `count`, `start`, and `reverse` params. Set `reverse=true` to get rows newest-first. Additional documentation regarding filters, timestamps, and authentication is available in [the main API documentation](https://www.bitmex.com/app/restAPI). *All* table data is available via the [Websocket](/app/wsAPI). We highly recommend using the socket if you want to have the quickest possible data without being subject to ratelimits. ##### Return Types By default, all data is returned as JSON. Send `?_format=csv` to get CSV data or `?_format=xml` to get XML data. ##### Trade Data Queries *This is only a small subset of what is available, to get you started.* Fill in the parameters and click the `Try it out!` button to try any of these queries. * [Pricing Data](#!/Quote/Quote_get) * [Trade Data](#!/Trade/Trade_get) * [OrderBook Data](#!/OrderBook/OrderBook_getL2) * [Settlement Data](#!/Settlement/Settlement_get) * [Exchange Statistics](#!/Stats/Stats_history) Every function of the BitMEX.com platform is exposed here and documented. Many more functions are available. ##### Swagger Specification [⇩ Download Swagger JSON](swagger.json) ## All API Endpoints Click to expand a section. 5 | * 6 | * OpenAPI spec version: 1.2.0 7 | * Contact: support@bitmex.com 8 | * Generated by: https://github.com/swagger-api/swagger-codegen.git 9 | */ 10 | 11 | package swagger 12 | 13 | import ( 14 | "time" 15 | ) 16 | 17 | type Affiliate struct { 18 | Account float32 `json:"account"` 19 | 20 | Currency string `json:"currency"` 21 | 22 | PrevPayout float32 `json:"prevPayout,omitempty"` 23 | 24 | PrevTurnover float32 `json:"prevTurnover,omitempty"` 25 | 26 | PrevComm float32 `json:"prevComm,omitempty"` 27 | 28 | PrevTimestamp time.Time `json:"prevTimestamp,omitempty"` 29 | 30 | ExecTurnover float32 `json:"execTurnover,omitempty"` 31 | 32 | ExecComm float32 `json:"execComm,omitempty"` 33 | 34 | TotalReferrals float32 `json:"totalReferrals,omitempty"` 35 | 36 | TotalTurnover float32 `json:"totalTurnover,omitempty"` 37 | 38 | TotalComm float32 `json:"totalComm,omitempty"` 39 | 40 | PayoutPcnt float64 `json:"payoutPcnt,omitempty"` 41 | 42 | PendingPayout float32 `json:"pendingPayout,omitempty"` 43 | 44 | Timestamp time.Time `json:"timestamp,omitempty"` 45 | 46 | ReferrerAccount float64 `json:"referrerAccount,omitempty"` 47 | } 48 | -------------------------------------------------------------------------------- /swagger/announcement.go: -------------------------------------------------------------------------------- 1 | /* 2 | * BitMEX API 3 | * 4 | * ## REST API for the BitMEX Trading Platform [View Changelog](/app/apiChangelog) #### Getting Started ##### Fetching Data All REST endpoints are documented below. You can try out any query right from this interface. Most table queries accept `count`, `start`, and `reverse` params. Set `reverse=true` to get rows newest-first. Additional documentation regarding filters, timestamps, and authentication is available in [the main API documentation](https://www.bitmex.com/app/restAPI). *All* table data is available via the [Websocket](/app/wsAPI). We highly recommend using the socket if you want to have the quickest possible data without being subject to ratelimits. ##### Return Types By default, all data is returned as JSON. Send `?_format=csv` to get CSV data or `?_format=xml` to get XML data. ##### Trade Data Queries *This is only a small subset of what is available, to get you started.* Fill in the parameters and click the `Try it out!` button to try any of these queries. * [Pricing Data](#!/Quote/Quote_get) * [Trade Data](#!/Trade/Trade_get) * [OrderBook Data](#!/OrderBook/OrderBook_getL2) * [Settlement Data](#!/Settlement/Settlement_get) * [Exchange Statistics](#!/Stats/Stats_history) Every function of the BitMEX.com platform is exposed here and documented. Many more functions are available. ##### Swagger Specification [⇩ Download Swagger JSON](swagger.json) ## All API Endpoints Click to expand a section. 5 | * 6 | * OpenAPI spec version: 1.2.0 7 | * Contact: support@bitmex.com 8 | * Generated by: https://github.com/swagger-api/swagger-codegen.git 9 | */ 10 | 11 | package swagger 12 | 13 | import ( 14 | "time" 15 | ) 16 | 17 | // Public Announcements 18 | type Announcement struct { 19 | Id float32 `json:"id"` 20 | 21 | Link string `json:"link,omitempty"` 22 | 23 | Title string `json:"title,omitempty"` 24 | 25 | Content string `json:"content,omitempty"` 26 | 27 | Date time.Time `json:"date,omitempty"` 28 | } 29 | -------------------------------------------------------------------------------- /swagger/announcement_api.go: -------------------------------------------------------------------------------- 1 | /* 2 | * BitMEX API 3 | * 4 | * ## REST API for the BitMEX Trading Platform [View Changelog](/app/apiChangelog) #### Getting Started ##### Fetching Data All REST endpoints are documented below. You can try out any query right from this interface. Most table queries accept `count`, `start`, and `reverse` params. Set `reverse=true` to get rows newest-first. Additional documentation regarding filters, timestamps, and authentication is available in [the main API documentation](https://www.bitmex.com/app/restAPI). *All* table data is available via the [Websocket](/app/wsAPI). We highly recommend using the socket if you want to have the quickest possible data without being subject to ratelimits. ##### Return Types By default, all data is returned as JSON. Send `?_format=csv` to get CSV data or `?_format=xml` to get XML data. ##### Trade Data Queries *This is only a small subset of what is available, to get you started.* Fill in the parameters and click the `Try it out!` button to try any of these queries. * [Pricing Data](#!/Quote/Quote_get) * [Trade Data](#!/Trade/Trade_get) * [OrderBook Data](#!/OrderBook/OrderBook_getL2) * [Settlement Data](#!/Settlement/Settlement_get) * [Exchange Statistics](#!/Stats/Stats_history) Every function of the BitMEX.com platform is exposed here and documented. Many more functions are available. ##### Swagger Specification [⇩ Download Swagger JSON](swagger.json) ## All API Endpoints Click to expand a section. 5 | * 6 | * OpenAPI spec version: 1.2.0 7 | * Contact: support@bitmex.com 8 | * Generated by: https://github.com/swagger-api/swagger-codegen.git 9 | */ 10 | 11 | package swagger 12 | 13 | import ( 14 | "encoding/json" 15 | "golang.org/x/net/context" 16 | "net/http" 17 | "net/url" 18 | "strings" 19 | ) 20 | 21 | // Linger please 22 | var ( 23 | _ context.Context 24 | ) 25 | 26 | type AnnouncementApiService service 27 | 28 | /* AnnouncementApiService Get site announcements. 29 | 30 | @param optional (nil or map[string]interface{}) with one or more of: 31 | @param "columns" (string) Array of column names to fetch. If omitted, will return all columns. 32 | @return []Announcement*/ 33 | func (a *AnnouncementApiService) AnnouncementGet(localVarOptionals map[string]interface{}) ([]Announcement, *http.Response, error) { 34 | var ( 35 | localVarHttpMethod = strings.ToUpper("Get") 36 | localVarPostBody interface{} 37 | localVarFileName string 38 | localVarFileBytes []byte 39 | successPayload []Announcement 40 | ) 41 | 42 | // create path and map variables 43 | localVarPath := a.client.cfg.BasePath + "/announcement" 44 | 45 | localVarHeaderParams := make(map[string]string) 46 | localVarQueryParams := url.Values{} 47 | localVarFormParams := url.Values{} 48 | 49 | if err := typeCheckParameter(localVarOptionals["columns"], "string", "columns"); err != nil { 50 | return successPayload, nil, err 51 | } 52 | 53 | if localVarTempParam, localVarOk := localVarOptionals["columns"].(string); localVarOk { 54 | localVarQueryParams.Add("columns", parameterToString(localVarTempParam, "")) 55 | } 56 | // to determine the Content-Type header 57 | localVarHttpContentTypes := []string{"application/json", "application/x-www-form-urlencoded"} 58 | 59 | // set Content-Type header 60 | localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) 61 | if localVarHttpContentType != "" { 62 | localVarHeaderParams["Content-Type"] = localVarHttpContentType 63 | } 64 | 65 | // to determine the Accept header 66 | localVarHttpHeaderAccepts := []string{ 67 | "application/json", 68 | "application/xml", 69 | "text/xml", 70 | "application/javascript", 71 | "text/javascript", 72 | } 73 | 74 | // set Accept header 75 | localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) 76 | if localVarHttpHeaderAccept != "" { 77 | localVarHeaderParams["Accept"] = localVarHttpHeaderAccept 78 | } 79 | r, err := a.client.prepareRequest(nil, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) 80 | if err != nil { 81 | return successPayload, nil, err 82 | } 83 | 84 | localVarHttpResponse, err := a.client.callAPI(r) 85 | if err != nil || localVarHttpResponse == nil { 86 | return successPayload, localVarHttpResponse, err 87 | } 88 | defer localVarHttpResponse.Body.Close() 89 | if localVarHttpResponse.StatusCode >= 300 { 90 | return successPayload, localVarHttpResponse, reportError(localVarHttpResponse.Status) 91 | } 92 | 93 | if err = json.NewDecoder(localVarHttpResponse.Body).Decode(&successPayload); err != nil { 94 | return successPayload, localVarHttpResponse, err 95 | } 96 | 97 | return successPayload, localVarHttpResponse, err 98 | } 99 | 100 | /* AnnouncementApiService Get urgent (banner) announcements. 101 | * @param ctx context.Context Authentication Context 102 | @return []Announcement*/ 103 | func (a *AnnouncementApiService) AnnouncementGetUrgent(ctx context.Context) ([]Announcement, *http.Response, error) { 104 | var ( 105 | localVarHttpMethod = strings.ToUpper("Get") 106 | localVarPostBody interface{} 107 | localVarFileName string 108 | localVarFileBytes []byte 109 | successPayload []Announcement 110 | ) 111 | 112 | // create path and map variables 113 | localVarPath := a.client.cfg.BasePath + "/announcement/urgent" 114 | 115 | localVarHeaderParams := make(map[string]string) 116 | localVarQueryParams := url.Values{} 117 | localVarFormParams := url.Values{} 118 | 119 | // to determine the Content-Type header 120 | localVarHttpContentTypes := []string{"application/json", "application/x-www-form-urlencoded"} 121 | 122 | // set Content-Type header 123 | localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) 124 | if localVarHttpContentType != "" { 125 | localVarHeaderParams["Content-Type"] = localVarHttpContentType 126 | } 127 | 128 | // to determine the Accept header 129 | localVarHttpHeaderAccepts := []string{ 130 | "application/json", 131 | "application/xml", 132 | "text/xml", 133 | "application/javascript", 134 | "text/javascript", 135 | } 136 | 137 | // set Accept header 138 | localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) 139 | if localVarHttpHeaderAccept != "" { 140 | localVarHeaderParams["Accept"] = localVarHttpHeaderAccept 141 | } 142 | if ctx != nil { 143 | // API Key Authentication 144 | if auth, ok := ctx.Value(ContextAPIKey).(APIKey); ok { 145 | var key string 146 | if auth.Prefix != "" { 147 | key = auth.Prefix + " " + auth.Key 148 | } else { 149 | key = auth.Key 150 | } 151 | localVarHeaderParams["api-key"] = key 152 | } 153 | } 154 | if ctx != nil { 155 | // API Key Authentication 156 | if auth, ok := ctx.Value(ContextAPIKey).(APIKey); ok { 157 | var key string 158 | if auth.Prefix != "" { 159 | key = auth.Prefix + " " + auth.Key 160 | } else { 161 | key = auth.Key 162 | } 163 | localVarHeaderParams["api-nonce"] = key 164 | } 165 | } 166 | if ctx != nil { 167 | // API Key Authentication 168 | if auth, ok := ctx.Value(ContextAPIKey).(APIKey); ok { 169 | var key string 170 | if auth.Prefix != "" { 171 | key = auth.Prefix + " " + auth.Key 172 | } else { 173 | key = auth.Key 174 | } 175 | localVarHeaderParams["api-signature"] = key 176 | } 177 | } 178 | r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) 179 | if err != nil { 180 | return successPayload, nil, err 181 | } 182 | 183 | localVarHttpResponse, err := a.client.callAPI(r) 184 | if err != nil || localVarHttpResponse == nil { 185 | return successPayload, localVarHttpResponse, err 186 | } 187 | defer localVarHttpResponse.Body.Close() 188 | if localVarHttpResponse.StatusCode >= 300 { 189 | return successPayload, localVarHttpResponse, reportError(localVarHttpResponse.Status) 190 | } 191 | 192 | if err = json.NewDecoder(localVarHttpResponse.Body).Decode(&successPayload); err != nil { 193 | return successPayload, localVarHttpResponse, err 194 | } 195 | 196 | return successPayload, localVarHttpResponse, err 197 | } 198 | -------------------------------------------------------------------------------- /swagger/api_key.go: -------------------------------------------------------------------------------- 1 | /* 2 | * BitMEX API 3 | * 4 | * ## REST API for the BitMEX Trading Platform [View Changelog](/app/apiChangelog) #### Getting Started ##### Fetching Data All REST endpoints are documented below. You can try out any query right from this interface. Most table queries accept `count`, `start`, and `reverse` params. Set `reverse=true` to get rows newest-first. Additional documentation regarding filters, timestamps, and authentication is available in [the main API documentation](https://www.bitmex.com/app/restAPI). *All* table data is available via the [Websocket](/app/wsAPI). We highly recommend using the socket if you want to have the quickest possible data without being subject to ratelimits. ##### Return Types By default, all data is returned as JSON. Send `?_format=csv` to get CSV data or `?_format=xml` to get XML data. ##### Trade Data Queries *This is only a small subset of what is available, to get you started.* Fill in the parameters and click the `Try it out!` button to try any of these queries. * [Pricing Data](#!/Quote/Quote_get) * [Trade Data](#!/Trade/Trade_get) * [OrderBook Data](#!/OrderBook/OrderBook_getL2) * [Settlement Data](#!/Settlement/Settlement_get) * [Exchange Statistics](#!/Stats/Stats_history) Every function of the BitMEX.com platform is exposed here and documented. Many more functions are available. ##### Swagger Specification [⇩ Download Swagger JSON](swagger.json) ## All API Endpoints Click to expand a section. 5 | * 6 | * OpenAPI spec version: 1.2.0 7 | * Contact: support@bitmex.com 8 | * Generated by: https://github.com/swagger-api/swagger-codegen.git 9 | */ 10 | 11 | package swagger 12 | 13 | import ( 14 | "time" 15 | ) 16 | 17 | // Persistent API Keys for Developers 18 | type ApiKey struct { 19 | Id string `json:"id"` 20 | 21 | Secret string `json:"secret"` 22 | 23 | Name string `json:"name"` 24 | 25 | Nonce float32 `json:"nonce"` 26 | 27 | Cidr string `json:"cidr,omitempty"` 28 | 29 | Permissions []XAny `json:"permissions,omitempty"` 30 | 31 | Enabled bool `json:"enabled,omitempty"` 32 | 33 | UserId float32 `json:"userId"` 34 | 35 | Created time.Time `json:"created,omitempty"` 36 | } 37 | -------------------------------------------------------------------------------- /swagger/api_response.go: -------------------------------------------------------------------------------- 1 | /* 2 | * BitMEX API 3 | * 4 | * ## REST API for the BitMEX Trading Platform [View Changelog](/app/apiChangelog) #### Getting Started ##### Fetching Data All REST endpoints are documented below. You can try out any query right from this interface. Most table queries accept `count`, `start`, and `reverse` params. Set `reverse=true` to get rows newest-first. Additional documentation regarding filters, timestamps, and authentication is available in [the main API documentation](https://www.bitmex.com/app/restAPI). *All* table data is available via the [Websocket](/app/wsAPI). We highly recommend using the socket if you want to have the quickest possible data without being subject to ratelimits. ##### Return Types By default, all data is returned as JSON. Send `?_format=csv` to get CSV data or `?_format=xml` to get XML data. ##### Trade Data Queries *This is only a small subset of what is available, to get you started.* Fill in the parameters and click the `Try it out!` button to try any of these queries. * [Pricing Data](#!/Quote/Quote_get) * [Trade Data](#!/Trade/Trade_get) * [OrderBook Data](#!/OrderBook/OrderBook_getL2) * [Settlement Data](#!/Settlement/Settlement_get) * [Exchange Statistics](#!/Stats/Stats_history) Every function of the BitMEX.com platform is exposed here and documented. Many more functions are available. ##### Swagger Specification [⇩ Download Swagger JSON](swagger.json) ## All API Endpoints Click to expand a section. 5 | * 6 | * OpenAPI spec version: 1.2.0 7 | * Contact: support@bitmex.com 8 | * Generated by: https://github.com/swagger-api/swagger-codegen.git 9 | */ 10 | 11 | package swagger 12 | 13 | import ( 14 | "net/http" 15 | ) 16 | 17 | type APIResponse struct { 18 | *http.Response `json:"-"` 19 | Message string `json:"message,omitempty"` 20 | // Operation is the name of the swagger operation. 21 | Operation string `json:"operation,omitempty"` 22 | // RequestURL is the request URL. This value is always available, even if the 23 | // embedded *http.Response is nil. 24 | RequestURL string `json:"url,omitempty"` 25 | // Method is the HTTP method used for the request. This value is always 26 | // available, even if the embedded *http.Response is nil. 27 | Method string `json:"method,omitempty"` 28 | // Payload holds the contents of the response body (which may be nil or empty). 29 | // This is provided here as the raw response.Body() reader will have already 30 | // been drained. 31 | Payload []byte `json:"-"` 32 | } 33 | 34 | func NewAPIResponse(r *http.Response) *APIResponse { 35 | 36 | response := &APIResponse{Response: r} 37 | return response 38 | } 39 | 40 | func NewAPIResponseWithError(errorMessage string) *APIResponse { 41 | 42 | response := &APIResponse{Message: errorMessage} 43 | return response 44 | } 45 | -------------------------------------------------------------------------------- /swagger/auth_util.go: -------------------------------------------------------------------------------- 1 | package swagger 2 | 3 | import ( 4 | "crypto/hmac" 5 | "crypto/sha256" 6 | "encoding/hex" 7 | "fmt" 8 | "net/http" 9 | "net/http/httputil" 10 | "net/url" 11 | "regexp" 12 | "strconv" 13 | "strings" 14 | "time" 15 | ) 16 | 17 | func SetAuthHeader(request *http.Request, apiKey APIKey, c *Configuration, httpMethod, path, postBody string, 18 | queryParams url.Values) { 19 | var expires = strconv.FormatInt(time.Now().Unix()+c.ExpireTime, 10) 20 | request.Header.Add("api-key", apiKey.Key) 21 | request.Header.Add("api-expires", expires) 22 | p := regexp.MustCompile("/api.*").FindString(path) 23 | request.Header.Add("api-signature", Signature(apiKey.Secret, httpMethod, p, queryParams.Encode(), 24 | expires, postBody)) 25 | } 26 | 27 | /** 28 | * nonce: nonce or expires 29 | */ 30 | func Signature(apiSecret, method, path, query, nonce, bodyStr string) string { 31 | str := "" 32 | if "" == query { 33 | str = strings.ToUpper(method) + path + nonce + bodyStr 34 | } else { 35 | str = strings.ToUpper(method) + path + "?" + query + nonce + bodyStr 36 | } 37 | return CalSignature(apiSecret, str) 38 | } 39 | 40 | func CalSignature(apiSecret, payload string) string { 41 | sig := hmac.New(sha256.New, []byte(apiSecret)) 42 | sig.Write([]byte(payload)) 43 | return hex.EncodeToString(sig.Sum(nil)) 44 | } 45 | 46 | // Save a copy of this request for debugging. 47 | func DebugHttpRequest(r *http.Request) { 48 | requestDump, err := httputil.DumpRequest(r, true) 49 | if err != nil { 50 | fmt.Println(err) 51 | } 52 | fmt.Println(string(requestDump)) 53 | } 54 | -------------------------------------------------------------------------------- /swagger/chat.go: -------------------------------------------------------------------------------- 1 | /* 2 | * BitMEX API 3 | * 4 | * ## REST API for the BitMEX Trading Platform [View Changelog](/app/apiChangelog) #### Getting Started ##### Fetching Data All REST endpoints are documented below. You can try out any query right from this interface. Most table queries accept `count`, `start`, and `reverse` params. Set `reverse=true` to get rows newest-first. Additional documentation regarding filters, timestamps, and authentication is available in [the main API documentation](https://www.bitmex.com/app/restAPI). *All* table data is available via the [Websocket](/app/wsAPI). We highly recommend using the socket if you want to have the quickest possible data without being subject to ratelimits. ##### Return Types By default, all data is returned as JSON. Send `?_format=csv` to get CSV data or `?_format=xml` to get XML data. ##### Trade Data Queries *This is only a small subset of what is available, to get you started.* Fill in the parameters and click the `Try it out!` button to try any of these queries. * [Pricing Data](#!/Quote/Quote_get) * [Trade Data](#!/Trade/Trade_get) * [OrderBook Data](#!/OrderBook/OrderBook_getL2) * [Settlement Data](#!/Settlement/Settlement_get) * [Exchange Statistics](#!/Stats/Stats_history) Every function of the BitMEX.com platform is exposed here and documented. Many more functions are available. ##### Swagger Specification [⇩ Download Swagger JSON](swagger.json) ## All API Endpoints Click to expand a section. 5 | * 6 | * OpenAPI spec version: 1.2.0 7 | * Contact: support@bitmex.com 8 | * Generated by: https://github.com/swagger-api/swagger-codegen.git 9 | */ 10 | 11 | package swagger 12 | 13 | import ( 14 | "time" 15 | ) 16 | 17 | // Trollbox Data 18 | type Chat struct { 19 | Id float32 `json:"id,omitempty"` 20 | 21 | Date time.Time `json:"date"` 22 | 23 | User string `json:"user"` 24 | 25 | Message string `json:"message"` 26 | 27 | Html string `json:"html"` 28 | 29 | FromBot bool `json:"fromBot,omitempty"` 30 | 31 | ChannelID float64 `json:"channelID,omitempty"` 32 | } 33 | -------------------------------------------------------------------------------- /swagger/chat_channel.go: -------------------------------------------------------------------------------- 1 | /* 2 | * BitMEX API 3 | * 4 | * ## REST API for the BitMEX Trading Platform [View Changelog](/app/apiChangelog) #### Getting Started ##### Fetching Data All REST endpoints are documented below. You can try out any query right from this interface. Most table queries accept `count`, `start`, and `reverse` params. Set `reverse=true` to get rows newest-first. Additional documentation regarding filters, timestamps, and authentication is available in [the main API documentation](https://www.bitmex.com/app/restAPI). *All* table data is available via the [Websocket](/app/wsAPI). We highly recommend using the socket if you want to have the quickest possible data without being subject to ratelimits. ##### Return Types By default, all data is returned as JSON. Send `?_format=csv` to get CSV data or `?_format=xml` to get XML data. ##### Trade Data Queries *This is only a small subset of what is available, to get you started.* Fill in the parameters and click the `Try it out!` button to try any of these queries. * [Pricing Data](#!/Quote/Quote_get) * [Trade Data](#!/Trade/Trade_get) * [OrderBook Data](#!/OrderBook/OrderBook_getL2) * [Settlement Data](#!/Settlement/Settlement_get) * [Exchange Statistics](#!/Stats/Stats_history) Every function of the BitMEX.com platform is exposed here and documented. Many more functions are available. ##### Swagger Specification [⇩ Download Swagger JSON](swagger.json) ## All API Endpoints Click to expand a section. 5 | * 6 | * OpenAPI spec version: 1.2.0 7 | * Contact: support@bitmex.com 8 | * Generated by: https://github.com/swagger-api/swagger-codegen.git 9 | */ 10 | 11 | package swagger 12 | 13 | type ChatChannel struct { 14 | Id float32 `json:"id,omitempty"` 15 | 16 | Name string `json:"name"` 17 | } 18 | -------------------------------------------------------------------------------- /swagger/configuration.go: -------------------------------------------------------------------------------- 1 | /* 2 | * BitMEX API 3 | * 4 | * ## REST API for the BitMEX Trading Platform [View Changelog](/app/apiChangelog) #### Getting Started ##### Fetching Data All REST endpoints are documented below. You can try out any query right from this interface. Most table queries accept `count`, `start`, and `reverse` params. Set `reverse=true` to get rows newest-first. Additional documentation regarding filters, timestamps, and authentication is available in [the main API documentation](https://www.bitmex.com/app/restAPI). *All* table data is available via the [Websocket](/app/wsAPI). We highly recommend using the socket if you want to have the quickest possible data without being subject to ratelimits. ##### Return Types By default, all data is returned as JSON. Send `?_format=csv` to get CSV data or `?_format=xml` to get XML data. ##### Trade Data Queries *This is only a small subset of what is available, to get you started.* Fill in the parameters and click the `Try it out!` button to try any of these queries. * [Pricing Data](#!/Quote/Quote_get) * [Trade Data](#!/Trade/Trade_get) * [OrderBook Data](#!/OrderBook/OrderBook_getL2) * [Settlement Data](#!/Settlement/Settlement_get) * [Exchange Statistics](#!/Stats/Stats_history) Every function of the BitMEX.com platform is exposed here and documented. Many more functions are available. ##### Swagger Specification [⇩ Download Swagger JSON](swagger.json) ## All API Endpoints Click to expand a section. 5 | * 6 | * OpenAPI spec version: 1.2.0 7 | * Contact: support@bitmex.com 8 | * Generated by: https://github.com/swagger-api/swagger-codegen.git 9 | */ 10 | 11 | package swagger 12 | 13 | import ( 14 | "net/http" 15 | ) 16 | 17 | const ContextOAuth2 int = 1 18 | const ContextBasicAuth int = 2 19 | const ContextAccessToken int = 3 20 | const ContextAPIKey int = 4 21 | 22 | type BasicAuth struct { 23 | UserName string `json:"userName,omitempty"` 24 | Password string `json:"password,omitempty"` 25 | } 26 | 27 | type APIKey struct { 28 | Key string 29 | Prefix string 30 | Secret string 31 | Host string 32 | Timeout int64 33 | } 34 | 35 | type Configuration struct { 36 | BasePath string `json:"basePath,omitempty"` 37 | Host string `json:"host,omitempty"` 38 | Scheme string `json:"scheme,omitempty"` 39 | DefaultHeader map[string]string `json:"defaultHeader,omitempty"` 40 | UserAgent string `json:"userAgent,omitempty"` 41 | HTTPClient *http.Client 42 | 43 | ExpireTime int64 44 | } 45 | 46 | func NewConfiguration() *Configuration { 47 | cfg := &Configuration{ 48 | BasePath: "https://www.bitmex.com/api/v1", 49 | DefaultHeader: make(map[string]string), 50 | UserAgent: "Swagger-Codegen/1.0.0/go", 51 | ExpireTime: 5, //seconds 52 | } 53 | return cfg 54 | } 55 | 56 | func (c *Configuration) AddDefaultHeader(key string, value string) { 57 | c.DefaultHeader[key] = value 58 | } 59 | -------------------------------------------------------------------------------- /swagger/connected_users.go: -------------------------------------------------------------------------------- 1 | /* 2 | * BitMEX API 3 | * 4 | * ## REST API for the BitMEX Trading Platform [View Changelog](/app/apiChangelog) #### Getting Started ##### Fetching Data All REST endpoints are documented below. You can try out any query right from this interface. Most table queries accept `count`, `start`, and `reverse` params. Set `reverse=true` to get rows newest-first. Additional documentation regarding filters, timestamps, and authentication is available in [the main API documentation](https://www.bitmex.com/app/restAPI). *All* table data is available via the [Websocket](/app/wsAPI). We highly recommend using the socket if you want to have the quickest possible data without being subject to ratelimits. ##### Return Types By default, all data is returned as JSON. Send `?_format=csv` to get CSV data or `?_format=xml` to get XML data. ##### Trade Data Queries *This is only a small subset of what is available, to get you started.* Fill in the parameters and click the `Try it out!` button to try any of these queries. * [Pricing Data](#!/Quote/Quote_get) * [Trade Data](#!/Trade/Trade_get) * [OrderBook Data](#!/OrderBook/OrderBook_getL2) * [Settlement Data](#!/Settlement/Settlement_get) * [Exchange Statistics](#!/Stats/Stats_history) Every function of the BitMEX.com platform is exposed here and documented. Many more functions are available. ##### Swagger Specification [⇩ Download Swagger JSON](swagger.json) ## All API Endpoints Click to expand a section. 5 | * 6 | * OpenAPI spec version: 1.2.0 7 | * Contact: support@bitmex.com 8 | * Generated by: https://github.com/swagger-api/swagger-codegen.git 9 | */ 10 | 11 | package swagger 12 | 13 | type ConnectedUsers struct { 14 | Users float32 `json:"users,omitempty"` 15 | 16 | Bots float32 `json:"bots,omitempty"` 17 | } 18 | -------------------------------------------------------------------------------- /swagger/error_error.go: -------------------------------------------------------------------------------- 1 | /* 2 | * BitMEX API 3 | * 4 | * ## REST API for the BitMEX Trading Platform [View Changelog](/app/apiChangelog) #### Getting Started ##### Fetching Data All REST endpoints are documented below. You can try out any query right from this interface. Most table queries accept `count`, `start`, and `reverse` params. Set `reverse=true` to get rows newest-first. Additional documentation regarding filters, timestamps, and authentication is available in [the main API documentation](https://www.bitmex.com/app/restAPI). *All* table data is available via the [Websocket](/app/wsAPI). We highly recommend using the socket if you want to have the quickest possible data without being subject to ratelimits. ##### Return Types By default, all data is returned as JSON. Send `?_format=csv` to get CSV data or `?_format=xml` to get XML data. ##### Trade Data Queries *This is only a small subset of what is available, to get you started.* Fill in the parameters and click the `Try it out!` button to try any of these queries. * [Pricing Data](#!/Quote/Quote_get) * [Trade Data](#!/Trade/Trade_get) * [OrderBook Data](#!/OrderBook/OrderBook_getL2) * [Settlement Data](#!/Settlement/Settlement_get) * [Exchange Statistics](#!/Stats/Stats_history) Every function of the BitMEX.com platform is exposed here and documented. Many more functions are available. ##### Swagger Specification [⇩ Download Swagger JSON](swagger.json) ## All API Endpoints Click to expand a section. 5 | * 6 | * OpenAPI spec version: 1.2.0 7 | * Contact: support@bitmex.com 8 | * Generated by: https://github.com/swagger-api/swagger-codegen.git 9 | */ 10 | 11 | package swagger 12 | 13 | type ErrorError struct { 14 | Message string `json:"message,omitempty"` 15 | 16 | Name string `json:"name,omitempty"` 17 | } 18 | -------------------------------------------------------------------------------- /swagger/execution.go: -------------------------------------------------------------------------------- 1 | /* 2 | * BitMEX API 3 | * 4 | * ## REST API for the BitMEX Trading Platform [View Changelog](/app/apiChangelog) #### Getting Started ##### Fetching Data All REST endpoints are documented below. You can try out any query right from this interface. Most table queries accept `count`, `start`, and `reverse` params. Set `reverse=true` to get rows newest-first. Additional documentation regarding filters, timestamps, and authentication is available in [the main API documentation](https://www.bitmex.com/app/restAPI). *All* table data is available via the [Websocket](/app/wsAPI). We highly recommend using the socket if you want to have the quickest possible data without being subject to ratelimits. ##### Return Types By default, all data is returned as JSON. Send `?_format=csv` to get CSV data or `?_format=xml` to get XML data. ##### Trade Data Queries *This is only a small subset of what is available, to get you started.* Fill in the parameters and click the `Try it out!` button to try any of these queries. * [Pricing Data](#!/Quote/Quote_get) * [Trade Data](#!/Trade/Trade_get) * [OrderBook Data](#!/OrderBook/OrderBook_getL2) * [Settlement Data](#!/Settlement/Settlement_get) * [Exchange Statistics](#!/Stats/Stats_history) Every function of the BitMEX.com platform is exposed here and documented. Many more functions are available. ##### Swagger Specification [⇩ Download Swagger JSON](swagger.json) ## All API Endpoints Click to expand a section. 5 | * 6 | * OpenAPI spec version: 1.2.0 7 | * Contact: support@bitmex.com 8 | * Generated by: https://github.com/swagger-api/swagger-codegen.git 9 | */ 10 | 11 | package swagger 12 | 13 | import ( 14 | "time" 15 | ) 16 | 17 | // Raw Order and Balance Data 18 | type Execution struct { 19 | ExecID string `json:"execID"` 20 | 21 | OrderID string `json:"orderID,omitempty"` 22 | 23 | ClOrdID string `json:"clOrdID,omitempty"` 24 | 25 | ClOrdLinkID string `json:"clOrdLinkID,omitempty"` 26 | 27 | Account float32 `json:"account,omitempty"` 28 | 29 | Symbol string `json:"symbol,omitempty"` 30 | 31 | Side string `json:"side,omitempty"` 32 | 33 | LastQty float32 `json:"lastQty,omitempty"` 34 | 35 | LastPx float64 `json:"lastPx,omitempty"` 36 | 37 | UnderlyingLastPx float64 `json:"underlyingLastPx,omitempty"` 38 | 39 | LastMkt string `json:"lastMkt,omitempty"` 40 | 41 | LastLiquidityInd string `json:"lastLiquidityInd,omitempty"` 42 | 43 | SimpleOrderQty float64 `json:"simpleOrderQty,omitempty"` 44 | 45 | OrderQty float32 `json:"orderQty,omitempty"` 46 | 47 | Price float64 `json:"price,omitempty"` 48 | 49 | DisplayQty float32 `json:"displayQty,omitempty"` 50 | 51 | StopPx float64 `json:"stopPx,omitempty"` 52 | 53 | PegOffsetValue float64 `json:"pegOffsetValue,omitempty"` 54 | 55 | PegPriceType string `json:"pegPriceType,omitempty"` 56 | 57 | Currency string `json:"currency,omitempty"` 58 | 59 | SettlCurrency string `json:"settlCurrency,omitempty"` 60 | 61 | ExecType string `json:"execType,omitempty"` 62 | 63 | OrdType string `json:"ordType,omitempty"` 64 | 65 | TimeInForce string `json:"timeInForce,omitempty"` 66 | 67 | ExecInst string `json:"execInst,omitempty"` 68 | 69 | ContingencyType string `json:"contingencyType,omitempty"` 70 | 71 | ExDestination string `json:"exDestination,omitempty"` 72 | 73 | OrdStatus string `json:"ordStatus,omitempty"` 74 | 75 | Triggered string `json:"triggered,omitempty"` 76 | 77 | WorkingIndicator bool `json:"workingIndicator,omitempty"` 78 | 79 | OrdRejReason string `json:"ordRejReason,omitempty"` 80 | 81 | SimpleLeavesQty float64 `json:"simpleLeavesQty,omitempty"` 82 | 83 | LeavesQty float32 `json:"leavesQty,omitempty"` 84 | 85 | SimpleCumQty float64 `json:"simpleCumQty,omitempty"` 86 | 87 | CumQty float32 `json:"cumQty,omitempty"` 88 | 89 | AvgPx float64 `json:"avgPx,omitempty"` 90 | 91 | Commission float64 `json:"commission,omitempty"` 92 | 93 | TradePublishIndicator string `json:"tradePublishIndicator,omitempty"` 94 | 95 | MultiLegReportingType string `json:"multiLegReportingType,omitempty"` 96 | 97 | Text string `json:"text,omitempty"` 98 | 99 | TrdMatchID string `json:"trdMatchID,omitempty"` 100 | 101 | ExecCost float32 `json:"execCost,omitempty"` 102 | 103 | ExecComm float32 `json:"execComm,omitempty"` 104 | 105 | HomeNotional float64 `json:"homeNotional,omitempty"` 106 | 107 | ForeignNotional float64 `json:"foreignNotional,omitempty"` 108 | 109 | TransactTime time.Time `json:"transactTime,omitempty"` 110 | 111 | Timestamp time.Time `json:"timestamp,omitempty"` 112 | } 113 | -------------------------------------------------------------------------------- /swagger/funding.go: -------------------------------------------------------------------------------- 1 | /* 2 | * BitMEX API 3 | * 4 | * ## REST API for the BitMEX Trading Platform [View Changelog](/app/apiChangelog) #### Getting Started ##### Fetching Data All REST endpoints are documented below. You can try out any query right from this interface. Most table queries accept `count`, `start`, and `reverse` params. Set `reverse=true` to get rows newest-first. Additional documentation regarding filters, timestamps, and authentication is available in [the main API documentation](https://www.bitmex.com/app/restAPI). *All* table data is available via the [Websocket](/app/wsAPI). We highly recommend using the socket if you want to have the quickest possible data without being subject to ratelimits. ##### Return Types By default, all data is returned as JSON. Send `?_format=csv` to get CSV data or `?_format=xml` to get XML data. ##### Trade Data Queries *This is only a small subset of what is available, to get you started.* Fill in the parameters and click the `Try it out!` button to try any of these queries. * [Pricing Data](#!/Quote/Quote_get) * [Trade Data](#!/Trade/Trade_get) * [OrderBook Data](#!/OrderBook/OrderBook_getL2) * [Settlement Data](#!/Settlement/Settlement_get) * [Exchange Statistics](#!/Stats/Stats_history) Every function of the BitMEX.com platform is exposed here and documented. Many more functions are available. ##### Swagger Specification [⇩ Download Swagger JSON](swagger.json) ## All API Endpoints Click to expand a section. 5 | * 6 | * OpenAPI spec version: 1.2.0 7 | * Contact: support@bitmex.com 8 | * Generated by: https://github.com/swagger-api/swagger-codegen.git 9 | */ 10 | 11 | package swagger 12 | 13 | import ( 14 | "time" 15 | ) 16 | 17 | // Swap Funding History 18 | type Funding struct { 19 | Timestamp time.Time `json:"timestamp"` 20 | 21 | Symbol string `json:"symbol"` 22 | 23 | FundingInterval time.Time `json:"fundingInterval,omitempty"` 24 | 25 | FundingRate float64 `json:"fundingRate,omitempty"` 26 | 27 | FundingRateDaily float64 `json:"fundingRateDaily,omitempty"` 28 | } 29 | -------------------------------------------------------------------------------- /swagger/funding_api.go: -------------------------------------------------------------------------------- 1 | /* 2 | * BitMEX API 3 | * 4 | * ## REST API for the BitMEX Trading Platform [View Changelog](/app/apiChangelog) #### Getting Started ##### Fetching Data All REST endpoints are documented below. You can try out any query right from this interface. Most table queries accept `count`, `start`, and `reverse` params. Set `reverse=true` to get rows newest-first. Additional documentation regarding filters, timestamps, and authentication is available in [the main API documentation](https://www.bitmex.com/app/restAPI). *All* table data is available via the [Websocket](/app/wsAPI). We highly recommend using the socket if you want to have the quickest possible data without being subject to ratelimits. ##### Return Types By default, all data is returned as JSON. Send `?_format=csv` to get CSV data or `?_format=xml` to get XML data. ##### Trade Data Queries *This is only a small subset of what is available, to get you started.* Fill in the parameters and click the `Try it out!` button to try any of these queries. * [Pricing Data](#!/Quote/Quote_get) * [Trade Data](#!/Trade/Trade_get) * [OrderBook Data](#!/OrderBook/OrderBook_getL2) * [Settlement Data](#!/Settlement/Settlement_get) * [Exchange Statistics](#!/Stats/Stats_history) Every function of the BitMEX.com platform is exposed here and documented. Many more functions are available. ##### Swagger Specification [⇩ Download Swagger JSON](swagger.json) ## All API Endpoints Click to expand a section. 5 | * 6 | * OpenAPI spec version: 1.2.0 7 | * Contact: support@bitmex.com 8 | * Generated by: https://github.com/swagger-api/swagger-codegen.git 9 | */ 10 | 11 | package swagger 12 | 13 | import ( 14 | "encoding/json" 15 | "golang.org/x/net/context" 16 | "net/http" 17 | "net/url" 18 | "strings" 19 | "time" 20 | ) 21 | 22 | // Linger please 23 | var ( 24 | _ context.Context 25 | ) 26 | 27 | type FundingApiService service 28 | 29 | /* FundingApiService Get funding history. 30 | 31 | @param optional (nil or map[string]interface{}) with one or more of: 32 | @param "symbol" (string) Instrument symbol. Send a bare series (e.g. XBU) to get data for the nearest expiring contract in that series. You can also send a timeframe, e.g. `XBU:monthly`. Timeframes are `daily`, `weekly`, `monthly`, `quarterly`, and `biquarterly`. 33 | @param "filter" (string) Generic table filter. Send JSON key/value pairs, such as `{\"key\": \"value\"}`. You can key on individual fields, and do more advanced querying on timestamps. See the [Timestamp Docs](https://www.bitmex.com/app/restAPI#timestamp-filters) for more details. 34 | @param "columns" (string) Array of column names to fetch. If omitted, will return all columns. Note that this method will always return item keys, even when not specified, so you may receive more columns that you expect. 35 | @param "count" (float32) Number of results to fetch. 36 | @param "start" (float32) Starting point for results. 37 | @param "reverse" (bool) If true, will sort results newest first. 38 | @param "startTime" (time.Time) Starting date filter for results. 39 | @param "endTime" (time.Time) Ending date filter for results. 40 | @return []Funding*/ 41 | func (a *FundingApiService) FundingGet(localVarOptionals map[string]interface{}) ([]Funding, *http.Response, error) { 42 | var ( 43 | localVarHttpMethod = strings.ToUpper("Get") 44 | localVarPostBody interface{} 45 | localVarFileName string 46 | localVarFileBytes []byte 47 | successPayload []Funding 48 | ) 49 | 50 | // create path and map variables 51 | localVarPath := a.client.cfg.BasePath + "/funding" 52 | 53 | localVarHeaderParams := make(map[string]string) 54 | localVarQueryParams := url.Values{} 55 | localVarFormParams := url.Values{} 56 | 57 | if err := typeCheckParameter(localVarOptionals["symbol"], "string", "symbol"); err != nil { 58 | return successPayload, nil, err 59 | } 60 | if err := typeCheckParameter(localVarOptionals["filter"], "string", "filter"); err != nil { 61 | return successPayload, nil, err 62 | } 63 | if err := typeCheckParameter(localVarOptionals["columns"], "string", "columns"); err != nil { 64 | return successPayload, nil, err 65 | } 66 | if err := typeCheckParameter(localVarOptionals["count"], "float32", "count"); err != nil { 67 | return successPayload, nil, err 68 | } 69 | if err := typeCheckParameter(localVarOptionals["start"], "float32", "start"); err != nil { 70 | return successPayload, nil, err 71 | } 72 | if err := typeCheckParameter(localVarOptionals["reverse"], "bool", "reverse"); err != nil { 73 | return successPayload, nil, err 74 | } 75 | if err := typeCheckParameter(localVarOptionals["startTime"], "time.Time", "startTime"); err != nil { 76 | return successPayload, nil, err 77 | } 78 | if err := typeCheckParameter(localVarOptionals["endTime"], "time.Time", "endTime"); err != nil { 79 | return successPayload, nil, err 80 | } 81 | 82 | if localVarTempParam, localVarOk := localVarOptionals["symbol"].(string); localVarOk { 83 | localVarQueryParams.Add("symbol", parameterToString(localVarTempParam, "")) 84 | } 85 | if localVarTempParam, localVarOk := localVarOptionals["filter"].(string); localVarOk { 86 | localVarQueryParams.Add("filter", parameterToString(localVarTempParam, "")) 87 | } 88 | if localVarTempParam, localVarOk := localVarOptionals["columns"].(string); localVarOk { 89 | localVarQueryParams.Add("columns", parameterToString(localVarTempParam, "")) 90 | } 91 | if localVarTempParam, localVarOk := localVarOptionals["count"].(float32); localVarOk { 92 | localVarQueryParams.Add("count", parameterToString(localVarTempParam, "")) 93 | } 94 | if localVarTempParam, localVarOk := localVarOptionals["start"].(float32); localVarOk { 95 | localVarQueryParams.Add("start", parameterToString(localVarTempParam, "")) 96 | } 97 | if localVarTempParam, localVarOk := localVarOptionals["reverse"].(bool); localVarOk { 98 | localVarQueryParams.Add("reverse", parameterToString(localVarTempParam, "")) 99 | } 100 | if localVarTempParam, localVarOk := localVarOptionals["startTime"].(time.Time); localVarOk { 101 | localVarQueryParams.Add("startTime", parameterToString(localVarTempParam, "")) 102 | } 103 | if localVarTempParam, localVarOk := localVarOptionals["endTime"].(time.Time); localVarOk { 104 | localVarQueryParams.Add("endTime", parameterToString(localVarTempParam, "")) 105 | } 106 | // to determine the Content-Type header 107 | localVarHttpContentTypes := []string{"application/json", "application/x-www-form-urlencoded"} 108 | 109 | // set Content-Type header 110 | localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) 111 | if localVarHttpContentType != "" { 112 | localVarHeaderParams["Content-Type"] = localVarHttpContentType 113 | } 114 | 115 | // to determine the Accept header 116 | localVarHttpHeaderAccepts := []string{ 117 | "application/json", 118 | "application/xml", 119 | "text/xml", 120 | "application/javascript", 121 | "text/javascript", 122 | } 123 | 124 | // set Accept header 125 | localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) 126 | if localVarHttpHeaderAccept != "" { 127 | localVarHeaderParams["Accept"] = localVarHttpHeaderAccept 128 | } 129 | r, err := a.client.prepareRequest(nil, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) 130 | if err != nil { 131 | return successPayload, nil, err 132 | } 133 | 134 | localVarHttpResponse, err := a.client.callAPI(r) 135 | if err != nil || localVarHttpResponse == nil { 136 | return successPayload, localVarHttpResponse, err 137 | } 138 | defer localVarHttpResponse.Body.Close() 139 | if localVarHttpResponse.StatusCode >= 300 { 140 | return successPayload, localVarHttpResponse, reportError(localVarHttpResponse.Status) 141 | } 142 | 143 | if err = json.NewDecoder(localVarHttpResponse.Body).Decode(&successPayload); err != nil { 144 | return successPayload, localVarHttpResponse, err 145 | } 146 | 147 | return successPayload, localVarHttpResponse, err 148 | } 149 | -------------------------------------------------------------------------------- /swagger/index_composite.go: -------------------------------------------------------------------------------- 1 | /* 2 | * BitMEX API 3 | * 4 | * ## REST API for the BitMEX Trading Platform [View Changelog](/app/apiChangelog) #### Getting Started ##### Fetching Data All REST endpoints are documented below. You can try out any query right from this interface. Most table queries accept `count`, `start`, and `reverse` params. Set `reverse=true` to get rows newest-first. Additional documentation regarding filters, timestamps, and authentication is available in [the main API documentation](https://www.bitmex.com/app/restAPI). *All* table data is available via the [Websocket](/app/wsAPI). We highly recommend using the socket if you want to have the quickest possible data without being subject to ratelimits. ##### Return Types By default, all data is returned as JSON. Send `?_format=csv` to get CSV data or `?_format=xml` to get XML data. ##### Trade Data Queries *This is only a small subset of what is available, to get you started.* Fill in the parameters and click the `Try it out!` button to try any of these queries. * [Pricing Data](#!/Quote/Quote_get) * [Trade Data](#!/Trade/Trade_get) * [OrderBook Data](#!/OrderBook/OrderBook_getL2) * [Settlement Data](#!/Settlement/Settlement_get) * [Exchange Statistics](#!/Stats/Stats_history) Every function of the BitMEX.com platform is exposed here and documented. Many more functions are available. ##### Swagger Specification [⇩ Download Swagger JSON](swagger.json) ## All API Endpoints Click to expand a section. 5 | * 6 | * OpenAPI spec version: 1.2.0 7 | * Contact: support@bitmex.com 8 | * Generated by: https://github.com/swagger-api/swagger-codegen.git 9 | */ 10 | 11 | package swagger 12 | 13 | import ( 14 | "time" 15 | ) 16 | 17 | type IndexComposite struct { 18 | Timestamp time.Time `json:"timestamp"` 19 | 20 | Symbol string `json:"symbol,omitempty"` 21 | 22 | IndexSymbol string `json:"indexSymbol,omitempty"` 23 | 24 | Reference string `json:"reference,omitempty"` 25 | 26 | LastPrice float64 `json:"lastPrice,omitempty"` 27 | 28 | Weight float64 `json:"weight,omitempty"` 29 | 30 | Logged time.Time `json:"logged,omitempty"` 31 | } 32 | -------------------------------------------------------------------------------- /swagger/inline_response_200.go: -------------------------------------------------------------------------------- 1 | /* 2 | * BitMEX API 3 | * 4 | * ## REST API for the BitMEX Trading Platform [View Changelog](/app/apiChangelog) #### Getting Started ##### Fetching Data All REST endpoints are documented below. You can try out any query right from this interface. Most table queries accept `count`, `start`, and `reverse` params. Set `reverse=true` to get rows newest-first. Additional documentation regarding filters, timestamps, and authentication is available in [the main API documentation](https://www.bitmex.com/app/restAPI). *All* table data is available via the [Websocket](/app/wsAPI). We highly recommend using the socket if you want to have the quickest possible data without being subject to ratelimits. ##### Return Types By default, all data is returned as JSON. Send `?_format=csv` to get CSV data or `?_format=xml` to get XML data. ##### Trade Data Queries *This is only a small subset of what is available, to get you started.* Fill in the parameters and click the `Try it out!` button to try any of these queries. * [Pricing Data](#!/Quote/Quote_get) * [Trade Data](#!/Trade/Trade_get) * [OrderBook Data](#!/OrderBook/OrderBook_getL2) * [Settlement Data](#!/Settlement/Settlement_get) * [Exchange Statistics](#!/Stats/Stats_history) Every function of the BitMEX.com platform is exposed here and documented. Many more functions are available. ##### Swagger Specification [⇩ Download Swagger JSON](swagger.json) ## All API Endpoints Click to expand a section. 5 | * 6 | * OpenAPI spec version: 1.2.0 7 | * Contact: support@bitmex.com 8 | * Generated by: https://github.com/swagger-api/swagger-codegen.git 9 | */ 10 | 11 | package swagger 12 | 13 | type InlineResponse200 struct { 14 | Success bool `json:"success,omitempty"` 15 | } 16 | -------------------------------------------------------------------------------- /swagger/instrument.go: -------------------------------------------------------------------------------- 1 | /* 2 | * BitMEX API 3 | * 4 | * ## REST API for the BitMEX Trading Platform [View Changelog](/app/apiChangelog) #### Getting Started ##### Fetching Data All REST endpoints are documented below. You can try out any query right from this interface. Most table queries accept `count`, `start`, and `reverse` params. Set `reverse=true` to get rows newest-first. Additional documentation regarding filters, timestamps, and authentication is available in [the main API documentation](https://www.bitmex.com/app/restAPI). *All* table data is available via the [Websocket](/app/wsAPI). We highly recommend using the socket if you want to have the quickest possible data without being subject to ratelimits. ##### Return Types By default, all data is returned as JSON. Send `?_format=csv` to get CSV data or `?_format=xml` to get XML data. ##### Trade Data Queries *This is only a small subset of what is available, to get you started.* Fill in the parameters and click the `Try it out!` button to try any of these queries. * [Pricing Data](#!/Quote/Quote_get) * [Trade Data](#!/Trade/Trade_get) * [OrderBook Data](#!/OrderBook/OrderBook_getL2) * [Settlement Data](#!/Settlement/Settlement_get) * [Exchange Statistics](#!/Stats/Stats_history) Every function of the BitMEX.com platform is exposed here and documented. Many more functions are available. ##### Swagger Specification [⇩ Download Swagger JSON](swagger.json) ## All API Endpoints Click to expand a section. 5 | * 6 | * OpenAPI spec version: 1.2.0 7 | * Contact: support@bitmex.com 8 | * Generated by: https://github.com/swagger-api/swagger-codegen.git 9 | */ 10 | 11 | package swagger 12 | 13 | import ( 14 | "time" 15 | ) 16 | 17 | // Tradeable Contracts, Indices, and History 18 | type Instrument struct { 19 | Symbol string `json:"symbol"` 20 | 21 | RootSymbol string `json:"rootSymbol,omitempty"` 22 | 23 | State string `json:"state,omitempty"` 24 | 25 | Typ string `json:"typ,omitempty"` 26 | 27 | Listing time.Time `json:"listing,omitempty"` 28 | 29 | Front time.Time `json:"front,omitempty"` 30 | 31 | Expiry time.Time `json:"expiry,omitempty"` 32 | 33 | Settle time.Time `json:"settle,omitempty"` 34 | 35 | RelistInterval time.Time `json:"relistInterval,omitempty"` 36 | 37 | InverseLeg string `json:"inverseLeg,omitempty"` 38 | 39 | SellLeg string `json:"sellLeg,omitempty"` 40 | 41 | BuyLeg string `json:"buyLeg,omitempty"` 42 | 43 | PositionCurrency string `json:"positionCurrency,omitempty"` 44 | 45 | Underlying string `json:"underlying,omitempty"` 46 | 47 | QuoteCurrency string `json:"quoteCurrency,omitempty"` 48 | 49 | UnderlyingSymbol string `json:"underlyingSymbol,omitempty"` 50 | 51 | Reference string `json:"reference,omitempty"` 52 | 53 | ReferenceSymbol string `json:"referenceSymbol,omitempty"` 54 | 55 | CalcInterval time.Time `json:"calcInterval,omitempty"` 56 | 57 | PublishInterval time.Time `json:"publishInterval,omitempty"` 58 | 59 | PublishTime time.Time `json:"publishTime,omitempty"` 60 | 61 | MaxOrderQty float32 `json:"maxOrderQty,omitempty"` 62 | 63 | MaxPrice float64 `json:"maxPrice,omitempty"` 64 | 65 | LotSize float32 `json:"lotSize,omitempty"` 66 | 67 | TickSize float64 `json:"tickSize,omitempty"` 68 | 69 | Multiplier float32 `json:"multiplier,omitempty"` 70 | 71 | SettlCurrency string `json:"settlCurrency,omitempty"` 72 | 73 | UnderlyingToPositionMultiplier float32 `json:"underlyingToPositionMultiplier,omitempty"` 74 | 75 | UnderlyingToSettleMultiplier float32 `json:"underlyingToSettleMultiplier,omitempty"` 76 | 77 | QuoteToSettleMultiplier float32 `json:"quoteToSettleMultiplier,omitempty"` 78 | 79 | IsQuanto bool `json:"isQuanto,omitempty"` 80 | 81 | IsInverse bool `json:"isInverse,omitempty"` 82 | 83 | InitMargin float64 `json:"initMargin,omitempty"` 84 | 85 | MaintMargin float64 `json:"maintMargin,omitempty"` 86 | 87 | RiskLimit float32 `json:"riskLimit,omitempty"` 88 | 89 | RiskStep float32 `json:"riskStep,omitempty"` 90 | 91 | Limit float64 `json:"limit,omitempty"` 92 | 93 | Capped bool `json:"capped,omitempty"` 94 | 95 | Taxed bool `json:"taxed,omitempty"` 96 | 97 | Deleverage bool `json:"deleverage,omitempty"` 98 | 99 | MakerFee float64 `json:"makerFee,omitempty"` 100 | 101 | TakerFee float64 `json:"takerFee,omitempty"` 102 | 103 | SettlementFee float64 `json:"settlementFee,omitempty"` 104 | 105 | InsuranceFee float64 `json:"insuranceFee,omitempty"` 106 | 107 | FundingBaseSymbol string `json:"fundingBaseSymbol,omitempty"` 108 | 109 | FundingQuoteSymbol string `json:"fundingQuoteSymbol,omitempty"` 110 | 111 | FundingPremiumSymbol string `json:"fundingPremiumSymbol,omitempty"` 112 | 113 | FundingTimestamp time.Time `json:"fundingTimestamp,omitempty"` 114 | 115 | FundingInterval time.Time `json:"fundingInterval,omitempty"` 116 | 117 | FundingRate float64 `json:"fundingRate,omitempty"` 118 | 119 | IndicativeFundingRate float64 `json:"indicativeFundingRate,omitempty"` 120 | 121 | RebalanceTimestamp time.Time `json:"rebalanceTimestamp,omitempty"` 122 | 123 | RebalanceInterval time.Time `json:"rebalanceInterval,omitempty"` 124 | 125 | OpeningTimestamp time.Time `json:"openingTimestamp,omitempty"` 126 | 127 | ClosingTimestamp time.Time `json:"closingTimestamp,omitempty"` 128 | 129 | SessionInterval time.Time `json:"sessionInterval,omitempty"` 130 | 131 | PrevClosePrice float64 `json:"prevClosePrice,omitempty"` 132 | 133 | LimitDownPrice float64 `json:"limitDownPrice,omitempty"` 134 | 135 | LimitUpPrice float64 `json:"limitUpPrice,omitempty"` 136 | 137 | BankruptLimitDownPrice float64 `json:"bankruptLimitDownPrice,omitempty"` 138 | 139 | BankruptLimitUpPrice float64 `json:"bankruptLimitUpPrice,omitempty"` 140 | 141 | PrevTotalVolume float32 `json:"prevTotalVolume,omitempty"` 142 | 143 | TotalVolume float32 `json:"totalVolume,omitempty"` 144 | 145 | Volume float32 `json:"volume,omitempty"` 146 | 147 | Volume24h float32 `json:"volume24h,omitempty"` 148 | 149 | PrevTotalTurnover float32 `json:"prevTotalTurnover,omitempty"` 150 | 151 | TotalTurnover float32 `json:"totalTurnover,omitempty"` 152 | 153 | Turnover float32 `json:"turnover,omitempty"` 154 | 155 | Turnover24h float32 `json:"turnover24h,omitempty"` 156 | 157 | PrevPrice24h float64 `json:"prevPrice24h,omitempty"` 158 | 159 | Vwap float64 `json:"vwap,omitempty"` 160 | 161 | HighPrice float64 `json:"highPrice,omitempty"` 162 | 163 | LowPrice float64 `json:"lowPrice,omitempty"` 164 | 165 | LastPrice float64 `json:"lastPrice,omitempty"` 166 | 167 | LastPriceProtected float64 `json:"lastPriceProtected,omitempty"` 168 | 169 | LastTickDirection string `json:"lastTickDirection,omitempty"` 170 | 171 | LastChangePcnt float64 `json:"lastChangePcnt,omitempty"` 172 | 173 | BidPrice float64 `json:"bidPrice,omitempty"` 174 | 175 | MidPrice float64 `json:"midPrice,omitempty"` 176 | 177 | AskPrice float64 `json:"askPrice,omitempty"` 178 | 179 | ImpactBidPrice float64 `json:"impactBidPrice,omitempty"` 180 | 181 | ImpactMidPrice float64 `json:"impactMidPrice,omitempty"` 182 | 183 | ImpactAskPrice float64 `json:"impactAskPrice,omitempty"` 184 | 185 | HasLiquidity bool `json:"hasLiquidity,omitempty"` 186 | 187 | OpenInterest float32 `json:"openInterest,omitempty"` 188 | 189 | OpenValue float32 `json:"openValue,omitempty"` 190 | 191 | FairMethod string `json:"fairMethod,omitempty"` 192 | 193 | FairBasisRate float64 `json:"fairBasisRate,omitempty"` 194 | 195 | FairBasis float64 `json:"fairBasis,omitempty"` 196 | 197 | FairPrice float64 `json:"fairPrice,omitempty"` 198 | 199 | MarkMethod string `json:"markMethod,omitempty"` 200 | 201 | MarkPrice float64 `json:"markPrice,omitempty"` 202 | 203 | IndicativeTaxRate float64 `json:"indicativeTaxRate,omitempty"` 204 | 205 | IndicativeSettlePrice float64 `json:"indicativeSettlePrice,omitempty"` 206 | 207 | SettledPrice float64 `json:"settledPrice,omitempty"` 208 | 209 | Timestamp time.Time `json:"timestamp,omitempty"` 210 | } 211 | -------------------------------------------------------------------------------- /swagger/instrument_interval.go: -------------------------------------------------------------------------------- 1 | /* 2 | * BitMEX API 3 | * 4 | * ## REST API for the BitMEX Trading Platform [View Changelog](/app/apiChangelog) #### Getting Started ##### Fetching Data All REST endpoints are documented below. You can try out any query right from this interface. Most table queries accept `count`, `start`, and `reverse` params. Set `reverse=true` to get rows newest-first. Additional documentation regarding filters, timestamps, and authentication is available in [the main API documentation](https://www.bitmex.com/app/restAPI). *All* table data is available via the [Websocket](/app/wsAPI). We highly recommend using the socket if you want to have the quickest possible data without being subject to ratelimits. ##### Return Types By default, all data is returned as JSON. Send `?_format=csv` to get CSV data or `?_format=xml` to get XML data. ##### Trade Data Queries *This is only a small subset of what is available, to get you started.* Fill in the parameters and click the `Try it out!` button to try any of these queries. * [Pricing Data](#!/Quote/Quote_get) * [Trade Data](#!/Trade/Trade_get) * [OrderBook Data](#!/OrderBook/OrderBook_getL2) * [Settlement Data](#!/Settlement/Settlement_get) * [Exchange Statistics](#!/Stats/Stats_history) Every function of the BitMEX.com platform is exposed here and documented. Many more functions are available. ##### Swagger Specification [⇩ Download Swagger JSON](swagger.json) ## All API Endpoints Click to expand a section. 5 | * 6 | * OpenAPI spec version: 1.2.0 7 | * Contact: support@bitmex.com 8 | * Generated by: https://github.com/swagger-api/swagger-codegen.git 9 | */ 10 | 11 | package swagger 12 | 13 | type InstrumentInterval struct { 14 | Intervals []string `json:"intervals"` 15 | 16 | Symbols []string `json:"symbols"` 17 | } 18 | -------------------------------------------------------------------------------- /swagger/insurance.go: -------------------------------------------------------------------------------- 1 | /* 2 | * BitMEX API 3 | * 4 | * ## REST API for the BitMEX Trading Platform [View Changelog](/app/apiChangelog) #### Getting Started ##### Fetching Data All REST endpoints are documented below. You can try out any query right from this interface. Most table queries accept `count`, `start`, and `reverse` params. Set `reverse=true` to get rows newest-first. Additional documentation regarding filters, timestamps, and authentication is available in [the main API documentation](https://www.bitmex.com/app/restAPI). *All* table data is available via the [Websocket](/app/wsAPI). We highly recommend using the socket if you want to have the quickest possible data without being subject to ratelimits. ##### Return Types By default, all data is returned as JSON. Send `?_format=csv` to get CSV data or `?_format=xml` to get XML data. ##### Trade Data Queries *This is only a small subset of what is available, to get you started.* Fill in the parameters and click the `Try it out!` button to try any of these queries. * [Pricing Data](#!/Quote/Quote_get) * [Trade Data](#!/Trade/Trade_get) * [OrderBook Data](#!/OrderBook/OrderBook_getL2) * [Settlement Data](#!/Settlement/Settlement_get) * [Exchange Statistics](#!/Stats/Stats_history) Every function of the BitMEX.com platform is exposed here and documented. Many more functions are available. ##### Swagger Specification [⇩ Download Swagger JSON](swagger.json) ## All API Endpoints Click to expand a section. 5 | * 6 | * OpenAPI spec version: 1.2.0 7 | * Contact: support@bitmex.com 8 | * Generated by: https://github.com/swagger-api/swagger-codegen.git 9 | */ 10 | 11 | package swagger 12 | 13 | import ( 14 | "time" 15 | ) 16 | 17 | // Insurance Fund Data 18 | type Insurance struct { 19 | Currency string `json:"currency"` 20 | 21 | Timestamp time.Time `json:"timestamp"` 22 | 23 | WalletBalance float32 `json:"walletBalance,omitempty"` 24 | } 25 | -------------------------------------------------------------------------------- /swagger/insurance_api.go: -------------------------------------------------------------------------------- 1 | /* 2 | * BitMEX API 3 | * 4 | * ## REST API for the BitMEX Trading Platform [View Changelog](/app/apiChangelog) #### Getting Started ##### Fetching Data All REST endpoints are documented below. You can try out any query right from this interface. Most table queries accept `count`, `start`, and `reverse` params. Set `reverse=true` to get rows newest-first. Additional documentation regarding filters, timestamps, and authentication is available in [the main API documentation](https://www.bitmex.com/app/restAPI). *All* table data is available via the [Websocket](/app/wsAPI). We highly recommend using the socket if you want to have the quickest possible data without being subject to ratelimits. ##### Return Types By default, all data is returned as JSON. Send `?_format=csv` to get CSV data or `?_format=xml` to get XML data. ##### Trade Data Queries *This is only a small subset of what is available, to get you started.* Fill in the parameters and click the `Try it out!` button to try any of these queries. * [Pricing Data](#!/Quote/Quote_get) * [Trade Data](#!/Trade/Trade_get) * [OrderBook Data](#!/OrderBook/OrderBook_getL2) * [Settlement Data](#!/Settlement/Settlement_get) * [Exchange Statistics](#!/Stats/Stats_history) Every function of the BitMEX.com platform is exposed here and documented. Many more functions are available. ##### Swagger Specification [⇩ Download Swagger JSON](swagger.json) ## All API Endpoints Click to expand a section. 5 | * 6 | * OpenAPI spec version: 1.2.0 7 | * Contact: support@bitmex.com 8 | * Generated by: https://github.com/swagger-api/swagger-codegen.git 9 | */ 10 | 11 | package swagger 12 | 13 | import ( 14 | "encoding/json" 15 | "golang.org/x/net/context" 16 | "net/http" 17 | "net/url" 18 | "strings" 19 | "time" 20 | ) 21 | 22 | // Linger please 23 | var ( 24 | _ context.Context 25 | ) 26 | 27 | type InsuranceApiService service 28 | 29 | /* InsuranceApiService Get insurance fund history. 30 | 31 | @param optional (nil or map[string]interface{}) with one or more of: 32 | @param "symbol" (string) Instrument symbol. Send a bare series (e.g. XBU) to get data for the nearest expiring contract in that series. You can also send a timeframe, e.g. `XBU:monthly`. Timeframes are `daily`, `weekly`, `monthly`, `quarterly`, and `biquarterly`. 33 | @param "filter" (string) Generic table filter. Send JSON key/value pairs, such as `{\"key\": \"value\"}`. You can key on individual fields, and do more advanced querying on timestamps. See the [Timestamp Docs](https://www.bitmex.com/app/restAPI#timestamp-filters) for more details. 34 | @param "columns" (string) Array of column names to fetch. If omitted, will return all columns. Note that this method will always return item keys, even when not specified, so you may receive more columns that you expect. 35 | @param "count" (float32) Number of results to fetch. 36 | @param "start" (float32) Starting point for results. 37 | @param "reverse" (bool) If true, will sort results newest first. 38 | @param "startTime" (time.Time) Starting date filter for results. 39 | @param "endTime" (time.Time) Ending date filter for results. 40 | @return []Insurance*/ 41 | func (a *InsuranceApiService) InsuranceGet(localVarOptionals map[string]interface{}) ([]Insurance, *http.Response, error) { 42 | var ( 43 | localVarHttpMethod = strings.ToUpper("Get") 44 | localVarPostBody interface{} 45 | localVarFileName string 46 | localVarFileBytes []byte 47 | successPayload []Insurance 48 | ) 49 | 50 | // create path and map variables 51 | localVarPath := a.client.cfg.BasePath + "/insurance" 52 | 53 | localVarHeaderParams := make(map[string]string) 54 | localVarQueryParams := url.Values{} 55 | localVarFormParams := url.Values{} 56 | 57 | if err := typeCheckParameter(localVarOptionals["symbol"], "string", "symbol"); err != nil { 58 | return successPayload, nil, err 59 | } 60 | if err := typeCheckParameter(localVarOptionals["filter"], "string", "filter"); err != nil { 61 | return successPayload, nil, err 62 | } 63 | if err := typeCheckParameter(localVarOptionals["columns"], "string", "columns"); err != nil { 64 | return successPayload, nil, err 65 | } 66 | if err := typeCheckParameter(localVarOptionals["count"], "float32", "count"); err != nil { 67 | return successPayload, nil, err 68 | } 69 | if err := typeCheckParameter(localVarOptionals["start"], "float32", "start"); err != nil { 70 | return successPayload, nil, err 71 | } 72 | if err := typeCheckParameter(localVarOptionals["reverse"], "bool", "reverse"); err != nil { 73 | return successPayload, nil, err 74 | } 75 | if err := typeCheckParameter(localVarOptionals["startTime"], "time.Time", "startTime"); err != nil { 76 | return successPayload, nil, err 77 | } 78 | if err := typeCheckParameter(localVarOptionals["endTime"], "time.Time", "endTime"); err != nil { 79 | return successPayload, nil, err 80 | } 81 | 82 | if localVarTempParam, localVarOk := localVarOptionals["symbol"].(string); localVarOk { 83 | localVarQueryParams.Add("symbol", parameterToString(localVarTempParam, "")) 84 | } 85 | if localVarTempParam, localVarOk := localVarOptionals["filter"].(string); localVarOk { 86 | localVarQueryParams.Add("filter", parameterToString(localVarTempParam, "")) 87 | } 88 | if localVarTempParam, localVarOk := localVarOptionals["columns"].(string); localVarOk { 89 | localVarQueryParams.Add("columns", parameterToString(localVarTempParam, "")) 90 | } 91 | if localVarTempParam, localVarOk := localVarOptionals["count"].(float32); localVarOk { 92 | localVarQueryParams.Add("count", parameterToString(localVarTempParam, "")) 93 | } 94 | if localVarTempParam, localVarOk := localVarOptionals["start"].(float32); localVarOk { 95 | localVarQueryParams.Add("start", parameterToString(localVarTempParam, "")) 96 | } 97 | if localVarTempParam, localVarOk := localVarOptionals["reverse"].(bool); localVarOk { 98 | localVarQueryParams.Add("reverse", parameterToString(localVarTempParam, "")) 99 | } 100 | if localVarTempParam, localVarOk := localVarOptionals["startTime"].(time.Time); localVarOk { 101 | localVarQueryParams.Add("startTime", parameterToString(localVarTempParam, "")) 102 | } 103 | if localVarTempParam, localVarOk := localVarOptionals["endTime"].(time.Time); localVarOk { 104 | localVarQueryParams.Add("endTime", parameterToString(localVarTempParam, "")) 105 | } 106 | // to determine the Content-Type header 107 | localVarHttpContentTypes := []string{"application/json", "application/x-www-form-urlencoded"} 108 | 109 | // set Content-Type header 110 | localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) 111 | if localVarHttpContentType != "" { 112 | localVarHeaderParams["Content-Type"] = localVarHttpContentType 113 | } 114 | 115 | // to determine the Accept header 116 | localVarHttpHeaderAccepts := []string{ 117 | "application/json", 118 | "application/xml", 119 | "text/xml", 120 | "application/javascript", 121 | "text/javascript", 122 | } 123 | 124 | // set Accept header 125 | localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) 126 | if localVarHttpHeaderAccept != "" { 127 | localVarHeaderParams["Accept"] = localVarHttpHeaderAccept 128 | } 129 | r, err := a.client.prepareRequest(nil, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) 130 | if err != nil { 131 | return successPayload, nil, err 132 | } 133 | 134 | localVarHttpResponse, err := a.client.callAPI(r) 135 | if err != nil || localVarHttpResponse == nil { 136 | return successPayload, localVarHttpResponse, err 137 | } 138 | defer localVarHttpResponse.Body.Close() 139 | if localVarHttpResponse.StatusCode >= 300 { 140 | return successPayload, localVarHttpResponse, reportError(localVarHttpResponse.Status) 141 | } 142 | 143 | if err = json.NewDecoder(localVarHttpResponse.Body).Decode(&successPayload); err != nil { 144 | return successPayload, localVarHttpResponse, err 145 | } 146 | 147 | return successPayload, localVarHttpResponse, err 148 | } 149 | -------------------------------------------------------------------------------- /swagger/leaderboard.go: -------------------------------------------------------------------------------- 1 | /* 2 | * BitMEX API 3 | * 4 | * ## REST API for the BitMEX Trading Platform [View Changelog](/app/apiChangelog) #### Getting Started ##### Fetching Data All REST endpoints are documented below. You can try out any query right from this interface. Most table queries accept `count`, `start`, and `reverse` params. Set `reverse=true` to get rows newest-first. Additional documentation regarding filters, timestamps, and authentication is available in [the main API documentation](https://www.bitmex.com/app/restAPI). *All* table data is available via the [Websocket](/app/wsAPI). We highly recommend using the socket if you want to have the quickest possible data without being subject to ratelimits. ##### Return Types By default, all data is returned as JSON. Send `?_format=csv` to get CSV data or `?_format=xml` to get XML data. ##### Trade Data Queries *This is only a small subset of what is available, to get you started.* Fill in the parameters and click the `Try it out!` button to try any of these queries. * [Pricing Data](#!/Quote/Quote_get) * [Trade Data](#!/Trade/Trade_get) * [OrderBook Data](#!/OrderBook/OrderBook_getL2) * [Settlement Data](#!/Settlement/Settlement_get) * [Exchange Statistics](#!/Stats/Stats_history) Every function of the BitMEX.com platform is exposed here and documented. Many more functions are available. ##### Swagger Specification [⇩ Download Swagger JSON](swagger.json) ## All API Endpoints Click to expand a section. 5 | * 6 | * OpenAPI spec version: 1.2.0 7 | * Contact: support@bitmex.com 8 | * Generated by: https://github.com/swagger-api/swagger-codegen.git 9 | */ 10 | 11 | package swagger 12 | 13 | // Information on Top Users 14 | type Leaderboard struct { 15 | Name string `json:"name"` 16 | 17 | IsRealName bool `json:"isRealName,omitempty"` 18 | 19 | IsMe bool `json:"isMe,omitempty"` 20 | 21 | Profit float64 `json:"profit,omitempty"` 22 | } 23 | -------------------------------------------------------------------------------- /swagger/leaderboard_api.go: -------------------------------------------------------------------------------- 1 | /* 2 | * BitMEX API 3 | * 4 | * ## REST API for the BitMEX Trading Platform [View Changelog](/app/apiChangelog) #### Getting Started ##### Fetching Data All REST endpoints are documented below. You can try out any query right from this interface. Most table queries accept `count`, `start`, and `reverse` params. Set `reverse=true` to get rows newest-first. Additional documentation regarding filters, timestamps, and authentication is available in [the main API documentation](https://www.bitmex.com/app/restAPI). *All* table data is available via the [Websocket](/app/wsAPI). We highly recommend using the socket if you want to have the quickest possible data without being subject to ratelimits. ##### Return Types By default, all data is returned as JSON. Send `?_format=csv` to get CSV data or `?_format=xml` to get XML data. ##### Trade Data Queries *This is only a small subset of what is available, to get you started.* Fill in the parameters and click the `Try it out!` button to try any of these queries. * [Pricing Data](#!/Quote/Quote_get) * [Trade Data](#!/Trade/Trade_get) * [OrderBook Data](#!/OrderBook/OrderBook_getL2) * [Settlement Data](#!/Settlement/Settlement_get) * [Exchange Statistics](#!/Stats/Stats_history) Every function of the BitMEX.com platform is exposed here and documented. Many more functions are available. ##### Swagger Specification [⇩ Download Swagger JSON](swagger.json) ## All API Endpoints Click to expand a section. 5 | * 6 | * OpenAPI spec version: 1.2.0 7 | * Contact: support@bitmex.com 8 | * Generated by: https://github.com/swagger-api/swagger-codegen.git 9 | */ 10 | 11 | package swagger 12 | 13 | import ( 14 | "encoding/json" 15 | "golang.org/x/net/context" 16 | "net/http" 17 | "net/url" 18 | "strings" 19 | ) 20 | 21 | // Linger please 22 | var ( 23 | _ context.Context 24 | ) 25 | 26 | type LeaderboardApiService service 27 | 28 | /* LeaderboardApiService Get current leaderboard. 29 | 30 | @param optional (nil or map[string]interface{}) with one or more of: 31 | @param "method" (string) Ranking type. Options: \"notional\", \"ROE\" 32 | @return []Leaderboard*/ 33 | func (a *LeaderboardApiService) LeaderboardGet(localVarOptionals map[string]interface{}) ([]Leaderboard, *http.Response, error) { 34 | var ( 35 | localVarHttpMethod = strings.ToUpper("Get") 36 | localVarPostBody interface{} 37 | localVarFileName string 38 | localVarFileBytes []byte 39 | successPayload []Leaderboard 40 | ) 41 | 42 | // create path and map variables 43 | localVarPath := a.client.cfg.BasePath + "/leaderboard" 44 | 45 | localVarHeaderParams := make(map[string]string) 46 | localVarQueryParams := url.Values{} 47 | localVarFormParams := url.Values{} 48 | 49 | if err := typeCheckParameter(localVarOptionals["method"], "string", "method"); err != nil { 50 | return successPayload, nil, err 51 | } 52 | 53 | if localVarTempParam, localVarOk := localVarOptionals["method"].(string); localVarOk { 54 | localVarQueryParams.Add("method", parameterToString(localVarTempParam, "")) 55 | } 56 | // to determine the Content-Type header 57 | localVarHttpContentTypes := []string{"application/json", "application/x-www-form-urlencoded"} 58 | 59 | // set Content-Type header 60 | localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) 61 | if localVarHttpContentType != "" { 62 | localVarHeaderParams["Content-Type"] = localVarHttpContentType 63 | } 64 | 65 | // to determine the Accept header 66 | localVarHttpHeaderAccepts := []string{ 67 | "application/json", 68 | "application/xml", 69 | "text/xml", 70 | "application/javascript", 71 | "text/javascript", 72 | } 73 | 74 | // set Accept header 75 | localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) 76 | if localVarHttpHeaderAccept != "" { 77 | localVarHeaderParams["Accept"] = localVarHttpHeaderAccept 78 | } 79 | r, err := a.client.prepareRequest(nil, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) 80 | if err != nil { 81 | return successPayload, nil, err 82 | } 83 | 84 | localVarHttpResponse, err := a.client.callAPI(r) 85 | if err != nil || localVarHttpResponse == nil { 86 | return successPayload, localVarHttpResponse, err 87 | } 88 | defer localVarHttpResponse.Body.Close() 89 | if localVarHttpResponse.StatusCode >= 300 { 90 | return successPayload, localVarHttpResponse, reportError(localVarHttpResponse.Status) 91 | } 92 | 93 | if err = json.NewDecoder(localVarHttpResponse.Body).Decode(&successPayload); err != nil { 94 | return successPayload, localVarHttpResponse, err 95 | } 96 | 97 | return successPayload, localVarHttpResponse, err 98 | } 99 | -------------------------------------------------------------------------------- /swagger/liquidation.go: -------------------------------------------------------------------------------- 1 | /* 2 | * BitMEX API 3 | * 4 | * ## REST API for the BitMEX Trading Platform [View Changelog](/app/apiChangelog) #### Getting Started ##### Fetching Data All REST endpoints are documented below. You can try out any query right from this interface. Most table queries accept `count`, `start`, and `reverse` params. Set `reverse=true` to get rows newest-first. Additional documentation regarding filters, timestamps, and authentication is available in [the main API documentation](https://www.bitmex.com/app/restAPI). *All* table data is available via the [Websocket](/app/wsAPI). We highly recommend using the socket if you want to have the quickest possible data without being subject to ratelimits. ##### Return Types By default, all data is returned as JSON. Send `?_format=csv` to get CSV data or `?_format=xml` to get XML data. ##### Trade Data Queries *This is only a small subset of what is available, to get you started.* Fill in the parameters and click the `Try it out!` button to try any of these queries. * [Pricing Data](#!/Quote/Quote_get) * [Trade Data](#!/Trade/Trade_get) * [OrderBook Data](#!/OrderBook/OrderBook_getL2) * [Settlement Data](#!/Settlement/Settlement_get) * [Exchange Statistics](#!/Stats/Stats_history) Every function of the BitMEX.com platform is exposed here and documented. Many more functions are available. ##### Swagger Specification [⇩ Download Swagger JSON](swagger.json) ## All API Endpoints Click to expand a section. 5 | * 6 | * OpenAPI spec version: 1.2.0 7 | * Contact: support@bitmex.com 8 | * Generated by: https://github.com/swagger-api/swagger-codegen.git 9 | */ 10 | 11 | package swagger 12 | 13 | // Active Liquidations 14 | type Liquidation struct { 15 | OrderID string `json:"orderID"` 16 | 17 | Symbol string `json:"symbol,omitempty"` 18 | 19 | Side string `json:"side,omitempty"` 20 | 21 | Price float64 `json:"price,omitempty"` 22 | 23 | LeavesQty float32 `json:"leavesQty,omitempty"` 24 | } 25 | -------------------------------------------------------------------------------- /swagger/liquidation_api.go: -------------------------------------------------------------------------------- 1 | /* 2 | * BitMEX API 3 | * 4 | * ## REST API for the BitMEX Trading Platform [View Changelog](/app/apiChangelog) #### Getting Started ##### Fetching Data All REST endpoints are documented below. You can try out any query right from this interface. Most table queries accept `count`, `start`, and `reverse` params. Set `reverse=true` to get rows newest-first. Additional documentation regarding filters, timestamps, and authentication is available in [the main API documentation](https://www.bitmex.com/app/restAPI). *All* table data is available via the [Websocket](/app/wsAPI). We highly recommend using the socket if you want to have the quickest possible data without being subject to ratelimits. ##### Return Types By default, all data is returned as JSON. Send `?_format=csv` to get CSV data or `?_format=xml` to get XML data. ##### Trade Data Queries *This is only a small subset of what is available, to get you started.* Fill in the parameters and click the `Try it out!` button to try any of these queries. * [Pricing Data](#!/Quote/Quote_get) * [Trade Data](#!/Trade/Trade_get) * [OrderBook Data](#!/OrderBook/OrderBook_getL2) * [Settlement Data](#!/Settlement/Settlement_get) * [Exchange Statistics](#!/Stats/Stats_history) Every function of the BitMEX.com platform is exposed here and documented. Many more functions are available. ##### Swagger Specification [⇩ Download Swagger JSON](swagger.json) ## All API Endpoints Click to expand a section. 5 | * 6 | * OpenAPI spec version: 1.2.0 7 | * Contact: support@bitmex.com 8 | * Generated by: https://github.com/swagger-api/swagger-codegen.git 9 | */ 10 | 11 | package swagger 12 | 13 | import ( 14 | "encoding/json" 15 | "golang.org/x/net/context" 16 | "net/http" 17 | "net/url" 18 | "strings" 19 | "time" 20 | ) 21 | 22 | // Linger please 23 | var ( 24 | _ context.Context 25 | ) 26 | 27 | type LiquidationApiService service 28 | 29 | /* LiquidationApiService Get liquidation orders. 30 | 31 | @param optional (nil or map[string]interface{}) with one or more of: 32 | @param "symbol" (string) Instrument symbol. Send a bare series (e.g. XBU) to get data for the nearest expiring contract in that series. You can also send a timeframe, e.g. `XBU:monthly`. Timeframes are `daily`, `weekly`, `monthly`, `quarterly`, and `biquarterly`. 33 | @param "filter" (string) Generic table filter. Send JSON key/value pairs, such as `{\"key\": \"value\"}`. You can key on individual fields, and do more advanced querying on timestamps. See the [Timestamp Docs](https://www.bitmex.com/app/restAPI#timestamp-filters) for more details. 34 | @param "columns" (string) Array of column names to fetch. If omitted, will return all columns. Note that this method will always return item keys, even when not specified, so you may receive more columns that you expect. 35 | @param "count" (float32) Number of results to fetch. 36 | @param "start" (float32) Starting point for results. 37 | @param "reverse" (bool) If true, will sort results newest first. 38 | @param "startTime" (time.Time) Starting date filter for results. 39 | @param "endTime" (time.Time) Ending date filter for results. 40 | @return []Liquidation*/ 41 | func (a *LiquidationApiService) LiquidationGet(localVarOptionals map[string]interface{}) ([]Liquidation, *http.Response, error) { 42 | var ( 43 | localVarHttpMethod = strings.ToUpper("Get") 44 | localVarPostBody interface{} 45 | localVarFileName string 46 | localVarFileBytes []byte 47 | successPayload []Liquidation 48 | ) 49 | 50 | // create path and map variables 51 | localVarPath := a.client.cfg.BasePath + "/liquidation" 52 | 53 | localVarHeaderParams := make(map[string]string) 54 | localVarQueryParams := url.Values{} 55 | localVarFormParams := url.Values{} 56 | 57 | if err := typeCheckParameter(localVarOptionals["symbol"], "string", "symbol"); err != nil { 58 | return successPayload, nil, err 59 | } 60 | if err := typeCheckParameter(localVarOptionals["filter"], "string", "filter"); err != nil { 61 | return successPayload, nil, err 62 | } 63 | if err := typeCheckParameter(localVarOptionals["columns"], "string", "columns"); err != nil { 64 | return successPayload, nil, err 65 | } 66 | if err := typeCheckParameter(localVarOptionals["count"], "float32", "count"); err != nil { 67 | return successPayload, nil, err 68 | } 69 | if err := typeCheckParameter(localVarOptionals["start"], "float32", "start"); err != nil { 70 | return successPayload, nil, err 71 | } 72 | if err := typeCheckParameter(localVarOptionals["reverse"], "bool", "reverse"); err != nil { 73 | return successPayload, nil, err 74 | } 75 | if err := typeCheckParameter(localVarOptionals["startTime"], "time.Time", "startTime"); err != nil { 76 | return successPayload, nil, err 77 | } 78 | if err := typeCheckParameter(localVarOptionals["endTime"], "time.Time", "endTime"); err != nil { 79 | return successPayload, nil, err 80 | } 81 | 82 | if localVarTempParam, localVarOk := localVarOptionals["symbol"].(string); localVarOk { 83 | localVarQueryParams.Add("symbol", parameterToString(localVarTempParam, "")) 84 | } 85 | if localVarTempParam, localVarOk := localVarOptionals["filter"].(string); localVarOk { 86 | localVarQueryParams.Add("filter", parameterToString(localVarTempParam, "")) 87 | } 88 | if localVarTempParam, localVarOk := localVarOptionals["columns"].(string); localVarOk { 89 | localVarQueryParams.Add("columns", parameterToString(localVarTempParam, "")) 90 | } 91 | if localVarTempParam, localVarOk := localVarOptionals["count"].(float32); localVarOk { 92 | localVarQueryParams.Add("count", parameterToString(localVarTempParam, "")) 93 | } 94 | if localVarTempParam, localVarOk := localVarOptionals["start"].(float32); localVarOk { 95 | localVarQueryParams.Add("start", parameterToString(localVarTempParam, "")) 96 | } 97 | if localVarTempParam, localVarOk := localVarOptionals["reverse"].(bool); localVarOk { 98 | localVarQueryParams.Add("reverse", parameterToString(localVarTempParam, "")) 99 | } 100 | if localVarTempParam, localVarOk := localVarOptionals["startTime"].(time.Time); localVarOk { 101 | localVarQueryParams.Add("startTime", parameterToString(localVarTempParam, "")) 102 | } 103 | if localVarTempParam, localVarOk := localVarOptionals["endTime"].(time.Time); localVarOk { 104 | localVarQueryParams.Add("endTime", parameterToString(localVarTempParam, "")) 105 | } 106 | // to determine the Content-Type header 107 | localVarHttpContentTypes := []string{"application/json", "application/x-www-form-urlencoded"} 108 | 109 | // set Content-Type header 110 | localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) 111 | if localVarHttpContentType != "" { 112 | localVarHeaderParams["Content-Type"] = localVarHttpContentType 113 | } 114 | 115 | // to determine the Accept header 116 | localVarHttpHeaderAccepts := []string{ 117 | "application/json", 118 | "application/xml", 119 | "text/xml", 120 | "application/javascript", 121 | "text/javascript", 122 | } 123 | 124 | // set Accept header 125 | localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) 126 | if localVarHttpHeaderAccept != "" { 127 | localVarHeaderParams["Accept"] = localVarHttpHeaderAccept 128 | } 129 | r, err := a.client.prepareRequest(nil, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) 130 | if err != nil { 131 | return successPayload, nil, err 132 | } 133 | 134 | localVarHttpResponse, err := a.client.callAPI(r) 135 | if err != nil || localVarHttpResponse == nil { 136 | return successPayload, localVarHttpResponse, err 137 | } 138 | defer localVarHttpResponse.Body.Close() 139 | if localVarHttpResponse.StatusCode >= 300 { 140 | return successPayload, localVarHttpResponse, reportError(localVarHttpResponse.Status) 141 | } 142 | 143 | if err = json.NewDecoder(localVarHttpResponse.Body).Decode(&successPayload); err != nil { 144 | return successPayload, localVarHttpResponse, err 145 | } 146 | 147 | return successPayload, localVarHttpResponse, err 148 | } 149 | -------------------------------------------------------------------------------- /swagger/margin.go: -------------------------------------------------------------------------------- 1 | /* 2 | * BitMEX API 3 | * 4 | * ## REST API for the BitMEX Trading Platform [View Changelog](/app/apiChangelog) #### Getting Started ##### Fetching Data All REST endpoints are documented below. You can try out any query right from this interface. Most table queries accept `count`, `start`, and `reverse` params. Set `reverse=true` to get rows newest-first. Additional documentation regarding filters, timestamps, and authentication is available in [the main API documentation](https://www.bitmex.com/app/restAPI). *All* table data is available via the [Websocket](/app/wsAPI). We highly recommend using the socket if you want to have the quickest possible data without being subject to ratelimits. ##### Return Types By default, all data is returned as JSON. Send `?_format=csv` to get CSV data or `?_format=xml` to get XML data. ##### Trade Data Queries *This is only a small subset of what is available, to get you started.* Fill in the parameters and click the `Try it out!` button to try any of these queries. * [Pricing Data](#!/Quote/Quote_get) * [Trade Data](#!/Trade/Trade_get) * [OrderBook Data](#!/OrderBook/OrderBook_getL2) * [Settlement Data](#!/Settlement/Settlement_get) * [Exchange Statistics](#!/Stats/Stats_history) Every function of the BitMEX.com platform is exposed here and documented. Many more functions are available. ##### Swagger Specification [⇩ Download Swagger JSON](swagger.json) ## All API Endpoints Click to expand a section. 5 | * 6 | * OpenAPI spec version: 1.2.0 7 | * Contact: support@bitmex.com 8 | * Generated by: https://github.com/swagger-api/swagger-codegen.git 9 | */ 10 | 11 | package swagger 12 | 13 | import ( 14 | "time" 15 | ) 16 | 17 | type Margin struct { 18 | Account float32 `json:"account"` 19 | 20 | Currency string `json:"currency"` 21 | 22 | RiskLimit float32 `json:"riskLimit,omitempty"` 23 | 24 | PrevState string `json:"prevState,omitempty"` 25 | 26 | State string `json:"state,omitempty"` 27 | 28 | Action string `json:"action,omitempty"` 29 | 30 | Amount float32 `json:"amount,omitempty"` 31 | 32 | PendingCredit float32 `json:"pendingCredit,omitempty"` 33 | 34 | PendingDebit float32 `json:"pendingDebit,omitempty"` 35 | 36 | ConfirmedDebit float32 `json:"confirmedDebit,omitempty"` 37 | 38 | PrevRealisedPnl float32 `json:"prevRealisedPnl,omitempty"` 39 | 40 | PrevUnrealisedPnl float32 `json:"prevUnrealisedPnl,omitempty"` 41 | 42 | GrossComm float32 `json:"grossComm,omitempty"` 43 | 44 | GrossOpenCost float32 `json:"grossOpenCost,omitempty"` 45 | 46 | GrossOpenPremium float32 `json:"grossOpenPremium,omitempty"` 47 | 48 | GrossExecCost float32 `json:"grossExecCost,omitempty"` 49 | 50 | GrossMarkValue float32 `json:"grossMarkValue,omitempty"` 51 | 52 | RiskValue float32 `json:"riskValue,omitempty"` 53 | 54 | TaxableMargin float32 `json:"taxableMargin,omitempty"` 55 | 56 | InitMargin float32 `json:"initMargin,omitempty"` 57 | 58 | MaintMargin float32 `json:"maintMargin,omitempty"` 59 | 60 | SessionMargin float32 `json:"sessionMargin,omitempty"` 61 | 62 | TargetExcessMargin float32 `json:"targetExcessMargin,omitempty"` 63 | 64 | VarMargin float32 `json:"varMargin,omitempty"` 65 | 66 | RealisedPnl float32 `json:"realisedPnl,omitempty"` 67 | 68 | UnrealisedPnl float32 `json:"unrealisedPnl,omitempty"` 69 | 70 | IndicativeTax float32 `json:"indicativeTax,omitempty"` 71 | 72 | UnrealisedProfit float32 `json:"unrealisedProfit,omitempty"` 73 | 74 | SyntheticMargin float32 `json:"syntheticMargin,omitempty"` 75 | 76 | WalletBalance float32 `json:"walletBalance,omitempty"` 77 | 78 | MarginBalance float32 `json:"marginBalance,omitempty"` 79 | 80 | MarginBalancePcnt float64 `json:"marginBalancePcnt,omitempty"` 81 | 82 | MarginLeverage float64 `json:"marginLeverage,omitempty"` 83 | 84 | MarginUsedPcnt float64 `json:"marginUsedPcnt,omitempty"` 85 | 86 | ExcessMargin float32 `json:"excessMargin,omitempty"` 87 | 88 | ExcessMarginPcnt float64 `json:"excessMarginPcnt,omitempty"` 89 | 90 | AvailableMargin float32 `json:"availableMargin,omitempty"` 91 | 92 | WithdrawableMargin float32 `json:"withdrawableMargin,omitempty"` 93 | 94 | Timestamp time.Time `json:"timestamp,omitempty"` 95 | 96 | GrossLastValue float32 `json:"grossLastValue,omitempty"` 97 | 98 | Commission float64 `json:"commission,omitempty"` 99 | } 100 | -------------------------------------------------------------------------------- /swagger/model_error.go: -------------------------------------------------------------------------------- 1 | /* 2 | * BitMEX API 3 | * 4 | * ## REST API for the BitMEX Trading Platform [View Changelog](/app/apiChangelog) #### Getting Started ##### Fetching Data All REST endpoints are documented below. You can try out any query right from this interface. Most table queries accept `count`, `start`, and `reverse` params. Set `reverse=true` to get rows newest-first. Additional documentation regarding filters, timestamps, and authentication is available in [the main API documentation](https://www.bitmex.com/app/restAPI). *All* table data is available via the [Websocket](/app/wsAPI). We highly recommend using the socket if you want to have the quickest possible data without being subject to ratelimits. ##### Return Types By default, all data is returned as JSON. Send `?_format=csv` to get CSV data or `?_format=xml` to get XML data. ##### Trade Data Queries *This is only a small subset of what is available, to get you started.* Fill in the parameters and click the `Try it out!` button to try any of these queries. * [Pricing Data](#!/Quote/Quote_get) * [Trade Data](#!/Trade/Trade_get) * [OrderBook Data](#!/OrderBook/OrderBook_getL2) * [Settlement Data](#!/Settlement/Settlement_get) * [Exchange Statistics](#!/Stats/Stats_history) Every function of the BitMEX.com platform is exposed here and documented. Many more functions are available. ##### Swagger Specification [⇩ Download Swagger JSON](swagger.json) ## All API Endpoints Click to expand a section. 5 | * 6 | * OpenAPI spec version: 1.2.0 7 | * Contact: support@bitmex.com 8 | * Generated by: https://github.com/swagger-api/swagger-codegen.git 9 | */ 10 | 11 | package swagger 12 | 13 | type ModelError struct { 14 | Error_ *ErrorError `json:"error,omitempty"` 15 | } 16 | -------------------------------------------------------------------------------- /swagger/notification.go: -------------------------------------------------------------------------------- 1 | /* 2 | * BitMEX API 3 | * 4 | * ## REST API for the BitMEX Trading Platform [View Changelog](/app/apiChangelog) #### Getting Started ##### Fetching Data All REST endpoints are documented below. You can try out any query right from this interface. Most table queries accept `count`, `start`, and `reverse` params. Set `reverse=true` to get rows newest-first. Additional documentation regarding filters, timestamps, and authentication is available in [the main API documentation](https://www.bitmex.com/app/restAPI). *All* table data is available via the [Websocket](/app/wsAPI). We highly recommend using the socket if you want to have the quickest possible data without being subject to ratelimits. ##### Return Types By default, all data is returned as JSON. Send `?_format=csv` to get CSV data or `?_format=xml` to get XML data. ##### Trade Data Queries *This is only a small subset of what is available, to get you started.* Fill in the parameters and click the `Try it out!` button to try any of these queries. * [Pricing Data](#!/Quote/Quote_get) * [Trade Data](#!/Trade/Trade_get) * [OrderBook Data](#!/OrderBook/OrderBook_getL2) * [Settlement Data](#!/Settlement/Settlement_get) * [Exchange Statistics](#!/Stats/Stats_history) Every function of the BitMEX.com platform is exposed here and documented. Many more functions are available. ##### Swagger Specification [⇩ Download Swagger JSON](swagger.json) ## All API Endpoints Click to expand a section. 5 | * 6 | * OpenAPI spec version: 1.2.0 7 | * Contact: support@bitmex.com 8 | * Generated by: https://github.com/swagger-api/swagger-codegen.git 9 | */ 10 | 11 | package swagger 12 | 13 | import ( 14 | "time" 15 | ) 16 | 17 | // Account Notifications 18 | type Notification struct { 19 | Id float32 `json:"id,omitempty"` 20 | 21 | Date time.Time `json:"date"` 22 | 23 | Title string `json:"title"` 24 | 25 | Body string `json:"body"` 26 | 27 | Ttl float32 `json:"ttl"` 28 | 29 | Type_ string `json:"type,omitempty"` 30 | 31 | Closable bool `json:"closable,omitempty"` 32 | 33 | Persist bool `json:"persist,omitempty"` 34 | 35 | WaitForVisibility bool `json:"waitForVisibility,omitempty"` 36 | 37 | Sound string `json:"sound,omitempty"` 38 | } 39 | -------------------------------------------------------------------------------- /swagger/notification_api.go: -------------------------------------------------------------------------------- 1 | /* 2 | * BitMEX API 3 | * 4 | * ## REST API for the BitMEX Trading Platform [View Changelog](/app/apiChangelog) #### Getting Started ##### Fetching Data All REST endpoints are documented below. You can try out any query right from this interface. Most table queries accept `count`, `start`, and `reverse` params. Set `reverse=true` to get rows newest-first. Additional documentation regarding filters, timestamps, and authentication is available in [the main API documentation](https://www.bitmex.com/app/restAPI). *All* table data is available via the [Websocket](/app/wsAPI). We highly recommend using the socket if you want to have the quickest possible data without being subject to ratelimits. ##### Return Types By default, all data is returned as JSON. Send `?_format=csv` to get CSV data or `?_format=xml` to get XML data. ##### Trade Data Queries *This is only a small subset of what is available, to get you started.* Fill in the parameters and click the `Try it out!` button to try any of these queries. * [Pricing Data](#!/Quote/Quote_get) * [Trade Data](#!/Trade/Trade_get) * [OrderBook Data](#!/OrderBook/OrderBook_getL2) * [Settlement Data](#!/Settlement/Settlement_get) * [Exchange Statistics](#!/Stats/Stats_history) Every function of the BitMEX.com platform is exposed here and documented. Many more functions are available. ##### Swagger Specification [⇩ Download Swagger JSON](swagger.json) ## All API Endpoints Click to expand a section. 5 | * 6 | * OpenAPI spec version: 1.2.0 7 | * Contact: support@bitmex.com 8 | * Generated by: https://github.com/swagger-api/swagger-codegen.git 9 | */ 10 | 11 | package swagger 12 | 13 | import ( 14 | "encoding/json" 15 | "golang.org/x/net/context" 16 | "net/http" 17 | "net/url" 18 | "strings" 19 | ) 20 | 21 | // Linger please 22 | var ( 23 | _ context.Context 24 | ) 25 | 26 | type NotificationApiService service 27 | 28 | /* NotificationApiService Get your current notifications. 29 | This is an upcoming feature and currently does not return data. 30 | * @param ctx context.Context Authentication Context 31 | @return []Notification*/ 32 | func (a *NotificationApiService) NotificationGet(ctx context.Context) ([]Notification, *http.Response, error) { 33 | var ( 34 | localVarHttpMethod = strings.ToUpper("Get") 35 | localVarPostBody interface{} 36 | localVarFileName string 37 | localVarFileBytes []byte 38 | successPayload []Notification 39 | ) 40 | 41 | // create path and map variables 42 | localVarPath := a.client.cfg.BasePath + "/notification" 43 | 44 | localVarHeaderParams := make(map[string]string) 45 | localVarQueryParams := url.Values{} 46 | localVarFormParams := url.Values{} 47 | 48 | // to determine the Content-Type header 49 | localVarHttpContentTypes := []string{"application/json", "application/x-www-form-urlencoded"} 50 | 51 | // set Content-Type header 52 | localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) 53 | if localVarHttpContentType != "" { 54 | localVarHeaderParams["Content-Type"] = localVarHttpContentType 55 | } 56 | 57 | // to determine the Accept header 58 | localVarHttpHeaderAccepts := []string{ 59 | "application/json", 60 | "application/xml", 61 | "text/xml", 62 | "application/javascript", 63 | "text/javascript", 64 | } 65 | 66 | // set Accept header 67 | localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) 68 | if localVarHttpHeaderAccept != "" { 69 | localVarHeaderParams["Accept"] = localVarHttpHeaderAccept 70 | } 71 | if ctx != nil { 72 | // API Key Authentication 73 | if auth, ok := ctx.Value(ContextAPIKey).(APIKey); ok { 74 | var key string 75 | if auth.Prefix != "" { 76 | key = auth.Prefix + " " + auth.Key 77 | } else { 78 | key = auth.Key 79 | } 80 | localVarHeaderParams["api-key"] = key 81 | } 82 | } 83 | if ctx != nil { 84 | // API Key Authentication 85 | if auth, ok := ctx.Value(ContextAPIKey).(APIKey); ok { 86 | var key string 87 | if auth.Prefix != "" { 88 | key = auth.Prefix + " " + auth.Key 89 | } else { 90 | key = auth.Key 91 | } 92 | localVarHeaderParams["api-nonce"] = key 93 | } 94 | } 95 | if ctx != nil { 96 | // API Key Authentication 97 | if auth, ok := ctx.Value(ContextAPIKey).(APIKey); ok { 98 | var key string 99 | if auth.Prefix != "" { 100 | key = auth.Prefix + " " + auth.Key 101 | } else { 102 | key = auth.Key 103 | } 104 | localVarHeaderParams["api-signature"] = key 105 | } 106 | } 107 | r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) 108 | if err != nil { 109 | return successPayload, nil, err 110 | } 111 | 112 | localVarHttpResponse, err := a.client.callAPI(r) 113 | if err != nil || localVarHttpResponse == nil { 114 | return successPayload, localVarHttpResponse, err 115 | } 116 | defer localVarHttpResponse.Body.Close() 117 | if localVarHttpResponse.StatusCode >= 300 { 118 | return successPayload, localVarHttpResponse, reportError(localVarHttpResponse.Status) 119 | } 120 | 121 | if err = json.NewDecoder(localVarHttpResponse.Body).Decode(&successPayload); err != nil { 122 | return successPayload, localVarHttpResponse, err 123 | } 124 | 125 | return successPayload, localVarHttpResponse, err 126 | } 127 | -------------------------------------------------------------------------------- /swagger/order.go: -------------------------------------------------------------------------------- 1 | /* 2 | * BitMEX API 3 | * 4 | * ## REST API for the BitMEX Trading Platform [View Changelog](/app/apiChangelog) #### Getting Started ##### Fetching Data All REST endpoints are documented below. You can try out any query right from this interface. Most table queries accept `count`, `start`, and `reverse` params. Set `reverse=true` to get rows newest-first. Additional documentation regarding filters, timestamps, and authentication is available in [the main API documentation](https://www.bitmex.com/app/restAPI). *All* table data is available via the [Websocket](/app/wsAPI). We highly recommend using the socket if you want to have the quickest possible data without being subject to ratelimits. ##### Return Types By default, all data is returned as JSON. Send `?_format=csv` to get CSV data or `?_format=xml` to get XML data. ##### Trade Data Queries *This is only a small subset of what is available, to get you started.* Fill in the parameters and click the `Try it out!` button to try any of these queries. * [Pricing Data](#!/Quote/Quote_get) * [Trade Data](#!/Trade/Trade_get) * [OrderBook Data](#!/OrderBook/OrderBook_getL2) * [Settlement Data](#!/Settlement/Settlement_get) * [Exchange Statistics](#!/Stats/Stats_history) Every function of the BitMEX.com platform is exposed here and documented. Many more functions are available. ##### Swagger Specification [⇩ Download Swagger JSON](swagger.json) ## All API Endpoints Click to expand a section. 5 | * 6 | * OpenAPI spec version: 1.2.0 7 | * Contact: support@bitmex.com 8 | * Generated by: https://github.com/swagger-api/swagger-codegen.git 9 | */ 10 | 11 | package swagger 12 | 13 | import ( 14 | "time" 15 | ) 16 | 17 | // Placement, Cancellation, Amending, and History 18 | type Order struct { 19 | OrderID string `json:"orderID"` 20 | 21 | ClOrdID string `json:"clOrdID,omitempty"` 22 | 23 | ClOrdLinkID string `json:"clOrdLinkID,omitempty"` 24 | 25 | Account float32 `json:"account,omitempty"` 26 | 27 | Symbol string `json:"symbol,omitempty"` 28 | 29 | Side string `json:"side,omitempty"` 30 | 31 | SimpleOrderQty float64 `json:"simpleOrderQty,omitempty"` 32 | 33 | OrderQty float32 `json:"orderQty,omitempty"` 34 | 35 | Price float64 `json:"price,omitempty"` 36 | 37 | DisplayQty float32 `json:"displayQty,omitempty"` 38 | 39 | StopPx float64 `json:"stopPx,omitempty"` 40 | 41 | PegOffsetValue float64 `json:"pegOffsetValue,omitempty"` 42 | 43 | PegPriceType string `json:"pegPriceType,omitempty"` 44 | 45 | Currency string `json:"currency,omitempty"` 46 | 47 | SettlCurrency string `json:"settlCurrency,omitempty"` 48 | 49 | OrdType string `json:"ordType,omitempty"` 50 | 51 | TimeInForce string `json:"timeInForce,omitempty"` 52 | 53 | ExecInst string `json:"execInst,omitempty"` 54 | 55 | ContingencyType string `json:"contingencyType,omitempty"` 56 | 57 | ExDestination string `json:"exDestination,omitempty"` 58 | 59 | OrdStatus string `json:"ordStatus,omitempty"` 60 | 61 | Triggered string `json:"triggered,omitempty"` 62 | 63 | WorkingIndicator bool `json:"workingIndicator,omitempty"` 64 | 65 | OrdRejReason string `json:"ordRejReason,omitempty"` 66 | 67 | SimpleLeavesQty float64 `json:"simpleLeavesQty,omitempty"` 68 | 69 | LeavesQty float32 `json:"leavesQty,omitempty"` 70 | 71 | SimpleCumQty float64 `json:"simpleCumQty,omitempty"` 72 | 73 | CumQty float32 `json:"cumQty,omitempty"` 74 | 75 | AvgPx float64 `json:"avgPx,omitempty"` 76 | 77 | MultiLegReportingType string `json:"multiLegReportingType,omitempty"` 78 | 79 | Text string `json:"text,omitempty"` 80 | 81 | TransactTime time.Time `json:"transactTime,omitempty"` 82 | 83 | Timestamp time.Time `json:"timestamp,omitempty"` 84 | } 85 | -------------------------------------------------------------------------------- /swagger/order_book.go: -------------------------------------------------------------------------------- 1 | /* 2 | * BitMEX API 3 | * 4 | * ## REST API for the BitMEX Trading Platform [View Changelog](/app/apiChangelog) #### Getting Started ##### Fetching Data All REST endpoints are documented below. You can try out any query right from this interface. Most table queries accept `count`, `start`, and `reverse` params. Set `reverse=true` to get rows newest-first. Additional documentation regarding filters, timestamps, and authentication is available in [the main API documentation](https://www.bitmex.com/app/restAPI). *All* table data is available via the [Websocket](/app/wsAPI). We highly recommend using the socket if you want to have the quickest possible data without being subject to ratelimits. ##### Return Types By default, all data is returned as JSON. Send `?_format=csv` to get CSV data or `?_format=xml` to get XML data. ##### Trade Data Queries *This is only a small subset of what is available, to get you started.* Fill in the parameters and click the `Try it out!` button to try any of these queries. * [Pricing Data](#!/Quote/Quote_get) * [Trade Data](#!/Trade/Trade_get) * [OrderBook Data](#!/OrderBook/OrderBook_getL2) * [Settlement Data](#!/Settlement/Settlement_get) * [Exchange Statistics](#!/Stats/Stats_history) Every function of the BitMEX.com platform is exposed here and documented. Many more functions are available. ##### Swagger Specification [⇩ Download Swagger JSON](swagger.json) ## All API Endpoints Click to expand a section. 5 | * 6 | * OpenAPI spec version: 1.2.0 7 | * Contact: support@bitmex.com 8 | * Generated by: https://github.com/swagger-api/swagger-codegen.git 9 | */ 10 | 11 | package swagger 12 | 13 | import ( 14 | "time" 15 | ) 16 | 17 | // Level 2 Book Data 18 | type OrderBook struct { 19 | Symbol string `json:"symbol"` 20 | 21 | Level float32 `json:"level"` 22 | 23 | BidSize float32 `json:"bidSize,omitempty"` 24 | 25 | BidPrice float64 `json:"bidPrice,omitempty"` 26 | 27 | AskPrice float64 `json:"askPrice,omitempty"` 28 | 29 | AskSize float32 `json:"askSize,omitempty"` 30 | 31 | Timestamp time.Time `json:"timestamp,omitempty"` 32 | } 33 | -------------------------------------------------------------------------------- /swagger/order_book_api.go: -------------------------------------------------------------------------------- 1 | /* 2 | * BitMEX API 3 | * 4 | * ## REST API for the BitMEX Trading Platform [View Changelog](/app/apiChangelog) #### Getting Started ##### Fetching Data All REST endpoints are documented below. You can try out any query right from this interface. Most table queries accept `count`, `start`, and `reverse` params. Set `reverse=true` to get rows newest-first. Additional documentation regarding filters, timestamps, and authentication is available in [the main API documentation](https://www.bitmex.com/app/restAPI). *All* table data is available via the [Websocket](/app/wsAPI). We highly recommend using the socket if you want to have the quickest possible data without being subject to ratelimits. ##### Return Types By default, all data is returned as JSON. Send `?_format=csv` to get CSV data or `?_format=xml` to get XML data. ##### Trade Data Queries *This is only a small subset of what is available, to get you started.* Fill in the parameters and click the `Try it out!` button to try any of these queries. * [Pricing Data](#!/Quote/Quote_get) * [Trade Data](#!/Trade/Trade_get) * [OrderBook Data](#!/OrderBook/OrderBook_getL2) * [Settlement Data](#!/Settlement/Settlement_get) * [Exchange Statistics](#!/Stats/Stats_history) Every function of the BitMEX.com platform is exposed here and documented. Many more functions are available. ##### Swagger Specification [⇩ Download Swagger JSON](swagger.json) ## All API Endpoints Click to expand a section. 5 | * 6 | * OpenAPI spec version: 1.2.0 7 | * Contact: support@bitmex.com 8 | * Generated by: https://github.com/swagger-api/swagger-codegen.git 9 | */ 10 | 11 | package swagger 12 | 13 | import ( 14 | "encoding/json" 15 | "golang.org/x/net/context" 16 | "net/http" 17 | "net/url" 18 | "strings" 19 | ) 20 | 21 | // Linger please 22 | var ( 23 | _ context.Context 24 | ) 25 | 26 | type OrderBookApiService service 27 | 28 | /* OrderBookApiService Get current orderbook [deprecated, use /orderBook/L2]. 29 | 30 | @param symbol Instrument symbol. Send a series (e.g. XBT) to get data for the nearest contract in that series. 31 | @param optional (nil or map[string]interface{}) with one or more of: 32 | @param "depth" (float32) Orderbook depth. 33 | @return []OrderBook*/ 34 | func (a *OrderBookApiService) OrderBookGet(symbol string, localVarOptionals map[string]interface{}) ([]OrderBook, *http.Response, error) { 35 | var ( 36 | localVarHttpMethod = strings.ToUpper("Get") 37 | localVarPostBody interface{} 38 | localVarFileName string 39 | localVarFileBytes []byte 40 | successPayload []OrderBook 41 | ) 42 | 43 | // create path and map variables 44 | localVarPath := a.client.cfg.BasePath + "/orderBook" 45 | 46 | localVarHeaderParams := make(map[string]string) 47 | localVarQueryParams := url.Values{} 48 | localVarFormParams := url.Values{} 49 | 50 | if err := typeCheckParameter(localVarOptionals["depth"], "float32", "depth"); err != nil { 51 | return successPayload, nil, err 52 | } 53 | 54 | localVarQueryParams.Add("symbol", parameterToString(symbol, "")) 55 | if localVarTempParam, localVarOk := localVarOptionals["depth"].(float32); localVarOk { 56 | localVarQueryParams.Add("depth", parameterToString(localVarTempParam, "")) 57 | } 58 | // to determine the Content-Type header 59 | localVarHttpContentTypes := []string{"application/json", "application/x-www-form-urlencoded"} 60 | 61 | // set Content-Type header 62 | localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) 63 | if localVarHttpContentType != "" { 64 | localVarHeaderParams["Content-Type"] = localVarHttpContentType 65 | } 66 | 67 | // to determine the Accept header 68 | localVarHttpHeaderAccepts := []string{ 69 | "application/json", 70 | "application/xml", 71 | "text/xml", 72 | "application/javascript", 73 | "text/javascript", 74 | } 75 | 76 | // set Accept header 77 | localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) 78 | if localVarHttpHeaderAccept != "" { 79 | localVarHeaderParams["Accept"] = localVarHttpHeaderAccept 80 | } 81 | r, err := a.client.prepareRequest(nil, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) 82 | if err != nil { 83 | return successPayload, nil, err 84 | } 85 | 86 | localVarHttpResponse, err := a.client.callAPI(r) 87 | if err != nil || localVarHttpResponse == nil { 88 | return successPayload, localVarHttpResponse, err 89 | } 90 | defer localVarHttpResponse.Body.Close() 91 | if localVarHttpResponse.StatusCode >= 300 { 92 | return successPayload, localVarHttpResponse, reportError(localVarHttpResponse.Status) 93 | } 94 | 95 | if err = json.NewDecoder(localVarHttpResponse.Body).Decode(&successPayload); err != nil { 96 | return successPayload, localVarHttpResponse, err 97 | } 98 | 99 | return successPayload, localVarHttpResponse, err 100 | } 101 | 102 | /* OrderBookApiService Get current orderbook in vertical format. 103 | 104 | @param symbol Instrument symbol. Send a series (e.g. XBT) to get data for the nearest contract in that series. 105 | @param optional (nil or map[string]interface{}) with one or more of: 106 | @param "depth" (float32) Orderbook depth per side. Send 0 for full depth. 107 | @return []OrderBookL2*/ 108 | func (a *OrderBookApiService) OrderBookGetL2(symbol string, localVarOptionals map[string]interface{}) ([]OrderBookL2, *http.Response, error) { 109 | var ( 110 | localVarHttpMethod = strings.ToUpper("Get") 111 | localVarPostBody interface{} 112 | localVarFileName string 113 | localVarFileBytes []byte 114 | successPayload []OrderBookL2 115 | ) 116 | 117 | // create path and map variables 118 | localVarPath := a.client.cfg.BasePath + "/orderBook/L2" 119 | 120 | localVarHeaderParams := make(map[string]string) 121 | localVarQueryParams := url.Values{} 122 | localVarFormParams := url.Values{} 123 | 124 | if err := typeCheckParameter(localVarOptionals["depth"], "float32", "depth"); err != nil { 125 | return successPayload, nil, err 126 | } 127 | 128 | localVarQueryParams.Add("symbol", parameterToString(symbol, "")) 129 | if localVarTempParam, localVarOk := localVarOptionals["depth"].(float32); localVarOk { 130 | localVarQueryParams.Add("depth", parameterToString(localVarTempParam, "")) 131 | } 132 | // to determine the Content-Type header 133 | localVarHttpContentTypes := []string{"application/json", "application/x-www-form-urlencoded"} 134 | 135 | // set Content-Type header 136 | localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) 137 | if localVarHttpContentType != "" { 138 | localVarHeaderParams["Content-Type"] = localVarHttpContentType 139 | } 140 | 141 | // to determine the Accept header 142 | localVarHttpHeaderAccepts := []string{ 143 | "application/json", 144 | "application/xml", 145 | "text/xml", 146 | "application/javascript", 147 | "text/javascript", 148 | } 149 | 150 | // set Accept header 151 | localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) 152 | if localVarHttpHeaderAccept != "" { 153 | localVarHeaderParams["Accept"] = localVarHttpHeaderAccept 154 | } 155 | r, err := a.client.prepareRequest(nil, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) 156 | if err != nil { 157 | return successPayload, nil, err 158 | } 159 | 160 | localVarHttpResponse, err := a.client.callAPI(r) 161 | if err != nil || localVarHttpResponse == nil { 162 | return successPayload, localVarHttpResponse, err 163 | } 164 | defer localVarHttpResponse.Body.Close() 165 | if localVarHttpResponse.StatusCode >= 300 { 166 | return successPayload, localVarHttpResponse, reportError(localVarHttpResponse.Status) 167 | } 168 | 169 | if err = json.NewDecoder(localVarHttpResponse.Body).Decode(&successPayload); err != nil { 170 | return successPayload, localVarHttpResponse, err 171 | } 172 | 173 | return successPayload, localVarHttpResponse, err 174 | } 175 | -------------------------------------------------------------------------------- /swagger/order_book_l2.go: -------------------------------------------------------------------------------- 1 | /* 2 | * BitMEX API 3 | * 4 | * ## REST API for the BitMEX Trading Platform [View Changelog](/app/apiChangelog) #### Getting Started ##### Fetching Data All REST endpoints are documented below. You can try out any query right from this interface. Most table queries accept `count`, `start`, and `reverse` params. Set `reverse=true` to get rows newest-first. Additional documentation regarding filters, timestamps, and authentication is available in [the main API documentation](https://www.bitmex.com/app/restAPI). *All* table data is available via the [Websocket](/app/wsAPI). We highly recommend using the socket if you want to have the quickest possible data without being subject to ratelimits. ##### Return Types By default, all data is returned as JSON. Send `?_format=csv` to get CSV data or `?_format=xml` to get XML data. ##### Trade Data Queries *This is only a small subset of what is available, to get you started.* Fill in the parameters and click the `Try it out!` button to try any of these queries. * [Pricing Data](#!/Quote/Quote_get) * [Trade Data](#!/Trade/Trade_get) * [OrderBook Data](#!/OrderBook/OrderBook_getL2) * [Settlement Data](#!/Settlement/Settlement_get) * [Exchange Statistics](#!/Stats/Stats_history) Every function of the BitMEX.com platform is exposed here and documented. Many more functions are available. ##### Swagger Specification [⇩ Download Swagger JSON](swagger.json) ## All API Endpoints Click to expand a section. 5 | * 6 | * OpenAPI spec version: 1.2.0 7 | * Contact: support@bitmex.com 8 | * Generated by: https://github.com/swagger-api/swagger-codegen.git 9 | */ 10 | 11 | package swagger 12 | 13 | type OrderBookL2 struct { 14 | Symbol string `json:"symbol"` 15 | 16 | Id float32 `json:"id"` 17 | 18 | Side string `json:"side"` 19 | 20 | Size float32 `json:"size,omitempty"` 21 | 22 | Price float64 `json:"price,omitempty"` 23 | } 24 | -------------------------------------------------------------------------------- /swagger/position.go: -------------------------------------------------------------------------------- 1 | /* 2 | * BitMEX API 3 | * 4 | * ## REST API for the BitMEX Trading Platform [View Changelog](/app/apiChangelog) #### Getting Started ##### Fetching Data All REST endpoints are documented below. You can try out any query right from this interface. Most table queries accept `count`, `start`, and `reverse` params. Set `reverse=true` to get rows newest-first. Additional documentation regarding filters, timestamps, and authentication is available in [the main API documentation](https://www.bitmex.com/app/restAPI). *All* table data is available via the [Websocket](/app/wsAPI). We highly recommend using the socket if you want to have the quickest possible data without being subject to ratelimits. ##### Return Types By default, all data is returned as JSON. Send `?_format=csv` to get CSV data or `?_format=xml` to get XML data. ##### Trade Data Queries *This is only a small subset of what is available, to get you started.* Fill in the parameters and click the `Try it out!` button to try any of these queries. * [Pricing Data](#!/Quote/Quote_get) * [Trade Data](#!/Trade/Trade_get) * [OrderBook Data](#!/OrderBook/OrderBook_getL2) * [Settlement Data](#!/Settlement/Settlement_get) * [Exchange Statistics](#!/Stats/Stats_history) Every function of the BitMEX.com platform is exposed here and documented. Many more functions are available. ##### Swagger Specification [⇩ Download Swagger JSON](swagger.json) ## All API Endpoints Click to expand a section. 5 | * 6 | * OpenAPI spec version: 1.2.0 7 | * Contact: support@bitmex.com 8 | * Generated by: https://github.com/swagger-api/swagger-codegen.git 9 | */ 10 | 11 | package swagger 12 | 13 | import ( 14 | "time" 15 | ) 16 | 17 | // Summary of Open and Closed Positions 18 | type Position struct { 19 | Account float32 `json:"account"` 20 | 21 | Symbol string `json:"symbol"` 22 | 23 | Currency string `json:"currency"` 24 | 25 | Underlying string `json:"underlying,omitempty"` 26 | 27 | QuoteCurrency string `json:"quoteCurrency,omitempty"` 28 | 29 | Commission float64 `json:"commission,omitempty"` 30 | 31 | InitMarginReq float64 `json:"initMarginReq,omitempty"` 32 | 33 | MaintMarginReq float64 `json:"maintMarginReq,omitempty"` 34 | 35 | RiskLimit float32 `json:"riskLimit,omitempty"` 36 | 37 | Leverage float64 `json:"leverage,omitempty"` 38 | 39 | CrossMargin bool `json:"crossMargin,omitempty"` 40 | 41 | DeleveragePercentile float64 `json:"deleveragePercentile,omitempty"` 42 | 43 | RebalancedPnl float32 `json:"rebalancedPnl,omitempty"` 44 | 45 | PrevRealisedPnl float32 `json:"prevRealisedPnl,omitempty"` 46 | 47 | PrevUnrealisedPnl float32 `json:"prevUnrealisedPnl,omitempty"` 48 | 49 | PrevClosePrice float64 `json:"prevClosePrice,omitempty"` 50 | 51 | OpeningTimestamp time.Time `json:"openingTimestamp,omitempty"` 52 | 53 | OpeningQty float32 `json:"openingQty,omitempty"` 54 | 55 | OpeningCost float32 `json:"openingCost,omitempty"` 56 | 57 | OpeningComm float32 `json:"openingComm,omitempty"` 58 | 59 | OpenOrderBuyQty float32 `json:"openOrderBuyQty,omitempty"` 60 | 61 | OpenOrderBuyCost float32 `json:"openOrderBuyCost,omitempty"` 62 | 63 | OpenOrderBuyPremium float32 `json:"openOrderBuyPremium,omitempty"` 64 | 65 | OpenOrderSellQty float32 `json:"openOrderSellQty,omitempty"` 66 | 67 | OpenOrderSellCost float32 `json:"openOrderSellCost,omitempty"` 68 | 69 | OpenOrderSellPremium float32 `json:"openOrderSellPremium,omitempty"` 70 | 71 | ExecBuyQty float32 `json:"execBuyQty,omitempty"` 72 | 73 | ExecBuyCost float32 `json:"execBuyCost,omitempty"` 74 | 75 | ExecSellQty float32 `json:"execSellQty,omitempty"` 76 | 77 | ExecSellCost float32 `json:"execSellCost,omitempty"` 78 | 79 | ExecQty float32 `json:"execQty,omitempty"` 80 | 81 | ExecCost float32 `json:"execCost,omitempty"` 82 | 83 | ExecComm float32 `json:"execComm,omitempty"` 84 | 85 | CurrentTimestamp time.Time `json:"currentTimestamp,omitempty"` 86 | 87 | CurrentQty float32 `json:"currentQty,omitempty"` 88 | 89 | CurrentCost float32 `json:"currentCost,omitempty"` 90 | 91 | CurrentComm float32 `json:"currentComm,omitempty"` 92 | 93 | RealisedCost float32 `json:"realisedCost,omitempty"` 94 | 95 | UnrealisedCost float32 `json:"unrealisedCost,omitempty"` 96 | 97 | GrossOpenCost float32 `json:"grossOpenCost,omitempty"` 98 | 99 | GrossOpenPremium float32 `json:"grossOpenPremium,omitempty"` 100 | 101 | GrossExecCost float32 `json:"grossExecCost,omitempty"` 102 | 103 | IsOpen bool `json:"isOpen,omitempty"` 104 | 105 | MarkPrice float64 `json:"markPrice,omitempty"` 106 | 107 | MarkValue float32 `json:"markValue,omitempty"` 108 | 109 | RiskValue float32 `json:"riskValue,omitempty"` 110 | 111 | HomeNotional float64 `json:"homeNotional,omitempty"` 112 | 113 | ForeignNotional float64 `json:"foreignNotional,omitempty"` 114 | 115 | PosState string `json:"posState,omitempty"` 116 | 117 | PosCost float32 `json:"posCost,omitempty"` 118 | 119 | PosCost2 float32 `json:"posCost2,omitempty"` 120 | 121 | PosCross float32 `json:"posCross,omitempty"` 122 | 123 | PosInit float32 `json:"posInit,omitempty"` 124 | 125 | PosComm float32 `json:"posComm,omitempty"` 126 | 127 | PosLoss float32 `json:"posLoss,omitempty"` 128 | 129 | PosMargin float32 `json:"posMargin,omitempty"` 130 | 131 | PosMaint float32 `json:"posMaint,omitempty"` 132 | 133 | PosAllowance float32 `json:"posAllowance,omitempty"` 134 | 135 | TaxableMargin float32 `json:"taxableMargin,omitempty"` 136 | 137 | InitMargin float32 `json:"initMargin,omitempty"` 138 | 139 | MaintMargin float32 `json:"maintMargin,omitempty"` 140 | 141 | SessionMargin float32 `json:"sessionMargin,omitempty"` 142 | 143 | TargetExcessMargin float32 `json:"targetExcessMargin,omitempty"` 144 | 145 | VarMargin float32 `json:"varMargin,omitempty"` 146 | 147 | RealisedGrossPnl float32 `json:"realisedGrossPnl,omitempty"` 148 | 149 | RealisedTax float32 `json:"realisedTax,omitempty"` 150 | 151 | RealisedPnl float32 `json:"realisedPnl,omitempty"` 152 | 153 | UnrealisedGrossPnl float32 `json:"unrealisedGrossPnl,omitempty"` 154 | 155 | LongBankrupt float32 `json:"longBankrupt,omitempty"` 156 | 157 | ShortBankrupt float32 `json:"shortBankrupt,omitempty"` 158 | 159 | TaxBase float32 `json:"taxBase,omitempty"` 160 | 161 | IndicativeTaxRate float64 `json:"indicativeTaxRate,omitempty"` 162 | 163 | IndicativeTax float32 `json:"indicativeTax,omitempty"` 164 | 165 | UnrealisedTax float32 `json:"unrealisedTax,omitempty"` 166 | 167 | UnrealisedPnl float32 `json:"unrealisedPnl,omitempty"` 168 | 169 | UnrealisedPnlPcnt float64 `json:"unrealisedPnlPcnt,omitempty"` 170 | 171 | UnrealisedRoePcnt float64 `json:"unrealisedRoePcnt,omitempty"` 172 | 173 | SimpleQty float64 `json:"simpleQty,omitempty"` 174 | 175 | SimpleCost float64 `json:"simpleCost,omitempty"` 176 | 177 | SimpleValue float64 `json:"simpleValue,omitempty"` 178 | 179 | SimplePnl float64 `json:"simplePnl,omitempty"` 180 | 181 | SimplePnlPcnt float64 `json:"simplePnlPcnt,omitempty"` 182 | 183 | AvgCostPrice float64 `json:"avgCostPrice,omitempty"` 184 | 185 | AvgEntryPrice float64 `json:"avgEntryPrice,omitempty"` 186 | 187 | BreakEvenPrice float64 `json:"breakEvenPrice,omitempty"` 188 | 189 | MarginCallPrice float64 `json:"marginCallPrice,omitempty"` 190 | 191 | LiquidationPrice float64 `json:"liquidationPrice,omitempty"` 192 | 193 | BankruptPrice float64 `json:"bankruptPrice,omitempty"` 194 | 195 | Timestamp time.Time `json:"timestamp,omitempty"` 196 | 197 | LastPrice float64 `json:"lastPrice,omitempty"` 198 | 199 | LastValue float32 `json:"lastValue,omitempty"` 200 | } 201 | -------------------------------------------------------------------------------- /swagger/quote.go: -------------------------------------------------------------------------------- 1 | /* 2 | * BitMEX API 3 | * 4 | * ## REST API for the BitMEX Trading Platform [View Changelog](/app/apiChangelog) #### Getting Started ##### Fetching Data All REST endpoints are documented below. You can try out any query right from this interface. Most table queries accept `count`, `start`, and `reverse` params. Set `reverse=true` to get rows newest-first. Additional documentation regarding filters, timestamps, and authentication is available in [the main API documentation](https://www.bitmex.com/app/restAPI). *All* table data is available via the [Websocket](/app/wsAPI). We highly recommend using the socket if you want to have the quickest possible data without being subject to ratelimits. ##### Return Types By default, all data is returned as JSON. Send `?_format=csv` to get CSV data or `?_format=xml` to get XML data. ##### Trade Data Queries *This is only a small subset of what is available, to get you started.* Fill in the parameters and click the `Try it out!` button to try any of these queries. * [Pricing Data](#!/Quote/Quote_get) * [Trade Data](#!/Trade/Trade_get) * [OrderBook Data](#!/OrderBook/OrderBook_getL2) * [Settlement Data](#!/Settlement/Settlement_get) * [Exchange Statistics](#!/Stats/Stats_history) Every function of the BitMEX.com platform is exposed here and documented. Many more functions are available. ##### Swagger Specification [⇩ Download Swagger JSON](swagger.json) ## All API Endpoints Click to expand a section. 5 | * 6 | * OpenAPI spec version: 1.2.0 7 | * Contact: support@bitmex.com 8 | * Generated by: https://github.com/swagger-api/swagger-codegen.git 9 | */ 10 | 11 | package swagger 12 | 13 | import ( 14 | "time" 15 | ) 16 | 17 | // Best Bid/Offer Snapshots & Historical Bins 18 | type Quote struct { 19 | Timestamp time.Time `json:"timestamp"` 20 | 21 | Symbol string `json:"symbol"` 22 | 23 | BidSize float32 `json:"bidSize,omitempty"` 24 | 25 | BidPrice float64 `json:"bidPrice,omitempty"` 26 | 27 | AskPrice float64 `json:"askPrice,omitempty"` 28 | 29 | AskSize float32 `json:"askSize,omitempty"` 30 | } 31 | -------------------------------------------------------------------------------- /swagger/schema_api.go: -------------------------------------------------------------------------------- 1 | /* 2 | * BitMEX API 3 | * 4 | * ## REST API for the BitMEX Trading Platform [View Changelog](/app/apiChangelog) #### Getting Started ##### Fetching Data All REST endpoints are documented below. You can try out any query right from this interface. Most table queries accept `count`, `start`, and `reverse` params. Set `reverse=true` to get rows newest-first. Additional documentation regarding filters, timestamps, and authentication is available in [the main API documentation](https://www.bitmex.com/app/restAPI). *All* table data is available via the [Websocket](/app/wsAPI). We highly recommend using the socket if you want to have the quickest possible data without being subject to ratelimits. ##### Return Types By default, all data is returned as JSON. Send `?_format=csv` to get CSV data or `?_format=xml` to get XML data. ##### Trade Data Queries *This is only a small subset of what is available, to get you started.* Fill in the parameters and click the `Try it out!` button to try any of these queries. * [Pricing Data](#!/Quote/Quote_get) * [Trade Data](#!/Trade/Trade_get) * [OrderBook Data](#!/OrderBook/OrderBook_getL2) * [Settlement Data](#!/Settlement/Settlement_get) * [Exchange Statistics](#!/Stats/Stats_history) Every function of the BitMEX.com platform is exposed here and documented. Many more functions are available. ##### Swagger Specification [⇩ Download Swagger JSON](swagger.json) ## All API Endpoints Click to expand a section. 5 | * 6 | * OpenAPI spec version: 1.2.0 7 | * Contact: support@bitmex.com 8 | * Generated by: https://github.com/swagger-api/swagger-codegen.git 9 | */ 10 | 11 | package swagger 12 | 13 | import ( 14 | "encoding/json" 15 | "golang.org/x/net/context" 16 | "net/http" 17 | "net/url" 18 | "strings" 19 | ) 20 | 21 | // Linger please 22 | var ( 23 | _ context.Context 24 | ) 25 | 26 | type SchemaApiService service 27 | 28 | /* SchemaApiService Get model schemata for data objects returned by this API. 29 | 30 | @param optional (nil or map[string]interface{}) with one or more of: 31 | @param "model" (string) Optional model filter. If omitted, will return all models. 32 | @return interface{}*/ 33 | func (a *SchemaApiService) SchemaGet(localVarOptionals map[string]interface{}) (interface{}, *http.Response, error) { 34 | var ( 35 | localVarHttpMethod = strings.ToUpper("Get") 36 | localVarPostBody interface{} 37 | localVarFileName string 38 | localVarFileBytes []byte 39 | successPayload interface{} 40 | ) 41 | 42 | // create path and map variables 43 | localVarPath := a.client.cfg.BasePath + "/schema" 44 | 45 | localVarHeaderParams := make(map[string]string) 46 | localVarQueryParams := url.Values{} 47 | localVarFormParams := url.Values{} 48 | 49 | if err := typeCheckParameter(localVarOptionals["model"], "string", "model"); err != nil { 50 | return successPayload, nil, err 51 | } 52 | 53 | if localVarTempParam, localVarOk := localVarOptionals["model"].(string); localVarOk { 54 | localVarQueryParams.Add("model", parameterToString(localVarTempParam, "")) 55 | } 56 | // to determine the Content-Type header 57 | localVarHttpContentTypes := []string{"application/json", "application/x-www-form-urlencoded"} 58 | 59 | // set Content-Type header 60 | localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) 61 | if localVarHttpContentType != "" { 62 | localVarHeaderParams["Content-Type"] = localVarHttpContentType 63 | } 64 | 65 | // to determine the Accept header 66 | localVarHttpHeaderAccepts := []string{ 67 | "application/json", 68 | "application/xml", 69 | "text/xml", 70 | "application/javascript", 71 | "text/javascript", 72 | } 73 | 74 | // set Accept header 75 | localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) 76 | if localVarHttpHeaderAccept != "" { 77 | localVarHeaderParams["Accept"] = localVarHttpHeaderAccept 78 | } 79 | r, err := a.client.prepareRequest(nil, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) 80 | if err != nil { 81 | return successPayload, nil, err 82 | } 83 | 84 | localVarHttpResponse, err := a.client.callAPI(r) 85 | if err != nil || localVarHttpResponse == nil { 86 | return successPayload, localVarHttpResponse, err 87 | } 88 | defer localVarHttpResponse.Body.Close() 89 | if localVarHttpResponse.StatusCode >= 300 { 90 | return successPayload, localVarHttpResponse, reportError(localVarHttpResponse.Status) 91 | } 92 | 93 | if err = json.NewDecoder(localVarHttpResponse.Body).Decode(&successPayload); err != nil { 94 | return successPayload, localVarHttpResponse, err 95 | } 96 | 97 | return successPayload, localVarHttpResponse, err 98 | } 99 | 100 | /* SchemaApiService Returns help text & subject list for websocket usage. 101 | 102 | @return interface{}*/ 103 | func (a *SchemaApiService) SchemaWebsocketHelp() (interface{}, *http.Response, error) { 104 | var ( 105 | localVarHttpMethod = strings.ToUpper("Get") 106 | localVarPostBody interface{} 107 | localVarFileName string 108 | localVarFileBytes []byte 109 | successPayload interface{} 110 | ) 111 | 112 | // create path and map variables 113 | localVarPath := a.client.cfg.BasePath + "/schema/websocketHelp" 114 | 115 | localVarHeaderParams := make(map[string]string) 116 | localVarQueryParams := url.Values{} 117 | localVarFormParams := url.Values{} 118 | 119 | // to determine the Content-Type header 120 | localVarHttpContentTypes := []string{"application/json", "application/x-www-form-urlencoded"} 121 | 122 | // set Content-Type header 123 | localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) 124 | if localVarHttpContentType != "" { 125 | localVarHeaderParams["Content-Type"] = localVarHttpContentType 126 | } 127 | 128 | // to determine the Accept header 129 | localVarHttpHeaderAccepts := []string{ 130 | "application/json", 131 | "application/xml", 132 | "text/xml", 133 | "application/javascript", 134 | "text/javascript", 135 | } 136 | 137 | // set Accept header 138 | localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) 139 | if localVarHttpHeaderAccept != "" { 140 | localVarHeaderParams["Accept"] = localVarHttpHeaderAccept 141 | } 142 | r, err := a.client.prepareRequest(nil, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) 143 | if err != nil { 144 | return successPayload, nil, err 145 | } 146 | 147 | localVarHttpResponse, err := a.client.callAPI(r) 148 | if err != nil || localVarHttpResponse == nil { 149 | return successPayload, localVarHttpResponse, err 150 | } 151 | defer localVarHttpResponse.Body.Close() 152 | if localVarHttpResponse.StatusCode >= 300 { 153 | return successPayload, localVarHttpResponse, reportError(localVarHttpResponse.Status) 154 | } 155 | 156 | if err = json.NewDecoder(localVarHttpResponse.Body).Decode(&successPayload); err != nil { 157 | return successPayload, localVarHttpResponse, err 158 | } 159 | 160 | return successPayload, localVarHttpResponse, err 161 | } 162 | -------------------------------------------------------------------------------- /swagger/settlement.go: -------------------------------------------------------------------------------- 1 | /* 2 | * BitMEX API 3 | * 4 | * ## REST API for the BitMEX Trading Platform [View Changelog](/app/apiChangelog) #### Getting Started ##### Fetching Data All REST endpoints are documented below. You can try out any query right from this interface. Most table queries accept `count`, `start`, and `reverse` params. Set `reverse=true` to get rows newest-first. Additional documentation regarding filters, timestamps, and authentication is available in [the main API documentation](https://www.bitmex.com/app/restAPI). *All* table data is available via the [Websocket](/app/wsAPI). We highly recommend using the socket if you want to have the quickest possible data without being subject to ratelimits. ##### Return Types By default, all data is returned as JSON. Send `?_format=csv` to get CSV data or `?_format=xml` to get XML data. ##### Trade Data Queries *This is only a small subset of what is available, to get you started.* Fill in the parameters and click the `Try it out!` button to try any of these queries. * [Pricing Data](#!/Quote/Quote_get) * [Trade Data](#!/Trade/Trade_get) * [OrderBook Data](#!/OrderBook/OrderBook_getL2) * [Settlement Data](#!/Settlement/Settlement_get) * [Exchange Statistics](#!/Stats/Stats_history) Every function of the BitMEX.com platform is exposed here and documented. Many more functions are available. ##### Swagger Specification [⇩ Download Swagger JSON](swagger.json) ## All API Endpoints Click to expand a section. 5 | * 6 | * OpenAPI spec version: 1.2.0 7 | * Contact: support@bitmex.com 8 | * Generated by: https://github.com/swagger-api/swagger-codegen.git 9 | */ 10 | 11 | package swagger 12 | 13 | import ( 14 | "time" 15 | ) 16 | 17 | // Historical Settlement Data 18 | type Settlement struct { 19 | Timestamp time.Time `json:"timestamp"` 20 | 21 | Symbol string `json:"symbol"` 22 | 23 | SettlementType string `json:"settlementType,omitempty"` 24 | 25 | SettledPrice float64 `json:"settledPrice,omitempty"` 26 | 27 | Bankrupt float32 `json:"bankrupt,omitempty"` 28 | 29 | TaxBase float32 `json:"taxBase,omitempty"` 30 | 31 | TaxRate float64 `json:"taxRate,omitempty"` 32 | } 33 | -------------------------------------------------------------------------------- /swagger/settlement_api.go: -------------------------------------------------------------------------------- 1 | /* 2 | * BitMEX API 3 | * 4 | * ## REST API for the BitMEX Trading Platform [View Changelog](/app/apiChangelog) #### Getting Started ##### Fetching Data All REST endpoints are documented below. You can try out any query right from this interface. Most table queries accept `count`, `start`, and `reverse` params. Set `reverse=true` to get rows newest-first. Additional documentation regarding filters, timestamps, and authentication is available in [the main API documentation](https://www.bitmex.com/app/restAPI). *All* table data is available via the [Websocket](/app/wsAPI). We highly recommend using the socket if you want to have the quickest possible data without being subject to ratelimits. ##### Return Types By default, all data is returned as JSON. Send `?_format=csv` to get CSV data or `?_format=xml` to get XML data. ##### Trade Data Queries *This is only a small subset of what is available, to get you started.* Fill in the parameters and click the `Try it out!` button to try any of these queries. * [Pricing Data](#!/Quote/Quote_get) * [Trade Data](#!/Trade/Trade_get) * [OrderBook Data](#!/OrderBook/OrderBook_getL2) * [Settlement Data](#!/Settlement/Settlement_get) * [Exchange Statistics](#!/Stats/Stats_history) Every function of the BitMEX.com platform is exposed here and documented. Many more functions are available. ##### Swagger Specification [⇩ Download Swagger JSON](swagger.json) ## All API Endpoints Click to expand a section. 5 | * 6 | * OpenAPI spec version: 1.2.0 7 | * Contact: support@bitmex.com 8 | * Generated by: https://github.com/swagger-api/swagger-codegen.git 9 | */ 10 | 11 | package swagger 12 | 13 | import ( 14 | "encoding/json" 15 | "golang.org/x/net/context" 16 | "net/http" 17 | "net/url" 18 | "strings" 19 | "time" 20 | ) 21 | 22 | // Linger please 23 | var ( 24 | _ context.Context 25 | ) 26 | 27 | type SettlementApiService service 28 | 29 | /* SettlementApiService Get settlement history. 30 | 31 | @param optional (nil or map[string]interface{}) with one or more of: 32 | @param "symbol" (string) Instrument symbol. Send a bare series (e.g. XBU) to get data for the nearest expiring contract in that series. You can also send a timeframe, e.g. `XBU:monthly`. Timeframes are `daily`, `weekly`, `monthly`, `quarterly`, and `biquarterly`. 33 | @param "filter" (string) Generic table filter. Send JSON key/value pairs, such as `{\"key\": \"value\"}`. You can key on individual fields, and do more advanced querying on timestamps. See the [Timestamp Docs](https://www.bitmex.com/app/restAPI#timestamp-filters) for more details. 34 | @param "columns" (string) Array of column names to fetch. If omitted, will return all columns. Note that this method will always return item keys, even when not specified, so you may receive more columns that you expect. 35 | @param "count" (float32) Number of results to fetch. 36 | @param "start" (float32) Starting point for results. 37 | @param "reverse" (bool) If true, will sort results newest first. 38 | @param "startTime" (time.Time) Starting date filter for results. 39 | @param "endTime" (time.Time) Ending date filter for results. 40 | @return []Settlement*/ 41 | func (a *SettlementApiService) SettlementGet(localVarOptionals map[string]interface{}) ([]Settlement, *http.Response, error) { 42 | var ( 43 | localVarHttpMethod = strings.ToUpper("Get") 44 | localVarPostBody interface{} 45 | localVarFileName string 46 | localVarFileBytes []byte 47 | successPayload []Settlement 48 | ) 49 | 50 | // create path and map variables 51 | localVarPath := a.client.cfg.BasePath + "/settlement" 52 | 53 | localVarHeaderParams := make(map[string]string) 54 | localVarQueryParams := url.Values{} 55 | localVarFormParams := url.Values{} 56 | 57 | if err := typeCheckParameter(localVarOptionals["symbol"], "string", "symbol"); err != nil { 58 | return successPayload, nil, err 59 | } 60 | if err := typeCheckParameter(localVarOptionals["filter"], "string", "filter"); err != nil { 61 | return successPayload, nil, err 62 | } 63 | if err := typeCheckParameter(localVarOptionals["columns"], "string", "columns"); err != nil { 64 | return successPayload, nil, err 65 | } 66 | if err := typeCheckParameter(localVarOptionals["count"], "float32", "count"); err != nil { 67 | return successPayload, nil, err 68 | } 69 | if err := typeCheckParameter(localVarOptionals["start"], "float32", "start"); err != nil { 70 | return successPayload, nil, err 71 | } 72 | if err := typeCheckParameter(localVarOptionals["reverse"], "bool", "reverse"); err != nil { 73 | return successPayload, nil, err 74 | } 75 | if err := typeCheckParameter(localVarOptionals["startTime"], "time.Time", "startTime"); err != nil { 76 | return successPayload, nil, err 77 | } 78 | if err := typeCheckParameter(localVarOptionals["endTime"], "time.Time", "endTime"); err != nil { 79 | return successPayload, nil, err 80 | } 81 | 82 | if localVarTempParam, localVarOk := localVarOptionals["symbol"].(string); localVarOk { 83 | localVarQueryParams.Add("symbol", parameterToString(localVarTempParam, "")) 84 | } 85 | if localVarTempParam, localVarOk := localVarOptionals["filter"].(string); localVarOk { 86 | localVarQueryParams.Add("filter", parameterToString(localVarTempParam, "")) 87 | } 88 | if localVarTempParam, localVarOk := localVarOptionals["columns"].(string); localVarOk { 89 | localVarQueryParams.Add("columns", parameterToString(localVarTempParam, "")) 90 | } 91 | if localVarTempParam, localVarOk := localVarOptionals["count"].(float32); localVarOk { 92 | localVarQueryParams.Add("count", parameterToString(localVarTempParam, "")) 93 | } 94 | if localVarTempParam, localVarOk := localVarOptionals["start"].(float32); localVarOk { 95 | localVarQueryParams.Add("start", parameterToString(localVarTempParam, "")) 96 | } 97 | if localVarTempParam, localVarOk := localVarOptionals["reverse"].(bool); localVarOk { 98 | localVarQueryParams.Add("reverse", parameterToString(localVarTempParam, "")) 99 | } 100 | if localVarTempParam, localVarOk := localVarOptionals["startTime"].(time.Time); localVarOk { 101 | localVarQueryParams.Add("startTime", parameterToString(localVarTempParam, "")) 102 | } 103 | if localVarTempParam, localVarOk := localVarOptionals["endTime"].(time.Time); localVarOk { 104 | localVarQueryParams.Add("endTime", parameterToString(localVarTempParam, "")) 105 | } 106 | // to determine the Content-Type header 107 | localVarHttpContentTypes := []string{"application/json", "application/x-www-form-urlencoded"} 108 | 109 | // set Content-Type header 110 | localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) 111 | if localVarHttpContentType != "" { 112 | localVarHeaderParams["Content-Type"] = localVarHttpContentType 113 | } 114 | 115 | // to determine the Accept header 116 | localVarHttpHeaderAccepts := []string{ 117 | "application/json", 118 | "application/xml", 119 | "text/xml", 120 | "application/javascript", 121 | "text/javascript", 122 | } 123 | 124 | // set Accept header 125 | localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) 126 | if localVarHttpHeaderAccept != "" { 127 | localVarHeaderParams["Accept"] = localVarHttpHeaderAccept 128 | } 129 | r, err := a.client.prepareRequest(nil, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) 130 | if err != nil { 131 | return successPayload, nil, err 132 | } 133 | 134 | localVarHttpResponse, err := a.client.callAPI(r) 135 | if err != nil || localVarHttpResponse == nil { 136 | return successPayload, localVarHttpResponse, err 137 | } 138 | defer localVarHttpResponse.Body.Close() 139 | if localVarHttpResponse.StatusCode >= 300 { 140 | return successPayload, localVarHttpResponse, reportError(localVarHttpResponse.Status) 141 | } 142 | 143 | if err = json.NewDecoder(localVarHttpResponse.Body).Decode(&successPayload); err != nil { 144 | return successPayload, localVarHttpResponse, err 145 | } 146 | 147 | return successPayload, localVarHttpResponse, err 148 | } 149 | -------------------------------------------------------------------------------- /swagger/stats.go: -------------------------------------------------------------------------------- 1 | /* 2 | * BitMEX API 3 | * 4 | * ## REST API for the BitMEX Trading Platform [View Changelog](/app/apiChangelog) #### Getting Started ##### Fetching Data All REST endpoints are documented below. You can try out any query right from this interface. Most table queries accept `count`, `start`, and `reverse` params. Set `reverse=true` to get rows newest-first. Additional documentation regarding filters, timestamps, and authentication is available in [the main API documentation](https://www.bitmex.com/app/restAPI). *All* table data is available via the [Websocket](/app/wsAPI). We highly recommend using the socket if you want to have the quickest possible data without being subject to ratelimits. ##### Return Types By default, all data is returned as JSON. Send `?_format=csv` to get CSV data or `?_format=xml` to get XML data. ##### Trade Data Queries *This is only a small subset of what is available, to get you started.* Fill in the parameters and click the `Try it out!` button to try any of these queries. * [Pricing Data](#!/Quote/Quote_get) * [Trade Data](#!/Trade/Trade_get) * [OrderBook Data](#!/OrderBook/OrderBook_getL2) * [Settlement Data](#!/Settlement/Settlement_get) * [Exchange Statistics](#!/Stats/Stats_history) Every function of the BitMEX.com platform is exposed here and documented. Many more functions are available. ##### Swagger Specification [⇩ Download Swagger JSON](swagger.json) ## All API Endpoints Click to expand a section. 5 | * 6 | * OpenAPI spec version: 1.2.0 7 | * Contact: support@bitmex.com 8 | * Generated by: https://github.com/swagger-api/swagger-codegen.git 9 | */ 10 | 11 | package swagger 12 | 13 | // Exchange Statistics 14 | type Stats struct { 15 | RootSymbol string `json:"rootSymbol"` 16 | 17 | Currency string `json:"currency,omitempty"` 18 | 19 | Volume24h float32 `json:"volume24h,omitempty"` 20 | 21 | Turnover24h float32 `json:"turnover24h,omitempty"` 22 | 23 | OpenInterest float32 `json:"openInterest,omitempty"` 24 | 25 | OpenValue float32 `json:"openValue,omitempty"` 26 | } 27 | -------------------------------------------------------------------------------- /swagger/stats_api.go: -------------------------------------------------------------------------------- 1 | /* 2 | * BitMEX API 3 | * 4 | * ## REST API for the BitMEX Trading Platform [View Changelog](/app/apiChangelog) #### Getting Started ##### Fetching Data All REST endpoints are documented below. You can try out any query right from this interface. Most table queries accept `count`, `start`, and `reverse` params. Set `reverse=true` to get rows newest-first. Additional documentation regarding filters, timestamps, and authentication is available in [the main API documentation](https://www.bitmex.com/app/restAPI). *All* table data is available via the [Websocket](/app/wsAPI). We highly recommend using the socket if you want to have the quickest possible data without being subject to ratelimits. ##### Return Types By default, all data is returned as JSON. Send `?_format=csv` to get CSV data or `?_format=xml` to get XML data. ##### Trade Data Queries *This is only a small subset of what is available, to get you started.* Fill in the parameters and click the `Try it out!` button to try any of these queries. * [Pricing Data](#!/Quote/Quote_get) * [Trade Data](#!/Trade/Trade_get) * [OrderBook Data](#!/OrderBook/OrderBook_getL2) * [Settlement Data](#!/Settlement/Settlement_get) * [Exchange Statistics](#!/Stats/Stats_history) Every function of the BitMEX.com platform is exposed here and documented. Many more functions are available. ##### Swagger Specification [⇩ Download Swagger JSON](swagger.json) ## All API Endpoints Click to expand a section. 5 | * 6 | * OpenAPI spec version: 1.2.0 7 | * Contact: support@bitmex.com 8 | * Generated by: https://github.com/swagger-api/swagger-codegen.git 9 | */ 10 | 11 | package swagger 12 | 13 | import ( 14 | "encoding/json" 15 | "golang.org/x/net/context" 16 | "net/http" 17 | "net/url" 18 | "strings" 19 | ) 20 | 21 | // Linger please 22 | var ( 23 | _ context.Context 24 | ) 25 | 26 | type StatsApiService service 27 | 28 | /* StatsApiService Get exchange-wide and per-series turnover and volume statistics. 29 | 30 | @return []Stats*/ 31 | func (a *StatsApiService) StatsGet() ([]Stats, *http.Response, error) { 32 | var ( 33 | localVarHttpMethod = strings.ToUpper("Get") 34 | localVarPostBody interface{} 35 | localVarFileName string 36 | localVarFileBytes []byte 37 | successPayload []Stats 38 | ) 39 | 40 | // create path and map variables 41 | localVarPath := a.client.cfg.BasePath + "/stats" 42 | 43 | localVarHeaderParams := make(map[string]string) 44 | localVarQueryParams := url.Values{} 45 | localVarFormParams := url.Values{} 46 | 47 | // to determine the Content-Type header 48 | localVarHttpContentTypes := []string{"application/json", "application/x-www-form-urlencoded"} 49 | 50 | // set Content-Type header 51 | localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) 52 | if localVarHttpContentType != "" { 53 | localVarHeaderParams["Content-Type"] = localVarHttpContentType 54 | } 55 | 56 | // to determine the Accept header 57 | localVarHttpHeaderAccepts := []string{ 58 | "application/json", 59 | "application/xml", 60 | "text/xml", 61 | "application/javascript", 62 | "text/javascript", 63 | } 64 | 65 | // set Accept header 66 | localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) 67 | if localVarHttpHeaderAccept != "" { 68 | localVarHeaderParams["Accept"] = localVarHttpHeaderAccept 69 | } 70 | r, err := a.client.prepareRequest(nil, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) 71 | if err != nil { 72 | return successPayload, nil, err 73 | } 74 | 75 | localVarHttpResponse, err := a.client.callAPI(r) 76 | if err != nil || localVarHttpResponse == nil { 77 | return successPayload, localVarHttpResponse, err 78 | } 79 | defer localVarHttpResponse.Body.Close() 80 | if localVarHttpResponse.StatusCode >= 300 { 81 | return successPayload, localVarHttpResponse, reportError(localVarHttpResponse.Status) 82 | } 83 | 84 | if err = json.NewDecoder(localVarHttpResponse.Body).Decode(&successPayload); err != nil { 85 | return successPayload, localVarHttpResponse, err 86 | } 87 | 88 | return successPayload, localVarHttpResponse, err 89 | } 90 | 91 | /* StatsApiService Get historical exchange-wide and per-series turnover and volume statistics. 92 | 93 | @return []StatsHistory*/ 94 | func (a *StatsApiService) StatsHistory() ([]StatsHistory, *http.Response, error) { 95 | var ( 96 | localVarHttpMethod = strings.ToUpper("Get") 97 | localVarPostBody interface{} 98 | localVarFileName string 99 | localVarFileBytes []byte 100 | successPayload []StatsHistory 101 | ) 102 | 103 | // create path and map variables 104 | localVarPath := a.client.cfg.BasePath + "/stats/history" 105 | 106 | localVarHeaderParams := make(map[string]string) 107 | localVarQueryParams := url.Values{} 108 | localVarFormParams := url.Values{} 109 | 110 | // to determine the Content-Type header 111 | localVarHttpContentTypes := []string{"application/json", "application/x-www-form-urlencoded"} 112 | 113 | // set Content-Type header 114 | localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) 115 | if localVarHttpContentType != "" { 116 | localVarHeaderParams["Content-Type"] = localVarHttpContentType 117 | } 118 | 119 | // to determine the Accept header 120 | localVarHttpHeaderAccepts := []string{ 121 | "application/json", 122 | "application/xml", 123 | "text/xml", 124 | "application/javascript", 125 | "text/javascript", 126 | } 127 | 128 | // set Accept header 129 | localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) 130 | if localVarHttpHeaderAccept != "" { 131 | localVarHeaderParams["Accept"] = localVarHttpHeaderAccept 132 | } 133 | r, err := a.client.prepareRequest(nil, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) 134 | if err != nil { 135 | return successPayload, nil, err 136 | } 137 | 138 | localVarHttpResponse, err := a.client.callAPI(r) 139 | if err != nil || localVarHttpResponse == nil { 140 | return successPayload, localVarHttpResponse, err 141 | } 142 | defer localVarHttpResponse.Body.Close() 143 | if localVarHttpResponse.StatusCode >= 300 { 144 | return successPayload, localVarHttpResponse, reportError(localVarHttpResponse.Status) 145 | } 146 | 147 | if err = json.NewDecoder(localVarHttpResponse.Body).Decode(&successPayload); err != nil { 148 | return successPayload, localVarHttpResponse, err 149 | } 150 | 151 | return successPayload, localVarHttpResponse, err 152 | } 153 | 154 | /* StatsApiService Get a summary of exchange statistics in USD. 155 | 156 | @return []StatsUsd*/ 157 | func (a *StatsApiService) StatsHistoryUSD() ([]StatsUsd, *http.Response, error) { 158 | var ( 159 | localVarHttpMethod = strings.ToUpper("Get") 160 | localVarPostBody interface{} 161 | localVarFileName string 162 | localVarFileBytes []byte 163 | successPayload []StatsUsd 164 | ) 165 | 166 | // create path and map variables 167 | localVarPath := a.client.cfg.BasePath + "/stats/historyUSD" 168 | 169 | localVarHeaderParams := make(map[string]string) 170 | localVarQueryParams := url.Values{} 171 | localVarFormParams := url.Values{} 172 | 173 | // to determine the Content-Type header 174 | localVarHttpContentTypes := []string{"application/json", "application/x-www-form-urlencoded"} 175 | 176 | // set Content-Type header 177 | localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) 178 | if localVarHttpContentType != "" { 179 | localVarHeaderParams["Content-Type"] = localVarHttpContentType 180 | } 181 | 182 | // to determine the Accept header 183 | localVarHttpHeaderAccepts := []string{ 184 | "application/json", 185 | "application/xml", 186 | "text/xml", 187 | "application/javascript", 188 | "text/javascript", 189 | } 190 | 191 | // set Accept header 192 | localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) 193 | if localVarHttpHeaderAccept != "" { 194 | localVarHeaderParams["Accept"] = localVarHttpHeaderAccept 195 | } 196 | r, err := a.client.prepareRequest(nil, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) 197 | if err != nil { 198 | return successPayload, nil, err 199 | } 200 | 201 | localVarHttpResponse, err := a.client.callAPI(r) 202 | if err != nil || localVarHttpResponse == nil { 203 | return successPayload, localVarHttpResponse, err 204 | } 205 | defer localVarHttpResponse.Body.Close() 206 | if localVarHttpResponse.StatusCode >= 300 { 207 | return successPayload, localVarHttpResponse, reportError(localVarHttpResponse.Status) 208 | } 209 | 210 | if err = json.NewDecoder(localVarHttpResponse.Body).Decode(&successPayload); err != nil { 211 | return successPayload, localVarHttpResponse, err 212 | } 213 | 214 | return successPayload, localVarHttpResponse, err 215 | } 216 | -------------------------------------------------------------------------------- /swagger/stats_history.go: -------------------------------------------------------------------------------- 1 | /* 2 | * BitMEX API 3 | * 4 | * ## REST API for the BitMEX Trading Platform [View Changelog](/app/apiChangelog) #### Getting Started ##### Fetching Data All REST endpoints are documented below. You can try out any query right from this interface. Most table queries accept `count`, `start`, and `reverse` params. Set `reverse=true` to get rows newest-first. Additional documentation regarding filters, timestamps, and authentication is available in [the main API documentation](https://www.bitmex.com/app/restAPI). *All* table data is available via the [Websocket](/app/wsAPI). We highly recommend using the socket if you want to have the quickest possible data without being subject to ratelimits. ##### Return Types By default, all data is returned as JSON. Send `?_format=csv` to get CSV data or `?_format=xml` to get XML data. ##### Trade Data Queries *This is only a small subset of what is available, to get you started.* Fill in the parameters and click the `Try it out!` button to try any of these queries. * [Pricing Data](#!/Quote/Quote_get) * [Trade Data](#!/Trade/Trade_get) * [OrderBook Data](#!/OrderBook/OrderBook_getL2) * [Settlement Data](#!/Settlement/Settlement_get) * [Exchange Statistics](#!/Stats/Stats_history) Every function of the BitMEX.com platform is exposed here and documented. Many more functions are available. ##### Swagger Specification [⇩ Download Swagger JSON](swagger.json) ## All API Endpoints Click to expand a section. 5 | * 6 | * OpenAPI spec version: 1.2.0 7 | * Contact: support@bitmex.com 8 | * Generated by: https://github.com/swagger-api/swagger-codegen.git 9 | */ 10 | 11 | package swagger 12 | 13 | import ( 14 | "time" 15 | ) 16 | 17 | type StatsHistory struct { 18 | Date time.Time `json:"date"` 19 | 20 | RootSymbol string `json:"rootSymbol"` 21 | 22 | Currency string `json:"currency,omitempty"` 23 | 24 | Volume float32 `json:"volume,omitempty"` 25 | 26 | Turnover float32 `json:"turnover,omitempty"` 27 | } 28 | -------------------------------------------------------------------------------- /swagger/stats_usd.go: -------------------------------------------------------------------------------- 1 | /* 2 | * BitMEX API 3 | * 4 | * ## REST API for the BitMEX Trading Platform [View Changelog](/app/apiChangelog) #### Getting Started ##### Fetching Data All REST endpoints are documented below. You can try out any query right from this interface. Most table queries accept `count`, `start`, and `reverse` params. Set `reverse=true` to get rows newest-first. Additional documentation regarding filters, timestamps, and authentication is available in [the main API documentation](https://www.bitmex.com/app/restAPI). *All* table data is available via the [Websocket](/app/wsAPI). We highly recommend using the socket if you want to have the quickest possible data without being subject to ratelimits. ##### Return Types By default, all data is returned as JSON. Send `?_format=csv` to get CSV data or `?_format=xml` to get XML data. ##### Trade Data Queries *This is only a small subset of what is available, to get you started.* Fill in the parameters and click the `Try it out!` button to try any of these queries. * [Pricing Data](#!/Quote/Quote_get) * [Trade Data](#!/Trade/Trade_get) * [OrderBook Data](#!/OrderBook/OrderBook_getL2) * [Settlement Data](#!/Settlement/Settlement_get) * [Exchange Statistics](#!/Stats/Stats_history) Every function of the BitMEX.com platform is exposed here and documented. Many more functions are available. ##### Swagger Specification [⇩ Download Swagger JSON](swagger.json) ## All API Endpoints Click to expand a section. 5 | * 6 | * OpenAPI spec version: 1.2.0 7 | * Contact: support@bitmex.com 8 | * Generated by: https://github.com/swagger-api/swagger-codegen.git 9 | */ 10 | 11 | package swagger 12 | 13 | type StatsUsd struct { 14 | RootSymbol string `json:"rootSymbol"` 15 | 16 | Currency string `json:"currency,omitempty"` 17 | 18 | Turnover24h float32 `json:"turnover24h,omitempty"` 19 | 20 | Turnover30d float32 `json:"turnover30d,omitempty"` 21 | 22 | Turnover365d float32 `json:"turnover365d,omitempty"` 23 | 24 | Turnover float32 `json:"turnover,omitempty"` 25 | } 26 | -------------------------------------------------------------------------------- /swagger/trade.go: -------------------------------------------------------------------------------- 1 | /* 2 | * BitMEX API 3 | * 4 | * ## REST API for the BitMEX Trading Platform [View Changelog](/app/apiChangelog) #### Getting Started ##### Fetching Data All REST endpoints are documented below. You can try out any query right from this interface. Most table queries accept `count`, `start`, and `reverse` params. Set `reverse=true` to get rows newest-first. Additional documentation regarding filters, timestamps, and authentication is available in [the main API documentation](https://www.bitmex.com/app/restAPI). *All* table data is available via the [Websocket](/app/wsAPI). We highly recommend using the socket if you want to have the quickest possible data without being subject to ratelimits. ##### Return Types By default, all data is returned as JSON. Send `?_format=csv` to get CSV data or `?_format=xml` to get XML data. ##### Trade Data Queries *This is only a small subset of what is available, to get you started.* Fill in the parameters and click the `Try it out!` button to try any of these queries. * [Pricing Data](#!/Quote/Quote_get) * [Trade Data](#!/Trade/Trade_get) * [OrderBook Data](#!/OrderBook/OrderBook_getL2) * [Settlement Data](#!/Settlement/Settlement_get) * [Exchange Statistics](#!/Stats/Stats_history) Every function of the BitMEX.com platform is exposed here and documented. Many more functions are available. ##### Swagger Specification [⇩ Download Swagger JSON](swagger.json) ## All API Endpoints Click to expand a section. 5 | * 6 | * OpenAPI spec version: 1.2.0 7 | * Contact: support@bitmex.com 8 | * Generated by: https://github.com/swagger-api/swagger-codegen.git 9 | */ 10 | 11 | package swagger 12 | 13 | import ( 14 | "time" 15 | ) 16 | 17 | // Individual & Bucketed Trades 18 | type Trade struct { 19 | Timestamp time.Time `json:"timestamp"` 20 | 21 | Symbol string `json:"symbol"` 22 | 23 | Side string `json:"side,omitempty"` 24 | 25 | Size float32 `json:"size,omitempty"` 26 | 27 | Price float64 `json:"price,omitempty"` 28 | 29 | TickDirection string `json:"tickDirection,omitempty"` 30 | 31 | TrdMatchID string `json:"trdMatchID,omitempty"` 32 | 33 | GrossValue float32 `json:"grossValue,omitempty"` 34 | 35 | HomeNotional float64 `json:"homeNotional,omitempty"` 36 | 37 | ForeignNotional float64 `json:"foreignNotional,omitempty"` 38 | } 39 | -------------------------------------------------------------------------------- /swagger/trade_bin.go: -------------------------------------------------------------------------------- 1 | /* 2 | * BitMEX API 3 | * 4 | * ## REST API for the BitMEX Trading Platform [View Changelog](/app/apiChangelog) #### Getting Started ##### Fetching Data All REST endpoints are documented below. You can try out any query right from this interface. Most table queries accept `count`, `start`, and `reverse` params. Set `reverse=true` to get rows newest-first. Additional documentation regarding filters, timestamps, and authentication is available in [the main API documentation](https://www.bitmex.com/app/restAPI). *All* table data is available via the [Websocket](/app/wsAPI). We highly recommend using the socket if you want to have the quickest possible data without being subject to ratelimits. ##### Return Types By default, all data is returned as JSON. Send `?_format=csv` to get CSV data or `?_format=xml` to get XML data. ##### Trade Data Queries *This is only a small subset of what is available, to get you started.* Fill in the parameters and click the `Try it out!` button to try any of these queries. * [Pricing Data](#!/Quote/Quote_get) * [Trade Data](#!/Trade/Trade_get) * [OrderBook Data](#!/OrderBook/OrderBook_getL2) * [Settlement Data](#!/Settlement/Settlement_get) * [Exchange Statistics](#!/Stats/Stats_history) Every function of the BitMEX.com platform is exposed here and documented. Many more functions are available. ##### Swagger Specification [⇩ Download Swagger JSON](swagger.json) ## All API Endpoints Click to expand a section. 5 | * 6 | * OpenAPI spec version: 1.2.0 7 | * Contact: support@bitmex.com 8 | * Generated by: https://github.com/swagger-api/swagger-codegen.git 9 | */ 10 | 11 | package swagger 12 | 13 | import ( 14 | "time" 15 | ) 16 | 17 | type TradeBin struct { 18 | Timestamp time.Time `json:"timestamp"` 19 | 20 | Symbol string `json:"symbol"` 21 | 22 | Open float64 `json:"open,omitempty"` 23 | 24 | High float64 `json:"high,omitempty"` 25 | 26 | Low float64 `json:"low,omitempty"` 27 | 28 | Close float64 `json:"close,omitempty"` 29 | 30 | Trades float32 `json:"trades,omitempty"` 31 | 32 | Volume float32 `json:"volume,omitempty"` 33 | 34 | Vwap float64 `json:"vwap,omitempty"` 35 | 36 | LastSize float32 `json:"lastSize,omitempty"` 37 | 38 | Turnover float32 `json:"turnover,omitempty"` 39 | 40 | HomeNotional float64 `json:"homeNotional,omitempty"` 41 | 42 | ForeignNotional float64 `json:"foreignNotional,omitempty"` 43 | } 44 | -------------------------------------------------------------------------------- /swagger/transaction.go: -------------------------------------------------------------------------------- 1 | /* 2 | * BitMEX API 3 | * 4 | * ## REST API for the BitMEX Trading Platform [View Changelog](/app/apiChangelog) #### Getting Started ##### Fetching Data All REST endpoints are documented below. You can try out any query right from this interface. Most table queries accept `count`, `start`, and `reverse` params. Set `reverse=true` to get rows newest-first. Additional documentation regarding filters, timestamps, and authentication is available in [the main API documentation](https://www.bitmex.com/app/restAPI). *All* table data is available via the [Websocket](/app/wsAPI). We highly recommend using the socket if you want to have the quickest possible data without being subject to ratelimits. ##### Return Types By default, all data is returned as JSON. Send `?_format=csv` to get CSV data or `?_format=xml` to get XML data. ##### Trade Data Queries *This is only a small subset of what is available, to get you started.* Fill in the parameters and click the `Try it out!` button to try any of these queries. * [Pricing Data](#!/Quote/Quote_get) * [Trade Data](#!/Trade/Trade_get) * [OrderBook Data](#!/OrderBook/OrderBook_getL2) * [Settlement Data](#!/Settlement/Settlement_get) * [Exchange Statistics](#!/Stats/Stats_history) Every function of the BitMEX.com platform is exposed here and documented. Many more functions are available. ##### Swagger Specification [⇩ Download Swagger JSON](swagger.json) ## All API Endpoints Click to expand a section. 5 | * 6 | * OpenAPI spec version: 1.2.0 7 | * Contact: support@bitmex.com 8 | * Generated by: https://github.com/swagger-api/swagger-codegen.git 9 | */ 10 | 11 | package swagger 12 | 13 | import ( 14 | "time" 15 | ) 16 | 17 | type Transaction struct { 18 | TransactID string `json:"transactID"` 19 | 20 | Account float32 `json:"account,omitempty"` 21 | 22 | Currency string `json:"currency,omitempty"` 23 | 24 | TransactType string `json:"transactType,omitempty"` 25 | 26 | Amount float32 `json:"amount,omitempty"` 27 | 28 | Fee float32 `json:"fee,omitempty"` 29 | 30 | TransactStatus string `json:"transactStatus,omitempty"` 31 | 32 | Address string `json:"address,omitempty"` 33 | 34 | Tx string `json:"tx,omitempty"` 35 | 36 | Text string `json:"text,omitempty"` 37 | 38 | TransactTime time.Time `json:"transactTime,omitempty"` 39 | 40 | Timestamp time.Time `json:"timestamp,omitempty"` 41 | } 42 | -------------------------------------------------------------------------------- /swagger/user.go: -------------------------------------------------------------------------------- 1 | /* 2 | * BitMEX API 3 | * 4 | * ## REST API for the BitMEX Trading Platform [View Changelog](/app/apiChangelog) #### Getting Started ##### Fetching Data All REST endpoints are documented below. You can try out any query right from this interface. Most table queries accept `count`, `start`, and `reverse` params. Set `reverse=true` to get rows newest-first. Additional documentation regarding filters, timestamps, and authentication is available in [the main API documentation](https://www.bitmex.com/app/restAPI). *All* table data is available via the [Websocket](/app/wsAPI). We highly recommend using the socket if you want to have the quickest possible data without being subject to ratelimits. ##### Return Types By default, all data is returned as JSON. Send `?_format=csv` to get CSV data or `?_format=xml` to get XML data. ##### Trade Data Queries *This is only a small subset of what is available, to get you started.* Fill in the parameters and click the `Try it out!` button to try any of these queries. * [Pricing Data](#!/Quote/Quote_get) * [Trade Data](#!/Trade/Trade_get) * [OrderBook Data](#!/OrderBook/OrderBook_getL2) * [Settlement Data](#!/Settlement/Settlement_get) * [Exchange Statistics](#!/Stats/Stats_history) Every function of the BitMEX.com platform is exposed here and documented. Many more functions are available. ##### Swagger Specification [⇩ Download Swagger JSON](swagger.json) ## All API Endpoints Click to expand a section. 5 | * 6 | * OpenAPI spec version: 1.2.0 7 | * Contact: support@bitmex.com 8 | * Generated by: https://github.com/swagger-api/swagger-codegen.git 9 | */ 10 | 11 | package swagger 12 | 13 | import ( 14 | "time" 15 | ) 16 | 17 | // Account Operations 18 | type User struct { 19 | Id float32 `json:"id,omitempty"` 20 | 21 | OwnerId float32 `json:"ownerId,omitempty"` 22 | 23 | Firstname string `json:"firstname,omitempty"` 24 | 25 | Lastname string `json:"lastname,omitempty"` 26 | 27 | Username string `json:"username"` 28 | 29 | Email string `json:"email"` 30 | 31 | Phone string `json:"phone,omitempty"` 32 | 33 | Created time.Time `json:"created,omitempty"` 34 | 35 | LastUpdated time.Time `json:"lastUpdated,omitempty"` 36 | 37 | Preferences *UserPreferences `json:"preferences,omitempty"` 38 | 39 | TFAEnabled string `json:"TFAEnabled,omitempty"` 40 | 41 | AffiliateID string `json:"affiliateID,omitempty"` 42 | 43 | PgpPubKey string `json:"pgpPubKey,omitempty"` 44 | 45 | Country string `json:"country,omitempty"` 46 | } 47 | -------------------------------------------------------------------------------- /swagger/user_commission.go: -------------------------------------------------------------------------------- 1 | /* 2 | * BitMEX API 3 | * 4 | * ## REST API for the BitMEX Trading Platform [View Changelog](/app/apiChangelog) #### Getting Started ##### Fetching Data All REST endpoints are documented below. You can try out any query right from this interface. Most table queries accept `count`, `start`, and `reverse` params. Set `reverse=true` to get rows newest-first. Additional documentation regarding filters, timestamps, and authentication is available in [the main API documentation](https://www.bitmex.com/app/restAPI). *All* table data is available via the [Websocket](/app/wsAPI). We highly recommend using the socket if you want to have the quickest possible data without being subject to ratelimits. ##### Return Types By default, all data is returned as JSON. Send `?_format=csv` to get CSV data or `?_format=xml` to get XML data. ##### Trade Data Queries *This is only a small subset of what is available, to get you started.* Fill in the parameters and click the `Try it out!` button to try any of these queries. * [Pricing Data](#!/Quote/Quote_get) * [Trade Data](#!/Trade/Trade_get) * [OrderBook Data](#!/OrderBook/OrderBook_getL2) * [Settlement Data](#!/Settlement/Settlement_get) * [Exchange Statistics](#!/Stats/Stats_history) Every function of the BitMEX.com platform is exposed here and documented. Many more functions are available. ##### Swagger Specification [⇩ Download Swagger JSON](swagger.json) ## All API Endpoints Click to expand a section. 5 | * 6 | * OpenAPI spec version: 1.2.0 7 | * Contact: support@bitmex.com 8 | * Generated by: https://github.com/swagger-api/swagger-codegen.git 9 | */ 10 | 11 | package swagger 12 | 13 | type UserCommission struct { 14 | MakerFee float64 `json:"makerFee,omitempty"` 15 | 16 | TakerFee float64 `json:"takerFee,omitempty"` 17 | 18 | SettlementFee float64 `json:"settlementFee,omitempty"` 19 | 20 | MaxFee float64 `json:"maxFee,omitempty"` 21 | } 22 | -------------------------------------------------------------------------------- /swagger/user_preferences.go: -------------------------------------------------------------------------------- 1 | /* 2 | * BitMEX API 3 | * 4 | * ## REST API for the BitMEX Trading Platform [View Changelog](/app/apiChangelog) #### Getting Started ##### Fetching Data All REST endpoints are documented below. You can try out any query right from this interface. Most table queries accept `count`, `start`, and `reverse` params. Set `reverse=true` to get rows newest-first. Additional documentation regarding filters, timestamps, and authentication is available in [the main API documentation](https://www.bitmex.com/app/restAPI). *All* table data is available via the [Websocket](/app/wsAPI). We highly recommend using the socket if you want to have the quickest possible data without being subject to ratelimits. ##### Return Types By default, all data is returned as JSON. Send `?_format=csv` to get CSV data or `?_format=xml` to get XML data. ##### Trade Data Queries *This is only a small subset of what is available, to get you started.* Fill in the parameters and click the `Try it out!` button to try any of these queries. * [Pricing Data](#!/Quote/Quote_get) * [Trade Data](#!/Trade/Trade_get) * [OrderBook Data](#!/OrderBook/OrderBook_getL2) * [Settlement Data](#!/Settlement/Settlement_get) * [Exchange Statistics](#!/Stats/Stats_history) Every function of the BitMEX.com platform is exposed here and documented. Many more functions are available. ##### Swagger Specification [⇩ Download Swagger JSON](swagger.json) ## All API Endpoints Click to expand a section. 5 | * 6 | * OpenAPI spec version: 1.2.0 7 | * Contact: support@bitmex.com 8 | * Generated by: https://github.com/swagger-api/swagger-codegen.git 9 | */ 10 | 11 | package swagger 12 | 13 | import ( 14 | "time" 15 | ) 16 | 17 | type UserPreferences struct { 18 | AlertOnLiquidations bool `json:"alertOnLiquidations,omitempty"` 19 | 20 | AnimationsEnabled bool `json:"animationsEnabled,omitempty"` 21 | 22 | AnnouncementsLastSeen time.Time `json:"announcementsLastSeen,omitempty"` 23 | 24 | ChatChannelID float64 `json:"chatChannelID,omitempty"` 25 | 26 | ColorTheme string `json:"colorTheme,omitempty"` 27 | 28 | Currency string `json:"currency,omitempty"` 29 | 30 | Debug bool `json:"debug,omitempty"` 31 | 32 | DisableEmails []string `json:"disableEmails,omitempty"` 33 | 34 | HideConfirmDialogs []string `json:"hideConfirmDialogs,omitempty"` 35 | 36 | HideConnectionModal bool `json:"hideConnectionModal,omitempty"` 37 | 38 | HideFromLeaderboard bool `json:"hideFromLeaderboard,omitempty"` 39 | 40 | HideNameFromLeaderboard bool `json:"hideNameFromLeaderboard,omitempty"` 41 | 42 | HideNotifications []string `json:"hideNotifications,omitempty"` 43 | 44 | Locale string `json:"locale,omitempty"` 45 | 46 | MsgsSeen []string `json:"msgsSeen,omitempty"` 47 | 48 | OrderBookBinning *interface{} `json:"orderBookBinning,omitempty"` 49 | 50 | OrderBookType string `json:"orderBookType,omitempty"` 51 | 52 | OrderClearImmediate bool `json:"orderClearImmediate,omitempty"` 53 | 54 | OrderControlsPlusMinus bool `json:"orderControlsPlusMinus,omitempty"` 55 | 56 | Sounds []string `json:"sounds,omitempty"` 57 | 58 | StrictIPCheck bool `json:"strictIPCheck,omitempty"` 59 | 60 | StrictTimeout bool `json:"strictTimeout,omitempty"` 61 | 62 | TickerGroup string `json:"tickerGroup,omitempty"` 63 | 64 | TickerPinned bool `json:"tickerPinned,omitempty"` 65 | 66 | TradeLayout string `json:"tradeLayout,omitempty"` 67 | } 68 | -------------------------------------------------------------------------------- /swagger/wallet.go: -------------------------------------------------------------------------------- 1 | /* 2 | * BitMEX API 3 | * 4 | * ## REST API for the BitMEX Trading Platform [View Changelog](/app/apiChangelog) #### Getting Started ##### Fetching Data All REST endpoints are documented below. You can try out any query right from this interface. Most table queries accept `count`, `start`, and `reverse` params. Set `reverse=true` to get rows newest-first. Additional documentation regarding filters, timestamps, and authentication is available in [the main API documentation](https://www.bitmex.com/app/restAPI). *All* table data is available via the [Websocket](/app/wsAPI). We highly recommend using the socket if you want to have the quickest possible data without being subject to ratelimits. ##### Return Types By default, all data is returned as JSON. Send `?_format=csv` to get CSV data or `?_format=xml` to get XML data. ##### Trade Data Queries *This is only a small subset of what is available, to get you started.* Fill in the parameters and click the `Try it out!` button to try any of these queries. * [Pricing Data](#!/Quote/Quote_get) * [Trade Data](#!/Trade/Trade_get) * [OrderBook Data](#!/OrderBook/OrderBook_getL2) * [Settlement Data](#!/Settlement/Settlement_get) * [Exchange Statistics](#!/Stats/Stats_history) Every function of the BitMEX.com platform is exposed here and documented. Many more functions are available. ##### Swagger Specification [⇩ Download Swagger JSON](swagger.json) ## All API Endpoints Click to expand a section. 5 | * 6 | * OpenAPI spec version: 1.2.0 7 | * Contact: support@bitmex.com 8 | * Generated by: https://github.com/swagger-api/swagger-codegen.git 9 | */ 10 | 11 | package swagger 12 | 13 | import ( 14 | "time" 15 | ) 16 | 17 | type Wallet struct { 18 | Account float32 `json:"account"` 19 | 20 | Currency string `json:"currency"` 21 | 22 | PrevDeposited float32 `json:"prevDeposited,omitempty"` 23 | 24 | PrevWithdrawn float32 `json:"prevWithdrawn,omitempty"` 25 | 26 | PrevTransferIn float32 `json:"prevTransferIn,omitempty"` 27 | 28 | PrevTransferOut float32 `json:"prevTransferOut,omitempty"` 29 | 30 | PrevAmount float32 `json:"prevAmount,omitempty"` 31 | 32 | PrevTimestamp time.Time `json:"prevTimestamp,omitempty"` 33 | 34 | DeltaDeposited float32 `json:"deltaDeposited,omitempty"` 35 | 36 | DeltaWithdrawn float32 `json:"deltaWithdrawn,omitempty"` 37 | 38 | DeltaTransferIn float32 `json:"deltaTransferIn,omitempty"` 39 | 40 | DeltaTransferOut float32 `json:"deltaTransferOut,omitempty"` 41 | 42 | DeltaAmount float32 `json:"deltaAmount,omitempty"` 43 | 44 | Deposited float32 `json:"deposited,omitempty"` 45 | 46 | Withdrawn float32 `json:"withdrawn,omitempty"` 47 | 48 | TransferIn float32 `json:"transferIn,omitempty"` 49 | 50 | TransferOut float32 `json:"transferOut,omitempty"` 51 | 52 | Amount float32 `json:"amount,omitempty"` 53 | 54 | PendingCredit float32 `json:"pendingCredit,omitempty"` 55 | 56 | PendingDebit float32 `json:"pendingDebit,omitempty"` 57 | 58 | ConfirmedDebit float32 `json:"confirmedDebit,omitempty"` 59 | 60 | Timestamp time.Time `json:"timestamp,omitempty"` 61 | 62 | Addr string `json:"addr,omitempty"` 63 | 64 | Script string `json:"script,omitempty"` 65 | 66 | WithdrawalLock []string `json:"withdrawalLock,omitempty"` 67 | } 68 | -------------------------------------------------------------------------------- /swagger/x_any.go: -------------------------------------------------------------------------------- 1 | /* 2 | * BitMEX API 3 | * 4 | * ## REST API for the BitMEX Trading Platform [View Changelog](/app/apiChangelog) #### Getting Started ##### Fetching Data All REST endpoints are documented below. You can try out any query right from this interface. Most table queries accept `count`, `start`, and `reverse` params. Set `reverse=true` to get rows newest-first. Additional documentation regarding filters, timestamps, and authentication is available in [the main API documentation](https://www.bitmex.com/app/restAPI). *All* table data is available via the [Websocket](/app/wsAPI). We highly recommend using the socket if you want to have the quickest possible data without being subject to ratelimits. ##### Return Types By default, all data is returned as JSON. Send `?_format=csv` to get CSV data or `?_format=xml` to get XML data. ##### Trade Data Queries *This is only a small subset of what is available, to get you started.* Fill in the parameters and click the `Try it out!` button to try any of these queries. * [Pricing Data](#!/Quote/Quote_get) * [Trade Data](#!/Trade/Trade_get) * [OrderBook Data](#!/OrderBook/OrderBook_getL2) * [Settlement Data](#!/Settlement/Settlement_get) * [Exchange Statistics](#!/Stats/Stats_history) Every function of the BitMEX.com platform is exposed here and documented. Many more functions are available. ##### Swagger Specification [⇩ Download Swagger JSON](swagger.json) ## All API Endpoints Click to expand a section. 5 | * 6 | * OpenAPI spec version: 1.2.0 7 | * Contact: support@bitmex.com 8 | * Generated by: https://github.com/swagger-api/swagger-codegen.git 9 | */ 10 | 11 | package swagger 12 | 13 | type XAny struct { 14 | } 15 | -------------------------------------------------------------------------------- /testdata/config.yaml.example: -------------------------------------------------------------------------------- 1 | proxy_url: http://127.0.0.1:1080 2 | testnet: true 3 | key: 8K2Oi0bnRRZ7GK4UJnY-38oj 4 | secret: 9EmGvk8mKX5nWa11y1KyPPGn78Lv2ZEiLx3TH0YasE_oE06y 5 | key2: 0fyfKgWNejv0konUuqEGA2oU 6 | secret2: YhIY9ukZyvoRw_pAf0JpY7UgBs7DR7Fh0gUqXmOlNyfXIhwC -------------------------------------------------------------------------------- /ws_test.go: -------------------------------------------------------------------------------- 1 | package bitmex 2 | 3 | import ( 4 | "fmt" 5 | "log" 6 | "testing" 7 | ) 8 | 9 | func testBitMeX() *BitMEX { 10 | b := New(nil, HostTestnet, "", "", true) 11 | //b.SetHttpProxy("http://127.0.0.1:1081") 12 | return b 13 | } 14 | 15 | func TestBitMEXConnect(t *testing.T) { 16 | b := testBitMeX() 17 | subscribeInfos := []SubscribeInfo{ 18 | {Op: BitmexWSOrderBookL2, Param: "XBTUSD"}, 19 | } 20 | err := b.Subscribe(subscribeInfos) 21 | if err != nil { 22 | log.Fatal(err) 23 | } 24 | 25 | b.On(BitmexWSOrderBookL2, func(ob OrderBookDataL2, symbol string) { 26 | m := ob.OrderBook() 27 | fmt.Printf("\rOrderbook Asks: %#v Bids: %#v ", m.Asks[0], m.Bids[0]) 28 | }) 29 | 30 | b.StartWS() 31 | 32 | select {} 33 | } 34 | 35 | func TestBitMEXWS(t *testing.T) { 36 | b := testBitMeX() 37 | subscribeInfos := []SubscribeInfo{ 38 | {Op: BitmexWSOrderBookL2, Param: "XBTUSD"}, 39 | } 40 | err := b.Subscribe(subscribeInfos) 41 | if err != nil { 42 | log.Fatal(err) 43 | } 44 | 45 | b.On(BitmexWSOrderBookL2, func(ob OrderBookDataL2, symbol string) { 46 | m := ob.OrderBook() 47 | fmt.Printf("\rOrderbook Asks: %#v Bids: %#v ", m.Asks[0], m.Bids[0]) 48 | }) 49 | 50 | b.StartWS() 51 | 52 | select {} 53 | } 54 | 55 | func TestBitMEX_Subscribe(t *testing.T) { 56 | b := testBitMeX() 57 | subscribeInfos := []SubscribeInfo{ 58 | {Op: BitmexWSOrderBookL2_25, Param: "XBTUSD"}, 59 | } 60 | err := b.Subscribe(subscribeInfos) 61 | if err != nil { 62 | log.Fatal(err) 63 | } 64 | 65 | b.On(BitmexWSOrderBookL2_25, func(ob OrderBookDataL2, symbol string) { 66 | m := ob.OrderBook() 67 | fmt.Printf("\rOrderbook Asks: %#v Bids: %#v ", m.Asks[0], m.Bids[0]) 68 | }) 69 | 70 | b.StartWS() 71 | 72 | select {} 73 | } 74 | --------------------------------------------------------------------------------