diff --git a/Makefile b/Makefile new file mode 100644 index 000000000..64d460955 --- /dev/null +++ b/Makefile @@ -0,0 +1,10 @@ +NAME = bitfinex-api-go + +############################# +### Swagger + +gen-docs: + @echo "Generating documentation" + godocdown ./v2/websocket > ./docs/ws_v2.md + godocdown ./v2/rest > ./docs/rest_v2.md + godocdown ./v1/ > ./docs/v1.md diff --git a/README.md b/README.md new file mode 100644 index 000000000..9c0c305e4 --- /dev/null +++ b/README.md @@ -0,0 +1,147 @@ +# Bitfinex Trading Library for GoLang - Bitcoin, Ethereum, Ripple and more + +![https://api.travis-ci.org/bitfinexcom/bitfinex-api-go.svg?branch=master](https://api.travis-ci.org/bitfinexcom/bitfinex-api-go.svg?branch=master) + +A Golang reference implementation of the Bitfinex API for both REST and websocket interaction. + +### Features +* Official implementation +* REST V1/V2 and Websocket +* Connection multiplexing +* Types for all data schemas + +## Installation + +``` bash +go get github.com/bitfinexcom/bitfinex-api-go +``` + +Optional - run the 'trade-feed' example to begin receiving realtime trade updates via the websocket + +```bash +cd $GOPATH/src/github.com/bitfinexcom/bitfinex-api-go +go run examples/v2/trade-feed/main.go +``` + +## Quickstart + +``` go +package main + +import ( + "fmt" + "github.com/bitfinexcom/bitfinex-api-go/v2" +) + +func main() { + client := bitfinex.NewClient().Credentials("API_KEY", "API_SEC") + + // create order + response, err := c.Orders.SubmitOrder(&bitfinex.OrderNewRequest{ + Symbol: "tBTCUSD", + CID: time.Now().Unix() / 1000, + Amount: 0.02, + Type: "EXCHANGE LIMIT", + Price: 5000, + }) + if err != nil { + panic(err) + } +} +``` + +## Docs + +* [V1](docs/v1.md) - Documentation (depreciated) +* [V2 Rest](docs/rest_v2.md) - Documentation +* [V2 Websocket](docs/ws_v2.md) - Documentation + +## Examples + +#### Authentication + +``` go +func main() { + client := bitfinex.NewClient().Credentials("API_KEY", "API_SEC") +} +``` + +#### Subscribe to Trades + +``` go +// using github.com/bitfinexcom/bitfinex-api-go/v2/websocket as client +_, err := client.SubscribeTrades(context.Background(), "tBTCUSD") +if err != nil { + log.Printf("Could not subscribe to trades: %s", err.Error()) +} +``` + +#### Get candles via REST + +```go +// using github.com/bitfinexcom/bitfinex-api-go/v2/rest as client +os, err := client.Orders.AllHistory() +if err != nil { + log.Fatalf("getting orders: %s", err) +} +``` + +See the [examples](https://github.com/bitfinexcom/bitfinex-api-go/tree/master/examples) directory for more, like: + +- [Creating/updating an order](https://github.com/bitfinexcom/bitfinex-api-go/blob/master/examples/v2/ws-update-order/main.go) +- [Subscribing to orderbook updates](https://github.com/bitfinexcom/bitfinex-api-go/blob/master/examples/v2/book-feed/main.go) +- [Integrating a custom logger](https://github.com/bitfinexcom/bitfinex-api-go/blob/master/examples/v2/ws-custom-logger/main.go) +- [Submitting funding offers](https://github.com/bitfinexcom/bitfinex-api-go/blob/master/examples/v2/rest-funding/main.go) +- [Retrieving active positions](https://github.com/bitfinexcom/bitfinex-api-go/blob/master/examples/v2/rest-positions/main.go) + +## FAQ + +### Is there any rate limiting? + +For a Websocket connection there is no limit to the number of requests sent down the connection (unlimited order operations) however an account can only create 15 new connections every 5 mins and each connection is only able to subscribe to 30 inbound data channels. Fortunately this library handles all of the load balancing/multiplexing for channels and will automatically create/destroy new connections when needed, however the user may still encounter the max connections rate limiting error. + +For rest the base limit per-user is 1,000 orders per 5 minute interval, and is shared between all account API connections. It increases proportionally to your trade volume based on the following formula: + +1000 + (TOTAL_PAIRS_PLATFORM * 60 * 5) / (250000000 / USER_VOL_LAST_30d) + +Where TOTAL_PAIRS_PLATFORM is the number of pairs on the Bitfinex platform (currently ~101) and USER_VOL_LAST_30d is in USD. + +### Will I always receive an `on` packet? + +No; if your order fills immediately, the first packet referencing the order will be an `oc` signaling the order has closed. If the order fills partially immediately after creation, an `on` packet will arrive with a status of `PARTIALLY FILLED...` + +For example, if you submit a `LIMIT` buy for 0.2 BTC and it is added to the order book, an `on` packet will arrive via ws2. After a partial fill of 0.1 BTC, an `ou` packet will arrive, followed by a final `oc` after the remaining 0.1 BTC fills. + +On the other hand, if the order fills immediately for 0.2 BTC, you will only receive an `oc` packet. + +### My websocket won't connect! + +Did you call `client.Connect()`? :) + +### nonce too small + +I make multiple parallel request and I receive an error that the nonce is too small. What does it mean? + +Nonces are used to guard against replay attacks. When multiple HTTP requests arrive at the API with the wrong nonce, e.g. because of an async timing issue, the API will reject the request. + +If you need to go parallel, you have to use multiple API keys right now. + +### How do `te` and `tu` messages differ? + +A `te` packet is sent first to the client immediately after a trade has been matched & executed, followed by a `tu` message once it has completed processing. During times of high load, the `tu` message may be noticably delayed, and as such only the `te` message should be used for a realtime feed. + +### What are the sequence numbers for? + +If you enable sequencing on v2 of the WS API, each incoming packet will have a public sequence number at the end, along with an auth sequence number in the case of channel `0` packets. The public seq numbers increment on each packet, and the auth seq numbers increment on each authenticated action (new orders, etc). These values allow you to verify that no packets have been missed/dropped, since they always increase monotonically. + +### What is the difference between R* and P* order books? + +Order books with precision `R0` are considered 'raw' and contain entries for each order submitted to the book, whereas `P*` books contain entries for each price level (which aggregate orders). + +## Contributing + +1. Fork it (https://github.com/bitfinexcom/bitfinex-api-go/fork) +2. Create your feature branch (`git checkout -b my-new-feature) +3. Commit your changes (`git commit -am 'Add some feature'`) +4. Push to the branch (`git push origin my-new-feature`) +5. Create a new Pull Request diff --git a/docs/rest_v2.md b/docs/rest_v2.md new file mode 100644 index 000000000..979c6de93 --- /dev/null +++ b/docs/rest_v2.md @@ -0,0 +1,821 @@ +# rest +-- + import "github.com/bitfinexcom/bitfinex-api-go/v2/rest" + + +## Usage + +```go +const ( + DERIV_TYPE = "deriv" +) +``` + +#### type BookService + +```go +type BookService struct { + Synchronous +} +``` + + +#### func (*BookService) All + +```go +func (b *BookService) All(symbol string, precision bitfinex.BookPrecision, priceLevels int) (*bitfinex.BookUpdateSnapshot, error) +``` +Retrieve all books for the given symbol with the given precision at the given +price level see https://docs.bitfinex.com/reference#rest-public-books for more +info + +#### type CandleService + +```go +type CandleService struct { + Synchronous +} +``` + +CandleService manages the Candles endpoint. + +#### func (*CandleService) History + +```go +func (c *CandleService) History(symbol string, resolution bitfinex.CandleResolution) (*bitfinex.CandleSnapshot, error) +``` +Retrieves all candles (Max=1000) with the given symbol and the given candle +resolution See https://docs.bitfinex.com/reference#rest-public-candles for more +info + +#### func (*CandleService) HistoryWithQuery + +```go +func (c *CandleService) HistoryWithQuery( + symbol string, + resolution bitfinex.CandleResolution, + start bitfinex.Mts, + end bitfinex.Mts, + limit bitfinex.QueryLimit, + sort bitfinex.SortOrder, +) (*bitfinex.CandleSnapshot, error) +``` +Retrieves all candles (Max=1000) that fit the given query criteria See +https://docs.bitfinex.com/reference#rest-public-candles for more info + +#### func (*CandleService) Last + +```go +func (c *CandleService) Last(symbol string, resolution bitfinex.CandleResolution) (*bitfinex.Candle, error) +``` +Retrieve the last candle for the given symbol with the given resolution See +https://docs.bitfinex.com/reference#rest-public-candles for more info + +#### type Client + +```go +type Client struct { + + // service providers + Candles CandleService + Orders OrderService + Positions PositionService + Trades TradeService + Tickers TickerService + Currencies CurrenciesService + Platform PlatformService + Book BookService + Wallet WalletService + Ledgers LedgerService + Stats StatsService + Status StatusService + Derivatives DerivativesService + Funding FundingService + + Synchronous +} +``` + + +#### func NewClient + +```go +func NewClient() *Client +``` +Create a new Rest client + +#### func NewClientWithHttpDo + +```go +func NewClientWithHttpDo(httpDo func(c *http.Client, r *http.Request) (*http.Response, error)) *Client +``` +Create a new Rest client with a custom http handler + +#### func NewClientWithSynchronousNonce + +```go +func NewClientWithSynchronousNonce(sync Synchronous, nonce utils.NonceGenerator) *Client +``` +Create a new Rest client with a synchronous HTTP handler and a custom nonce +generaotr + +#### func NewClientWithSynchronousURLNonce + +```go +func NewClientWithSynchronousURLNonce(sync Synchronous, url string, nonce utils.NonceGenerator) *Client +``` +Create a new Rest client with a synchronous HTTP handler and a custom base url +and nonce generator + +#### func NewClientWithURL + +```go +func NewClientWithURL(url string) *Client +``` +Create a new Rest client with a custom base url + +#### func NewClientWithURLHttpDo + +```go +func NewClientWithURLHttpDo(base string, httpDo func(c *http.Client, r *http.Request) (*http.Response, error)) *Client +``` +Create a new Rest client with a custom base url and HTTP handler + +#### func NewClientWithURLHttpDoNonce + +```go +func NewClientWithURLHttpDoNonce(base string, httpDo func(c *http.Client, r *http.Request) (*http.Response, error), nonce utils.NonceGenerator) *Client +``` +Create a new Rest client with a custom base url, HTTP handler and none generator + +#### func NewClientWithURLNonce + +```go +func NewClientWithURLNonce(url string, nonce utils.NonceGenerator) *Client +``` +Create a new Rest client with a custom nonce generator + +#### func (*Client) Credentials + +```go +func (c *Client) Credentials(key string, secret string) *Client +``` +Set the clients credentials in order to make authenticated requests + +#### func (*Client) NewAuthenticatedRequest + +```go +func (c *Client) NewAuthenticatedRequest(permissionType bitfinex.PermissionType, refURL string) (Request, error) +``` +Create a new authenticated GET request with the given permission type and +endpoint url For example permissionType = "r" and refUrl = "/orders" then the +target endpoint will be https://api.bitfinex.com/v2/auth/r/orders/:Symbol + +#### func (*Client) NewAuthenticatedRequestWithBytes + +```go +func (c *Client) NewAuthenticatedRequestWithBytes(permissionType bitfinex.PermissionType, refURL string, data []byte) (Request, error) +``` +Create a new authenticated POST request with the given permission type,endpoint +url and data (bytes) as the body For example permissionType = "r" and refUrl = +"/orders" then the target endpoint will be +https://api.bitfinex.com/v2/auth/r/orders/:Symbol + +#### func (*Client) NewAuthenticatedRequestWithData + +```go +func (c *Client) NewAuthenticatedRequestWithData(permissionType bitfinex.PermissionType, refURL string, data map[string]interface{}) (Request, error) +``` +Create a new authenticated POST request with the given permission type,endpoint +url and data (map[string]interface{}) as the body For example permissionType = +"r" and refUrl = "/orders" then the target endpoint will be +https://api.bitfinex.com/v2/auth/r/orders/:Symbol + +#### type CurrenciesService + +```go +type CurrenciesService struct { + Synchronous +} +``` + +TradeService manages the Trade endpoint. + +#### func (*CurrenciesService) Conf + +```go +func (cs *CurrenciesService) Conf(label, symbol, unit, explorer, pairs bool) ([]bitfinex.CurrencyConf, error) +``` +Retreive currency and symbol service configuration data see +https://docs.bitfinex.com/reference#rest-public-conf for more info + +#### type DerivativesService + +```go +type DerivativesService struct { + Synchronous +} +``` + +OrderService manages data flow for the Order API endpoint + +#### type ErrorResponse + +```go +type ErrorResponse struct { + Response *Response + Message string `json:"message"` + Code int `json:"code"` +} +``` + +In case if API will wrong response code ErrorResponse will be returned to caller + +#### func (*ErrorResponse) Error + +```go +func (r *ErrorResponse) Error() string +``` + +#### type FundingService + +```go +type FundingService struct { + Synchronous +} +``` + +LedgerService manages the Ledgers endpoint. + +#### func (*FundingService) CancelOffer + +```go +func (fs *FundingService) CancelOffer(fc *bitfinex.FundingOfferCancelRequest) (*bitfinex.Notification, error) +``` +Submits a request to cancel the given offer see +https://docs.bitfinex.com/reference#cancel-funding-offer for more info + +#### func (*FundingService) Credits + +```go +func (fs *FundingService) Credits(symbol string) (*bitfinex.FundingCreditSnapshot, error) +``` +Retreive all of the active credits used in positions see +https://docs.bitfinex.com/reference#rest-auth-funding-credits for more info + +#### func (*FundingService) CreditsHistory + +```go +func (fs *FundingService) CreditsHistory(symbol string) (*bitfinex.FundingCreditSnapshot, error) +``` +Retreive all of the past in-active credits used in positions see +https://docs.bitfinex.com/reference#rest-auth-funding-credits-hist for more info + +#### func (*FundingService) Loans + +```go +func (fs *FundingService) Loans(symbol string) (*bitfinex.FundingLoanSnapshot, error) +``` +Retreive all of the active funding loans see +https://docs.bitfinex.com/reference#rest-auth-funding-loans for more info + +#### func (*FundingService) LoansHistory + +```go +func (fs *FundingService) LoansHistory(symbol string) (*bitfinex.FundingLoanSnapshot, error) +``` +Retreive all of the past in-active funding loans see +https://docs.bitfinex.com/reference#rest-auth-funding-loans-hist for more info + +#### func (*FundingService) OfferHistory + +```go +func (fs *FundingService) OfferHistory(symbol string) (*bitfinex.FundingOfferSnapshot, error) +``` +Retreive all of the past in-active funding offers see +https://docs.bitfinex.com/reference#rest-auth-funding-offers-hist for more info + +#### func (*FundingService) Offers + +```go +func (fs *FundingService) Offers(symbol string) (*bitfinex.FundingOfferSnapshot, error) +``` +Retreive all of the active fundign offers see +https://docs.bitfinex.com/reference#rest-auth-funding-offers for more info + +#### func (*FundingService) SubmitOffer + +```go +func (fs *FundingService) SubmitOffer(fo *bitfinex.FundingOfferRequest) (*bitfinex.Notification, error) +``` +Submits a request to create a new funding offer see +https://docs.bitfinex.com/reference#submit-funding-offer for more info + +#### func (*FundingService) Trades + +```go +func (fs *FundingService) Trades(symbol string) (*bitfinex.FundingTradeSnapshot, error) +``` +Retreive all of the matched funding trades see +https://docs.bitfinex.com/reference#rest-auth-funding-trades-hist for more info + +#### type HttpTransport + +```go +type HttpTransport struct { + BaseURL *url.URL + HTTPClient *http.Client +} +``` + + +#### func (HttpTransport) Request + +```go +func (h HttpTransport) Request(req Request) ([]interface{}, error) +``` + +#### type LedgerService + +```go +type LedgerService struct { + Synchronous +} +``` + +LedgerService manages the Ledgers endpoint. + +#### func (*LedgerService) Ledgers + +```go +func (s *LedgerService) Ledgers(currency string, start int64, end int64, max int32) (*bitfinex.LedgerSnapshot, error) +``` +Retrieves all of the past ledger entreies see +https://docs.bitfinex.com/reference#ledgers for more info + +#### type OrderService + +```go +type OrderService struct { + Synchronous +} +``` + +OrderService manages data flow for the Order API endpoint + +#### func (*OrderService) All + +```go +func (s *OrderService) All() (*bitfinex.OrderSnapshot, error) +``` +Retrieves all of the active orders See +https://docs.bitfinex.com/reference#rest-auth-orders for more info + +#### func (*OrderService) AllHistory + +```go +func (s *OrderService) AllHistory() (*bitfinex.OrderSnapshot, error) +``` +Retrieves all past orders See https://docs.bitfinex.com/reference#orders-history +for more info + +#### func (*OrderService) GetByOrderId + +```go +func (s *OrderService) GetByOrderId(orderID int64) (o *bitfinex.Order, err error) +``` +Retrieve an active order by the given ID See +https://docs.bitfinex.com/reference#rest-auth-orders for more info + +#### func (*OrderService) GetBySymbol + +```go +func (s *OrderService) GetBySymbol(symbol string) (*bitfinex.OrderSnapshot, error) +``` +Retrieves all of the active orders with for the given symbol See +https://docs.bitfinex.com/reference#rest-auth-orders for more info + +#### func (*OrderService) GetHistoryByOrderId + +```go +func (s *OrderService) GetHistoryByOrderId(orderID int64) (o *bitfinex.Order, err error) +``` +Retrieve a single order in history with the given id See +https://docs.bitfinex.com/reference#orders-history for more info + +#### func (*OrderService) GetHistoryBySymbol + +```go +func (s *OrderService) GetHistoryBySymbol(symbol string) (*bitfinex.OrderSnapshot, error) +``` +Retrieves all past orders with the given symbol See +https://docs.bitfinex.com/reference#orders-history for more info + +#### func (*OrderService) OrderTrades + +```go +func (s *OrderService) OrderTrades(symbol string, orderID int64) (*bitfinex.TradeExecutionUpdateSnapshot, error) +``` +Retrieves the trades generated by an order See +https://docs.bitfinex.com/reference#orders-history for more info + +#### func (*OrderService) SubmitCancelOrder + +```go +func (s *OrderService) SubmitCancelOrder(oc *bitfinex.OrderCancelRequest) error +``` +Submit a request to cancel an order with the given Id see +https://docs.bitfinex.com/reference#cancel-order for more info + +#### func (*OrderService) SubmitOrder + +```go +func (s *OrderService) SubmitOrder(order *bitfinex.OrderNewRequest) (*bitfinex.Notification, error) +``` +Submit a request to create a new order see +https://docs.bitfinex.com/reference#submit-order for more info + +#### func (*OrderService) SubmitUpdateOrder + +```go +func (s *OrderService) SubmitUpdateOrder(order *bitfinex.OrderUpdateRequest) (*bitfinex.Notification, error) +``` +Submit a request to update an order with the given id with the given changes see +https://docs.bitfinex.com/reference#order-update for more info + +#### type PlatformService + +```go +type PlatformService struct { + Synchronous +} +``` + + +#### func (*PlatformService) Status + +```go +func (p *PlatformService) Status() (bool, error) +``` +Retrieves the current status of the platform see +https://docs.bitfinex.com/reference#rest-public-platform-status for more info + +#### type PositionService + +```go +type PositionService struct { + Synchronous +} +``` + +PositionService manages the Position endpoint. + +#### func (*PositionService) All + +```go +func (s *PositionService) All() (*bitfinex.PositionSnapshot, error) +``` +Retrieves all of the active positions see +https://docs.bitfinex.com/reference#rest-auth-positions for more info + +#### func (*PositionService) Claim + +```go +func (s *PositionService) Claim(cp *bitfinex.ClaimPositionRequest) (*bitfinex.Notification, error) +``` +Submits a request to claim an active position with the given id see +https://docs.bitfinex.com/reference#claim-position for more info + +#### type Request + +```go +type Request struct { + RefURL string // ref url + Data []byte // body data + Method string // http method + Params url.Values // query parameters + Headers map[string]string +} +``` + +Request is a wrapper for standard http.Request. Default method is POST with no +data. + +#### func NewRequest + +```go +func NewRequest(refURL string) Request +``` +Create new POST request with an empty body as payload + +#### func NewRequestWithBytes + +```go +func NewRequestWithBytes(refURL string, data []byte) Request +``` +Create a new POST request with the given bytes as body + +#### func NewRequestWithData + +```go +func NewRequestWithData(refURL string, data map[string]interface{}) (Request, error) +``` +Create a new POST request with the given data (map[string]interface{}) as body + +#### func NewRequestWithDataMethod + +```go +func NewRequestWithDataMethod(refURL string, data []byte, method string) Request +``` +Create a new request with a given method (POST | GET) with bytes as body + +#### func NewRequestWithMethod + +```go +func NewRequestWithMethod(refURL string, method string) Request +``` +Create a new request with the given method (POST | GET) + +#### type Response + +```go +type Response struct { + Response *http.Response + Body []byte +} +``` + +Response is a wrapper for standard http.Response and provides more methods. + +#### func (*Response) String + +```go +func (r *Response) String() string +``` +String converts response body to string. An empty string will be returned if +error. + +#### type StatsService + +```go +type StatsService struct { + Synchronous +} +``` + +TradeService manages the Trade endpoint. + +#### func (*StatsService) CreditSizeHistory + +```go +func (ss *StatsService) CreditSizeHistory(symbol string, side bitfinex.OrderSide) ([]bitfinex.Stat, error) +``` +Retrieves platform statistics for credit size history see +https://docs.bitfinex.com/reference#rest-public-stats for more info + +#### func (*StatsService) CreditSizeLast + +```go +func (ss *StatsService) CreditSizeLast(symbol string, side bitfinex.OrderSide) (*bitfinex.Stat, error) +``` +Retrieves platform statistics for credit size last see +https://docs.bitfinex.com/reference#rest-public-stats for more info + +#### func (*StatsService) FundingHistory + +```go +func (ss *StatsService) FundingHistory(symbol string) ([]bitfinex.Stat, error) +``` +Retrieves platform statistics for funding history see +https://docs.bitfinex.com/reference#rest-public-stats for more info + +#### func (*StatsService) FundingLast + +```go +func (ss *StatsService) FundingLast(symbol string) (*bitfinex.Stat, error) +``` +Retrieves platform statistics for funding last see +https://docs.bitfinex.com/reference#rest-public-stats for more info + +#### func (*StatsService) PositionHistory + +```go +func (ss *StatsService) PositionHistory(symbol string, side bitfinex.OrderSide) ([]bitfinex.Stat, error) +``` +Retrieves platform statistics for position history see +https://docs.bitfinex.com/reference#rest-public-stats for more info + +#### func (*StatsService) PositionLast + +```go +func (ss *StatsService) PositionLast(symbol string, side bitfinex.OrderSide) (*bitfinex.Stat, error) +``` +Retrieves platform statistics for position last see +https://docs.bitfinex.com/reference#rest-public-stats for more info + +#### func (*StatsService) SymbolCreditSizeHistory + +```go +func (ss *StatsService) SymbolCreditSizeHistory(fundingSymbol string, tradingSymbol string) ([]bitfinex.Stat, error) +``` +Retrieves platform statistics for credit size history see +https://docs.bitfinex.com/reference#rest-public-stats for more info + +#### func (*StatsService) SymbolCreditSizeLast + +```go +func (ss *StatsService) SymbolCreditSizeLast(fundingSymbol string, tradingSymbol string) (*bitfinex.Stat, error) +``` +Retrieves platform statistics for credit size last see +https://docs.bitfinex.com/reference#rest-public-stats for more info + +#### type StatusService + +```go +type StatusService struct { + Synchronous +} +``` + +TradeService manages the Trade endpoint. + +#### func (*StatusService) DerivativeStatus + +```go +func (ss *StatusService) DerivativeStatus(symbol string) (*bitfinex.DerivativeStatus, error) +``` +Retrieves derivative status information for the given symbol from the platform +see https://docs.bitfinex.com/reference#rest-public-status for more info + +#### func (*StatusService) DerivativeStatusAll + +```go +func (ss *StatusService) DerivativeStatusAll() ([]*bitfinex.DerivativeStatus, error) +``` +Retrieves derivative status information for all symbols from the platform see +https://docs.bitfinex.com/reference#rest-public-status for more info + +#### func (*StatusService) DerivativeStatusMulti + +```go +func (ss *StatusService) DerivativeStatusMulti(symbols []string) ([]*bitfinex.DerivativeStatus, error) +``` +Retrieves derivative status information for the given symbols from the platform +see https://docs.bitfinex.com/reference#rest-public-status for more info + +#### type Synchronous + +```go +type Synchronous interface { + Request(request Request) ([]interface{}, error) +} +``` + + +#### type TickerService + +```go +type TickerService struct { + Synchronous +} +``` + +TradeService manages the Trade endpoint. + +#### func (*TickerService) All + +```go +func (s *TickerService) All() (*[]bitfinex.Ticker, error) +``` +Retrieves all tickers for all symbols see +https://docs.bitfinex.com/reference#rest-public-ticker for more info + +#### func (*TickerService) Get + +```go +func (s *TickerService) Get(symbol string) (*bitfinex.Ticker, error) +``` +Retrieves the ticker for the given symbol see +https://docs.bitfinex.com/reference#rest-public-ticker for more info + +#### func (*TickerService) GetMulti + +```go +func (s *TickerService) GetMulti(symbols []string) (*[]bitfinex.Ticker, error) +``` +Retrieves the tickers for the given symbols see +https://docs.bitfinex.com/reference#rest-public-ticker for more info + +#### type TradeService + +```go +type TradeService struct { + Synchronous +} +``` + +TradeService manages the Trade endpoint. + +#### func (*TradeService) AccountAll + +```go +func (s *TradeService) AccountAll() (*bitfinex.TradeExecutionUpdateSnapshot, error) +``` +Retrieves all matched trades for the account see +https://docs.bitfinex.com/reference#rest-auth-trades-hist for more info + +#### func (*TradeService) AccountAllWithSymbol + +```go +func (s *TradeService) AccountAllWithSymbol(symbol string) (*bitfinex.TradeExecutionUpdateSnapshot, error) +``` +Retrieves all matched trades with the given symbol for the account see +https://docs.bitfinex.com/reference#rest-auth-trades-hist for more info + +#### func (*TradeService) AccountHistoryWithQuery + +```go +func (s *TradeService) AccountHistoryWithQuery( + symbol string, + start bitfinex.Mts, + end bitfinex.Mts, + limit bitfinex.QueryLimit, + sort bitfinex.SortOrder, +) (*bitfinex.TradeExecutionUpdateSnapshot, error) +``` +Queries all matched trades with group of optional parameters see +https://docs.bitfinex.com/reference#rest-auth-trades-hist for more info + +#### func (*TradeService) PublicHistoryWithQuery + +```go +func (s *TradeService) PublicHistoryWithQuery( + symbol string, + start bitfinex.Mts, + end bitfinex.Mts, + limit bitfinex.QueryLimit, + sort bitfinex.SortOrder, +) (*bitfinex.TradeSnapshot, error) +``` +Queries all public trades with a group of optional paramters see +https://docs.bitfinex.com/reference#rest-public-trades for more info + +#### type WalletService + +```go +type WalletService struct { + Synchronous +} +``` + +WalletService manages data flow for the Wallet API endpoint + +#### func (*WalletService) CreateDepositAddress + +```go +func (ws *WalletService) CreateDepositAddress(wallet, method string) (*bitfinex.Notification, error) +``` +Submits a request to create a new deposit address for the give Bitfinex wallet. +Old addresses are still valid. See +https://docs.bitfinex.com/reference#deposit-address for more info + +#### func (*WalletService) DepositAddress + +```go +func (ws *WalletService) DepositAddress(wallet, method string) (*bitfinex.Notification, error) +``` +Retrieves the deposit address for the given Bitfinex wallet see +https://docs.bitfinex.com/reference#deposit-address for more info + +#### func (*WalletService) SetCollateral + +```go +func (s *WalletService) SetCollateral(symbol string, amount float64) (bool, error) +``` +Update the amount of collateral for a Derivative position see +https://docs.bitfinex.com/reference#rest-auth-deriv-pos-collateral-set for more +info + +#### func (*WalletService) Transfer + +```go +func (ws *WalletService) Transfer(from, to, currency, currencyTo string, amount float64) (*bitfinex.Notification, error) +``` +Submits a request to transfer funds from one Bitfinex wallet to another see +https://docs.bitfinex.com/reference#transfer-between-wallets for more info + +#### func (*WalletService) Wallet + +```go +func (s *WalletService) Wallet() (*bitfinex.WalletSnapshot, error) +``` +Retrieves all of the wallets for the account see +https://docs.bitfinex.com/reference#rest-auth-wallets for more info + +#### func (*WalletService) Withdraw + +```go +func (ws *WalletService) Withdraw(wallet, method string, amount float64, address string) (*bitfinex.Notification, error) +``` +Submits a request to withdraw funds from the given Bitfinex wallet to the given +address See https://docs.bitfinex.com/reference#withdraw for more info diff --git a/docs/v1.md b/docs/v1.md new file mode 100644 index 000000000..eb27ec331 --- /dev/null +++ b/docs/v1.md @@ -0,0 +1,1168 @@ +# bitfinex +-- + import "github.com/bitfinexcom/bitfinex-api-go/v1" + +Package bitfinex is the official client to access to bitfinex.com API + +## Usage + +```go +const ( + // BaseURL is the v1 REST endpoint. + BaseURL = "https://api.bitfinex.com/v1/" + // WebSocketURL the v1 Websocket endpoint. + WebSocketURL = "wss://api-pub.bitfinex.com/ws/" +) +``` + +```go +const ( + LEND = "lend" + LOAN = "loan" +) +``` + +```go +const ( + OrderTypeMarket = "market" + OrderTypeLimit = "limit" + OrderTypeStop = "stop" + OrderTypeTrailingStop = "trailing-stop" + OrderTypeFillOrKill = "fill-or-kill" + OrderTypeExchangeMarket = "exchange market" + OrderTypeExchangeLimit = "exchange limit" + OrderTypeExchangeStop = "exchange stop" + OrderTypeExchangeTrailingStop = "exchange trailing-stop" + OrderTypeExchangeFillOrKill = "exchange fill-or-kill" +) +``` +Order types that the API can return. + +```go +const ( + WALLET_TRADING = "trading" + WALLET_EXCHANGE = "exchange" + WALLET_DEPOSIT = "deposit" +) +``` + +```go +const ( + // Pairs + BTCUSD = "BTCUSD" + LTCUSD = "LTCUSD" + LTCBTC = "LTCBTC" + ETHUSD = "ETHUSD" + ETHBTC = "ETHBTC" + ETCUSD = "ETCUSD" + ETCBTC = "ETCBTC" + BFXUSD = "BFXUSD" + BFXBTC = "BFXBTC" + ZECUSD = "ZECUSD" + ZECBTC = "ZECBTC" + XMRUSD = "XMRUSD" + XMRBTC = "XMRBTC" + RRTUSD = "RRTUSD" + RRTBTC = "RRTBTC" + XRPUSD = "XRPUSD" + XRPBTC = "XRPBTC" + EOSETH = "EOSETH" + EOSUSD = "EOSUSD" + EOSBTC = "EOSBTC" + IOTUSD = "IOTUSD" + IOTBTC = "IOTBTC" + IOTETH = "IOTETH" + BCCBTC = "BCCBTC" + BCUBTC = "BCUBTC" + BCCUSD = "BCCUSD" + BCUUSD = "BCUUSD" + + // Channels + ChanBook = "book" + ChanTrade = "trades" + ChanTicker = "ticker" +) +``` +Pairs available + +#### type AccountInfo + +```go +type AccountInfo struct { + MakerFees float64 `json:"maker_fees,string"` + TakerFees float64 `json:"taker_fees,string"` + Fees []AccountPairFee +} +``` + + +#### type AccountPairFee + +```go +type AccountPairFee struct { + Pair string + MakerFees float64 `json:"maker_fees,string"` + TakerFees float64 `json:"taker_fees,string"` +} +``` + + +#### type AccountService + +```go +type AccountService struct { +} +``` + + +#### func (*AccountService) Info + +```go +func (a *AccountService) Info() (AccountInfo, error) +``` +GET account_infos + +#### func (*AccountService) KeyPermission + +```go +func (a *AccountService) KeyPermission() (Permissions, error) +``` + +#### func (*AccountService) Summary + +```go +func (a *AccountService) Summary() (Summary, error) +``` + +#### type ActiveOffer + +```go +type ActiveOffer struct { + ID int64 + Currency string + Rate string + Period int + Direction string + Timestamp string + IsLive bool `json:"is_live"` + IsCancelled bool `json:"is_cancelled"` + OriginalAmount string `json:"original_amount"` + RemainingAmount string `json:"remaining_amount"` + ExecutedAmount string `json:"executed_amount"` +} +``` + + +#### type Balance + +```go +type Balance struct { + Currency string + Amount string + Balance string + Description string + Timestamp string +} +``` + + +#### type BalancesService + +```go +type BalancesService struct { +} +``` + + +#### func (*BalancesService) All + +```go +func (b *BalancesService) All() ([]WalletBalance, error) +``` +GET balances + +#### type BankAccount + +```go +type BankAccount struct { + AccountName string // Account name + AccountNumber string // Account number or IBAN + BankName string // Bank Name + BankAddress string // Bank Address + BankCity string // Bank City + BankCountry string // Bank Country + SwiftCode string // SWIFT Code +} +``` + + +#### type Client + +```go +type Client struct { + // Base URL for API requests. + BaseURL *url.URL + WebSocketURL string + WebSocketTLSSkipVerify bool + + // Auth data + APIKey string + APISecret string + + // Services + Pairs *PairsService + Stats *StatsService + Ticker *TickerService + Account *AccountService + Balances *BalancesService + Offers *OffersService + Credits *CreditsService + Deposit *DepositService + Lendbook *LendbookService + MarginInfo *MarginInfoService + MarginFunding *MarginFundingService + OrderBook *OrderBookService + Orders *OrderService + Trades *TradesService + Positions *PositionsService + History *HistoryService + WebSocket *WebSocketService + Wallet *WalletService +} +``` + +Client manages all the communication with the Bitfinex API. + +#### func NewClient + +```go +func NewClient() *Client +``` +NewClient creates new Bitfinex.com API client. + +#### func (*Client) Auth + +```go +func (c *Client) Auth(key string, secret string) *Client +``` +Auth sets api key and secret for usage is requests that requires authentication. + +#### type Credit + +```go +type Credit struct { + Id int + Currency string + Status string + Rate float64 `json:",string"` + Period float64 + Amount float64 `json:",string"` + Timestamp string +} +``` + + +#### type CreditsService + +```go +type CreditsService struct { +} +``` + + +#### func (*CreditsService) All + +```go +func (c *CreditsService) All() ([]Credit, error) +``` +Returns an array of Credit + +#### type DepositResponse + +```go +type DepositResponse struct { + Result string + Method string + Currency string + Address string +} +``` + + +#### func (*DepositResponse) Success + +```go +func (d *DepositResponse) Success() (bool, error) +``` + +#### type DepositService + +```go +type DepositService struct { +} +``` + + +#### func (*DepositService) New + +```go +func (s *DepositService) New(method, walletName string, renew int) (DepositResponse, error) +``` + +#### type ErrorResponse + +```go +type ErrorResponse struct { + Response *Response + Message string `json:"message"` +} +``` + +ErrorResponse is the custom error type that is returned if the API returns an +error. + +#### func (*ErrorResponse) Error + +```go +func (r *ErrorResponse) Error() string +``` + +#### type HistoryService + +```go +type HistoryService struct { +} +``` + + +#### func (*HistoryService) Balance + +```go +func (s *HistoryService) Balance(currency, wallet string, since, until time.Time, limit int) ([]Balance, error) +``` + +#### func (*HistoryService) Movements + +```go +func (s *HistoryService) Movements(currency, method string, since, until time.Time, limit int) ([]Movement, error) +``` + +#### func (*HistoryService) Trades + +```go +func (s *HistoryService) Trades(pair string, since, until time.Time, limit int, reverse bool) ([]PastTrade, error) +``` + +#### type KeyPerm + +```go +type KeyPerm struct { + Read bool + Write bool +} +``` + + +#### type Lend + +```go +type Lend struct { + Rate string + Amount string + Period int + Timestamp string + Frr string +} +``` + + +#### func (*Lend) ParseTime + +```go +func (el *Lend) ParseTime() (*time.Time, error) +``` + +#### type Lendbook + +```go +type Lendbook struct { + Bids []Lend + Asks []Lend +} +``` + + +#### type LendbookService + +```go +type LendbookService struct { +} +``` + + +#### func (*LendbookService) Get + +```go +func (s *LendbookService) Get(currency string, limitBids, limitAsks int) (Lendbook, error) +``` +GET /lendbook/:currency + +#### func (*LendbookService) Lends + +```go +func (s *LendbookService) Lends(currency string) ([]Lends, error) +``` +GET /lends/:currency + +#### type Lends + +```go +type Lends struct { + Rate string + AmountLent string `json:"amount_lent"` + AmountUsed string `json:"amount_used"` + Timestamp int64 +} +``` + + +#### func (*Lends) Time + +```go +func (el *Lends) Time() *time.Time +``` + +#### type MarginFundingService + +```go +type MarginFundingService struct { +} +``` + + +#### func (*MarginFundingService) Cancel + +```go +func (s *MarginFundingService) Cancel(offerId int64) (MarginOffer, error) +``` + +#### func (*MarginFundingService) Credits + +```go +func (s *MarginFundingService) Credits() ([]ActiveOffer, error) +``` + +#### func (*MarginFundingService) NewLend + +```go +func (s *MarginFundingService) NewLend(currency string, amount, rate float64, period int) (MarginOffer, error) +``` + +#### func (*MarginFundingService) NewLoan + +```go +func (s *MarginFundingService) NewLoan(currency string, amount, rate float64, period int) (MarginOffer, error) +``` + +#### func (*MarginFundingService) Offers + +```go +func (s *MarginFundingService) Offers() ([]ActiveOffer, error) +``` + +#### func (*MarginFundingService) Status + +```go +func (s *MarginFundingService) Status(offerId int64) (MarginOffer, error) +``` + +#### type MarginInfo + +```go +type MarginInfo struct { + MarginBalance float64 `json:"margin_balance,string"` + TradableBalance float64 `json:"tradable_balance,string"` + UnrealizedPl float64 `json:"unrealized_pl,string"` + UnrealizedSwap float64 `json:"unrealized_swap,string"` + NetValue float64 `json:"net_value,string"` + RequiredMargin float64 `json:"required_margin,string"` + Leverage float64 `json:"leverage,string"` + MarginRequirement float64 `json:"margin_requirement,string"` + MarginLimits []MarginLimit `json:"margin_limits,string"` + Message string `json:"message"` +} +``` + + +#### type MarginInfoService + +```go +type MarginInfoService struct { +} +``` + + +#### func (*MarginInfoService) All + +```go +func (s *MarginInfoService) All() ([]MarginInfo, error) +``` +GET /margin_infos + +#### type MarginLimit + +```go +type MarginLimit struct { + OnPair string `json:"on_pair"` + InitialMargin float64 `json:"initial_margin,string"` + MarginRequirement float64 `json:"margin_requirement,string"` + TradableBalance float64 `json:"tradable_balance,string"` +} +``` + + +#### type MarginOffer + +```go +type MarginOffer struct { + ID int64 + Currency string + Rate string + Period int + Direction string + Timestamp string + IsLive bool `json:"is_live"` + IsCancelled bool `json:"is_cancelled"` + OriginalAmount string `json:"original_amount"` + RemainingAmount string `json:"remaining_amount"` + ExecutedAmount string `json:"executed_amount"` + OfferId int +} +``` + + +#### type Movement + +```go +type Movement struct { + ID int64 `json:",int"` + Currency string + Method string + Type string + Amount string + Description string + Status string + Timestamp string +} +``` + + +#### type MultipleOrderResponse + +```go +type MultipleOrderResponse struct { + Orders []Order `json:"order_ids"` + Status string +} +``` + +MultipleOrderResponse bundles orders returned by the CreateMulti method. + +#### type Offer + +```go +type Offer struct { + Id int64 + Currency string + Rate string + Period int64 + Direction string + Timestamp string + IsLive bool `json:"is_live"` + IsCancelled bool `json:"is_cancelled"` + OriginalAmount string `json:"original_amount:string"` + RemainingAmount string `json:"remaining_amount:string"` + ExecutedAmount string `json:"executed_amount:string"` + OfferId int64 `json:"offer_id"` +} +``` + + +#### type OffersService + +```go +type OffersService struct { +} +``` + + +#### func (*OffersService) Cancel + +```go +func (s *OffersService) Cancel(offerId int64) (Offer, error) +``` + +#### func (*OffersService) New + +```go +func (s *OffersService) New(currency string, amount, rate float64, period int64, direction string) (Offer, error) +``` +Create new offer for LEND or LOAN a currency, use LEND or LOAN constants as +direction + +#### func (*OffersService) Status + +```go +func (s *OffersService) Status(offerId int64) (Offer, error) +``` + +#### type Order + +```go +type Order struct { + ID int64 + Symbol string + Exchange string + Price string + AvgExecutionPrice string `json:"avg_execution_price"` + Side string + Type string + Timestamp string + IsLive bool `json:"is_live"` + IsCanceled bool `json:"is_cancelled"` + IsHidden bool `json:"is_hidden"` + WasForced bool `json:"was_forced"` + OriginalAmount string `json:"original_amount"` + RemainingAmount string `json:"remaining_amount"` + ExecutedAmount string `json:"executed_amount"` +} +``` + +Order represents one order on the bitfinex platform. + +#### type OrderBook + +```go +type OrderBook struct { + Bids []OrderBookEntry + Asks []OrderBookEntry +} +``` + + +#### type OrderBookEntry + +```go +type OrderBookEntry struct { + Price string + Rate string + Amount string + Period int + Timestamp string + Frr string +} +``` + + +#### func (*OrderBookEntry) ParseTime + +```go +func (el *OrderBookEntry) ParseTime() (*time.Time, error) +``` + +#### type OrderBookService + +```go +type OrderBookService struct { +} +``` + + +#### func (*OrderBookService) Get + +```go +func (s *OrderBookService) Get(pair string, limitBids, limitAsks int, noGroup bool) (OrderBook, error) +``` +GET /book + +#### type OrderService + +```go +type OrderService struct { +} +``` + +OrderService manages the Order endpoint. + +#### func (*OrderService) All + +```go +func (s *OrderService) All() ([]Order, error) +``` +All returns all orders for the authenticated account. + +#### func (*OrderService) Cancel + +```go +func (s *OrderService) Cancel(orderID int64) error +``` +Cancel the order with id `orderID`. + +#### func (*OrderService) CancelAll + +```go +func (s *OrderService) CancelAll() error +``` +CancelAll active orders for the authenticated account. + +#### func (*OrderService) CancelMulti + +```go +func (s *OrderService) CancelMulti(orderIDS []int64) (string, error) +``` +CancelMulti allows batch cancellation of orders. + +#### func (*OrderService) Create + +```go +func (s *OrderService) Create(symbol string, amount float64, price float64, orderType string) (*Order, error) +``` +Create a new order. + +#### func (*OrderService) CreateMulti + +```go +func (s *OrderService) CreateMulti(orders []SubmitOrder) (MultipleOrderResponse, error) +``` +CreateMulti allows batch creation of orders. + +#### func (*OrderService) Replace + +```go +func (s *OrderService) Replace(orderID int64, useRemaining bool, newOrder SubmitOrder) (Order, error) +``` +Replace an Order + +#### func (*OrderService) Status + +```go +func (s *OrderService) Status(orderID int64) (Order, error) +``` +Status retrieves the given order from the API. + +#### type Pair + +```go +type Pair struct { + Pair string + PricePrecision int `json:"price_precision,int"` + InitialMargin float64 `json:"initial_margin,string"` + MinimumMargin float64 `json:"minimum_margin,string"` + MaximumOrderSize float64 `json:"maximum_order_size,string"` + MinimumOrderSize float64 `json:"minimum_order_size,string"` + Expiration string + Margin bool +} +``` + +Detailed Pair + +#### type PairsService + +```go +type PairsService struct { +} +``` + + +#### func (*PairsService) All + +```go +func (p *PairsService) All() ([]string, error) +``` +Get all Pair names as array of strings + +#### func (*PairsService) AllDetailed + +```go +func (p *PairsService) AllDetailed() ([]Pair, error) +``` +Return a list of detailed pairs + +#### type PastTrade + +```go +type PastTrade struct { + Price string + Amount string + Timestamp string + Exchange string + Type string + FeeCurrency string `json:"fee_currency"` + FeeAmount string `json:"fee_amount"` + TID int64 + OrderId int64 `json:"order_id,int"` +} +``` + + +#### type Permissions + +```go +type Permissions struct { + Account KeyPerm + History KeyPerm + Orders KeyPerm + Positions KeyPerm + Funding KeyPerm + Wallets KeyPerm + Withdraw KeyPerm +} +``` + + +#### type Position + +```go +type Position struct { + ID int + Symbol string + Amount string + Status string + Base string + Timestamp string + Swap string + Pl string +} +``` + +Position structure + +#### func (*Position) ParseTime + +```go +func (p *Position) ParseTime() (*time.Time, error) +``` + +#### type PositionsService + +```go +type PositionsService struct { +} +``` + +PositionsService structure + +#### func (*PositionsService) All + +```go +func (b *PositionsService) All() ([]Position, error) +``` +All - gets all positions + +#### func (*PositionsService) Claim + +```go +func (b *PositionsService) Claim(positionId int, amount string) (Position, error) +``` +Claim a position + +#### type Response + +```go +type Response struct { + Response *http.Response + Body []byte +} +``` + +Response is wrapper for standard http.Response and provides more methods. + +#### func (*Response) String + +```go +func (r *Response) String() string +``` +String converts response body to string. An empty string will be returned if +error. + +#### type Stats + +```go +type Stats struct { + Period int64 + Volume float64 `json:"volume,string"` +} +``` + + +#### type StatsService + +```go +type StatsService struct { +} +``` + + +#### func (*StatsService) All + +```go +func (s *StatsService) All(pair string, period, volume string) ([]Stats, error) +``` +All(pair) - Volume stats for specified pair + +#### type SubmitOrder + +```go +type SubmitOrder struct { + Symbol string + Amount float64 + Price float64 + Type string +} +``` + +SubmitOrder is an order to be created on the bitfinex platform. + +#### type Summary + +```go +type Summary struct { + TradeVolume SummaryVolume `json:"trade_vol_30d"` + FundingProfit SummaryProfit `json:"funding_profit_30d"` + MakerFee string `json:"maker_fee"` + TakerFee string `json:"taker_fee"` +} +``` + + +#### type SummaryProfit + +```go +type SummaryProfit struct { + Currency string `json:"curr"` + Volume string `json:"amount"` +} +``` + + +#### type SummaryVolume + +```go +type SummaryVolume struct { + Currency string `json:"curr"` + Volume string `json:"vol"` +} +``` + + +#### type TermData + +```go +type TermData struct { + // Data term. E.g: ps, ws, ou, etc... See official documentation for more details. + Term string + // Data will contain different number of elements for each term. + // Examples: + // Term: ws, Data: ["exchange","BTC",0.01410829,0] + // Term: oc, Data: [0,"BTCUSD",0,-0.01,"","CANCELED",270,0,"2015-10-15T11:26:13Z",0] + Data []interface{} + Error string +} +``` + + +#### func (*TermData) HasError + +```go +func (c *TermData) HasError() bool +``` + +#### type Tick + +```go +type Tick struct { + Mid string + Bid string + Ask string + LastPrice string `json:"last_price"` + Low string + High string + Volume string + Timestamp string +} +``` + + +#### func (*Tick) ParseTime + +```go +func (el *Tick) ParseTime() (*time.Time, error) +``` +ParseTime - return Timestamp in time.Time format + +#### type TickerService + +```go +type TickerService struct { +} +``` + + +#### func (*TickerService) Get + +```go +func (s *TickerService) Get(pair string) (Tick, error) +``` +Get(pair) - return last Tick for specified pair + +#### type Trade + +```go +type Trade struct { + Price string + Amount string + Exchange string + Type string + Timestamp int64 + TradeId int64 `json:"tid,int"` +} +``` + + +#### func (*Trade) Time + +```go +func (el *Trade) Time() *time.Time +``` + +#### type TradesService + +```go +type TradesService struct { +} +``` + + +#### func (*TradesService) All + +```go +func (s *TradesService) All(pair string, timestamp time.Time, limitTrades int) ([]Trade, error) +``` + +#### type TransferStatus + +```go +type TransferStatus struct { + Status string + Message string +} +``` + + +#### type WalletBalance + +```go +type WalletBalance struct { + Type string + Currency string + Amount string + Available string +} +``` + + +#### type WalletService + +```go +type WalletService struct { +} +``` + + +#### func (*WalletService) Transfer + +```go +func (c *WalletService) Transfer(amount float64, currency, from, to string) ([]TransferStatus, error) +``` +Transfer funds between wallets + +#### func (*WalletService) WithdrawCrypto + +```go +func (c *WalletService) WithdrawCrypto(amount float64, currency, wallet, destinationAddress string) ([]WithdrawStatus, error) +``` +Withdraw a cryptocurrency to a digital wallet + +#### func (*WalletService) WithdrawWire + +```go +func (c *WalletService) WithdrawWire(amount float64, expressWire bool, wallet string, beneficiaryBank, intermediaryBank BankAccount, message string) ([]WithdrawStatus, error) +``` + +#### type WebSocketService + +```go +type WebSocketService struct { +} +``` + +WebSocketService allow to connect and receive stream data from bitfinex.com ws +service. nolint:megacheck,structcheck + +#### func NewWebSocketService + +```go +func NewWebSocketService(c *Client) *WebSocketService +``` +NewWebSocketService returns a WebSocketService using the given client. + +#### func (*WebSocketService) AddSubscribe + +```go +func (w *WebSocketService) AddSubscribe(channel string, pair string, c chan []float64) +``` + +#### func (*WebSocketService) ClearSubscriptions + +```go +func (w *WebSocketService) ClearSubscriptions() +``` + +#### func (*WebSocketService) Close + +```go +func (w *WebSocketService) Close() +``` +Close web socket connection + +#### func (*WebSocketService) Connect + +```go +func (w *WebSocketService) Connect() error +``` +Connect create new bitfinex websocket connection + +#### func (*WebSocketService) ConnectPrivate + +```go +func (w *WebSocketService) ConnectPrivate(ch chan TermData) +``` + +#### func (*WebSocketService) Subscribe + +```go +func (w *WebSocketService) Subscribe() error +``` +Subscribe allows to subsribe to channels and watch for new updates. This method +supports next channels: book, trade, ticker. + +#### type WithdrawStatus + +```go +type WithdrawStatus struct { + Status string + Message string + WithdrawalID int `json:"withdrawal_id"` +} +``` diff --git a/docs/ws_v2.md b/docs/ws_v2.md new file mode 100644 index 000000000..4f531bf0f --- /dev/null +++ b/docs/ws_v2.md @@ -0,0 +1,981 @@ +# websocket +-- + import "github.com/bitfinexcom/bitfinex-api-go/v2/websocket" + + +## Usage + +```go +const ( + ChanBook = "book" + ChanTrades = "trades" + ChanTicker = "ticker" + ChanCandles = "candles" + ChanStatus = "status" +) +``` +Available channels + +```go +const ( + EventSubscribe = "subscribe" + EventUnsubscribe = "unsubscribe" + EventPing = "ping" +) +``` +Events + +```go +const ( + ErrorCodeUnknownEvent int = 10000 + ErrorCodeUnknownPair int = 10001 + ErrorCodeUnknownBookPrecision int = 10011 + ErrorCodeUnknownBookLength int = 10012 + ErrorCodeSubscriptionFailed int = 10300 + ErrorCodeAlreadySubscribed int = 10301 + ErrorCodeUnknownChannel int = 10302 + ErrorCodeUnsubscribeFailed int = 10400 + ErrorCodeNotSubscribed int = 10401 +) +``` +error codes pulled from v2 docs & API usage + +```go +const DMSCancelOnDisconnect int = 4 +``` +DMSCancelOnDisconnect cancels session orders on disconnect. + +```go +const KEEP_ALIVE_TIMEOUT = 10 +``` +seconds to wait in between re-sending the keep alive ping + +```go +const MaxChannels = 25 +``` + +```go +const WS_READ_CAPACITY = 10 +``` +size of channel that the websocket reader routine pushes websocket updates into + +```go +const WS_WRITE_CAPACITY = 100 +``` +size of channel that the websocket writer routine pulls from + +```go +var ( + ErrWSNotConnected = fmt.Errorf("websocket connection not established") + ErrWSAlreadyConnected = fmt.Errorf("websocket connection already established") +) +``` +ws-specific errors + +#### func ConvertBytesToJsonNumberArray + +```go +func ConvertBytesToJsonNumberArray(raw_bytes []byte) ([]interface{}, error) +``` + +#### type Asynchronous + +```go +type Asynchronous interface { + Connect() error + Send(ctx context.Context, msg interface{}) error + Listen() <-chan []byte + Close() + Done() <-chan error +} +``` + +Asynchronous interface decouples the underlying transport from API logic. + +#### type AsynchronousFactory + +```go +type AsynchronousFactory interface { + Create() Asynchronous +} +``` + +AsynchronousFactory provides an interface to re-create asynchronous transports +during reconnect events. + +#### func NewWebsocketAsynchronousFactory + +```go +func NewWebsocketAsynchronousFactory(parameters *Parameters) AsynchronousFactory +``` +NewWebsocketAsynchronousFactory creates a new websocket factory with a given +URL. + +#### type AuthEvent + +```go +type AuthEvent struct { + Event string `json:"event"` + Status string `json:"status"` + ChanID int64 `json:"chanId,omitempty"` + UserID int64 `json:"userId,omitempty"` + SubID string `json:"subId"` + AuthID string `json:"auth_id,omitempty"` + Message string `json:"msg,omitempty"` + Caps Capabilities `json:"caps"` +} +``` + + +#### type AuthState + +```go +type AuthState authState // prevent user construction of authStates + +``` + +AuthState provides a typed authentication state. + +```go +const ( + NoAuthentication AuthState = 0 + PendingAuthentication AuthState = 1 + SuccessfulAuthentication AuthState = 2 + RejectedAuthentication AuthState = 3 +) +``` +Authentication states + +#### type BookFactory + +```go +type BookFactory struct { +} +``` + + +#### func (*BookFactory) Build + +```go +func (f *BookFactory) Build(chanID int64, objType string, raw []interface{}, raw_bytes []byte) (interface{}, error) +``` + +#### func (*BookFactory) BuildSnapshot + +```go +func (f *BookFactory) BuildSnapshot(chanID int64, raw [][]interface{}, raw_bytes []byte) (interface{}, error) +``` + +#### func (BookFactory) Close + +```go +func (s BookFactory) Close() +``` +Close is terminal. Do not call heartbeat after close. + +#### func (BookFactory) ListenDisconnect + +```go +func (s BookFactory) ListenDisconnect() <-chan HeartbeatDisconnect +``` +ListenDisconnect returns an error channel which receives a message when a +heartbeat has expired a channel. + +#### func (BookFactory) ResetAll + +```go +func (s BookFactory) ResetAll() +``` +Removes all tracked subscriptions + +#### func (BookFactory) ResetSocketSubscriptions + +```go +func (s BookFactory) ResetSocketSubscriptions(socketId SocketId) []*subscription +``` +Reset clears all subscriptions assigned to the given socket ID, and returns a +slice of the existing subscriptions prior to reset + +#### type CandlesFactory + +```go +type CandlesFactory struct { +} +``` + + +#### func (*CandlesFactory) Build + +```go +func (f *CandlesFactory) Build(chanID int64, objType string, raw []interface{}, raw_bytes []byte) (interface{}, error) +``` + +#### func (*CandlesFactory) BuildSnapshot + +```go +func (f *CandlesFactory) BuildSnapshot(chanID int64, raw [][]interface{}, raw_bytes []byte) (interface{}, error) +``` + +#### func (CandlesFactory) Close + +```go +func (s CandlesFactory) Close() +``` +Close is terminal. Do not call heartbeat after close. + +#### func (CandlesFactory) ListenDisconnect + +```go +func (s CandlesFactory) ListenDisconnect() <-chan HeartbeatDisconnect +``` +ListenDisconnect returns an error channel which receives a message when a +heartbeat has expired a channel. + +#### func (CandlesFactory) ResetAll + +```go +func (s CandlesFactory) ResetAll() +``` +Removes all tracked subscriptions + +#### func (CandlesFactory) ResetSocketSubscriptions + +```go +func (s CandlesFactory) ResetSocketSubscriptions(socketId SocketId) []*subscription +``` +Reset clears all subscriptions assigned to the given socket ID, and returns a +slice of the existing subscriptions prior to reset + +#### type Capabilities + +```go +type Capabilities struct { + Orders Capability `json:"orders"` + Account Capability `json:"account"` + Funding Capability `json:"funding"` + History Capability `json:"history"` + Wallets Capability `json:"wallets"` + Withdraw Capability `json:"withdraw"` + Positions Capability `json:"positions"` +} +``` + + +#### type Capability + +```go +type Capability struct { + Read int `json:"read"` + Write int `json:"write"` +} +``` + + +#### type Client + +```go +type Client struct { + Authentication AuthState +} +``` + +Client provides a unified interface for users to interact with the Bitfinex V2 +Websocket API. nolint:megacheck,structcheck + +#### func New + +```go +func New() *Client +``` +New creates a default client. + +#### func NewWithAsyncFactory + +```go +func NewWithAsyncFactory(async AsynchronousFactory) *Client +``` +NewWithAsyncFactory creates a new default client with a given asynchronous +transport factory interface. + +#### func NewWithAsyncFactoryNonce + +```go +func NewWithAsyncFactoryNonce(async AsynchronousFactory, nonce utils.NonceGenerator) *Client +``` +NewWithAsyncFactoryNonce creates a new default client with a given asynchronous +transport factory and nonce generator. + +#### func NewWithParams + +```go +func NewWithParams(params *Parameters) *Client +``` +NewWithParams creates a new default client with a given set of parameters. + +#### func NewWithParamsAsyncFactory + +```go +func NewWithParamsAsyncFactory(params *Parameters, async AsynchronousFactory) *Client +``` +NewWithParamsAsyncFactory creates a new default client with a given set of +parameters and asynchronous transport factory interface. + +#### func NewWithParamsAsyncFactoryNonce + +```go +func NewWithParamsAsyncFactoryNonce(params *Parameters, async AsynchronousFactory, nonce utils.NonceGenerator) *Client +``` +NewWithParamsAsyncFactoryNonce creates a new client with a given set of +parameters, asynchronous transport factory, and nonce generator interfaces. + +#### func NewWithParamsNonce + +```go +func NewWithParamsNonce(params *Parameters, nonce utils.NonceGenerator) *Client +``` +NewWithParamsNonce creates a new default client with a given set of parameters +and nonce generator. + +#### func (*Client) AvailableCapacity + +```go +func (c *Client) AvailableCapacity() int +``` +Get the available capacity of the current websocket connections + +#### func (*Client) CancelOnDisconnect + +```go +func (c *Client) CancelOnDisconnect(cxl bool) *Client +``` +CancelOnDisconnect ensures all orders will be canceled if this API session is +disconnected. + +#### func (*Client) Close + +```go +func (c *Client) Close() +``` +Close the websocket client which will cause for all active sockets to be exited +and the Done() function to be called + +#### func (*Client) Connect + +```go +func (c *Client) Connect() error +``` +Connect to the Bitfinex API, this should only be called once. + +#### func (*Client) ConnectionCount + +```go +func (c *Client) ConnectionCount() int +``` +Gen the count of currently active websocket connections + +#### func (*Client) Credentials + +```go +func (c *Client) Credentials(key string, secret string) *Client +``` +Credentials assigns authentication credentials to a connection request. + +#### func (*Client) EnableFlag + +```go +func (c *Client) EnableFlag(ctx context.Context, flag int) (string, error) +``` +Submit a request to enable the given flag + +#### func (*Client) GetAuthenticatedSocket + +```go +func (c *Client) GetAuthenticatedSocket() (*Socket, error) +``` +Get the authenticated socket. Due to rate limitations there can only be one +authenticated socket active at a time + +#### func (*Client) GetOrderbook + +```go +func (c *Client) GetOrderbook(symbol string) (*Orderbook, error) +``` +Retrieve the Orderbook for the given symbol which is managed locally. This +requires ManageOrderbook=True and an active chanel subscribed to the given +symbols orderbook + +#### func (*Client) IsConnected + +```go +func (c *Client) IsConnected() bool +``` +Returns true if the underlying asynchronous transport is connected to an +endpoint. + +#### func (*Client) Listen + +```go +func (c *Client) Listen() <-chan interface{} +``` +Listen for all incoming api websocket messages When a websocket connection is +terminated, the publisher channel will close. + +#### func (*Client) LookupSubscription + +```go +func (c *Client) LookupSubscription(subID string) (*SubscriptionRequest, error) +``` +Get a subscription request using a subscription ID + +#### func (*Client) Send + +```go +func (c *Client) Send(ctx context.Context, msg interface{}) error +``` +Send publishes a generic message to the Bitfinex API. + +#### func (*Client) StartNewConnection + +```go +func (c *Client) StartNewConnection() error +``` +Start a new websocket connection. This function is only exposed in case you want +to implicitly add new connections otherwise connection management is already +handled for you. + +#### func (*Client) SubmitCancel + +```go +func (c *Client) SubmitCancel(ctx context.Context, cancel *bitfinex.OrderCancelRequest) error +``` +Submit a cancel request for an existing order + +#### func (*Client) SubmitFundingCancel + +```go +func (c *Client) SubmitFundingCancel(ctx context.Context, fundingOffer *bitfinex.FundingOfferCancelRequest) error +``` +Submit a request to cancel and existing funding offer + +#### func (*Client) SubmitFundingOffer + +```go +func (c *Client) SubmitFundingOffer(ctx context.Context, fundingOffer *bitfinex.FundingOfferRequest) error +``` +Submit a new funding offer request + +#### func (*Client) SubmitOrder + +```go +func (c *Client) SubmitOrder(ctx context.Context, order *bitfinex.OrderNewRequest) error +``` +Submit a request to create a new order + +#### func (*Client) SubmitUpdateOrder + +```go +func (c *Client) SubmitUpdateOrder(ctx context.Context, orderUpdate *bitfinex.OrderUpdateRequest) error +``` +Submit and update request to change an existing orders values + +#### func (*Client) Subscribe + +```go +func (c *Client) Subscribe(ctx context.Context, req *SubscriptionRequest) (string, error) +``` +Submit a request to subscribe to the given SubscriptionRequuest + +#### func (*Client) SubscribeBook + +```go +func (c *Client) SubscribeBook(ctx context.Context, symbol string, precision bitfinex.BookPrecision, frequency bitfinex.BookFrequency, priceLevel int) (string, error) +``` +Submit a subscription request for market data for the given symbol, at the given +frequency, with the given precision, returning no more than priceLevels price +entries. Default values are Precision0, Frequency0, and priceLevels=25. + +#### func (*Client) SubscribeCandles + +```go +func (c *Client) SubscribeCandles(ctx context.Context, symbol string, resolution bitfinex.CandleResolution) (string, error) +``` +Submit a subscription request to receive candle updates + +#### func (*Client) SubscribeStatus + +```go +func (c *Client) SubscribeStatus(ctx context.Context, symbol string, sType bitfinex.StatusType) (string, error) +``` +Submit a subscription request for status updates + +#### func (*Client) SubscribeTicker + +```go +func (c *Client) SubscribeTicker(ctx context.Context, symbol string) (string, error) +``` +Submit a request to receive ticker updates + +#### func (*Client) SubscribeTrades + +```go +func (c *Client) SubscribeTrades(ctx context.Context, symbol string) (string, error) +``` +Submit a request to receive trade updates + +#### func (*Client) Unsubscribe + +```go +func (c *Client) Unsubscribe(ctx context.Context, id string) error +``` +Unsubscribe from the existing subscription with the given id + +#### type ConfEvent + +```go +type ConfEvent struct { + Flags int `json:"flags"` +} +``` + + +#### type ErrorEvent + +```go +type ErrorEvent struct { + Code int `json:"code"` + Message string `json:"msg"` + + // also contain members related to subscription reject + SubID string `json:"subId"` + Channel string `json:"channel"` + ChanID int64 `json:"chanId"` + Symbol string `json:"symbol"` + Precision string `json:"prec,omitempty"` + Frequency string `json:"freq,omitempty"` + Key string `json:"key,omitempty"` + Len string `json:"len,omitempty"` + Pair string `json:"pair"` +} +``` + + +#### type FlagRequest + +```go +type FlagRequest struct { + Event string `json:"event"` + Flags int `json:"flags"` +} +``` + + +#### type HeartbeatDisconnect + +```go +type HeartbeatDisconnect struct { + Subscription *subscription + Error error +} +``` + + +#### type InfoEvent + +```go +type InfoEvent struct { + Version float64 `json:"version"` + ServerId string `json:"serverId"` + Platform PlatformInfo `json:"platform"` + Code int `json:"code"` + Msg string `json:"msg"` +} +``` + + +#### type Orderbook + +```go +type Orderbook struct { +} +``` + + +#### func (*Orderbook) Asks + +```go +func (ob *Orderbook) Asks() []bitfinex.BookUpdate +``` + +#### func (*Orderbook) Bids + +```go +func (ob *Orderbook) Bids() []bitfinex.BookUpdate +``` + +#### func (*Orderbook) Checksum + +```go +func (ob *Orderbook) Checksum() uint32 +``` + +#### func (*Orderbook) SetWithSnapshot + +```go +func (ob *Orderbook) SetWithSnapshot(bs *bitfinex.BookUpdateSnapshot) +``` + +#### func (*Orderbook) Symbol + +```go +func (ob *Orderbook) Symbol() string +``` + +#### func (*Orderbook) UpdateWith + +```go +func (ob *Orderbook) UpdateWith(bu *bitfinex.BookUpdate) +``` + +#### type Parameters + +```go +type Parameters struct { + AutoReconnect bool + ReconnectInterval time.Duration + ReconnectAttempts int + + ShutdownTimeout time.Duration + CapacityPerConnection int + Logger *logging.Logger + + ResubscribeOnReconnect bool + + HeartbeatTimeout time.Duration + LogTransport bool + + URL string + ManageOrderbook bool +} +``` + +Parameters defines adapter behavior. + +#### func NewDefaultParameters + +```go +func NewDefaultParameters() *Parameters +``` + +#### type PlatformInfo + +```go +type PlatformInfo struct { + Status int `json:"status"` +} +``` + + +#### type RawEvent + +```go +type RawEvent struct { + Data interface{} +} +``` + + +#### type Socket + +```go +type Socket struct { + Id SocketId + Asynchronous + IsConnected bool + ResetSubscriptions []*subscription + IsAuthenticated bool +} +``` + + +#### type SocketId + +```go +type SocketId int +``` + + +#### type StatsFactory + +```go +type StatsFactory struct { +} +``` + + +#### func (*StatsFactory) Build + +```go +func (f *StatsFactory) Build(chanID int64, objType string, raw []interface{}, raw_bytes []byte) (interface{}, error) +``` + +#### func (*StatsFactory) BuildSnapshot + +```go +func (f *StatsFactory) BuildSnapshot(chanID int64, raw [][]interface{}, raw_bytes []byte) (interface{}, error) +``` + +#### func (StatsFactory) Close + +```go +func (s StatsFactory) Close() +``` +Close is terminal. Do not call heartbeat after close. + +#### func (StatsFactory) ListenDisconnect + +```go +func (s StatsFactory) ListenDisconnect() <-chan HeartbeatDisconnect +``` +ListenDisconnect returns an error channel which receives a message when a +heartbeat has expired a channel. + +#### func (StatsFactory) ResetAll + +```go +func (s StatsFactory) ResetAll() +``` +Removes all tracked subscriptions + +#### func (StatsFactory) ResetSocketSubscriptions + +```go +func (s StatsFactory) ResetSocketSubscriptions(socketId SocketId) []*subscription +``` +Reset clears all subscriptions assigned to the given socket ID, and returns a +slice of the existing subscriptions prior to reset + +#### type SubscribeEvent + +```go +type SubscribeEvent struct { + SubID string `json:"subId"` + Channel string `json:"channel"` + ChanID int64 `json:"chanId"` + Symbol string `json:"symbol"` + Precision string `json:"prec,omitempty"` + Frequency string `json:"freq,omitempty"` + Key string `json:"key,omitempty"` + Len string `json:"len,omitempty"` + Pair string `json:"pair"` +} +``` + + +#### type SubscriptionRequest + +```go +type SubscriptionRequest struct { + SubID string `json:"subId"` + Event string `json:"event"` + + // authenticated + APIKey string `json:"apiKey,omitempty"` + AuthSig string `json:"authSig,omitempty"` + AuthPayload string `json:"authPayload,omitempty"` + AuthNonce string `json:"authNonce,omitempty"` + Filter []string `json:"filter,omitempty"` + DMS int `json:"dms,omitempty"` // dead man switch + + // unauthenticated + Channel string `json:"channel,omitempty"` + Symbol string `json:"symbol,omitempty"` + Precision string `json:"prec,omitempty"` + Frequency string `json:"freq,omitempty"` + Key string `json:"key,omitempty"` + Len string `json:"len,omitempty"` + Pair string `json:"pair,omitempty"` +} +``` + + +#### func (*SubscriptionRequest) String + +```go +func (s *SubscriptionRequest) String() string +``` + +#### type SubscriptionSet + +```go +type SubscriptionSet []*subscription +``` + +SubscriptionSet is a typed version of an array of subscription pointers, +intended to meet the sortable interface. We need to sort Reset()'s return values +for tests with more than 1 subscription (range map order is undefined) + +#### func (SubscriptionSet) Len + +```go +func (s SubscriptionSet) Len() int +``` + +#### func (SubscriptionSet) Less + +```go +func (s SubscriptionSet) Less(i, j int) bool +``` + +#### func (SubscriptionSet) RemoveByChannelId + +```go +func (s SubscriptionSet) RemoveByChannelId(chanId int64) SubscriptionSet +``` + +#### func (SubscriptionSet) RemoveBySubscriptionId + +```go +func (s SubscriptionSet) RemoveBySubscriptionId(subID string) SubscriptionSet +``` + +#### func (SubscriptionSet) Swap + +```go +func (s SubscriptionSet) Swap(i, j int) +``` + +#### type TickerFactory + +```go +type TickerFactory struct { +} +``` + + +#### func (*TickerFactory) Build + +```go +func (f *TickerFactory) Build(chanID int64, objType string, raw []interface{}, raw_bytes []byte) (interface{}, error) +``` + +#### func (*TickerFactory) BuildSnapshot + +```go +func (f *TickerFactory) BuildSnapshot(chanID int64, raw [][]interface{}, raw_bytes []byte) (interface{}, error) +``` + +#### func (TickerFactory) Close + +```go +func (s TickerFactory) Close() +``` +Close is terminal. Do not call heartbeat after close. + +#### func (TickerFactory) ListenDisconnect + +```go +func (s TickerFactory) ListenDisconnect() <-chan HeartbeatDisconnect +``` +ListenDisconnect returns an error channel which receives a message when a +heartbeat has expired a channel. + +#### func (TickerFactory) ResetAll + +```go +func (s TickerFactory) ResetAll() +``` +Removes all tracked subscriptions + +#### func (TickerFactory) ResetSocketSubscriptions + +```go +func (s TickerFactory) ResetSocketSubscriptions(socketId SocketId) []*subscription +``` +Reset clears all subscriptions assigned to the given socket ID, and returns a +slice of the existing subscriptions prior to reset + +#### type TradeFactory + +```go +type TradeFactory struct { +} +``` + + +#### func (*TradeFactory) Build + +```go +func (f *TradeFactory) Build(chanID int64, objType string, raw []interface{}, raw_bytes []byte) (interface{}, error) +``` + +#### func (*TradeFactory) BuildSnapshot + +```go +func (f *TradeFactory) BuildSnapshot(chanID int64, raw [][]interface{}, raw_bytes []byte) (interface{}, error) +``` + +#### func (TradeFactory) Close + +```go +func (s TradeFactory) Close() +``` +Close is terminal. Do not call heartbeat after close. + +#### func (TradeFactory) ListenDisconnect + +```go +func (s TradeFactory) ListenDisconnect() <-chan HeartbeatDisconnect +``` +ListenDisconnect returns an error channel which receives a message when a +heartbeat has expired a channel. + +#### func (TradeFactory) ResetAll + +```go +func (s TradeFactory) ResetAll() +``` +Removes all tracked subscriptions + +#### func (TradeFactory) ResetSocketSubscriptions + +```go +func (s TradeFactory) ResetSocketSubscriptions(socketId SocketId) []*subscription +``` +Reset clears all subscriptions assigned to the given socket ID, and returns a +slice of the existing subscriptions prior to reset + +#### type UnsubscribeEvent + +```go +type UnsubscribeEvent struct { + Status string `json:"status"` + ChanID int64 `json:"chanId"` +} +``` + + +#### type UnsubscribeRequest + +```go +type UnsubscribeRequest struct { + Event string `json:"event"` + ChanID int64 `json:"chanId"` +} +``` + + +#### type WebsocketAsynchronousFactory + +```go +type WebsocketAsynchronousFactory struct { +} +``` + +WebsocketAsynchronousFactory creates a websocket-based asynchronous transport. + +#### func (*WebsocketAsynchronousFactory) Create + +```go +func (w *WebsocketAsynchronousFactory) Create() Asynchronous +``` +Create returns a new websocket transport. diff --git a/readme.md b/readme.md deleted file mode 100644 index b30f0eafd..000000000 --- a/readme.md +++ /dev/null @@ -1,77 +0,0 @@ -# Bitfinex Trading API for Golang -## Bitcoin, Ether and Litecoin trading ![https://api.travis-ci.org/bitfinexcom/bitfinex-api-go.svg?branch=master](https://api.travis-ci.org/bitfinexcom/bitfinex-api-go.svg?branch=master) -* Official implementation -* REST API -* WebSockets API - -## Installation - -``` bash -go get github.com/bitfinexcom/bitfinex-api-go -``` - -## Usage - -### Basic requests - -``` go -package main - -import ( - "fmt" - "github.com/bitfinexcom/bitfinex-api-go/v1" -) - -func main() { - client := bitfinex.NewClient().Auth("api-key", "api-secret") - info, err := client.Account.Info() - - if err != nil { - fmt.Println(err) - } else { - fmt.Println(info) - } -} -``` - -### Authentication - -``` go -func main() { - client := bitfinex.NewClient().Auth("api-key", "api-secret") -} -``` - -### Order create - -``` go -order, err := client.Orders.Create(bitfinex.BTCUSD, -0.01, 260.99, bitfinex.OrderTypeExchangeLimit) - -if err != nil { - return err -} else { - return order -} -``` - -See [examples](https://github.com/bitfinexcom/bitfinex-api-go/tree/master/examples) and [doc.go](https://github.com/bitfinexcom/bitfinex-api-go/blob/master/doc.go) for more examples. - -## Testing - -All integration tests are stored in `tests/integration` directory. Because these tests are running using live data, there is a much higher probability of false positives in test failures due to network issues, test data having been changed, etc. - -Run tests using: - -``` bash -export BFX_API_KEY="api-key" -export BFX_API_SECRET="api-secret" -go test -v ./tests/integration -``` - -## Contributing - -1. Fork it (https://github.com/bitfinexcom/bitfinex-api-go/fork) -2. Create your feature branch (`git checkout -b my-new-feature) -3. Commit your changes (`git commit -am 'Add some feature'`) -4. Push to the branch (`git push origin my-new-feature`) -5. Create a new Pull Request diff --git a/v2/rest/book.go b/v2/rest/book.go index 39606d144..7532d0881 100644 --- a/v2/rest/book.go +++ b/v2/rest/book.go @@ -11,6 +11,8 @@ type BookService struct { Synchronous } +// Retrieve all books for the given symbol with the given precision at the given price level +// see https://docs.bitfinex.com/reference#rest-public-books for more info func (b *BookService) All(symbol string, precision bitfinex.BookPrecision, priceLevels int) (*bitfinex.BookUpdateSnapshot, error) { req := NewRequestWithMethod(path.Join("book", symbol, string(precision)), "GET") req.Params = make(url.Values) diff --git a/v2/rest/candles.go b/v2/rest/candles.go index 0781e53ec..be79f0dba 100644 --- a/v2/rest/candles.go +++ b/v2/rest/candles.go @@ -14,7 +14,8 @@ type CandleService struct { Synchronous } -// Return Candles for the public account. +// Retrieve the last candle for the given symbol with the given resolution +// See https://docs.bitfinex.com/reference#rest-public-candles for more info func (c *CandleService) Last(symbol string, resolution bitfinex.CandleResolution) (*bitfinex.Candle, error) { if symbol == "" { return nil, fmt.Errorf("symbol cannot be empty") @@ -39,7 +40,8 @@ func (c *CandleService) Last(symbol string, resolution bitfinex.CandleResolution return cs, nil } -// Return Candles for the public account. +// Retrieves all candles (Max=1000) with the given symbol and the given candle resolution +// See https://docs.bitfinex.com/reference#rest-public-candles for more info func (c *CandleService) History(symbol string, resolution bitfinex.CandleResolution) (*bitfinex.CandleSnapshot, error) { if symbol == "" { return nil, fmt.Errorf("symbol cannot be empty") @@ -78,7 +80,8 @@ func (c *CandleService) History(symbol string, resolution bitfinex.CandleResolut } -// Return Candles for the public account. +// Retrieves all candles (Max=1000) that fit the given query criteria +// See https://docs.bitfinex.com/reference#rest-public-candles for more info func (c *CandleService) HistoryWithQuery( symbol string, resolution bitfinex.CandleResolution, diff --git a/v2/rest/client.go b/v2/rest/client.go index b475de30e..27652a57d 100644 --- a/v2/rest/client.go +++ b/v2/rest/client.go @@ -51,10 +51,12 @@ type Client struct { Synchronous } +// Create a new Rest client func NewClient() *Client { return NewClientWithURLNonce(productionBaseURL, utils.NewEpochNonceGenerator()) } +// Create a new Rest client with a custom nonce generator func NewClientWithURLNonce(url string, nonce utils.NonceGenerator) *Client { httpDo := func(c *http.Client, req *http.Request) (*http.Response, error) { return c.Do(req) @@ -62,14 +64,17 @@ func NewClientWithURLNonce(url string, nonce utils.NonceGenerator) *Client { return NewClientWithURLHttpDoNonce(url, httpDo, nonce) } +// Create a new Rest client with a custom http handler func NewClientWithHttpDo(httpDo func(c *http.Client, r *http.Request) (*http.Response, error)) *Client { return NewClientWithURLHttpDo(productionBaseURL, httpDo) } +// Create a new Rest client with a custom base url and HTTP handler func NewClientWithURLHttpDo(base string, httpDo func(c *http.Client, r *http.Request) (*http.Response, error)) *Client { return NewClientWithURLHttpDoNonce(base, httpDo, utils.NewEpochNonceGenerator()) } +// Create a new Rest client with a custom base url, HTTP handler and none generator func NewClientWithURLHttpDoNonce(base string, httpDo func(c *http.Client, r *http.Request) (*http.Response, error), nonce utils.NonceGenerator) *Client { url, _ := url.Parse(base) sync := &HttpTransport{ @@ -80,6 +85,7 @@ func NewClientWithURLHttpDoNonce(base string, httpDo func(c *http.Client, r *htt return NewClientWithSynchronousNonce(sync, nonce) } +// Create a new Rest client with a custom base url func NewClientWithURL(url string) *Client { httpDo := func(c *http.Client, req *http.Request) (*http.Response, error) { return c.Do(req) @@ -87,11 +93,12 @@ func NewClientWithURL(url string) *Client { return NewClientWithURLHttpDo(url, httpDo) } +// Create a new Rest client with a synchronous HTTP handler and a custom nonce generaotr func NewClientWithSynchronousNonce(sync Synchronous, nonce utils.NonceGenerator) *Client { return NewClientWithSynchronousURLNonce(sync, productionBaseURL, nonce) } -// mock me in tests +// Create a new Rest client with a synchronous HTTP handler and a custom base url and nonce generator func NewClientWithSynchronousURLNonce(sync Synchronous, url string, nonce utils.NonceGenerator) *Client { c := &Client{ Synchronous: sync, @@ -114,6 +121,7 @@ func NewClientWithSynchronousURLNonce(sync Synchronous, url string, nonce utils. return c } +// Set the clients credentials in order to make authenticated requests func (c *Client) Credentials(key string, secret string) *Client { c.apiKey = key c.apiSecret = secret @@ -144,10 +152,16 @@ func (c *Client) sign(msg string) (string, error) { return hex.EncodeToString(sig.Sum(nil)), nil } +// Create a new authenticated GET request with the given permission type and endpoint url +// For example permissionType = "r" and refUrl = "/orders" then the target endpoint will be +// https://api.bitfinex.com/v2/auth/r/orders/:Symbol func (c *Client) NewAuthenticatedRequest(permissionType bitfinex.PermissionType, refURL string) (Request, error) { return c.NewAuthenticatedRequestWithBytes(permissionType, refURL, []byte("{}")) } +// Create a new authenticated POST request with the given permission type,endpoint url and data (bytes) as the body +// For example permissionType = "r" and refUrl = "/orders" then the target endpoint will be +// https://api.bitfinex.com/v2/auth/r/orders/:Symbol func (c *Client) NewAuthenticatedRequestWithBytes(permissionType bitfinex.PermissionType, refURL string, data []byte) (Request, error) { authURL := fmt.Sprintf("auth/%s/%s", string(permissionType), refURL) req := NewRequestWithBytes(authURL, data) @@ -165,6 +179,9 @@ func (c *Client) NewAuthenticatedRequestWithBytes(permissionType bitfinex.Permis return req, nil } +// Create a new authenticated POST request with the given permission type,endpoint url and data (map[string]interface{}) as the body +// For example permissionType = "r" and refUrl = "/orders" then the target endpoint will be +// https://api.bitfinex.com/v2/auth/r/orders/:Symbol func (c *Client) NewAuthenticatedRequestWithData(permissionType bitfinex.PermissionType,refURL string, data map[string]interface{}) (Request, error) { b, err := json.Marshal(data) if err != nil { @@ -173,18 +190,22 @@ func (c *Client) NewAuthenticatedRequestWithData(permissionType bitfinex.Permiss return c.NewAuthenticatedRequestWithBytes(permissionType, refURL, b) } +// Create new POST request with an empty body as payload func NewRequest(refURL string) Request { return NewRequestWithDataMethod(refURL, []byte("{}"), "POST") } +// Create a new request with the given method (POST | GET) func NewRequestWithMethod(refURL string, method string) Request { return NewRequestWithDataMethod(refURL, []byte("{}"), method) } +// Create a new POST request with the given bytes as body func NewRequestWithBytes(refURL string, data []byte) Request { return NewRequestWithDataMethod(refURL, data, "POST") } +// Create a new POST request with the given data (map[string]interface{}) as body func NewRequestWithData(refURL string, data map[string]interface{}) (Request, error) { b, err := json.Marshal(data) if err != nil { @@ -193,6 +214,7 @@ func NewRequestWithData(refURL string, data map[string]interface{}) (Request, er return NewRequestWithDataMethod(refURL, b, "POST"), nil } +// Create a new request with a given method (POST | GET) with bytes as body func NewRequestWithDataMethod(refURL string, data []byte, method string) Request { return Request{ RefURL: refURL, diff --git a/v2/rest/currencies.go b/v2/rest/currencies.go index f8d5a0230..229d97401 100644 --- a/v2/rest/currencies.go +++ b/v2/rest/currencies.go @@ -12,7 +12,8 @@ type CurrenciesService struct { Synchronous } -// All returns all orders for the authenticated account. +// Retreive currency and symbol service configuration data +// see https://docs.bitfinex.com/reference#rest-public-conf for more info func (cs *CurrenciesService) Conf(label, symbol, unit, explorer, pairs bool) ([]bitfinex.CurrencyConf, error) { segments := make([]string, 0) if label { diff --git a/v2/rest/derivatives.go b/v2/rest/derivatives.go index 22d098408..8fd1cf9a5 100644 --- a/v2/rest/derivatives.go +++ b/v2/rest/derivatives.go @@ -11,7 +11,8 @@ type DerivativesService struct { Synchronous } -// All returns all orders for the authenticated account. +// Update the amount of collateral for a Derivative position +// see https://docs.bitfinex.com/reference#rest-auth-deriv-pos-collateral-set for more info func (s *WalletService) SetCollateral(symbol string, amount float64) (bool, error) { urlPath := path.Join("deriv", "collateral", "set") data := map[string]interface{}{ diff --git a/v2/rest/funding.go b/v2/rest/funding.go index 40d211adf..ad4b66b0d 100644 --- a/v2/rest/funding.go +++ b/v2/rest/funding.go @@ -12,7 +12,8 @@ type FundingService struct { Synchronous } -// All returns all ledgers for the authenticated account +// Retreive all of the active fundign offers +// see https://docs.bitfinex.com/reference#rest-auth-funding-offers for more info func (fs *FundingService) Offers(symbol string) (*bitfinex.FundingOfferSnapshot, error) { req, err :=fs.requestFactory.NewAuthenticatedRequest(bitfinex.PermissionRead, path.Join("funding/offers", symbol)) if err != nil { @@ -29,6 +30,8 @@ func (fs *FundingService) Offers(symbol string) (*bitfinex.FundingOfferSnapshot, return offers, nil } +// Retreive all of the past in-active funding offers +// see https://docs.bitfinex.com/reference#rest-auth-funding-offers-hist for more info func (fs *FundingService) OfferHistory(symbol string) (*bitfinex.FundingOfferSnapshot, error) { req, err :=fs.requestFactory.NewAuthenticatedRequest(bitfinex.PermissionRead, path.Join("funding/offers", symbol, "hist")) if err != nil { @@ -45,6 +48,8 @@ func (fs *FundingService) OfferHistory(symbol string) (*bitfinex.FundingOfferSna return offers, nil } +// Retreive all of the active funding loans +// see https://docs.bitfinex.com/reference#rest-auth-funding-loans for more info func (fs *FundingService) Loans(symbol string) (*bitfinex.FundingLoanSnapshot, error) { req, err := fs.requestFactory.NewAuthenticatedRequest(bitfinex.PermissionRead, path.Join("funding/loans", symbol)) if err != nil { @@ -61,6 +66,8 @@ func (fs *FundingService) Loans(symbol string) (*bitfinex.FundingLoanSnapshot, e return loans, nil } +// Retreive all of the past in-active funding loans +// see https://docs.bitfinex.com/reference#rest-auth-funding-loans-hist for more info func (fs *FundingService) LoansHistory(symbol string) (*bitfinex.FundingLoanSnapshot, error) { req, err := fs.requestFactory.NewAuthenticatedRequest(bitfinex.PermissionRead, path.Join("funding/loans", symbol, "hist")) if err != nil { @@ -77,6 +84,8 @@ func (fs *FundingService) LoansHistory(symbol string) (*bitfinex.FundingLoanSnap return loans, nil } +// Retreive all of the active credits used in positions +// see https://docs.bitfinex.com/reference#rest-auth-funding-credits for more info func (fs *FundingService) Credits(symbol string) (*bitfinex.FundingCreditSnapshot, error) { req, err := fs.requestFactory.NewAuthenticatedRequest(bitfinex.PermissionRead, path.Join("funding/credits", symbol)) if err != nil { @@ -93,6 +102,8 @@ func (fs *FundingService) Credits(symbol string) (*bitfinex.FundingCreditSnapsho return loans, nil } +// Retreive all of the past in-active credits used in positions +// see https://docs.bitfinex.com/reference#rest-auth-funding-credits-hist for more info func (fs *FundingService) CreditsHistory(symbol string) (*bitfinex.FundingCreditSnapshot, error) { req, err := fs.requestFactory.NewAuthenticatedRequest(bitfinex.PermissionRead, path.Join("funding/credits", symbol, "hist")) if err != nil { @@ -109,6 +120,8 @@ func (fs *FundingService) CreditsHistory(symbol string) (*bitfinex.FundingCredit return loans, nil } +// Retreive all of the matched funding trades +// see https://docs.bitfinex.com/reference#rest-auth-funding-trades-hist for more info func (fs *FundingService) Trades(symbol string) (*bitfinex.FundingTradeSnapshot, error) { req, err := fs.requestFactory.NewAuthenticatedRequest(bitfinex.PermissionRead, path.Join("funding/trades", symbol, "hist")) if err != nil { @@ -125,6 +138,8 @@ func (fs *FundingService) Trades(symbol string) (*bitfinex.FundingTradeSnapshot, return loans, nil } +// Submits a request to create a new funding offer +// see https://docs.bitfinex.com/reference#submit-funding-offer for more info func (fs *FundingService) SubmitOffer(fo *bitfinex.FundingOfferRequest) (*bitfinex.Notification, error) { bytes, err := fo.ToJSON() if err != nil { @@ -141,6 +156,8 @@ func (fs *FundingService) SubmitOffer(fo *bitfinex.FundingOfferRequest) (*bitfin return bitfinex.NewNotificationFromRaw(raw) } +// Submits a request to cancel the given offer +// see https://docs.bitfinex.com/reference#cancel-funding-offer for more info func (fs *FundingService) CancelOffer(fc *bitfinex.FundingOfferCancelRequest) (*bitfinex.Notification, error) { bytes, err := fc.ToJSON() if err != nil { diff --git a/v2/rest/ledgers.go b/v2/rest/ledgers.go index f9326fbd8..ac581b848 100644 --- a/v2/rest/ledgers.go +++ b/v2/rest/ledgers.go @@ -12,7 +12,8 @@ type LedgerService struct { Synchronous } -// All returns all ledgers for the authenticated account. +// Retrieves all of the past ledger entreies +// see https://docs.bitfinex.com/reference#ledgers for more info func (s *LedgerService) Ledgers(currency string, start int64, end int64, max int32) (*bitfinex.LedgerSnapshot, error) { if max > 500 { return nil, fmt.Errorf("Max request limit is higher then 500 : %#v", max) diff --git a/v2/rest/orders.go b/v2/rest/orders.go index b71453d3c..5ce44b103 100644 --- a/v2/rest/orders.go +++ b/v2/rest/orders.go @@ -12,19 +12,22 @@ type OrderService struct { Synchronous } -// Get all active orders +// Retrieves all of the active orders +// See https://docs.bitfinex.com/reference#rest-auth-orders for more info func (s *OrderService) All() (*bitfinex.OrderSnapshot, error) { // use no symbol, this will get all orders return s.getActiveOrders("") } -// Get all active orders with the given symbol +// Retrieves all of the active orders with for the given symbol +// See https://docs.bitfinex.com/reference#rest-auth-orders for more info func (s *OrderService) GetBySymbol(symbol string) (*bitfinex.OrderSnapshot, error) { // use no symbol, this will get all orders return s.getActiveOrders(symbol) } -// Get an active order using its order id +// Retrieve an active order by the given ID +// See https://docs.bitfinex.com/reference#rest-auth-orders for more info func (s *OrderService) GetByOrderId(orderID int64) (o *bitfinex.Order, err error) { os, err := s.All() if err != nil { @@ -38,19 +41,22 @@ func (s *OrderService) GetByOrderId(orderID int64) (o *bitfinex.Order, err error return nil, bitfinex.ErrNotFound } -// Get all historical orders +// Retrieves all past orders +// See https://docs.bitfinex.com/reference#orders-history for more info func (s *OrderService) AllHistory() (*bitfinex.OrderSnapshot, error) { // use no symbol, this will get all orders return s.getHistoricalOrders("") } -// Get all historical orders with the given symbol +// Retrieves all past orders with the given symbol +// See https://docs.bitfinex.com/reference#orders-history for more info func (s *OrderService) GetHistoryBySymbol(symbol string) (*bitfinex.OrderSnapshot, error) { // use no symbol, this will get all orders return s.getHistoricalOrders(symbol) } -// Get a historical order using its order id +// Retrieve a single order in history with the given id +// See https://docs.bitfinex.com/reference#orders-history for more info func (s *OrderService) GetHistoryByOrderId(orderID int64) (o *bitfinex.Order, err error) { os, err := s.AllHistory() if err != nil { @@ -64,7 +70,8 @@ func (s *OrderService) GetHistoryByOrderId(orderID int64) (o *bitfinex.Order, er return nil, bitfinex.ErrNotFound } -// OrderTrades returns a set of executed trades related to an order. +// Retrieves the trades generated by an order +// See https://docs.bitfinex.com/reference#orders-history for more info func (s *OrderService) OrderTrades(symbol string, orderID int64) (*bitfinex.TradeExecutionUpdateSnapshot, error) { key := fmt.Sprintf("%s:%d", symbol, orderID) req, err := s.requestFactory.NewAuthenticatedRequest(bitfinex.PermissionRead, path.Join("order", key, "trades")) @@ -116,6 +123,8 @@ func (s *OrderService) getHistoricalOrders(symbol string) (*bitfinex.OrderSnapsh return os, nil } +// Submit a request to create a new order +// see https://docs.bitfinex.com/reference#submit-order for more info func (s *OrderService) SubmitOrder(order *bitfinex.OrderNewRequest) (*bitfinex.Notification, error) { bytes, err := order.ToJSON() if err != nil { @@ -132,6 +141,8 @@ func (s *OrderService) SubmitOrder(order *bitfinex.OrderNewRequest) (*bitfinex.N return bitfinex.NewNotificationFromRaw(raw) } +// Submit a request to update an order with the given id with the given changes +// see https://docs.bitfinex.com/reference#order-update for more info func (s *OrderService) SubmitUpdateOrder(order *bitfinex.OrderUpdateRequest) (*bitfinex.Notification, error) { bytes, err := order.ToJSON() if err != nil { @@ -148,6 +159,8 @@ func (s *OrderService) SubmitUpdateOrder(order *bitfinex.OrderUpdateRequest) (*b return bitfinex.NewNotificationFromRaw(raw) } +// Submit a request to cancel an order with the given Id +// see https://docs.bitfinex.com/reference#cancel-order for more info func (s *OrderService) SubmitCancelOrder(oc *bitfinex.OrderCancelRequest) (error) { bytes, err := oc.ToJSON() if err != nil { diff --git a/v2/rest/platform_status.go b/v2/rest/platform_status.go index 8cdbcc510..0bee98e92 100644 --- a/v2/rest/platform_status.go +++ b/v2/rest/platform_status.go @@ -4,7 +4,8 @@ type PlatformService struct { Synchronous } -// Status indicates whether the platform is currently operative or not. +// Retrieves the current status of the platform +// see https://docs.bitfinex.com/reference#rest-public-platform-status for more info func (p *PlatformService) Status() (bool, error) { raw, err := p.Request(NewRequestWithMethod("platform/status", "GET")) if err != nil { diff --git a/v2/rest/positions.go b/v2/rest/positions.go index a723d7591..f87a95fc5 100644 --- a/v2/rest/positions.go +++ b/v2/rest/positions.go @@ -11,7 +11,8 @@ type PositionService struct { Synchronous } -// All returns all positions for the authenticated account. +// Retrieves all of the active positions +// see https://docs.bitfinex.com/reference#rest-auth-positions for more info func (s *PositionService) All() (*bitfinex.PositionSnapshot, error) { req, err := s.requestFactory.NewAuthenticatedRequest(bitfinex.PermissionRead, "positions") if err != nil { @@ -31,6 +32,8 @@ func (s *PositionService) All() (*bitfinex.PositionSnapshot, error) { return os, nil } +// Submits a request to claim an active position with the given id +// see https://docs.bitfinex.com/reference#claim-position for more info func (s *PositionService) Claim(cp *bitfinex.ClaimPositionRequest) (*bitfinex.Notification, error) { bytes, err := cp.ToJSON() if err != nil { diff --git a/v2/rest/stats.go b/v2/rest/stats.go index fabc0f666..7b8c6aa21 100644 --- a/v2/rest/stats.go +++ b/v2/rest/stats.go @@ -55,30 +55,45 @@ func (ss *StatsService) getLast(symbol string, key bitfinex.StatKey, extra strin return &bitfinex.Stat{Period: int64(period), Volume: volume}, nil } + +// Retrieves platform statistics for funding history +// see https://docs.bitfinex.com/reference#rest-public-stats for more info func (ss *StatsService) FundingHistory(symbol string) ([]bitfinex.Stat, error) { return ss.getHistory(symbol, bitfinex.FundingSizeKey, "") } +// Retrieves platform statistics for funding last +// see https://docs.bitfinex.com/reference#rest-public-stats for more info func (ss *StatsService) FundingLast(symbol string) (*bitfinex.Stat, error) { return ss.getLast(symbol, bitfinex.FundingSizeKey, "") } +// Retrieves platform statistics for credit size history +// see https://docs.bitfinex.com/reference#rest-public-stats for more info func (ss *StatsService) CreditSizeHistory(symbol string, side bitfinex.OrderSide) ([]bitfinex.Stat, error) { return ss.getHistory(symbol, bitfinex.CreditSizeKey, "") } +// Retrieves platform statistics for credit size last +// see https://docs.bitfinex.com/reference#rest-public-stats for more info func (ss *StatsService) CreditSizeLast(symbol string, side bitfinex.OrderSide) (*bitfinex.Stat, error) { return ss.getLast(symbol, bitfinex.CreditSizeKey, "") } +// Retrieves platform statistics for credit size history +// see https://docs.bitfinex.com/reference#rest-public-stats for more info func (ss *StatsService) SymbolCreditSizeHistory(fundingSymbol string, tradingSymbol string) ([]bitfinex.Stat, error) { return ss.getHistory(fundingSymbol, bitfinex.CreditSizeSymKey, tradingSymbol) } +// Retrieves platform statistics for credit size last +// see https://docs.bitfinex.com/reference#rest-public-stats for more info func (ss *StatsService) SymbolCreditSizeLast(fundingSymbol string, tradingSymbol string) (*bitfinex.Stat, error) { return ss.getLast(fundingSymbol, bitfinex.CreditSizeSymKey, tradingSymbol) } +// Retrieves platform statistics for position history +// see https://docs.bitfinex.com/reference#rest-public-stats for more info func (ss *StatsService) PositionHistory(symbol string, side bitfinex.OrderSide) ([]bitfinex.Stat, error) { var strSide string if side == bitfinex.Long { @@ -91,6 +106,8 @@ func (ss *StatsService) PositionHistory(symbol string, side bitfinex.OrderSide) return ss.getHistory(symbol, bitfinex.PositionSizeKey, strSide) } +// Retrieves platform statistics for position last +// see https://docs.bitfinex.com/reference#rest-public-stats for more info func (ss *StatsService) PositionLast(symbol string, side bitfinex.OrderSide) (*bitfinex.Stat, error) { var strSide string if side == bitfinex.Long { diff --git a/v2/rest/status.go b/v2/rest/status.go index 7b09804ca..5fb99e021 100644 --- a/v2/rest/status.go +++ b/v2/rest/status.go @@ -37,6 +37,8 @@ func (ss *StatusService) get(sType string, key string) (*bitfinex.DerivativeStat return s, nil } +// Retrieves derivative status information for the given symbol from the platform +// see https://docs.bitfinex.com/reference#rest-public-status for more info func (ss *StatusService) DerivativeStatus(symbol string) (*bitfinex.DerivativeStatus, error) { data, err := ss.get(DERIV_TYPE, symbol) if err != nil { @@ -48,6 +50,8 @@ func (ss *StatusService) DerivativeStatus(symbol string) (*bitfinex.DerivativeSt return data.Snapshot[0], err } +// Retrieves derivative status information for the given symbols from the platform +// see https://docs.bitfinex.com/reference#rest-public-status for more info func (ss *StatusService) DerivativeStatusMulti(symbols []string) ([]*bitfinex.DerivativeStatus, error) { key := strings.Join(symbols, ",") data, err := ss.get(DERIV_TYPE, key) @@ -57,6 +61,8 @@ func (ss *StatusService) DerivativeStatusMulti(symbols []string) ([]*bitfinex.De return data.Snapshot, err } +// Retrieves derivative status information for all symbols from the platform +// see https://docs.bitfinex.com/reference#rest-public-status for more info func (ss *StatusService) DerivativeStatusAll() ([]*bitfinex.DerivativeStatus, error) { data, err := ss.get(DERIV_TYPE, "ALL") if err != nil { diff --git a/v2/rest/tickers.go b/v2/rest/tickers.go index 4d5284224..5cb5c18a0 100644 --- a/v2/rest/tickers.go +++ b/v2/rest/tickers.go @@ -12,7 +12,8 @@ type TickerService struct { Synchronous } -// All returns all orders for the authenticated account. +// Retrieves the ticker for the given symbol +// see https://docs.bitfinex.com/reference#rest-public-ticker for more info func (s *TickerService) Get(symbol string) (*bitfinex.Ticker, error) { req := NewRequestWithMethod("tickers", "GET") req.Params = make(url.Values) @@ -29,6 +30,8 @@ func (s *TickerService) Get(symbol string) (*bitfinex.Ticker, error) { return ticker, nil } +// Retrieves the tickers for the given symbols +// see https://docs.bitfinex.com/reference#rest-public-ticker for more info func (s *TickerService) GetMulti(symbols []string) (*[]bitfinex.Ticker, error) { req := NewRequestWithMethod("tickers", "GET") req.Params = make(url.Values) @@ -49,6 +52,8 @@ func (s *TickerService) GetMulti(symbols []string) (*[]bitfinex.Ticker, error) { return &tickers, nil } +// Retrieves all tickers for all symbols +// see https://docs.bitfinex.com/reference#rest-public-ticker for more info func (s *TickerService) All() (*[]bitfinex.Ticker, error) { req := NewRequestWithMethod("tickers", "GET") req.Params = make(url.Values) diff --git a/v2/rest/trades.go b/v2/rest/trades.go index 5be6218ea..01fe65d6c 100644 --- a/v2/rest/trades.go +++ b/v2/rest/trades.go @@ -39,15 +39,20 @@ func (s *TradeService) allAccount() (*bitfinex.TradeExecutionUpdateSnapshot, err return parseRawPrivateToSnapshot(raw) } +// Retrieves all matched trades for the account +// see https://docs.bitfinex.com/reference#rest-auth-trades-hist for more info func (s *TradeService) AccountAll() (*bitfinex.TradeExecutionUpdateSnapshot, error) { return s.allAccount() } +// Retrieves all matched trades with the given symbol for the account +// see https://docs.bitfinex.com/reference#rest-auth-trades-hist for more info func (s *TradeService) AccountAllWithSymbol(symbol string) (*bitfinex.TradeExecutionUpdateSnapshot, error) { return s.allAccountWithSymbol(symbol) } -// return account trades that fit the given conditions +// Queries all matched trades with group of optional parameters +// see https://docs.bitfinex.com/reference#rest-auth-trades-hist for more info func (s *TradeService) AccountHistoryWithQuery( symbol string, start bitfinex.Mts, @@ -71,7 +76,8 @@ func (s *TradeService) AccountHistoryWithQuery( return parseRawPrivateToSnapshot(raw) } -// return publicly executed trades that fit the given query conditions +// Queries all public trades with a group of optional paramters +// see https://docs.bitfinex.com/reference#rest-public-trades for more info func (s *TradeService) PublicHistoryWithQuery( symbol string, start bitfinex.Mts, diff --git a/v2/rest/wallet.go b/v2/rest/wallet.go index 4c0889c81..22663df5c 100644 --- a/v2/rest/wallet.go +++ b/v2/rest/wallet.go @@ -11,7 +11,8 @@ type WalletService struct { Synchronous } -// All returns all orders for the authenticated account. +// Retrieves all of the wallets for the account +// see https://docs.bitfinex.com/reference#rest-auth-wallets for more info func (s *WalletService) Wallet() (*bitfinex.WalletSnapshot, error) { req, err := s.requestFactory.NewAuthenticatedRequest(bitfinex.PermissionRead, "wallets") if err != nil { @@ -30,8 +31,9 @@ func (s *WalletService) Wallet() (*bitfinex.WalletSnapshot, error) { return os, nil } +// Submits a request to transfer funds from one Bitfinex wallet to another +// see https://docs.bitfinex.com/reference#transfer-between-wallets for more info func (ws *WalletService) Transfer(from, to, currency, currencyTo string, amount float64) (*bitfinex.Notification, error) { - // `/v2/auth/w/transfer` (params: `from`, `to`, `currency`, `currency_to`, `amount`) body := map[string]interface{}{ "from": from, "to": to, @@ -51,7 +53,6 @@ func (ws *WalletService) Transfer(from, to, currency, currencyTo string, amount } func (ws *WalletService) depositAddress(wallet string, method string, renew int) (*bitfinex.Notification, error) { - // `/v2/auth/w/deposit/address` (params: `wallet`, `method`, `op_renew`(=1 to regenerate the wallet address)) body := map[string]interface{}{ "wallet": wallet, "method": method, @@ -68,18 +69,21 @@ func (ws *WalletService) depositAddress(wallet string, method string, renew int) return bitfinex.NewNotificationFromRaw(raw) } +// Retrieves the deposit address for the given Bitfinex wallet +// see https://docs.bitfinex.com/reference#deposit-address for more info func (ws *WalletService) DepositAddress(wallet, method string) (*bitfinex.Notification, error) { - // `/v2/auth/w/deposit/address` (params: `wallet`, `method`, `op_renew`(=1 to regenerate the wallet address)) return ws.depositAddress(wallet, method, 0) } +// Submits a request to create a new deposit address for the give Bitfinex wallet. Old addresses are still valid. +// See https://docs.bitfinex.com/reference#deposit-address for more info func (ws *WalletService) CreateDepositAddress(wallet, method string) (*bitfinex.Notification, error) { - // `/v2/auth/w/deposit/address` (params: `wallet`, `method`, `op_renew`(=1 to regenerate the wallet address)) return ws.depositAddress(wallet, method, 1) } +// Submits a request to withdraw funds from the given Bitfinex wallet to the given address +// See https://docs.bitfinex.com/reference#withdraw for more info func (ws *WalletService) Withdraw(wallet, method string, amount float64, address string) (*bitfinex.Notification, error) { - // `/v2/auth/w/withdraw` (params: `wallet`, `method`, `amount`, `address` body := map[string]interface{}{ "wallet": wallet, "method": method, diff --git a/v2/websocket/api.go b/v2/websocket/api.go index 479315af0..6557fa0f3 100644 --- a/v2/websocket/api.go +++ b/v2/websocket/api.go @@ -22,6 +22,7 @@ func (c *Client) Send(ctx context.Context, msg interface{}) error { return socket.Asynchronous.Send(ctx, msg) } +// Submit a request to enable the given flag func (c *Client) EnableFlag(ctx context.Context, flag int) (string, error) { req := &FlagRequest{ Event: "conf", @@ -44,18 +45,20 @@ func (c *Client) EnableFlag(ctx context.Context, flag int) (string, error) { return "", nil } -// returns the count of websocket connections that are currently active +// Gen the count of currently active websocket connections func (c *Client) ConnectionCount() int { c.mtx.RLock() defer c.mtx.RUnlock() return len(c.sockets) } +// Get the available capacity of the current +// websocket connections func (c *Client) AvailableCapacity() int { return c.getTotalAvailableSocketCapacity() } -// starts a new websocket connection. This function is only exposed in case you want to +// Start a new websocket connection. This function is only exposed in case you want to // implicitly add new connections otherwise connection management is already handled for you. func (c *Client) StartNewConnection() error { return c.connectSocket(SocketId(c.ConnectionCount())) @@ -71,7 +74,7 @@ func (c *Client) subscribeBySocket(ctx context.Context, socket *Socket, req *Sub return req.SubID, nil } -// Subscribe sends a subscription request to the Bitfinex API and tracks the subscription status by ID. +// Submit a request to subscribe to the given SubscriptionRequuest func (c *Client) Subscribe(ctx context.Context, req *SubscriptionRequest) (string, error) { if c.getTotalAvailableSocketCapacity() <= 1 { err := c.StartNewConnection() @@ -87,7 +90,7 @@ func (c *Client) Subscribe(ctx context.Context, req *SubscriptionRequest) (strin return c.subscribeBySocket(ctx, socket, req) } -// SubscribeTicker sends a subscription request for the ticker. +// Submit a request to receive ticker updates func (c *Client) SubscribeTicker(ctx context.Context, symbol string) (string, error) { req := &SubscriptionRequest{ SubID: c.nonce.GetNonce(), @@ -98,7 +101,7 @@ func (c *Client) SubscribeTicker(ctx context.Context, symbol string) (string, er return c.Subscribe(ctx, req) } -// SubscribeTrades sends a subscription request for the trade feed. +// Submit a request to receive trade updates func (c *Client) SubscribeTrades(ctx context.Context, symbol string) (string, error) { req := &SubscriptionRequest{ SubID: c.nonce.GetNonce(), @@ -109,7 +112,7 @@ func (c *Client) SubscribeTrades(ctx context.Context, symbol string) (string, er return c.Subscribe(ctx, req) } -// SubscribeBook sends a subscription request for market data for a given symbol, at a given frequency, with a given precision, returning no more than priceLevels price entries. +// Submit a subscription request for market data for the given symbol, at the given frequency, with the given precision, returning no more than priceLevels price entries. // Default values are Precision0, Frequency0, and priceLevels=25. func (c *Client) SubscribeBook(ctx context.Context, symbol string, precision bitfinex.BookPrecision, frequency bitfinex.BookFrequency, priceLevel int) (string, error) { if priceLevel < 0 { @@ -129,7 +132,7 @@ func (c *Client) SubscribeBook(ctx context.Context, symbol string, precision bit return c.Subscribe(ctx, req) } -// SubscribeCandles sends a subscription request for OHLC candles. +// Submit a subscription request to receive candle updates func (c *Client) SubscribeCandles(ctx context.Context, symbol string, resolution bitfinex.CandleResolution) (string, error) { req := &SubscriptionRequest{ SubID: c.nonce.GetNonce(), @@ -140,6 +143,7 @@ func (c *Client) SubscribeCandles(ctx context.Context, symbol string, resolution return c.Subscribe(ctx, req) } +// Submit a subscription request for status updates func (c *Client) SubscribeStatus(ctx context.Context, symbol string, sType bitfinex.StatusType) (string, error) { req := &SubscriptionRequest{ SubID: c.nonce.GetNonce(), @@ -150,6 +154,9 @@ func (c *Client) SubscribeStatus(ctx context.Context, symbol string, sType bitfi return c.Subscribe(ctx, req) } +// Retrieve the Orderbook for the given symbol which is managed locally. +// This requires ManageOrderbook=True and an active chanel subscribed to the given +// symbols orderbook func (c *Client) GetOrderbook(symbol string) (*Orderbook, error) { c.mtx.RLock() defer c.mtx.RUnlock() @@ -160,7 +167,7 @@ func (c *Client) GetOrderbook(symbol string) (*Orderbook, error) { return nil, fmt.Errorf("Orderbook %s does not exist", symbol) } -// SubmitOrder sends an order request. +// Submit a request to create a new order func (c *Client) SubmitOrder(ctx context.Context, order *bitfinex.OrderNewRequest) error { socket, err := c.GetAuthenticatedSocket() if err != nil { @@ -169,6 +176,7 @@ func (c *Client) SubmitOrder(ctx context.Context, order *bitfinex.OrderNewReques return socket.Asynchronous.Send(ctx, order) } +// Submit and update request to change an existing orders values func (c *Client) SubmitUpdateOrder(ctx context.Context, orderUpdate *bitfinex.OrderUpdateRequest) error { socket, err := c.GetAuthenticatedSocket() if err != nil { @@ -177,7 +185,7 @@ func (c *Client) SubmitUpdateOrder(ctx context.Context, orderUpdate *bitfinex.Or return socket.Asynchronous.Send(ctx, orderUpdate) } -// SubmitCancel sends a cancel request. +// Submit a cancel request for an existing order func (c *Client) SubmitCancel(ctx context.Context, cancel *bitfinex.OrderCancelRequest) error { socket, err := c.GetAuthenticatedSocket() if err != nil { @@ -186,7 +194,7 @@ func (c *Client) SubmitCancel(ctx context.Context, cancel *bitfinex.OrderCancelR return socket.Asynchronous.Send(ctx, cancel) } -// LookupSubscription looks up a subscription request by ID +// Get a subscription request using a subscription ID func (c *Client) LookupSubscription(subID string) (*SubscriptionRequest, error) { s, err := c.subscriptions.lookupBySubscriptionID(subID) if err != nil { @@ -195,6 +203,7 @@ func (c *Client) LookupSubscription(subID string) (*SubscriptionRequest, error) return s.Request, nil } +// Submit a new funding offer request func (c *Client) SubmitFundingOffer(ctx context.Context, fundingOffer *bitfinex.FundingOfferRequest) error { socket, err := c.GetAuthenticatedSocket() if err != nil { @@ -203,6 +212,7 @@ func (c *Client) SubmitFundingOffer(ctx context.Context, fundingOffer *bitfinex. return socket.Asynchronous.Send(ctx, fundingOffer) } +// Submit a request to cancel and existing funding offer func (c *Client) SubmitFundingCancel(ctx context.Context, fundingOffer *bitfinex.FundingOfferCancelRequest) error { socket, err := c.GetAuthenticatedSocket() if err != nil { diff --git a/v2/websocket/client.go b/v2/websocket/client.go index 446380cea..7f472db23 100644 --- a/v2/websocket/client.go +++ b/v2/websocket/client.go @@ -222,7 +222,7 @@ func (c *Client) Connect() error { } -// IsConnected returns true if the underlying asynchronous transport is connected to an endpoint. +// Returns true if the underlying asynchronous transport is connected to an endpoint. func (c *Client) IsConnected() bool { c.mtx.RLock() defer c.mtx.RUnlock() @@ -234,14 +234,15 @@ func (c *Client) IsConnected() bool { return false } -// Listen provides an atomic interface for receiving API messages. +// Listen for all incoming api websocket messages // When a websocket connection is terminated, the publisher channel will close. func (c *Client) Listen() <-chan interface{} { return c.listener } -// Close provides an interface for a user initiated shutdown. -// Close will close the Done() channel. +// Close the websocket client which will cause for all +// active sockets to be exited and the Done() function +// to be called func (c *Client) Close() { c.terminal = true var wg sync.WaitGroup @@ -263,7 +264,7 @@ func (c *Client) Close() { close(c.listener) } -// Unsubscribe looks up an existing subscription by ID and sends an unsubscribe request. +// Unsubscribe from the existing subscription with the given id func (c *Client) Unsubscribe(ctx context.Context, id string) error { sub, err := c.subscriptions.lookupBySubscriptionID(id) if err != nil { @@ -662,7 +663,8 @@ func (c *Client) getAvailableSocketCapacity(socketId SocketId) int { return c.parameters.CapacityPerConnection } -// get the authenticated socket +// Get the authenticated socket. Due to rate limitations +// there can only be one authenticated socket active at a time func (c *Client) GetAuthenticatedSocket() (*Socket, error) { c.mtx.RLock() defer c.mtx.RUnlock()