hitbtc

package
v0.0.0-...-a2c5123 Latest Latest
Warning

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

Go to latest
Published: Sep 26, 2018 License: MIT Imports: 16 Imported by: 0

README

GoCryptoTrader package Hitbtc

Build Status Software License GoDoc Coverage Status Go Report Card

This hitbtc package is part of the GoCryptoTrader codebase.

This is still in active development

You can track ideas, planned features and what's in progresss on this Trello board: https://trello.com/b/ZAhMhpOy/gocryptotrader.

Join our slack to discuss all things related to GoCryptoTrader! GoCryptoTrader Slack

HitBTC Exchange

Current Features
  • REST Support
  • Websocket Support
How to enable
  // Exchanges will be abstracted out in further updates and examples will be
  // supplied then
How to do REST public/private calls
  • If enabled via "configuration".json file the exchange will be added to the IBotExchange array in the go var bot Bot and you will only be able to use the wrapper interface functions for accessing exchange data. View routines.go for an example of integration usage with GoCryptoTrader. Rudimentary example below:

main.go

var h exchange.IBotExchange

for i := range bot.exchanges {
  if bot.exchanges[i].GetName() == "HitBTC" {
    h = bot.exchanges[i]
  }
}

// Public calls - wrapper functions

// Fetches current ticker information
tick, err := h.GetTickerPrice()
if err != nil {
  // Handle error
}

// Fetches current orderbook information
ob, err := h.GetOrderbookEx()
if err != nil {
  // Handle error
}

// Private calls - wrapper functions - make sure your APIKEY and APISECRET are
// set and AuthenticatedAPISupport is set to true

// Fetches current account information
accountInfo, err := h.GetExchangeAccountInfo()
if err != nil {
  // Handle error
}
  • If enabled via individually importing package, rudimentary example below:
// Public calls

// Fetches current ticker information
ticker, err := h.GetTicker()
if err != nil {
  // Handle error
}

// Fetches current orderbook information
ob, err := h.GetOrderBook()
if err != nil {
  // Handle error
}

// Private calls - make sure your APIKEY and APISECRET are set and
// AuthenticatedAPISupport is set to true

// GetUserInfo returns account info
accountInfo, err := h.GetUserInfo(...)
if err != nil {
  // Handle error
}

// Submits an order and the exchange and returns its tradeID
tradeID, err := h.Trade(...)
if err != nil {
  // Handle error
}
How to do Websocket public/private calls
  // Exchanges will be abstracted out in further updates and examples will be
  // supplied then
Please click GoDocs chevron above to view current GoDoc information for this package

Contribution

Please feel free to submit any pull requests or suggest any desired features to be added.

When submitting a PR, please abide by our coding guidelines:

  • Code must adhere to the official Go formatting guidelines (i.e. uses gofmt).
  • Code must be documented adhering to the official Go commentary guidelines.
  • Code must adhere to our coding style.
  • Pull requests need to be based on and opened against the master branch.

Donations

If this framework helped you in any way, or you would like to support the developers working on it, please donate Bitcoin to:

1F5zVDgNjorJ51oGebSvNCrSAHpwGkUdDB

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func OnDepthOrTrade

func OnDepthOrTrade(args []interface{}, kwargs map[string]interface{})

OnDepthOrTrade converts depth and trade data

func OnTicker

func OnTicker(args []interface{}, kwargs map[string]interface{})

OnTicker converts ticker to websocket ticker

func OnTrollbox

func OnTrollbox(args []interface{}, kwargs map[string]interface{})

OnTrollbox converts trollbox messages

Types

type ActiveLoans

type ActiveLoans struct {
	Provided []LoanOffer `json:"provided"`
	Used     []LoanOffer `json:"used"`
}

ActiveLoans holds information about your active loans

type AuthenticatedTradeHistoryAll

type AuthenticatedTradeHistoryAll struct {
	Data map[string][]AuthentictedTradeHistory
}

AuthenticatedTradeHistoryAll contains the full trade history

type AuthenticatedTradeHistoryResponse

type AuthenticatedTradeHistoryResponse struct {
	Data []AuthentictedTradeHistory
}

AuthenticatedTradeHistoryResponse is the resp type for trade history

type AuthentictedTradeHistory

type AuthentictedTradeHistory struct {
	GlobalTradeID int64   `json:"globalTradeID"`
	TradeID       int64   `json:"tradeID,string"`
	Date          string  `json:"date"`
	Rate          float64 `json:"rate,string"`
	Amount        float64 `json:"amount,string"`
	Total         float64 `json:"total,string"`
	Fee           float64 `json:"fee,string"`
	OrderNumber   int64   `json:"orderNumber,string"`
	Type          string  `json:"type"`
	Category      string  `json:"category"`
}

AuthentictedTradeHistory contains trade history data

type Balance

type Balance struct {
	Currency  string  `json:"currency"`
	Available float64 `json:"available,string"` // Amount available for trading or transfer to main account
	Reserved  float64 `json:"reserved,string"`  // Amount reserved for active orders or incomplete transfers to main account

}

Balance is a simple balance type

type ChartData

type ChartData struct {
	Timestamp   time.Time `json:"timestamp,string"`
	Max         float64   `json:"max,string"`         // Max price
	Min         float64   `json:"min,string"`         // Min price
	Open        float64   `json:"open,string"`        // Open price
	Close       float64   `json:"close,string"`       // Close price
	Volume      float64   `json:"volume,string"`      // Volume in base currency
	VolumeQuote float64   `json:"volumeQuote,string"` // Volume in quote currency
}

ChartData contains chart data

type Currencies

type Currencies struct {
	ID                 string `json:"id"`                 // Currency identifier.
	FullName           string `json:"fullName"`           // Currency full name
	Crypto             bool   `json:"crypto,boolean"`     // Is currency belongs to blockchain (false for ICO and fiat, like EUR)
	PayinEnabled       bool   `json:"payinEnabled"`       // Is allowed for deposit (false for ICO)
	PayinPaymentID     bool   `json:"payinPaymentId"`     // Is required to provide additional information other than the address for deposit
	PayinConfirmations int64  `json:"payinConfirmations"` // Blocks confirmations count for deposit
	PayoutEnabled      bool   `json:"payoutEnabled"`      // Is allowed for withdraw (false for ICO)
	PayoutIsPaymentID  bool   `json:"payoutIsPaymentId"`  // Is allowed to provide additional information for withdraw
	TransferEnabled    bool   `json:"transferEnabled"`    // Is allowed to transfer between trading and account (may be disabled on maintain)
}

Currencies hold the full range of data for a specified currency

type DepositCryptoAddresses

type DepositCryptoAddresses struct {
	Address   string `json:"address"`   // Address for deposit
	PaymentID string `json:"paymentId"` // Optional additional parameter. Required for deposit if persist
}

DepositCryptoAddresses contains address information

type Fee

type Fee struct {
	TakeLiquidityRate    float64 `json:"takeLiquidityRate,string"`    // Taker
	ProvideLiquidityRate float64 `json:"provideLiquidityRate,string"` // Maker
}

Fee holds fee structure

type GenericResponse

type GenericResponse struct {
	Success int    `json:"success"`
	Error   string `json:"error"`
}

GenericResponse is the common response from HitBTC

type HitBTC

type HitBTC struct {
	exchange.Base
}

HitBTC is the overarching type across the hitbtc package

func (*HitBTC) CancelAllExchangeOrders

func (h *HitBTC) CancelAllExchangeOrders() error

CancelAllExchangeOrders cancels all orders associated with a currency pair

func (*HitBTC) CancelExchangeOrder

func (h *HitBTC) CancelExchangeOrder(orderID int64) error

CancelExchangeOrder cancels an order by its corresponding ID number

func (*HitBTC) CancelOrder

func (p *HitBTC) CancelOrder(orderID int64) (bool, error)

CancelOrder cancels a specific order by OrderID

func (*HitBTC) GenerateNewAddress

func (p *HitBTC) GenerateNewAddress(currency string) (DepositCryptoAddresses, error)

GenerateNewAddress generates a new deposit address for a currency

func (*HitBTC) GetActiveorders

func (p *HitBTC) GetActiveorders(currency string) ([]Order, error)

GetActiveorders returns all your active orders

func (*HitBTC) GetAuthenticatedTradeHistory

func (p *HitBTC) GetAuthenticatedTradeHistory(currency, start, end string) (interface{}, error)

GetAuthenticatedTradeHistory returns your trade history

func (*HitBTC) GetBalances

func (p *HitBTC) GetBalances() (map[string]Balance, error)

GetBalances returns full balance for your account

func (*HitBTC) GetCandles

func (p *HitBTC) GetCandles(currencyPair, limit, period string) ([]ChartData, error)

GetCandles returns candles which is used for OHLC a specific symbol. Note: Result contain candles only with non zero volume.

func (*HitBTC) GetCurrencies

func (p *HitBTC) GetCurrencies(currency string) (map[string]Currencies, error)

GetCurrencies returns the actual list of available currencies, tokens, ICO etc.

func (*HitBTC) GetDepositAddresses

func (p *HitBTC) GetDepositAddresses(currency string) (DepositCryptoAddresses, error)

GetDepositAddresses returns a deposit address for a specific currency

func (*HitBTC) GetExchangeAccountInfo

func (h *HitBTC) GetExchangeAccountInfo() (exchange.AccountInfo, error)

GetExchangeAccountInfo retrieves balances for all enabled currencies for the HitBTC exchange

func (*HitBTC) GetExchangeDepositAddress

func (h *HitBTC) GetExchangeDepositAddress(cryptocurrency pair.CurrencyItem) (string, error)

GetExchangeDepositAddress returns a deposit address for a specified currency

func (*HitBTC) GetExchangeFundTransferHistory

func (h *HitBTC) GetExchangeFundTransferHistory() ([]exchange.FundHistory, error)

GetExchangeFundTransferHistory returns funding history, deposits and withdrawals

func (*HitBTC) GetExchangeHistory

func (h *HitBTC) GetExchangeHistory(p pair.CurrencyPair, assetType string) ([]exchange.TradeHistory, error)

GetExchangeHistory returns historic trade data since exchange opening.

func (*HitBTC) GetExchangeOrderInfo

func (h *HitBTC) GetExchangeOrderInfo(orderID int64) (exchange.OrderDetail, error)

GetExchangeOrderInfo returns information on a current open order

func (*HitBTC) GetFee

func (p *HitBTC) GetFee() float64

GetFee returns the fee for hitbtc

func (*HitBTC) GetFeeInfo

func (p *HitBTC) GetFeeInfo(currencyPair string) (Fee, error)

GetFeeInfo returns current fee information

func (*HitBTC) GetOrderbook

func (p *HitBTC) GetOrderbook(currencyPair string, limit int) (Orderbook, error)

GetOrderbook an order book is an electronic list of buy and sell orders for a specific symbol, organized by price level.

func (*HitBTC) GetOrderbookEx

func (h *HitBTC) GetOrderbookEx(currencyPair pair.CurrencyPair, assetType string) (orderbook.Base, error)

GetOrderbookEx returns orderbook base on the currency pair

func (*HitBTC) GetSymbols

func (p *HitBTC) GetSymbols(symbol string) ([]string, error)

GetSymbols Return the actual list of currency symbols (currency pairs) traded on HitBTC exchange. The first listed currency of a symbol is called the base currency, and the second currency is called the quote currency. The currency pair indicates how much of the quote currency is needed to purchase one unit of the base currency.

func (*HitBTC) GetSymbolsDetailed

func (p *HitBTC) GetSymbolsDetailed() ([]Symbol, error)

GetSymbolsDetailed is the same as above but returns an array of symbols with all their details.

func (*HitBTC) GetTicker

func (p *HitBTC) GetTicker(symbol string) (map[string]Ticker, error)

GetTicker returns ticker information

func (*HitBTC) GetTickerPrice

func (h *HitBTC) GetTickerPrice(currencyPair pair.CurrencyPair, assetType string) (ticker.Price, error)

GetTickerPrice returns the ticker for a currency pair

func (*HitBTC) GetTradableBalances

func (p *HitBTC) GetTradableBalances() (map[string]map[string]float64, error)

GetTradableBalances returns current tradable balances

func (*HitBTC) GetTrades

func (p *HitBTC) GetTrades(currencyPair, from, till, limit, offset, by, sort string) ([]TradeHistory, error)

GetTrades returns trades from hitbtc

func (*HitBTC) ModifyExchangeOrder

func (h *HitBTC) ModifyExchangeOrder(orderID int64, action exchange.ModifyOrder) (int64, error)

ModifyExchangeOrder will allow of changing orderbook placement and limit to market conversion

func (*HitBTC) MoveOrder

func (p *HitBTC) MoveOrder(orderID int64, rate, amount float64) (MoveOrderResponse, error)

MoveOrder generates a new move order

func (*HitBTC) PlaceOrder

func (p *HitBTC) PlaceOrder(currency string, rate, amount float64, immediate, fillOrKill, buy bool) (OrderResponse, error)

PlaceOrder places an order on the exchange

func (*HitBTC) Run

func (h *HitBTC) Run()

Run implements the HitBTC wrapper

func (*HitBTC) SendAuthenticatedHTTPRequest

func (p *HitBTC) SendAuthenticatedHTTPRequest(method, endpoint string, values url.Values, result interface{}) error

SendAuthenticatedHTTPRequest sends an authenticated http request

func (*HitBTC) SendHTTPRequest

func (p *HitBTC) SendHTTPRequest(path string, result interface{}) error

SendHTTPRequest sends an unauthenticated HTTP request

func (*HitBTC) SetDefaults

func (p *HitBTC) SetDefaults()

SetDefaults sets default settings for hitbtc

func (*HitBTC) Setup

func (p *HitBTC) Setup(exch config.ExchangeConfig)

Setup sets user exchange configuration settings

func (*HitBTC) Start

func (h *HitBTC) Start(wg *sync.WaitGroup)

Start starts the HitBTC go routine

func (*HitBTC) SubmitExchangeOrder

func (h *HitBTC) SubmitExchangeOrder(p pair.CurrencyPair, side exchange.OrderSide, orderType exchange.OrderType, amount, price float64, clientID string) (int64, error)

SubmitExchangeOrder submits a new order

func (*HitBTC) TransferBalance

func (p *HitBTC) TransferBalance(currency, from, to string, amount float64) (bool, error)

TransferBalance transfers a balance

func (*HitBTC) UpdateOrderbook

func (h *HitBTC) UpdateOrderbook(currencyPair pair.CurrencyPair, assetType string) (orderbook.Base, error)

UpdateOrderbook updates and returns the orderbook for a currency pair

func (*HitBTC) UpdateTicker

func (h *HitBTC) UpdateTicker(currencyPair pair.CurrencyPair, assetType string) (ticker.Price, error)

UpdateTicker updates and returns the ticker for a currency pair

func (*HitBTC) WebsocketClient

func (p *HitBTC) WebsocketClient()

WebsocketClient initiates a websocket client

func (*HitBTC) Withdraw

func (p *HitBTC) Withdraw(currency, address string, amount float64) (bool, error)

Withdraw allows for the withdrawal to a specific address

func (*HitBTC) WithdrawCryptoExchangeFunds

func (h *HitBTC) WithdrawCryptoExchangeFunds(address string, cryptocurrency pair.CurrencyItem, amount float64) (string, error)

WithdrawCryptoExchangeFunds returns a withdrawal ID when a withdrawal is submitted

func (*HitBTC) WithdrawFiatExchangeFunds

func (h *HitBTC) WithdrawFiatExchangeFunds(currency pair.CurrencyItem, amount float64) (string, error)

WithdrawFiatExchangeFunds returns a withdrawal ID when a withdrawal is submitted

func (*HitBTC) WithdrawFiatExchangeFundsToInternationalBank

func (h *HitBTC) WithdrawFiatExchangeFundsToInternationalBank(currency pair.CurrencyItem, amount float64) (string, error)

WithdrawFiatExchangeFundsToInternationalBank returns a withdrawal ID when a withdrawal is submitted

type LendingHistory

type LendingHistory struct {
	ID       int64   `json:"id"`
	Currency string  `json:"currency"`
	Rate     float64 `json:"rate,string"`
	Amount   float64 `json:"amount,string"`
	Duration float64 `json:"duration,string"`
	Interest float64 `json:"interest,string"`
	Fee      float64 `json:"fee,string"`
	Earned   float64 `json:"earned,string"`
	Open     string  `json:"open"`
	Close    string  `json:"close"`
}

LendingHistory contains lending history data

type LoanOffer

type LoanOffer struct {
	ID        int64   `json:"id"`
	Rate      float64 `json:"rate,string"`
	Amount    float64 `json:"amount,string"`
	Duration  int     `json:"duration"`
	AutoRenew bool    `json:"autoRenew,int"`
	Date      string  `json:"date"`
}

LoanOffer holds information about your loan offers

type LoanOrder

type LoanOrder struct {
	Rate     float64 `json:"rate,string"`
	Amount   float64 `json:"amount,string"`
	RangeMin int     `json:"rangeMin"`
	RangeMax int     `json:"rangeMax"`
}

LoanOrder contains information about your loans

type LoanOrders

type LoanOrders struct {
	Offers  []LoanOrder `json:"offers"`
	Demands []LoanOrder `json:"demands"`
}

LoanOrders holds information on the full range of loan orders

type Margin

type Margin struct {
	TotalValue    float64 `json:"totalValue,string"`
	ProfitLoss    float64 `json:"pl,string"`
	LendingFees   float64 `json:"lendingFees,string"`
	NetValue      float64 `json:"netValue,string"`
	BorrowedValue float64 `json:"totalBorrowedValue,string"`
	CurrentMargin float64 `json:"currentMargin,string"`
}

Margin holds full margin information

type MarginPosition

type MarginPosition struct {
	Amount            float64 `json:"amount,string"`
	Total             float64 `json:"total,string"`
	BasePrice         float64 `json:"basePrice,string"`
	LiquidiationPrice float64 `json:"liquidiationPrice"`
	ProfitLoss        float64 `json:"pl,string"`
	LendingFees       float64 `json:"lendingFees,string"`
	Type              string  `json:"type"`
}

MarginPosition holds information about your current margin position

type MoveOrderResponse

type MoveOrderResponse struct {
	Success     int                          `json:"success"`
	Error       string                       `json:"error"`
	OrderNumber int64                        `json:"orderNumber,string"`
	Trades      map[string][]ResultingTrades `json:"resultingTrades"`
}

MoveOrderResponse holds information about a move order

type OpenOrdersResponse

type OpenOrdersResponse struct {
	Data []Order
}

OpenOrdersResponse contains open order information

type OpenOrdersResponseAll

type OpenOrdersResponseAll struct {
	Data map[string][]Order
}

OpenOrdersResponseAll holds the full open order response

type Order

type Order struct {
	ID            int64  `json:"id,string"`     //  Unique identifier for Order as assigned by exchange
	ClientOrderID string `json:"clientOrderId"` // Unique identifier for Order as assigned by trader. Uniqueness must be
	// guaranteed within a single trading day, including all active orders.
	Symbol      string `json:"symbol"`      // Trading symbol
	Side        string `json:"side"`        // sell buy
	Status      string `json:"status"`      // new, suspended, partiallyFilled, filled, canceled, expired
	Type        string `json:"type"`        // Enum: limit, market, stopLimit, stopMarket
	TimeInForce string `json:"timeInForce"` // Time in force is a special instruction used when placing a trade to
	//   indicate how long an order will remain active before it is executed or expires
	// GTC - Good till cancel. GTC order won't close until it is filled.
	// IOC - An immediate or cancel order is an order to buy or sell that must be executed immediately, and any portion
	//   of the order that cannot be immediately filled is cancelled.
	// FOK - Fill or kill is a type of time-in-force designation used in securities trading that instructs a brokerage
	//   to execute a transaction immediately and completely or not at all.
	// Day - keeps the order active until the end of the trading day in UTC.
	// GTD - Good till date specified in expireTime.
	Quantity    float64   `json:"quantity,string"`    // Order quantity
	Price       float64   `json:"price,string"`       // Order price
	CumQuantity float64   `json:"cumQuantity,string"` // Cumulative executed quantity
	CreatedAt   time.Time `json:"createdAt,string"`
	UpdatedAt   time.Time `json:"updatedAt,string"`
	StopPrice   float64   `json:"stopPrice,string"`
	ExpireTime  time.Time `json:"expireTime,string"`
}

Order contains information about an order

type OrderResponse

type OrderResponse struct {
	OrderNumber int64             `json:"orderNumber,string"`
	Trades      []ResultingTrades `json:"resultingTrades"`
}

OrderResponse holds the order response information

type Orderbook

type Orderbook struct {
	Asks []OrderbookItem `json:"asks"`
	Bids []OrderbookItem `json:"bids"`
}

Orderbook contains orderbook data

type OrderbookItem

type OrderbookItem struct {
	Price  float64 `json:"price,string"` // Price level
	Amount float64 `json:"size,string"`  // Total volume of orders with the specified price
}

OrderbookItem is a sub type for orderbook response

type OrderbookResponse

type OrderbookResponse struct {
	Asks []OrderbookItem `json:"ask"` // Ask side array of levels
	Bids []OrderbookItem `json:"bid"` // Bid side array of levels
}

OrderbookResponse is the full orderbook response

type ResultingTrades

type ResultingTrades struct {
	Amount  float64 `json:"amount,string"`
	Date    string  `json:"date"`
	Rate    float64 `json:"rate,string"`
	Total   float64 `json:"total,string"`
	TradeID int64   `json:"tradeID,string"`
	Type    string  `json:"type"`
}

ResultingTrades holds resulting trade information

type Symbol

type Symbol struct {
	ID                   string  `json:"id"` // Symbol identifier. In the future, the description will simply use the symbol
	BaseCurrency         string  `json:"baseCurrency"`
	QuoteCurrency        string  `json:"quoteCurrency"`
	QuantityIncrement    float64 `json:"quantityIncrement,string"`
	TickSize             float64 `json:"tickSize,string"`
	TakeLiquidityRate    float64 `json:"takeLiquidityRate,string"`    // Default fee rate
	ProvideLiquidityRate float64 `json:"provideLiquidityRate,string"` // Default fee rate for market making trades
	FeeCurrency          string  `json:"feeCurrency"`                 // Default fee rate for market making trades
}

Symbol holds symbol data

type Ticker

type Ticker struct {
	Last        float64
	Ask         float64
	Bid         float64
	Timestamp   time.Time
	Volume      float64
	VolumeQuote float64
	Symbol      string
	High        float64
	Low         float64
	Open        float64
}

Ticker holds ticker information

type TickerResponse

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

TickerResponse is the response type

type TradeHistory

type TradeHistory struct {
	ID        int64   `json:"id"`              // Trade id
	Timestamp string  `json:"timestamp"`       // Trade timestamp
	Side      string  `json:"side"`            // Trade side sell or buy
	Price     float64 `json:"price,string"`    // Trade price
	Quantity  float64 `json:"quantity,string"` // Trade quantity
}

TradeHistory contains trade history data

type WebsocketTicker

type WebsocketTicker struct {
	CurrencyPair  string
	Last          float64
	LowestAsk     float64
	HighestBid    float64
	PercentChange float64
	BaseVolume    float64
	QuoteVolume   float64
	IsFrozen      bool
	High          float64
	Low           float64
}

WebsocketTicker holds ticker data

type WebsocketTrollboxMessage

type WebsocketTrollboxMessage struct {
	MessageNumber float64
	Username      string
	Message       string
	Reputation    float64
}

WebsocketTrollboxMessage contains trollbox message information

type Withdraw

type Withdraw struct {
	Response string `json:"response"`
	Error    string `json:"error"`
}

Withdraw holds response for a withdrawal process

Jump to

Keyboard shortcuts

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