Skip to content
This repository has been archived by the owner on Jun 9, 2020. It is now read-only.

Commit

Permalink
Init
Browse files Browse the repository at this point in the history
  • Loading branch information
vmpartner committed Apr 9, 2018
1 parent 13c04c5 commit 49a96f9
Show file tree
Hide file tree
Showing 72 changed files with 10,565 additions and 0 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
/.idea
21 changes: 21 additions & 0 deletions bitmex/bitmex.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package bitmex

import (
"encoding/json"
)

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

func DecodeMessage(message []byte) (Response, error) {
var res Response
err := json.Unmarshal(message, &res)

return res, err
}
13 changes: 13 additions & 0 deletions bitmex/bitmex_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package bitmex

import (
"testing"
)

func TestDecodeMessage(t *testing.T) {
message := []byte(`{"Success":true,"Subscribe":"","Request":"","Table":"order","Action":"partial","Data":""}`)
res, err := DecodeMessage(message)
if err != nil || res.Success != true || res.Table != "order" {
t.Error("Error decode message")
}
}
13 changes: 13 additions & 0 deletions config.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
{
"IsDev": false,
"Master": {
"Host": "www.bitmex.com",
"Key": "123",
"Secret": "abc"
},
"Dev": {
"Host": "testnet.bitmex.com",
"Key": "123",
"Secret": "abc"
}
}
40 changes: 40 additions & 0 deletions config/config.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package config

import (
"os"
"encoding/json"
"gitlab.com/vitams/bitmex/tools"
)

type Config struct {
Host string
Key string
Secret string
}

type MasterConfig struct {
IsDev bool
Master Config
Dev Config
}

func LoadConfig(path string) Config {
config := LoadMasterConfig(path)
if config.IsDev {
return config.Dev
}

return config.Master
}

func LoadMasterConfig(path string) MasterConfig {
file, err := os.Open(path)
tools.CheckErr(err)
defer file.Close()
decoder := json.NewDecoder(file)
config := MasterConfig{}
err = decoder.Decode(&config)
tools.CheckErr(err)

return config
}
25 changes: 25 additions & 0 deletions config/config_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package config

import (
"testing"
)

func TestGetConfig(t *testing.T) {
config := LoadConfig("../config.json")
if config.Host == "" {
t.Error("No config")
}
if config.Key == "" {
t.Error("No config")
}
if config.Secret == "" {
t.Error("No config")
}
}

func TestGetMasterConfig(t *testing.T) {
config := LoadMasterConfig("../config.json")
if config.Master.Host == "" {
t.Error("No config")
}
}
76 changes: 76 additions & 0 deletions main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
package main

import (
"github.com/vmpartner/bitmex/config"
"github.com/vmpartner/bitmex/rest"
"github.com/vmpartner/bitmex/websocket"
"fmt"
"strings"
"github.com/vmpartner/bitmex/bitmex"
"github.com/vmpartner/bitmex/tools"
)

// Usage example
func main() {

// Load config
cfg := config.LoadConfig("config.json")
ctx := rest.MakeContext(cfg.Key, cfg.Secret, cfg.Host)

// Get wallet
w, response, err := rest.GetWallet(ctx)
tools.CheckErr(err)
fmt.Printf("Status: %v, wallet amount: %v\n", response.StatusCode, w.Amount)

// Connect to WS
conn := websocket.Connect(cfg.Host)
defer conn.Close()

// Listen read WS
chReadFromWS := make(chan []byte, 100)
go websocket.ReadFromWSToChannel(conn, chReadFromWS)

// Listen write WS
chWriteToWS := make(chan interface{}, 100)
go websocket.WriteFromChannelToWS(conn, chWriteToWS)

// Authorize
chWriteToWS <- websocket.GetAuthMessage(cfg.Key, cfg.Secret)

// Read first response message
message := <-chReadFromWS
if !strings.Contains(string(message), "Welcome to the BitMEX") {
fmt.Println(string(message))
panic("No welcome message")
}

// Read auth response success
message = <-chReadFromWS
res, err := bitmex.DecodeMessage(message)
tools.CheckErr(err)
if res.Success != true || res.Request.(map[string]interface{})["op"] != "authKey" {
panic("No auth response success")
}

// Listen websocket before subscribe
go func() {
for {
message := <-chReadFromWS
res, err := bitmex.DecodeMessage(message)
tools.CheckErr(err)

// Your logic here
fmt.Printf("%+v\n", res)
}
}()

// Subscribe
messageWS := websocket.Message{Op: "subscribe"}
messageWS.AddArgument("orderBookL2:XBTUSD")
messageWS.AddArgument("order")
messageWS.AddArgument("position")
chWriteToWS <- messageWS

// Loop forever
select {}
}
79 changes: 79 additions & 0 deletions rest/rest.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
package rest

import (
"context"
"github.com/vmpartner/bitmex/swagger"
"net/http"
)

func MakeContext(key string, secret string, host string) context.Context {
return context.WithValue(context.TODO(), swagger.ContextAPIKey, swagger.APIKey{
Key: key,
Secret: secret,
Host: host,
})
}

func GetClient(ctx context.Context) *swagger.APIClient {
c := ctx.Value(swagger.ContextAPIKey).(swagger.APIKey)
cfg := &swagger.Configuration{
BasePath: "https://" + c.Host + "/api/v1",
DefaultHeader: make(map[string]string),
UserAgent: "Swagger-Codegen/1.0.0/go",
ExpireTime: 5, //seconds
}

return swagger.NewAPIClient(cfg)
}

func NewOrder(ctx context.Context, params map[string]interface{}) (swagger.Order, *http.Response, error) {
client := GetClient(ctx)
order, response, err := client.OrderApi.OrderNew(ctx, "XBTUSD", params)

return order, response, err
}

func AmendOrder(ctx context.Context, params map[string]interface{}) (swagger.Order, *http.Response, error) {
client := GetClient(ctx)
order, response, err := client.OrderApi.OrderAmend(ctx, params)

return order, response, err
}

func GetOrder(ctx context.Context, params map[string]interface{}) ([]swagger.Order, *http.Response, error) {
client := GetClient(ctx)
orders, response, err := client.OrderApi.OrderGetOrders(ctx, params)

return orders, response, err
}

func GetPosition(ctx context.Context, params map[string]interface{}) ([]swagger.Position, *http.Response, error) {
client := GetClient(ctx)
positions, response, err := client.PositionApi.PositionGet(ctx, params)

return positions, response, err
}

func GetTrade(ctx context.Context, params map[string]interface{}) ([]swagger.Trade, *http.Response, error) {
client := GetClient(ctx)
positions, response, err := client.TradeApi.TradeGet(params)

return positions, response, err
}

func CancelOrder(ctx context.Context, params map[string]interface{}) ([]swagger.Order, *http.Response, error) {
client := GetClient(ctx)
orders, response, err := client.OrderApi.OrderCancel(ctx, params)

return orders, response, err
}

func GetWallet(ctx context.Context) (swagger.Wallet, *http.Response, error) {
params := map[string]interface{}{
"currency": "",
}
client := GetClient(ctx)
wallet, response, err := client.UserApi.UserGetWallet(ctx, params)

return wallet, response, err
}
26 changes: 26 additions & 0 deletions swagger/access_token.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
/*
* BitMEX API
*
* ## 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.
*
* OpenAPI spec version: 1.2.0
* Contact: [email protected]
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/

package swagger

import (
"time"
)

type AccessToken struct {
Id string `json:"id"`

// time to live in seconds (2 weeks by default)
Ttl float64 `json:"ttl,omitempty"`

Created time.Time `json:"created,omitempty"`

UserId float64 `json:"userId,omitempty"`
}
47 changes: 47 additions & 0 deletions swagger/affiliate.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
/*
* BitMEX API
*
* ## 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.
*
* OpenAPI spec version: 1.2.0
* Contact: [email protected]
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/

package swagger

import (
"time"
)

type Affiliate struct {
Account float32 `json:"account"`

Currency string `json:"currency"`

PrevPayout float32 `json:"prevPayout,omitempty"`

PrevTurnover float32 `json:"prevTurnover,omitempty"`

PrevComm float32 `json:"prevComm,omitempty"`

PrevTimestamp time.Time `json:"prevTimestamp,omitempty"`

ExecTurnover float32 `json:"execTurnover,omitempty"`

ExecComm float32 `json:"execComm,omitempty"`

TotalReferrals float32 `json:"totalReferrals,omitempty"`

TotalTurnover float32 `json:"totalTurnover,omitempty"`

TotalComm float32 `json:"totalComm,omitempty"`

PayoutPcnt float64 `json:"payoutPcnt,omitempty"`

PendingPayout float32 `json:"pendingPayout,omitempty"`

Timestamp time.Time `json:"timestamp,omitempty"`

ReferrerAccount float64 `json:"referrerAccount,omitempty"`
}
28 changes: 28 additions & 0 deletions swagger/announcement.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
/*
* BitMEX API
*
* ## 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.
*
* OpenAPI spec version: 1.2.0
* Contact: [email protected]
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/

package swagger

import (
"time"
)

// Public Announcements
type Announcement struct {
Id float32 `json:"id"`

Link string `json:"link,omitempty"`

Title string `json:"title,omitempty"`

Content string `json:"content,omitempty"`

Date time.Time `json:"date,omitempty"`
}
Loading

0 comments on commit 49a96f9

Please sign in to comment.