gateio

package
v0.0.0-...-4ab53fc Latest Latest
Warning

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

Go to latest
Published: Apr 21, 2021 License: MIT Imports: 18 Imported by: 0

README

GoCryptoTrader package Gateio

Build Status Software License GoDoc Coverage Status Go Report Card

This gateio 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

GateIO Exchange

Current Features
  • REST functions
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 g exchange.IBotExchange

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

// Public calls - wrapper functions

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

// Fetches current orderbook information
ob, err := g.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 := g.GetAccountInfo()
if err != nil {
  // Handle error
}
  • If enabled via individually importing package, rudimentary example below:
// Public calls

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

// Fetches current orderbook information
ob, err := g.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 := g.GetUserInfo(...)
if err != nil {
  // Handle error
}

// Submits an order and the exchange and returns its tradeID
tradeID, err := g.Trade(...)
if err != nil {
  // Handle error
}
How to do LongPolling 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

View Source
var (
	// SpotNewOrderRequestParamsTypeBuy buy order
	SpotNewOrderRequestParamsTypeBuy = SpotNewOrderRequestParamsType("buy")

	// SpotNewOrderRequestParamsTypeSell sell order
	SpotNewOrderRequestParamsTypeSell = SpotNewOrderRequestParamsType("sell")
)
View Source
var (
	TimeIntervalMinute         = TimeInterval(60)
	TimeIntervalThreeMinutes   = TimeInterval(60 * 3)
	TimeIntervalFiveMinutes    = TimeInterval(60 * 5)
	TimeIntervalFifteenMinutes = TimeInterval(60 * 15)
	TimeIntervalThirtyMinutes  = TimeInterval(60 * 30)
	TimeIntervalHour           = TimeInterval(60 * 60)
	TimeIntervalTwoHours       = TimeInterval(2 * 60 * 60)
	TimeIntervalFourHours      = TimeInterval(4 * 60 * 60)
	TimeIntervalSixHours       = TimeInterval(6 * 60 * 60)
	TimeIntervalDay            = TimeInterval(60 * 60 * 24)
)

TimeInterval vars

View Source
var WithdrawalFees = map[currency.Code]float64{}/* 204 elements not displayed */

WithdrawalFees the large list of predefined withdrawal fees Prone to change

Functions

This section is empty.

Types

type BalancesResponse

type BalancesResponse struct {
	Result    string      `json:"result"`
	Available interface{} `json:"available"`
	Locked    interface{} `json:"locked"`
}

BalancesResponse holds the user balances

type Gateio

type Gateio struct {
	WebsocketConn *wshandler.WebsocketConnection
	exchange.Base
}

Gateio is the overarching type across this package

func (*Gateio) AuthenticateWebsocket

func (g *Gateio) AuthenticateWebsocket() error

AuthenticateWebsocket sends an authentication message to the websocket

func (*Gateio) CancelAllExistingOrders

func (g *Gateio) CancelAllExistingOrders(orderType int64, symbol string) error

CancelAllExistingOrders all orders for a given symbol and side orderType (0: sell,1: buy,-1: unlimited)

func (*Gateio) CancelAllOrders

CancelAllOrders cancels all orders associated with a currency pair

func (*Gateio) CancelExistingOrder

func (g *Gateio) CancelExistingOrder(orderID int64, symbol string) (bool, error)

CancelExistingOrder cancels an order given the supplied orderID and symbol orderID order ID number symbol trade pair (ltc_btc)

func (*Gateio) CancelOrder

func (g *Gateio) CancelOrder(order *exchange.OrderCancellation) error

CancelOrder cancels an order by its corresponding ID number

func (*Gateio) GenerateAuthenticatedSubscriptions

func (g *Gateio) GenerateAuthenticatedSubscriptions()

GenerateAuthenticatedSubscriptions Adds authenticated subscriptions to websocket to be handled by ManageSubscriptions()

func (*Gateio) GenerateDefaultSubscriptions

func (g *Gateio) GenerateDefaultSubscriptions()

GenerateDefaultSubscriptions Adds default subscriptions to websocket to be handled by ManageSubscriptions()

func (*Gateio) GenerateSignature

func (g *Gateio) GenerateSignature(message string) []byte

GenerateSignature returns hash for authenticated requests

func (*Gateio) GetAccountInfo

func (g *Gateio) GetAccountInfo() (exchange.AccountInfo, error)

GetAccountInfo retrieves balances for all enabled currencies for the ZB exchange

func (*Gateio) GetActiveOrders

func (g *Gateio) GetActiveOrders(getOrdersRequest *exchange.GetOrdersRequest) ([]exchange.OrderDetail, error)

GetActiveOrders retrieves any orders that are active/open

func (*Gateio) GetBalances

func (g *Gateio) GetBalances() (BalancesResponse, error)

GetBalances obtains the users account balance

func (*Gateio) GetCryptoDepositAddress

func (g *Gateio) GetCryptoDepositAddress(currency string) (string, error)

GetCryptoDepositAddress returns a deposit address for a cryptocurrency

func (*Gateio) GetDepositAddress

func (g *Gateio) GetDepositAddress(cryptocurrency currency.Code, _ string) (string, error)

GetDepositAddress returns a deposit address for a specified currency

func (*Gateio) GetExchangeHistory

func (g *Gateio) GetExchangeHistory(p currency.Pair, assetType string) ([]exchange.TradeHistory, error)

GetExchangeHistory returns historic trade data since exchange opening.

func (*Gateio) GetFee

func (g *Gateio) GetFee(feeBuilder *exchange.FeeBuilder) (fee float64, err error)

GetFee returns an estimate of fee based on type of transaction

func (*Gateio) GetFeeByType

func (g *Gateio) GetFeeByType(feeBuilder *exchange.FeeBuilder) (float64, error)

GetFeeByType returns an estimate of fee based on type of transaction

func (*Gateio) GetFundingHistory

func (g *Gateio) GetFundingHistory() ([]exchange.FundHistory, error)

GetFundingHistory returns funding history, deposits and withdrawals

func (*Gateio) GetLatestSpotPrice

func (g *Gateio) GetLatestSpotPrice(symbol string) (float64, error)

GetLatestSpotPrice returns latest spot price of symbol updated every 10 seconds

symbol: string of currency pair

func (*Gateio) GetMarketInfo

func (g *Gateio) GetMarketInfo() (MarketInfoResponse, error)

GetMarketInfo returns information about all trading pairs, including transaction fee, minimum order quantity, price accuracy and so on

func (*Gateio) GetOpenOrders

func (g *Gateio) GetOpenOrders(symbol string) (OpenOrdersResponse, error)

GetOpenOrders retrieves all open orders with an optional symbol filter

func (*Gateio) GetOrderHistory

func (g *Gateio) GetOrderHistory(getOrdersRequest *exchange.GetOrdersRequest) ([]exchange.OrderDetail, error)

GetOrderHistory retrieves account order information Can Limit response to specific order status

func (*Gateio) GetOrderInfo

func (g *Gateio) GetOrderInfo(orderID string) (exchange.OrderDetail, error)

GetOrderInfo returns information on a current open order

func (*Gateio) GetOrderbook

func (g *Gateio) GetOrderbook(symbol string) (Orderbook, error)

GetOrderbook returns the orderbook data for a suppled symbol

func (*Gateio) GetOrderbookEx

func (g *Gateio) GetOrderbookEx(currency currency.Pair, assetType string) (orderbook.Base, error)

GetOrderbookEx returns orderbook base on the currency pair

func (*Gateio) GetSpotKline

func (g *Gateio) GetSpotKline(arg KlinesRequestParams) ([]*KLineResponse, error)

GetSpotKline returns kline data for the most recent time period

func (*Gateio) GetSubscriptions

func (g *Gateio) GetSubscriptions() ([]wshandler.WebsocketChannelSubscription, error)

GetSubscriptions returns a copied list of subscriptions

func (*Gateio) GetSymbols

func (g *Gateio) GetSymbols() ([]string, error)

GetSymbols returns all supported symbols

func (*Gateio) GetTicker

func (g *Gateio) GetTicker(symbol string) (TickerResponse, error)

GetTicker returns a ticker for the supplied symbol updated every 10 seconds

func (*Gateio) GetTickerPrice

func (g *Gateio) GetTickerPrice(p currency.Pair, assetType string) (ticker.Price, error)

GetTickerPrice returns the ticker for a currency pair

func (*Gateio) GetTickers

func (g *Gateio) GetTickers() (map[string]TickerResponse, error)

GetTickers returns tickers for all symbols

func (*Gateio) GetTradeHistory

func (g *Gateio) GetTradeHistory(symbol string) (TradHistoryResponse, error)

GetTradeHistory retrieves all orders with an optional symbol filter

func (*Gateio) GetWebsocket

func (g *Gateio) GetWebsocket() (*wshandler.Websocket, error)

GetWebsocket returns a pointer to the exchange websocket

func (*Gateio) ModifyOrder

func (g *Gateio) ModifyOrder(action *exchange.ModifyOrder) (string, error)

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

func (*Gateio) Run

func (g *Gateio) Run()

Run implements the GateIO wrapper

func (*Gateio) SendAuthenticatedHTTPRequest

func (g *Gateio) SendAuthenticatedHTTPRequest(method, endpoint, param string, result interface{}) error

SendAuthenticatedHTTPRequest sends authenticated requests to the Gateio API To use this you must setup an APIKey and APISecret from the exchange

func (*Gateio) SendHTTPRequest

func (g *Gateio) SendHTTPRequest(path string, result interface{}) error

SendHTTPRequest sends an unauthenticated HTTP request

func (*Gateio) SetDefaults

func (g *Gateio) SetDefaults()

SetDefaults sets default values for the exchange

func (*Gateio) Setup

func (g *Gateio) Setup(exch *config.ExchangeConfig)

Setup sets user configuration

func (*Gateio) SpotNewOrder

SpotNewOrder places a new order

func (*Gateio) Start

func (g *Gateio) Start(wg *sync.WaitGroup)

Start starts the GateIO go routine

func (*Gateio) SubmitOrder

func (g *Gateio) SubmitOrder(p currency.Pair, side exchange.OrderSide, _ exchange.OrderType, amount, price float64, _ string) (exchange.SubmitOrderResponse, error)

SubmitOrder submits a new order TODO: support multiple order types (IOC)

func (*Gateio) Subscribe

func (g *Gateio) Subscribe(channelToSubscribe wshandler.WebsocketChannelSubscription) error

Subscribe sends a websocket message to receive data from the channel

func (*Gateio) SubscribeToWebsocketChannels

func (g *Gateio) SubscribeToWebsocketChannels(channels []wshandler.WebsocketChannelSubscription) error

SubscribeToWebsocketChannels appends to ChannelsToSubscribe which lets websocket.manageSubscriptions handle subscribing

func (*Gateio) Unsubscribe

func (g *Gateio) Unsubscribe(channelToSubscribe wshandler.WebsocketChannelSubscription) error

Unsubscribe sends a websocket message to stop receiving data from the channel

func (*Gateio) UnsubscribeToWebsocketChannels

func (g *Gateio) UnsubscribeToWebsocketChannels(channels []wshandler.WebsocketChannelSubscription) error

UnsubscribeToWebsocketChannels removes from ChannelsToSubscribe which lets websocket.manageSubscriptions handle unsubscribing

func (*Gateio) UpdateOrderbook

func (g *Gateio) UpdateOrderbook(p currency.Pair, assetType string) (orderbook.Base, error)

UpdateOrderbook updates and returns the orderbook for a currency pair

func (*Gateio) UpdateTicker

func (g *Gateio) UpdateTicker(p currency.Pair, assetType string) (ticker.Price, error)

UpdateTicker updates and returns the ticker for a currency pair

func (*Gateio) WithdrawCrypto

func (g *Gateio) WithdrawCrypto(currency, address string, amount float64) (string, error)

WithdrawCrypto withdraws cryptocurrency to your selected wallet

func (*Gateio) WithdrawCryptocurrencyFunds

func (g *Gateio) WithdrawCryptocurrencyFunds(withdrawRequest *exchange.WithdrawRequest) (string, error)

WithdrawCryptocurrencyFunds returns a withdrawal ID when a withdrawal is submitted

func (*Gateio) WithdrawFiatFunds

func (g *Gateio) WithdrawFiatFunds(withdrawRequest *exchange.WithdrawRequest) (string, error)

WithdrawFiatFunds returns a withdrawal ID when a withdrawal is submitted

func (*Gateio) WithdrawFiatFundsToInternationalBank

func (g *Gateio) WithdrawFiatFundsToInternationalBank(withdrawRequest *exchange.WithdrawRequest) (string, error)

WithdrawFiatFundsToInternationalBank returns a withdrawal ID when a withdrawal is submitted

func (*Gateio) WsConnect

func (g *Gateio) WsConnect() error

WsConnect initiates a websocket connection

func (*Gateio) WsHandleData

func (g *Gateio) WsHandleData()

WsHandleData handles all the websocket data coming from the websocket connection

type KLineResponse

type KLineResponse struct {
	ID        float64
	KlineTime time.Time
	Open      float64
	Time      float64
	High      float64
	Low       float64
	Close     float64
	Volume    float64
	Amount    float64 `db:"amount"`
}

KLineResponse holds the kline response data

type KlinesRequestParams

type KlinesRequestParams struct {
	Symbol   string // Required field; example LTCBTC,BTCUSDT
	HourSize int    // How many hours of data
	GroupSec TimeInterval
}

KlinesRequestParams represents Klines request data.

type MarketInfoPairsResponse

type MarketInfoPairsResponse struct {
	Symbol string
	// DecimalPlaces symbol price accuracy
	DecimalPlaces float64
	// MinAmount minimum order amount
	MinAmount float64
	// Fee transaction fee
	Fee float64
}

MarketInfoPairsResponse holds the market info response data

type MarketInfoResponse

type MarketInfoResponse struct {
	Result string                    `json:"result"`
	Pairs  []MarketInfoPairsResponse `json:"pairs"`
}

MarketInfoResponse holds the market info data

type OpenOrder

type OpenOrder struct {
	Amount        float64 `json:"amount,string"`
	CurrencyPair  string  `json:"currencyPair"`
	FilledAmount  float64 `json:"filledAmount,string"`
	FilledRate    float64 `json:"filledRate"`
	InitialAmount float64 `json:"initialAmount"`
	InitialRate   float64 `json:"initialRate"`
	OrderNumber   string  `json:"orderNumber"`
	Rate          float64 `json:"rate"`
	Status        string  `json:"status"`
	Timestamp     int64   `json:"timestamp"`
	Total         float64 `json:"total,string"`
	Type          string  `json:"type"`
}

OpenOrder details each open order

type OpenOrdersResponse

type OpenOrdersResponse struct {
	Code    int         `json:"code"`
	Elapsed string      `json:"elapsed"`
	Message string      `json:"message"`
	Orders  []OpenOrder `json:"orders"`
	Result  string      `json:"result"`
}

OpenOrdersResponse the main response from GetOpenOrders

type Orderbook

type Orderbook struct {
	Result  string
	Elapsed string
	Bids    []OrderbookItem
	Asks    []OrderbookItem
}

Orderbook stores the orderbook data

type OrderbookItem

type OrderbookItem struct {
	Price  float64
	Amount float64
}

OrderbookItem stores an orderbook item

type OrderbookResponse

type OrderbookResponse struct {
	Result  string `json:"result"`
	Elapsed string `json:"elapsed"`
	Asks    [][]string
	Bids    [][]string
}

OrderbookResponse stores the orderbook data

type SpotNewOrderRequestParams

type SpotNewOrderRequestParams struct {
	Amount float64                       `json:"amount"` // Order quantity
	Price  float64                       `json:"price"`  // Order price
	Symbol string                        `json:"symbol"` // Trading pair; btc_usdt, eth_btc......
	Type   SpotNewOrderRequestParamsType `json:"type"`   // Order type (buy or sell),
}

SpotNewOrderRequestParams Order params

type SpotNewOrderRequestParamsType

type SpotNewOrderRequestParamsType string

SpotNewOrderRequestParamsType order type (buy or sell)

type SpotNewOrderResponse

type SpotNewOrderResponse struct {
	OrderNumber  int64       `json:"orderNumber"`         // OrderID number
	Price        float64     `json:"rate,string"`         // Order price
	LeftAmount   float64     `json:"leftAmount,string"`   // The remaining amount to fill
	FilledAmount float64     `json:"filledAmount,string"` // The filled amount
	Filledrate   interface{} `json:"filledRate"`          // FilledPrice. if we send a market order, the exchange returns float64.

}

SpotNewOrderResponse Order response

type TickerResponse

type TickerResponse struct {
	Result        string  `json:"result"`
	Volume        float64 `json:"baseVolume,string"`    // Trading volume
	High          float64 `json:"high24hr,string"`      // 24 hour high price
	Open          float64 `json:"highestBid,string"`    // Openening price
	Last          float64 `json:"last,string"`          // Last price
	Low           float64 `json:"low24hr,string"`       // 24 hour low price
	Close         float64 `json:"lowestAsk,string"`     // Closing price
	PercentChange float64 `json:"percentChange,string"` // Percentage change
	QuoteVolume   float64 `json:"quoteVolume,string"`   // Quote currency volume
}

TickerResponse holds the ticker response data

type TimeInterval

type TimeInterval int

TimeInterval Interval represents interval enum.

type TradHistoryResponse

type TradHistoryResponse struct {
	Code    int              `json:"code,omitempty"`
	Elapsed string           `json:"elapsed,omitempty"`
	Message string           `json:"message"`
	Trades  []TradesResponse `json:"trades"`
	Result  string           `json:"result"`
}

TradHistoryResponse The full response for retrieving all user trade history

type TradesResponse

type TradesResponse struct {
	ID       int64   `json:"tradeID"`
	OrderID  int64   `json:"orderNumber"`
	Pair     string  `json:"pair"`
	Type     string  `json:"type"`
	Rate     float64 `json:"rate,string"`
	Amount   float64 `json:"amount,string"`
	Total    float64 `json:"total"`
	Time     string  `json:"date"`
	TimeUnix int64   `json:"time_unix"`
}

TradesResponse details trade history

type WebSocketOrderQueryRecords

type WebSocketOrderQueryRecords struct {
	ID           int     `json:"id"`
	Market       string  `json:"market"`
	User         int     `json:"user"`
	Ctime        float64 `json:"ctime"`
	Mtime        float64 `json:"mtime"`
	Price        string  `json:"price"`
	Amount       string  `json:"amount"`
	Left         string  `json:"left"`
	DealFee      string  `json:"dealFee"`
	OrderType    int     `json:"orderType"`
	Type         int     `json:"type"`
	FilledAmount string  `json:"filledAmount"`
	FilledTotal  string  `json:"filledTotal"`
}

WebSocketOrderQueryRecords contains order information from a order.query websocket request

type WebSocketOrderQueryResult

type WebSocketOrderQueryResult struct {
	Limit                      int                          `json:"limit"`
	Offset                     int                          `json:"offset"`
	Total                      int                          `json:"total"`
	WebSocketOrderQueryRecords []WebSocketOrderQueryRecords `json:"records"`
}

WebSocketOrderQueryResult data returned from a websocket ordre query holds slice of WebSocketOrderQueryRecords

type WebsocketAuthenticationResponse

type WebsocketAuthenticationResponse struct {
	Error  string `json:"error"`
	Result struct {
		Status string `json:"status"`
	} `json:"result"`
	ID int64 `json:"id"`
}

WebsocketAuthenticationResponse contains the result of a login request

type WebsocketBalance

type WebsocketBalance struct {
	Currency []WebsocketBalanceCurrency
}

WebsocketBalance holds a slice of WebsocketBalanceCurrency

type WebsocketBalanceCurrency

type WebsocketBalanceCurrency struct {
	Currency  string
	Available string `json:"available"`
	Locked    string `json:"freeze"`
}

WebsocketBalanceCurrency contains currency name funds available and frozen

type WebsocketError

type WebsocketError struct {
	Code    int64  `json:"code"`
	Message string `json:"message"`
}

WebsocketError defines a websocket error type

type WebsocketRequest

type WebsocketRequest struct {
	ID     int64         `json:"id"`
	Method string        `json:"method"`
	Params []interface{} `json:"params"`
}

WebsocketRequest defines the initial request in JSON

type WebsocketResponse

type WebsocketResponse struct {
	Time    int64             `json:"time"`
	Channel string            `json:"channel"`
	Error   WebsocketError    `json:"error"`
	Result  json.RawMessage   `json:"result"`
	ID      int64             `json:"id"`
	Method  string            `json:"method"`
	Params  []json.RawMessage `json:"params"`
}

WebsocketResponse defines a websocket response from gateio

type WebsocketTicker

type WebsocketTicker struct {
	Period      int64   `json:"period"`
	Open        float64 `json:"open,string"`
	Close       float64 `json:"close,string"`
	High        float64 `json:"high,string"`
	Low         float64 `json:"Low,string"`
	Last        float64 `json:"last,string"`
	Change      float64 `json:"change,string"`
	QuoteVolume float64 `json:"quoteVolume,string"`
	BaseVolume  float64 `json:"baseVolume,string"`
}

WebsocketTicker defines ticker data

type WebsocketTrade

type WebsocketTrade struct {
	ID     int64   `json:"id"`
	Time   float64 `json:"time"`
	Price  float64 `json:"price,string"`
	Amount float64 `json:"amount,string"`
	Type   string  `json:"type"`
}

WebsocketTrade defines trade data

type WsGetBalanceResponse

type WsGetBalanceResponse struct {
	Error  interface{}                                `json:"error"`
	Result map[currency.Code]WsGetBalanceResponseData `json:"result,omitempty"`
	ID     int64                                      `json:"id"`
}

WsGetBalanceResponse stores WS GetBalance response

type WsGetBalanceResponseData

type WsGetBalanceResponseData struct {
	Available float64 `json:"available,string"`
	Freeze    float64 `json:"freeze,string"`
}

WsGetBalanceResponseData contains currency data

Jump to

Keyboard shortcuts

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