mirror of
https://github.com/d0zingcat/gocryptotrader.git
synced 2026-05-30 15:10:40 +00:00
* Step one: Sets up connection handler for websockets to always be connected until a shutdown event is received. Sets up a vague subscription handler to ensure subscriptions are subscribed * Adds support for resubscriptions for bitfinex, bitstamp, bitmex and btcc. Adds subscription params for special websocket subscription requirements. Removes subscription monitor from wait group so that it can exist despite a shutdown and continuously check * Adds channel subscription support to bitmex, btse, coibasepro, coinut, gateio, gemini, hitbtc, huobi, hadax, kraken, okgroup, poloniex and zb * Implements unsubscribe for bitfinex, btcc, btse, coinbasepro, gateio, gitbtc, huobi, hadax * ManageSubscriptions now called from WSConnect and made private instead of inside individual exchanges. ManageSubscriptions can now unsubscribe. exchange_websocket_types.go now contains all exchange_websocket.go types to avoid clutter * Adds it to websocket functionality so managesubscriptions will close when not supported * Separates functions into testable functions to ensure logic works. Adds tests. Updates websocket setup to include verbosity (inherited from exchange). Adds no connection tolerance to fatal on failed reconnects * More exchange_websocket tests. Updating to use pointers. Creation of equals func to make comparison easier * Fixes okex, okcoin tests. Fixes race conditions. Removes pointer usage again. * Adds subscribe and unsubscribe to wrappers * Fixes deadlock. Fixes ws verbosity. * Updates all exchanges to properly support subscription/connection feature. Also reintroduces race conditions.... * Moves connection varialbes to struct from package to allow each websocket to have their own reconnection checks. Neatens up logs * Fixes lint/critic issues. Fixes tests. Removes unused function. * Moves websocket ratelimiter to their own const variables. Fixes more race conditions with connecting variable * Removes redundant subscribe functions. Ensuring only the exchange_websocket.go can manage subscriptions. Fixes debug logs to be verbose wrapped * Fixes issue with slice copying. Re-adds okgroup default channels * Adds nolint to append * Adds comments and adds support for gateio auth request subscriptions * Adds new test to ensure slices dont point to the same vars * removes fatals. gofmt goimports * more gofmts * Addresses PR comments, removing empty and redundant lines * Addresses PR comments. Ensures that writing to the websocket is single-threaded by adding a mutex to exchanges. Minimises wrapper code and moves subscription loops to exchange_websocket. Privatises ChannelsToSubscribe, Connecting properties and removeChannelToSubscribe func to prevent unnecessary tampering. * Removes unused mutex. FMTS and IMPORTS * Fixes request lock time change * More specific logs * Renames ws mutex. Fixes bitmex subscriptions. Increased gateio ratelimiter to 120ms. Removes ratelimiter from bitfinex, bitmex, bitstamp, btcc, btse, coibasepro, hitbtc, huobi, hadax, poloniex and zb * changes recieved typo due to not being well received * Fixes parsing issue with Huobi and hadax * Fixes data race with more locks * removes defer locks. fixes huobi/hadax verbose output * Fixes double JSONEncode for coinut. Fixes verbose output for coinut * gofmt,goimport for coinut * Fixes issue where multiple connection monitors can spawn * Removes defer exchange.WebsocketConn.Close() in defer handledata exit as connectionmonitor handles connections instead * gofmt and go import * More fmts
264 lines
6.2 KiB
Go
264 lines
6.2 KiB
Go
package btse
|
|
|
|
import (
|
|
"errors"
|
|
"fmt"
|
|
"net/http"
|
|
"net/url"
|
|
"strconv"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/gorilla/websocket"
|
|
"github.com/thrasher-/gocryptotrader/common"
|
|
"github.com/thrasher-/gocryptotrader/currency"
|
|
exchange "github.com/thrasher-/gocryptotrader/exchanges"
|
|
"github.com/thrasher-/gocryptotrader/exchanges/orderbook"
|
|
log "github.com/thrasher-/gocryptotrader/logger"
|
|
)
|
|
|
|
const (
|
|
btseWebsocket = "wss://ws.btse.com/api/ws-feed"
|
|
)
|
|
|
|
// WsConnect connects the websocket client
|
|
func (b *BTSE) WsConnect() error {
|
|
if !b.Websocket.IsEnabled() || !b.IsEnabled() {
|
|
return errors.New(exchange.WebsocketNotEnabled)
|
|
}
|
|
|
|
var dialer websocket.Dialer
|
|
|
|
if b.Websocket.GetProxyAddress() != "" {
|
|
proxy, err := url.Parse(b.Websocket.GetProxyAddress())
|
|
if err != nil {
|
|
return fmt.Errorf("%s websocket error - proxy address %s",
|
|
b.Name, err)
|
|
}
|
|
|
|
dialer.Proxy = http.ProxyURL(proxy)
|
|
}
|
|
|
|
var err error
|
|
b.WebsocketConn, _, err = dialer.Dial(b.Websocket.GetWebsocketURL(),
|
|
http.Header{})
|
|
if err != nil {
|
|
return fmt.Errorf("%s websocket error - unable to connect %s",
|
|
b.Name, err)
|
|
}
|
|
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
go b.WsHandleData()
|
|
b.GenerateDefaultSubscriptions()
|
|
|
|
return nil
|
|
}
|
|
|
|
// WsReadData reads data from the websocket connection
|
|
func (b *BTSE) WsReadData() (exchange.WebsocketResponse, error) {
|
|
_, resp, err := b.WebsocketConn.ReadMessage()
|
|
if err != nil {
|
|
return exchange.WebsocketResponse{}, err
|
|
}
|
|
|
|
b.Websocket.TrafficAlert <- struct{}{}
|
|
return exchange.WebsocketResponse{Raw: resp}, nil
|
|
}
|
|
|
|
// WsHandleData handles read data from websocket connection
|
|
func (b *BTSE) WsHandleData() {
|
|
b.Websocket.Wg.Add(1)
|
|
|
|
defer func() {
|
|
b.Websocket.Wg.Done()
|
|
}()
|
|
|
|
for {
|
|
select {
|
|
case <-b.Websocket.ShutdownC:
|
|
return
|
|
|
|
default:
|
|
resp, err := b.WsReadData()
|
|
if err != nil {
|
|
b.Websocket.DataHandler <- err
|
|
return
|
|
}
|
|
|
|
type MsgType struct {
|
|
Type string `json:"type"`
|
|
ProductID string `json:"product_id"`
|
|
}
|
|
|
|
if strings.Contains(string(resp.Raw), "connect success") {
|
|
if b.Verbose {
|
|
log.Debugf("%s websocket client successfully connected to %s",
|
|
b.Name, b.Websocket.GetWebsocketURL())
|
|
}
|
|
continue
|
|
}
|
|
|
|
msgType := MsgType{}
|
|
err = common.JSONDecode(resp.Raw, &msgType)
|
|
if err != nil {
|
|
b.Websocket.DataHandler <- err
|
|
continue
|
|
}
|
|
switch msgType.Type {
|
|
case "ticker":
|
|
var t wsTicker
|
|
err = common.JSONDecode(resp.Raw, &t)
|
|
if err != nil {
|
|
b.Websocket.DataHandler <- err
|
|
continue
|
|
}
|
|
p := strings.Replace(t.Price.(string), ",", "", -1)
|
|
price, err := strconv.ParseFloat(p, 64)
|
|
if err != nil {
|
|
b.Websocket.DataHandler <- err
|
|
continue
|
|
}
|
|
|
|
b.Websocket.DataHandler <- exchange.TickerData{
|
|
Timestamp: time.Now(),
|
|
Pair: currency.NewPairDelimiter(t.ProductID, "-"),
|
|
AssetType: "SPOT",
|
|
Exchange: b.GetName(),
|
|
OpenPrice: price,
|
|
}
|
|
case "snapshot":
|
|
snapshot := websocketOrderbookSnapshot{}
|
|
err := common.JSONDecode(resp.Raw, &snapshot)
|
|
if err != nil {
|
|
b.Websocket.DataHandler <- err
|
|
continue
|
|
}
|
|
|
|
err = b.wsProcessSnapshot(&snapshot)
|
|
if err != nil {
|
|
b.Websocket.DataHandler <- err
|
|
continue
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
// ProcessSnapshot processes the initial orderbook snap shot
|
|
func (b *BTSE) wsProcessSnapshot(snapshot *websocketOrderbookSnapshot) error {
|
|
var base orderbook.Base
|
|
for _, bid := range snapshot.Bids {
|
|
p := strings.Replace(bid[0].(string), ",", "", -1)
|
|
price, err := strconv.ParseFloat(p, 64)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
a := strings.Replace(bid[1].(string), ",", "", -1)
|
|
amount, err := strconv.ParseFloat(a, 64)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
base.Bids = append(base.Bids,
|
|
orderbook.Item{Price: price, Amount: amount})
|
|
}
|
|
|
|
for _, ask := range snapshot.Asks {
|
|
p := strings.Replace(ask[0].(string), ",", "", -1)
|
|
price, err := strconv.ParseFloat(p, 64)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
a := strings.Replace(ask[1].(string), ",", "", -1)
|
|
amount, err := strconv.ParseFloat(a, 64)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
base.Asks = append(base.Asks,
|
|
orderbook.Item{Price: price, Amount: amount})
|
|
}
|
|
|
|
p := currency.NewPairDelimiter(snapshot.ProductID, "-")
|
|
base.AssetType = "SPOT"
|
|
base.Pair = p
|
|
base.LastUpdated = time.Now()
|
|
base.ExchangeName = b.Name
|
|
|
|
err := base.Process()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
b.Websocket.DataHandler <- exchange.WebsocketOrderbookUpdate{
|
|
Pair: p,
|
|
Asset: "SPOT",
|
|
Exchange: b.GetName(),
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
// GenerateDefaultSubscriptions Adds default subscriptions to websocket to be handled by ManageSubscriptions()
|
|
func (b *BTSE) GenerateDefaultSubscriptions() {
|
|
var channels = []string{"snapshot", "ticker"}
|
|
enabledCurrencies := b.GetEnabledCurrencies()
|
|
subscriptions := []exchange.WebsocketChannelSubscription{}
|
|
for i := range channels {
|
|
for j := range enabledCurrencies {
|
|
subscriptions = append(subscriptions, exchange.WebsocketChannelSubscription{
|
|
Channel: channels[i],
|
|
Currency: enabledCurrencies[j],
|
|
})
|
|
}
|
|
}
|
|
b.Websocket.SubscribeToChannels(subscriptions)
|
|
}
|
|
|
|
// Subscribe sends a websocket message to receive data from the channel
|
|
func (b *BTSE) Subscribe(channelToSubscribe exchange.WebsocketChannelSubscription) error {
|
|
subscribe := websocketSubscribe{
|
|
Type: "subscribe",
|
|
Channels: []websocketChannel{
|
|
{
|
|
Name: channelToSubscribe.Channel,
|
|
ProductIDs: []string{channelToSubscribe.Currency.String()},
|
|
},
|
|
},
|
|
}
|
|
return b.wsSend(subscribe)
|
|
}
|
|
|
|
// Unsubscribe sends a websocket message to stop receiving data from the channel
|
|
func (b *BTSE) Unsubscribe(channelToSubscribe exchange.WebsocketChannelSubscription) error {
|
|
subscribe := websocketSubscribe{
|
|
Type: "unsubscribe",
|
|
Channels: []websocketChannel{
|
|
{
|
|
Name: channelToSubscribe.Channel,
|
|
ProductIDs: []string{channelToSubscribe.Currency.String()},
|
|
},
|
|
},
|
|
}
|
|
return b.wsSend(subscribe)
|
|
}
|
|
|
|
// WsSend sends data to the websocket server
|
|
func (b *BTSE) wsSend(data interface{}) error {
|
|
b.wsRequestMtx.Lock()
|
|
defer b.wsRequestMtx.Unlock()
|
|
if b.Verbose {
|
|
log.Debugf("%v sending message to websocket %v", b.Name, data)
|
|
}
|
|
json, err := common.JSONEncode(data)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
return b.WebsocketConn.WriteMessage(websocket.TextMessage, json)
|
|
}
|