Files
gocryptotrader/exchanges/bitstamp/bitstamp_websocket.go
Gareth Kirwan f9437dbd08 Bitfinex: Websocket subscription improvements (#1353)
* Websockets: Add keys to websocket subscriptions

* This switches all RO uses of the mutex to use a RLock method.
* The mutex used for discrete field access has had scope drift from
  name 'connectionMutex' so rename to more appropriate fieldsMutex
* The mutex used for Set/CanUseAuthEndpoints moves from the
  subscriptions endpoint to the fieldsMutex
* Add GetSubscription by key
* Expose stream.Matcher type

* Bitfinex: Subscribe and Unsubscribe atomicly

* Fix Auth failures ignored
* This change makes it so that Subscribe and Unsubscribe wait for success
** Tells the DataHandler about errors
** Errors are returned to consumers
* Subscribes concurrently to the channels
* It also simplifies the chanId to stream mapping
* Removes unable to locate chanID: %d errors which are just noise
* Paves the way for unified channelSubscription id handling
* Adds support for subId for Book subscriptions, which is more robust

* Vastly simplifies what we need to test TestWsSubscribedResponse
This test was working to ensure that the various fancy key parsing
mechanisms all worked. Now that we use subId, we just need a thorough
test of that
* Expose Match.Set in order to capture websocket incoming data
Can't see another way of doing this. Doesn't seem too bad

* Allow tests to run with auth or WS
These flags made it difficult to run the tests whilst working on
websockets

* Enable API auth and WS in testconfig
This change minimises the changes requires for a full test run against
live endpoints, so that new contributors have a clearer testing path.
I cannot see any reason to turn WS off and Auth endpoints off when we're
not going to run API tests without Creds being set, and we're not going
to do live fire tests without canManipulateRealOrders

* TestWsSubscribe and various fixes
** Enables the websocket for live non-authed integration tests by default
** Adds an integration test for subscriptions
** Changes the Ws tests to respect canManipulateRealOrders
** Uses WsConnect instead of setupWs; fixes seqNo config not sent for WS tests
** Allows api creds to live in config/testdata.json which might be
  less likely to accidentally commit, and less obtrusive

* Bitfinex: Support period and timeframe for Candles

* Fixes manual Subscribe() symbol or key formatting
* Unifies handling of params for DefaultSubscriptions and manual
  subsrciptions

* Bitfinex: Handle conf and info WS channel events

* Bitfinex: Better tests for subscriptions

* fixup! Websockets: Add keys to websocket subscriptions

* fixup! Bitfinex: Subscribe and Unsubscribe atomicly

* fixup! Websockets: Add keys to websocket subscriptions

* Websockets: Add Pending subscription status

Add a status tracker so that Sub/Unsub can prevent duplicates,
and also fixes when first message comes before we have added the sub
to the tracker

* Websockets: Add State instead of pending

This change allows more clarity about the current state and
checks for specifically already Unsubing

* Bitfinex: Fix first sub message maybe lost

The only link we have between a sub req and the sub resp is the subID.
And the only link we have between a sub message and the sub is the chanID.
We can't derive a link using Pair or anything else.

This meant that by sending the resp and its chanID down the IncomingData
channel, we allowed the channel reader to maybe process the next
message, the first message on the channel, before the runtime executed
the switch back to subscribeToChan waiting on the chan.

To fix this, we key initially on subId.(string), and then replace it
with chanId.(int64) when we have it *inside* the wsHandleData so we
know we've procedurally handled it before the next message.

subscribeToChan is then free to remove the subId keyed Sub regardless of
error or not

If there's an error, we don't need to inline handling because there
won't be any second update.

Expands test coverage to make sure those subId keyed subscriptions are
removed.

* Websocket: Validate state in SetChanState

* fixup! Bitfinex: Fix first sub message maybe lost

* Websockets: Rename RemoveUnsuccessfulSubs

Implementation doesn't imply Unsuccessful or need to.
This change supports the registering of Pending subs

* Bitfinex: Fix race in Tests
2023-11-02 12:10:43 +11:00

458 lines
12 KiB
Go

package bitstamp
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"strconv"
"strings"
"time"
"github.com/gorilla/websocket"
"github.com/thrasher-corp/gocryptotrader/common"
"github.com/thrasher-corp/gocryptotrader/currency"
exchange "github.com/thrasher-corp/gocryptotrader/exchanges"
"github.com/thrasher-corp/gocryptotrader/exchanges/asset"
"github.com/thrasher-corp/gocryptotrader/exchanges/order"
"github.com/thrasher-corp/gocryptotrader/exchanges/orderbook"
"github.com/thrasher-corp/gocryptotrader/exchanges/stream"
"github.com/thrasher-corp/gocryptotrader/exchanges/trade"
"github.com/thrasher-corp/gocryptotrader/log"
)
const (
bitstampWSURL = "wss://ws.bitstamp.net" //nolint // gosec false positive
hbInterval = 8 * time.Second // Connection monitor defaults to 10s inactivity
)
var (
hbMsg = []byte(`{"event":"bts:heartbeat"}`)
defaultSubChannels = []string{
bitstampAPIWSTrades,
bitstampAPIWSOrderbook,
}
defaultAuthSubChannels = []string{
bitstampAPIWSMyOrders,
bitstampAPIWSMyTrades,
}
)
// WsConnect connects to a websocket feed
func (b *Bitstamp) WsConnect() error {
if !b.Websocket.IsEnabled() || !b.IsEnabled() {
return errors.New(stream.WebsocketNotEnabled)
}
var dialer websocket.Dialer
err := b.Websocket.Conn.Dial(&dialer, http.Header{})
if err != nil {
return err
}
if b.Verbose {
log.Debugf(log.ExchangeSys, "%s Connected to Websocket.\n", b.Name)
}
b.Websocket.Conn.SetupPingHandler(stream.PingHandler{
MessageType: websocket.TextMessage,
Message: hbMsg,
Delay: hbInterval,
})
err = b.seedOrderBook(context.TODO())
if err != nil {
b.Websocket.DataHandler <- err
}
b.Websocket.Wg.Add(1)
go b.wsReadData()
return nil
}
// wsReadData receives and passes on websocket messages for processing
func (b *Bitstamp) wsReadData() {
defer b.Websocket.Wg.Done()
for {
resp := b.Websocket.Conn.ReadMessage()
if resp.Raw == nil {
return
}
if err := b.wsHandleData(resp.Raw); err != nil {
b.Websocket.DataHandler <- err
}
}
}
func (b *Bitstamp) wsHandleData(respRaw []byte) error {
wsResponse := &websocketResponse{}
if err := json.Unmarshal(respRaw, wsResponse); err != nil {
return err
}
if err := b.parseChannelName(wsResponse); err != nil {
return err
}
switch wsResponse.Event {
case "bts:heartbeat":
return nil
case "bts:subscribe", "bts:subscription_succeeded":
if b.Verbose {
log.Debugf(log.ExchangeSys, "%v - Websocket subscription acknowledgement", b.Name)
}
case "bts:unsubscribe":
if b.Verbose {
log.Debugf(log.ExchangeSys, "%v - Websocket unsubscribe acknowledgement", b.Name)
}
case "bts:request_reconnect":
if b.Verbose {
log.Debugf(log.ExchangeSys, "%v - Websocket reconnection request received", b.Name)
}
go func() {
err := b.Websocket.Shutdown()
if err != nil {
log.Errorf(log.WebsocketMgr, "%s failed to shutdown websocket: %v", b.Name, err)
}
}() // Connection monitor will reconnect
case "data":
if err := b.handleWSOrderbook(wsResponse, respRaw); err != nil {
return err
}
case "trade":
if err := b.handleWSTrade(wsResponse, respRaw); err != nil {
return err
}
case "order_created", "order_deleted", "order_changed":
// Only process MyOrders, not orders from the LiveOrder channel
if wsResponse.channelType == bitstampAPIWSMyOrders {
if err := b.handleWSOrder(wsResponse, respRaw); err != nil {
return err
}
}
default:
b.Websocket.DataHandler <- stream.UnhandledMessageWarning{Message: b.Name + stream.UnhandledMessage + string(respRaw)}
}
return nil
}
func (b *Bitstamp) handleWSOrderbook(wsResp *websocketResponse, msg []byte) error {
if wsResp.pair.IsEmpty() {
return errWSPairParsingError
}
wsOrderBookTemp := websocketOrderBookResponse{}
err := json.Unmarshal(msg, &wsOrderBookTemp)
if err != nil {
return err
}
return b.wsUpdateOrderbook(&wsOrderBookTemp.Data, wsResp.pair, asset.Spot)
}
func (b *Bitstamp) handleWSTrade(wsResp *websocketResponse, msg []byte) error {
if !b.IsSaveTradeDataEnabled() {
return nil
}
if wsResp.pair.IsEmpty() {
return errWSPairParsingError
}
wsTradeTemp := websocketTradeResponse{}
if err := json.Unmarshal(msg, &wsTradeTemp); err != nil {
return err
}
side := order.Buy
if wsTradeTemp.Data.Type == 1 {
side = order.Sell
}
return trade.AddTradesToBuffer(b.Name, trade.Data{
Timestamp: time.Unix(wsTradeTemp.Data.Timestamp, 0),
CurrencyPair: wsResp.pair,
AssetType: asset.Spot,
Exchange: b.Name,
Price: wsTradeTemp.Data.Price,
Amount: wsTradeTemp.Data.Amount,
Side: side,
TID: strconv.FormatInt(wsTradeTemp.Data.ID, 10),
})
}
func (b *Bitstamp) handleWSOrder(wsResp *websocketResponse, msg []byte) error {
r := &websocketOrderResponse{}
if err := json.Unmarshal(msg, &r); err != nil {
return err
}
if r.Order.ID == 0 && r.Order.ClientOrderID == "" {
return fmt.Errorf("unable to parse an order id from order msg: %s", msg)
}
var status order.Status
switch wsResp.Event {
case "order_created":
status = order.New
case "order_changed":
if r.Order.ExecutedAmount > 0 {
status = order.PartiallyFilled
}
case "order_deleted":
if r.Order.RemainingAmount == 0 && r.Order.Amount > 0 {
status = order.Filled
} else {
status = order.Cancelled
}
}
// r.Order.ExecutedAmount is an atomic partial fill amount; We want total
executedAmount := r.Order.Amount - r.Order.RemainingAmount
d := &order.Detail{
Price: r.Order.Price,
Amount: r.Order.Amount,
RemainingAmount: r.Order.RemainingAmount,
ExecutedAmount: executedAmount,
Exchange: b.Name,
OrderID: r.Order.IDStr,
ClientOrderID: r.Order.ClientOrderID,
Side: r.Order.Side.Side(),
Status: status,
AssetType: asset.Spot,
Date: r.Order.Microtimestamp.Time(),
Pair: wsResp.pair,
}
b.Websocket.DataHandler <- d
return nil
}
func (b *Bitstamp) generateDefaultSubscriptions() ([]stream.ChannelSubscription, error) {
enabledCurrencies, err := b.GetEnabledPairs(asset.Spot)
if err != nil {
return nil, err
}
var subscriptions []stream.ChannelSubscription
for i := range enabledCurrencies {
p, err := b.FormatExchangeCurrency(enabledCurrencies[i], asset.Spot)
if err != nil {
return nil, err
}
for j := range defaultSubChannels {
subscriptions = append(subscriptions, stream.ChannelSubscription{
Channel: defaultSubChannels[j] + "_" + p.String(),
Asset: asset.Spot,
Currency: p,
})
}
if b.Websocket.CanUseAuthenticatedEndpoints() {
for j := range defaultAuthSubChannels {
subscriptions = append(subscriptions, stream.ChannelSubscription{
Channel: defaultAuthSubChannels[j] + "_" + p.String(),
Asset: asset.Spot,
Currency: p,
Params: map[string]interface{}{
"auth": struct{}{},
},
})
}
}
}
return subscriptions, nil
}
// Subscribe sends a websocket message to receive data from the channel
func (b *Bitstamp) Subscribe(channelsToSubscribe []stream.ChannelSubscription) error {
var errs error
var auth *WebsocketAuthResponse
for i := range channelsToSubscribe {
if _, ok := channelsToSubscribe[i].Params["auth"]; ok {
var err error
auth, err = b.FetchWSAuth(context.TODO())
if err != nil {
errs = common.AppendError(errs, err)
}
break
}
}
for i := range channelsToSubscribe {
req := websocketEventRequest{
Event: "bts:subscribe",
Data: websocketData{
Channel: channelsToSubscribe[i].Channel,
},
}
if _, ok := channelsToSubscribe[i].Params["auth"]; ok && auth != nil {
req.Data.Channel = "private-" + req.Data.Channel + "-" + strconv.Itoa(int(auth.UserID))
req.Data.Auth = auth.Token
}
err := b.Websocket.Conn.SendJSONMessage(req)
if err != nil {
errs = common.AppendError(errs, err)
continue
}
b.Websocket.AddSuccessfulSubscriptions(channelsToSubscribe[i])
}
return errs
}
// Unsubscribe sends a websocket message to stop receiving data from the channel
func (b *Bitstamp) Unsubscribe(channelsToUnsubscribe []stream.ChannelSubscription) error {
var errs error
for i := range channelsToUnsubscribe {
req := websocketEventRequest{
Event: "bts:unsubscribe",
Data: websocketData{
Channel: channelsToUnsubscribe[i].Channel,
},
}
err := b.Websocket.Conn.SendJSONMessage(req)
if err != nil {
errs = common.AppendError(errs, err)
continue
}
b.Websocket.RemoveSubscriptions(channelsToUnsubscribe[i])
}
return errs
}
func (b *Bitstamp) wsUpdateOrderbook(update *websocketOrderBook, p currency.Pair, assetType asset.Item) error {
if len(update.Asks) == 0 && len(update.Bids) == 0 {
return errors.New("no orderbook data")
}
obUpdate := &orderbook.Base{
Bids: make(orderbook.Items, len(update.Bids)),
Asks: make(orderbook.Items, len(update.Asks)),
Pair: p,
LastUpdated: time.UnixMicro(update.Microtimestamp),
Asset: assetType,
Exchange: b.Name,
VerifyOrderbook: b.CanVerifyOrderbook,
}
for i := range update.Asks {
target, err := strconv.ParseFloat(update.Asks[i][0], 64)
if err != nil {
return err
}
amount, err := strconv.ParseFloat(update.Asks[i][1], 64)
if err != nil {
return err
}
obUpdate.Asks[i] = orderbook.Item{Price: target, Amount: amount}
}
for i := range update.Bids {
target, err := strconv.ParseFloat(update.Bids[i][0], 64)
if err != nil {
return err
}
amount, err := strconv.ParseFloat(update.Bids[i][1], 64)
if err != nil {
return err
}
obUpdate.Bids[i] = orderbook.Item{Price: target, Amount: amount}
}
filterOrderbookZeroBidPrice(obUpdate)
return b.Websocket.Orderbook.LoadSnapshot(obUpdate)
}
func (b *Bitstamp) seedOrderBook(ctx context.Context) error {
p, err := b.GetEnabledPairs(asset.Spot)
if err != nil {
return err
}
for x := range p {
pairFmt, err := b.FormatExchangeCurrency(p[x], asset.Spot)
if err != nil {
return err
}
orderbookSeed, err := b.GetOrderbook(ctx, pairFmt.String())
if err != nil {
return err
}
newOrderBook := &orderbook.Base{
Pair: p[x],
Asset: asset.Spot,
Exchange: b.Name,
VerifyOrderbook: b.CanVerifyOrderbook,
Bids: make(orderbook.Items, len(orderbookSeed.Bids)),
Asks: make(orderbook.Items, len(orderbookSeed.Asks)),
LastUpdated: time.Unix(orderbookSeed.Timestamp, 0),
}
for i := range orderbookSeed.Asks {
newOrderBook.Asks[i] = orderbook.Item{
Price: orderbookSeed.Asks[i].Price,
Amount: orderbookSeed.Asks[i].Amount,
}
}
for i := range orderbookSeed.Bids {
newOrderBook.Bids[i] = orderbook.Item{
Price: orderbookSeed.Bids[i].Price,
Amount: orderbookSeed.Bids[i].Amount,
}
}
filterOrderbookZeroBidPrice(newOrderBook)
err = b.Websocket.Orderbook.LoadSnapshot(newOrderBook)
if err != nil {
return err
}
}
return nil
}
// FetchWSAuth Retrieves a userID and auth-token from REST for subscribing to a websocket channel
// The token life-expectancy is only about 60s; use it immediately and do not store it
func (b *Bitstamp) FetchWSAuth(ctx context.Context) (*WebsocketAuthResponse, error) {
resp := &WebsocketAuthResponse{}
err := b.SendAuthenticatedHTTPRequest(ctx, exchange.RestSpot, bitstampAPIWSAuthToken, true, nil, resp)
if err != nil {
return nil, fmt.Errorf("error fetching auth token: %w", err)
}
return resp, nil
}
// parseChannel splits the ws response channel and sets the channel type and pair
func (b *Bitstamp) parseChannelName(r *websocketResponse) error {
if r.Channel == "" {
return nil
}
chanName := r.Channel
authParts := strings.Split(r.Channel, "-")
switch len(authParts) {
case 1:
// Not an auth channel
case 3:
chanName = authParts[1]
default:
return fmt.Errorf("channel name does not contain exactly 0 or 2 hyphens: %v", r.Channel)
}
parts := strings.Split(chanName, "_")
if len(parts) != 3 {
return fmt.Errorf("%w: channel name does not contain exactly 2 underscores: %v", errWSPairParsingError, r.Channel)
}
r.channelType = parts[0] + "_" + parts[1]
symbol := parts[2]
enabledPairs, err := b.GetEnabledPairs(asset.Spot)
if err == nil {
r.pair, err = enabledPairs.DeriveFrom(symbol)
}
return err
}