hitbtc

package module
v0.0.0-...-2adae5a Latest Latest
Warning

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

Go to latest
Published: Feb 1, 2019 License: MIT Imports: 16 Imported by: 7

README

go-hitbtc

go-hitbtc is an implementation of the HitBTC API (public and private) in Golang.

This version implement V2 HitBTC API.

Import

import "github.com/bitbandi/go-hitbtc"

Usage

In order to use the client with go's default http client settings you can do:

package main

import (
	"fmt"
	"github.com/bitbandi/go-hitbtc"
)

const (
	API_KEY    = "YOUR_API_KEY"
	API_SECRET = "YOUR_API_SECRET"
)

func main() {
	// hitbtc client
	hitbtc := hitbtc.New(API_KEY, API_SECRET)

	// Get balances
	balances, err := hitbtc.GetBalances()
	fmt.Println(err, balances)
}

In order to use custom settings for the http client do:

package main

import (
	"fmt"
	"net/http"
	"time"
	"github.com/bitbandi/go-hitbtc"
)

const (
	API_KEY    = "YOUR_API_KEY"
	API_SECRET = "YOUR_API_SECRET"
)

func main() {
	httpClient := &http.Client{
		Timeout: time.Second * 10,
	}

	// hitbtc client
	bc := hitbtc.NewWithCustomHttpClient(conf.hitbtc.ApiKey, conf.hitbtc.ApiSecret, httpClient)

	// Get balances
	balances, err := hitbtc.GetBalances()
	fmt.Println(err, balances)

	// Initialize websocket connection
	client, err := hitbtc.NewWSClient()
	if err != nil {
		handleError(err) // do something
	}
	defer client.Close()

	// Subscribe and handle
	tickerFeed, err := client.SubscribeTicker("ETHBTC")
	for {
		ticker := <-tickerFeed
		fmt.Println(ticker)
	}


}

See "Examples" folder for more... examples

Projects using this library

Documentation

Overview

Package hitbtc is an implementation of the HitBTC API in Golang.

Index

Constants

View Source
const (
	// TransferTypeBankToExchange represent a transfer from bank (withdraw) balance to exchange (trading) balance.
	TransferTypeBankToExchange transferType = "bankToExchange"
	// TransferTypeExchangeToBank represent a transfer from exchange (trading) balance to bank (withdraw) balance.
	TransferTypeExchangeToBank transferType = "exchangeToBank"
)
View Source
const (
	// Interval30Minutes is 30 minutes interval for candle data.
	Interval30Minutes string = "M30"
	// Interval1Hour is 1 hour interval for candle data.
	Interval1Hour string = "H1"
)
View Source
const (
	API_BASE = "https://api.hitbtc.com/api/2" // HitBtc API endpoint
)

Variables

This section is empty.

Functions

func NewClient

func NewClient(apiKey, apiSecret string) (c *client)

NewClient return a new HitBtc HTTP client

func NewClientWithCustomHttpConfig

func NewClientWithCustomHttpConfig(apiKey, apiSecret string, httpClient *http.Client) (c *client)

NewClientWithCustomHttpConfig returns a new HitBtc HTTP client using the predefined http client

func NewClientWithCustomTimeout

func NewClientWithCustomTimeout(apiKey, apiSecret string, timeout time.Duration) (c *client)

NewClient returns a new HitBtc HTTP client with custom timeout

Types

type Balance

type Balance struct {
	Currency  string  `json:"currency"`
	Available float64 `json:"available,string"`
	Reserved  float64 `json:"reserved,string"`
}

Balance represents a cryptocurrency balance on the exchange

type Currency

type Currency struct {
	Id                 string `json:"id"`
	FullName           string `json:"fullName"`
	Crypto             bool   `json:"crypto"`
	PayinEnabled       bool   `json:"payinEnabled"`
	PayinPaymentId     bool   `json:"payinPaymentId"`
	PayinConfirmations uint   `json:"payinConfirmations"`
	PayoutEnabled      bool   `json:"payoutEnabled"`
	PayoutIsPaymentId  bool   `json:"payoutIsPaymentId"`
	TransferEnabled    bool   `json:"transferEnabled"`
}

Currency represents currency data.

type HitBtc

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

HitBtc represent a HitBTC client

func New

func New(apiKey, apiSecret string) *HitBtc

New returns an instantiated HitBTC struct

func NewWithCustomHttpClient

func NewWithCustomHttpClient(apiKey, apiSecret string, httpClient *http.Client) *HitBtc

NewWithCustomHttpClient returns an instantiated HitBTC struct with custom http client

func NewWithCustomTimeout

func NewWithCustomTimeout(apiKey, apiSecret string, timeout time.Duration) *HitBtc

NewWithCustomTimeout returns an instantiated HitBTC struct with custom timeout

func (*HitBtc) CancelOrder

func (b *HitBtc) CancelOrder(currencyPair string) (orders []Order, err error)

CancelOrder cancels a pending order

func (*HitBtc) GetAllTicker

func (b *HitBtc) GetAllTicker() (tickers Tickers, err error)

GetAllTicker is used to get the current ticker values for all markets.

func (*HitBtc) GetBalance

func (b *HitBtc) GetBalance(currency string) (balance Balance, err error)

GetBalance is used to retrieve the balance from your account for a specific currency. currency: a string literal for the currency (ex: LTC)

func (*HitBtc) GetBalances

func (b *HitBtc) GetBalances() (balances []Balance, err error)

GetBalances is used to retrieve all balances from your account

func (*HitBtc) GetCurrencies

func (b *HitBtc) GetCurrencies() (currencies []Currency, err error)

GetCurrencies is used to get all supported currencies at HitBtc along with other meta data.

func (*HitBtc) GetOpenOrders

func (b *HitBtc) GetOpenOrders() (orders []Order, err error)

GetOpenOrders gets the open orders of an user.

func (*HitBtc) GetOrder

func (b *HitBtc) GetOrder(orderId string) (orders []Order, err error)

GetOrder gets a pending order data.

func (*HitBtc) GetOrderHistory

func (b *HitBtc) GetOrderHistory() (orders []Order, err error)

GetOrderHistory gets the history of orders for an user.

func (*HitBtc) GetOrderbook

func (b *HitBtc) GetOrderbook(market string) (orderbook Orderbook, err error)

GetOrderbook is used to get the current order book for a market.

func (*HitBtc) GetSymbols

func (b *HitBtc) GetSymbols() (symbols []Symbol, err error)

GetSymbols is used to get the open and available trading markets at HitBtc along with other meta data.

func (*HitBtc) GetTicker

func (b *HitBtc) GetTicker(market string) (ticker Ticker, err error)

GetTicker is used to get the current ticker values for a market.

func (*HitBtc) GetTrades

func (b *HitBtc) GetTrades(currencyPair string) (trades []Trade, err error)

GetTrades used to retrieve your trade history. market string literal for the market (ie. BTC/LTC). If set to "all", will return for all market

func (*HitBtc) GetTransactions

func (b *HitBtc) GetTransactions(start uint64, end uint64, limit uint32) (transactions []Transaction, err error)

GetTransactions is used to retrieve your withdrawal and deposit history "Start" and "end" are given in UNIX timestamp format in miliseconds and used to specify the date range for the data returned.

func (*HitBtc) PlaceOrder

func (b *HitBtc) PlaceOrder(requestOrder Order) (responseOrder Order, err error)

PlaceOrder creates a new order.

func (*HitBtc) SetDebug

func (b *HitBtc) SetDebug(enable bool)

SetDebug sets enable/disable http request/response dump

func (*HitBtc) TransferBalance

func (b *HitBtc) TransferBalance(currency string, amount float64, transferType transferType) (transferID string, err error)

TransferBalance performs a balance transfer operation between trading and bank accounts (both directions).

func (*HitBtc) Withdraw

func (b *HitBtc) Withdraw(address string, currency string, amount float64) (withdrawID string, err error)

Withdraw performs a withdrawal operation.

type Order

type Order struct {
	ClientOrderId string    `json:"clientOrderId"`
	Symbol        string    `json:"symbol"`
	Side          string    `json:"side"`
	Status        string    `json:"status"`
	Type          string    `json:"type"`
	TimeInForce   string    `json:"timeInForce"`
	Quantity      float64   `json:"quantity,string"`
	Price         float64   `json:"price,string"`
	CumQuantity   float64   `json:"cumQuantity,string"`
	Created       time.Time `json:"createdAt"`
	Updated       time.Time `json:"updatedAt"`
	StopPrice     float64   `json:"stopPrice,string"`
	Expire        time.Time `json:"expireTime"`
}

Order represents an order made on the exchange.

func (*Order) UnmarshalJSON

func (t *Order) UnmarshalJSON(data []byte) error

type OrderBookItem

type OrderBookItem struct {
	Price float64 `json:"price,string"`
	Size  float64 `json:"size,string"`
}

OrderBookItem for Ask and Bid field.

type Orderbook

type Orderbook struct {
	Ask []OrderBookItem `json:"ask,struct"`
	Bid []OrderBookItem `json:"bid,struct"`
}

Orderbook represents an orderbook from hitbtc api.

func (*Orderbook) UnmarshalJSON

func (t *Orderbook) UnmarshalJSON(data []byte) error

UnmarshalJSON for OrderBook function

type Symbol

type Symbol struct {
	Id                   string  `json:"id"`
	BaseCurrency         string  `json:"baseCurrency"`
	QuoteCurrency        string  `json:"quoteCurrency"`
	QuantityIncrement    float64 `json:"quantityIncrement,string"`
	TickSize             float64 `json:"tickSize,string"`
	TakeLiquidityRate    float64 `json:"takeLiquidityRate,string"`
	ProvideLiquidityRate float64 `json:"provideLiquidityRate,string"`
	FeeCurrency          string  `json:"feeCurrency"`
}

Symbol represents data of a Currency Pair on a market.

type Ticker

type Ticker struct {
	Ask         float64   `json:"ask,string"`
	Bid         float64   `json:"bid,string"`
	Last        float64   `json:"last,string"`
	Open        float64   `json:"open,string"`
	Low         float64   `json:"low,string,omitempty"`
	High        float64   `json:"high,string,omitempty"`
	Volume      float64   `json:"volume,string"`
	VolumeQuote float64   `json:"volumeQuote,string"`
	Timestamp   time.Time `json:"timestamp"`
	Symbol      string    `json:"symbol"`
}

Ticker represents a Ticker from hitbtc API.

func (*Ticker) UnmarshalJSON

func (t *Ticker) UnmarshalJSON(data []byte) error

type Tickers

type Tickers []Ticker

type Trade

type Trade struct {
	Id            uint64    `json:"id"`
	OrderId       uint64    `json:"orderId"`
	ClientOrderId string    `json:"clientOrderId"`
	Symbol        string    `json:"symbol"`
	Type          string    `json:"side"`
	Price         float64   `json:"price,string"`
	Quantity      float64   `json:"quantity,string"`
	Fee           float64   `json:"fee,string"`
	Timestamp     time.Time `json:"timestamp"`
}

Trade represents a single trade made by a user.

func (*Trade) UnmarshalJSON

func (t *Trade) UnmarshalJSON(data []byte) error

UnmarshalJSON allows the obejct to be JSON Unmarshallable.

type Transaction

type Transaction struct {
	Id         string    `json:"id"`
	Index      uint64    `json:"index"`
	Currency   string    `json:"currency"`
	Amount     float64   `json:"amount,string"`
	Fee        float64   `json:"fee,string"`
	NetworkFee float64   `json:"networkFee,string"`
	Address    string    `json:"address"`
	Hash       string    `json:"hash"`
	Status     string    `json:"status"`
	Type       string    `json:"type"`
	Created    time.Time `json:"createdAt"`
	Updated    time.Time `json:"updatedAt"`
}

Transaction represents a transaction of money incoming or leaving the user account.

func (*Transaction) UnmarshalJSON

func (t *Transaction) UnmarshalJSON(data []byte) error

type WSCandles

type WSCandles struct {
	Timestamp   time.Time `json:"timestamp,required"`
	Open        string    `json:"open,required"`
	Close       string    `json:"close,required"`
	Min         string    `json:"min,required"`
	Max         string    `json:"max,required"`
	Volume      string    `json:"volume,required"`      // Total trading amount within 24 hours in base currency
	VolumeQuote string    `json:"volumeQuote,required"` // Total trading amount within 24 hours in quote currency
}

WSCandles is item for WSCandles

type WSCandlesSubscriptionRequest

type WSCandlesSubscriptionRequest struct {
	Symbol string `json:"symbol,required"`
	Period string `json:"period,required"`
}

WSCandlesSubscriptionRequest is a request to subscribe for candle data.

type WSClient

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

WSClient represents a JSON RPC v2 Connection over Websocket,

func NewWSClient

func NewWSClient() (*WSClient, error)

NewWSClient creates a new WSClient

func (*WSClient) Close

func (c *WSClient) Close()

Close closes the Websocket connected to the hitbtc api.

func (*WSClient) GetCurrencyInfo

func (c *WSClient) GetCurrencyInfo(symbol string) (*WSGetCurrencyResponse, error)

GetCurrencyInfo get the info about a currency.

func (*WSClient) GetSymbol

func (c *WSClient) GetSymbol(symbol string) (*WSGetSymbolResponse, error)

GetSymbol obtains the data of a market.

func (*WSClient) GetTrades

func (c *WSClient) GetTrades(symbol string) (*WSGetTradesResponse, error)

GetTrades obtains the data of a series of trades, based on the specified filters.

func (*WSClient) SubscribeCandles

func (c *WSClient) SubscribeCandles(symbol string, timeframe string) (<-chan WSNotificationCandlesUpdate, <-chan WSNotificationCandlesSnapshot, error)

SubscribeCandles subscribes to the specified market candle notifications for the specified timeframe.

func (*WSClient) SubscribeOrderbook

func (c *WSClient) SubscribeOrderbook(symbol string) (<-chan WSNotificationOrderbookUpdate, <-chan WSNotificationOrderbookSnapshot, error)

SubscribeOrderbook subscribes to the specified market order book notifications.

func (*WSClient) SubscribeTicker

func (c *WSClient) SubscribeTicker(symbol string) (<-chan WSNotificationTickerResponse, error)

SubscribeTicker subscribes to the specified market ticker notifications.

func (*WSClient) SubscribeTrades

func (c *WSClient) SubscribeTrades(symbol string) (<-chan WSNotificationTradesUpdate, <-chan WSNotificationTradesSnapshot, error)

SubscribeTrades subscribes to the specified market trades notifications.

func (*WSClient) UnsubscribeCandles

func (c *WSClient) UnsubscribeCandles(symbol string, timeframe string) error

UnsubscribeCandles unsubscribes from the specified market candle notifications for the specified timeframe.

This closes also the connected channel of updates.

func (*WSClient) UnsubscribeOrderbook

func (c *WSClient) UnsubscribeOrderbook(symbol string) error

UnsubscribeOrderbook unsubscribes from the specified market order book notifications and snapshot.

This closes also the connected channel of updates.

func (*WSClient) UnsubscribeTicker

func (c *WSClient) UnsubscribeTicker(symbol string) error

UnsubscribeTicker subscribes to the specified market ticker notifications.

This closes also the connected channel of updates.

func (*WSClient) UnsubscribeTrades

func (c *WSClient) UnsubscribeTrades(symbol string) error

UnsubscribeTrades unsubscribes from the specified market trades notifications and snapshot.

This closes also the connected channel of updates.

type WSGetCurrencyRequest

type WSGetCurrencyRequest struct {
	Currency string `json:"currency,required"`
}

WSGetCurrencyRequest is get currency request type on websocket

type WSGetCurrencyResponse

type WSGetCurrencyResponse struct {
	ID                 string `json:"id,required"`
	FullName           string `json:"fullname,required"`
	Crypto             bool   `json:"crypto,required"`
	PayinEnabled       bool   `json:"payinEnabled,required"`
	PayinPaymentID     bool   `json:"payinPaymentId,required"`
	PayinConfirmations int    `json:"payinConfirmations,required"`
	PayoutEnabled      bool   `json:"payoutEnabled,required"`
	PayoutIsPaymentID  bool   `json:"payoutIsPaymentId,required"`
	TransferEnabled    bool   `json:"transferEnabled,required"`
	Delisted           bool   `json:"delisted,required"`
	PayoutFee          string `json:"payoutFee,required"`
}

WSGetCurrencyResponse is get currency response type on websocket

type WSGetSymbolRequest

type WSGetSymbolRequest struct {
	Symbol string `json:"symbol,required"`
}

WSGetSymbolRequest is get symbols request type on websocket

type WSGetSymbolResponse

type WSGetSymbolResponse struct {
	ID                   string `json:"id,required"`
	BaseCurrency         string `json:"baseCurrency,required"`
	QuoteCurrency        string `json:"quoteCurrency,required"`
	QuantityIncrement    string `json:"quantityIncrement,required"`
	TickSize             string `json:"tickSize,required"`
	TakeLiquidityRate    string `json:"takeLiquidityRate,required"`
	ProvideLiquidityRate string `json:"provideLiquidityRate,required"`
	FeeCurrency          string `json:"feeCurrency,required"`
}

WSGetSymbolResponse is get symbols response type on websocket

type WSGetTradesRequest

type WSGetTradesRequest struct {
	Symbol string     `json:"symbol,required"`
	Limit  int        `json:"limit,required"`
	Sort   string     `json:"sort,required"`
	By     string     `json:"by,required"`
	From   *time.Time `json:"from,omitempty"`
	Till   *time.Time `json:"till,omitempty"`
	Offset *string    `json:"offset,omitempty"`
}

WSGetTradesRequest is get trades request type on websocket

type WSGetTradesResponse

type WSGetTradesResponse struct {
	Data []WSTrades `json:"data,required"`
}

WSGetTradesResponse is get symbols response type on websocket

type WSNotificationCandlesSnapshot

type WSNotificationCandlesSnapshot struct {
	Data   []WSCandles `json:"data,required"`
	Symbol string      `json:"symbol,required"`
	Period string      `json:"period,required"`
}

WSNotificationCandlesSnapshot is subscribe response type to candles on websocket

type WSNotificationCandlesUpdate

type WSNotificationCandlesUpdate struct {
	Data   WSCandles `json:"data,required"`
	Symbol string    `json:"symbol,required"`
	Period string    `json:"period,required"`
}

WSNotificationCandlesUpdate is subscribe response type to candles on websocket

type WSNotificationOrderbookSnapshot

type WSNotificationOrderbookSnapshot struct {
	Ask      []WSSubtypeTrade `json:"ask,required"`
	Bid      []WSSubtypeTrade `json:"bid,required"`
	Symbol   string           `json:"symbol,required"`
	Sequence int64            `json:"sequence,required"` // used to see if update is the latest received
}

WSNotificationOrderbookSnapshot is notification response type to orderbook snapshot on websocket

type WSNotificationOrderbookUpdate

type WSNotificationOrderbookUpdate struct {
	Ask      []WSSubtypeTrade `json:"ask,required"`
	Bid      []WSSubtypeTrade `json:"bid,required"`
	Symbol   string           `json:"symbol,required"`
	Sequence int64            `json:"sequence,required"` // used to see if the snapshot is the latest
}

WSNotificationOrderbookUpdate is notification response type to orderbook snapshot on websocket

type WSNotificationTickerResponse

type WSNotificationTickerResponse struct {
	Ask         string `json:"ask,required"`         // Best ask price
	Bid         string `json:"bid,required"`         // Best bid price
	Last        string `json:"last,required"`        // Last trade price
	Open        string `json:"open,required"`        // Last trade price 24 hours ago
	Low         string `json:"low,required"`         // Lowest trade price within 24 hours
	High        string `json:"high,required"`        // Highest trade price within 24 hours
	Volume      string `json:"volume,required"`      // Total trading amount within 24 hours in base currency
	VolumeQuote string `json:"volumeQuote,required"` // Total trading amount within 24 hours in quote currency
	Timestamp   string `json:"timestamp,required"`   // Last update or refresh ticker timestamp
	Symbol      string `json:"symbol,required"`
}

WSNotificationTickerResponse is notification response type on websocket

type WSNotificationTradesSnapshot

type WSNotificationTradesSnapshot struct {
	Data   []WSTrades `json:"data,required"`
	Symbol string     `json:"symbol,required"`
}

WSNotificationTradesSnapshot is notification response type to trades on websocket

type WSNotificationTradesUpdate

type WSNotificationTradesUpdate struct {
	Data   WSTrades `json:"data,required"`
	Symbol string   `json:"symbol,required"`
}

WSNotificationTradesUpdate is notification response type to trades on websocket

type WSSubscriptionRequest

type WSSubscriptionRequest struct {
	Symbol string `json:"symbol,required"`
}

WSSubscriptionRequest is request type on websocket subscription.

type WSSubtypeTrade

type WSSubtypeTrade struct {
	Price string `json:"price,required"`
	Size  string `json:"size,required"`
}

WSSubtypeTrade is element of market trade type

type WSTrades

type WSTrades struct {
	ID        int    `json:"id,required"`
	Price     string `json:"price,required"`
	Quantity  string `json:"quantity"`
	Side      string `json:"side,required"`
	Timestamp string `json:"timestamp,required"`
}

WSTrades is item for Trades

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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