mirror of
https://github.com/d0zingcat/gocryptotrader.git
synced 2026-05-16 23:16:48 +00:00
* gateio: Add multi asset websocket support WIP. * meow * Add tests and shenanigans * integrate flushing and for enabling/disabling pairs from rpc shenanigans * some changes * linter: fixes strikes again. * Change name ConnectionAssociation -> ConnectionCandidate for better clarity on purpose. Change connections map to point to candidate to track subscriptions for future dynamic connections holder and drop struct ConnectionDetails. * Add subscription tests (state functional) * glorious:nits + proxy handling * Spelling * linter: fixerino * instead of nil, dont do nil. * clean up nils * cya nils * don't need to set URL or check if its running * stop ping handler routine leak * * Fix bug where reader routine on error that is not a disconnection error but websocket frame error or anything really makes the reader routine return and then connection never cycles and the buffer gets filled. * Handle reconnection via an errors.Is check which is simpler and in that scope allow for quick disconnect reconnect without waiting for connection cycle. * Dial now uses code from DialContext but just calls context.Background() * Don't allow reader to return on parse binary response error. Just output error and return a non nil response * Allow rollback on connect on any error across all connections * fix shadow jutsu * glorious/gk: nitters - adds in ws mock server * linter: fix * fix deadlock on connection as the previous channel had no reader and would hang connection reader for eternity. * gk: nits * Leak issue and edge case * gk: nits * gk: drain brain * glorious: nits * Update exchanges/stream/websocket.go Co-authored-by: Scott <gloriousCode@users.noreply.github.com> * glorious: nits * add tests * linter: fix * After merge * Add error connection info * Fix edge case where it does not reconnect made by an already closed connection * stream coverage * glorious: nits * glorious: nits removed asset error handling in stream package * linter: fix * rm block * Add basic readme * fix asset enabled flush cycle for multi connection * spella: fix * linter: fix * Add glorious suggestions, fix some race thing * reinstate name before any routine gets spawned * stop on error in mock tests * glorious: nits * glorious: nits found in CI build * Add test for drain, bumped wait times as there seems to be something happening on macos CI builds, used context.WithTimeout because its instant. * mutex across shutdown and connect for protection * lint: fix * test time withoffset, reinstate stop * fix whoops * const trafficCheckInterval; rm testmain * y * fix lint * bump time check window * stream: fix intermittant test failures while testing routines and remove code that is not needed. * spells * cant do what I did * protect race due to routine. * update testURL * use mock websocket connection instead of test URL's * linter: fix * remove url because its throwing errors on CI builds * connections drop all the time, don't need to worry about not being able to echo back ws data as it can be easily reviewed _test file side. * remove another superfluous url thats not really set up for this * spawn overwatch routine when there is no errors, inline checker instead of waiting for a time period, add sleep inline with echo handler as this is really quick and wanted to ensure that latency is handing correctly * linter: fixerino uperino * glorious: panix * linter: things * whoops * defer lock and use functions that don't require locking in SetProxyAddress * lint: fix * thrasher: nits --------- Co-authored-by: shazbert <ryan.oharareid@thrasher.io> Co-authored-by: Scott <gloriousCode@users.noreply.github.com>
218 lines
5.0 KiB
Go
218 lines
5.0 KiB
Go
package bithumb
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"fmt"
|
|
"net/http"
|
|
"time"
|
|
|
|
"github.com/gorilla/websocket"
|
|
"github.com/thrasher-corp/gocryptotrader/common"
|
|
"github.com/thrasher-corp/gocryptotrader/exchanges/asset"
|
|
"github.com/thrasher-corp/gocryptotrader/exchanges/request"
|
|
"github.com/thrasher-corp/gocryptotrader/exchanges/stream"
|
|
"github.com/thrasher-corp/gocryptotrader/exchanges/subscription"
|
|
"github.com/thrasher-corp/gocryptotrader/exchanges/ticker"
|
|
"github.com/thrasher-corp/gocryptotrader/exchanges/trade"
|
|
)
|
|
|
|
const (
|
|
wsEndpoint = "wss://pubwss.bithumb.com/pub/ws"
|
|
tickerTimeLayout = "20060102150405"
|
|
tradeTimeLayout = time.DateTime + ".000000"
|
|
)
|
|
|
|
var (
|
|
wsDefaultTickTypes = []string{"30M"} // alternatives "1H", "12H", "24H", "MID"
|
|
location *time.Location
|
|
)
|
|
|
|
// WsConnect initiates a websocket connection
|
|
func (b *Bithumb) WsConnect() error {
|
|
if !b.Websocket.IsEnabled() || !b.IsEnabled() {
|
|
return stream.ErrWebsocketNotEnabled
|
|
}
|
|
|
|
var dialer websocket.Dialer
|
|
dialer.HandshakeTimeout = b.Config.HTTPTimeout
|
|
dialer.Proxy = http.ProxyFromEnvironment
|
|
|
|
err := b.Websocket.Conn.Dial(&dialer, http.Header{})
|
|
if err != nil {
|
|
return fmt.Errorf("%v - Unable to connect to Websocket. Error: %w",
|
|
b.Name,
|
|
err)
|
|
}
|
|
|
|
b.Websocket.Wg.Add(1)
|
|
go b.wsReadData()
|
|
|
|
b.setupOrderbookManager()
|
|
return nil
|
|
}
|
|
|
|
// wsReadData receives and passes on websocket messages for processing
|
|
func (b *Bithumb) wsReadData() {
|
|
defer b.Websocket.Wg.Done()
|
|
|
|
for {
|
|
select {
|
|
case <-b.Websocket.ShutdownC:
|
|
return
|
|
default:
|
|
resp := b.Websocket.Conn.ReadMessage()
|
|
if resp.Raw == nil {
|
|
return
|
|
}
|
|
err := b.wsHandleData(resp.Raw)
|
|
if err != nil {
|
|
b.Websocket.DataHandler <- err
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
func (b *Bithumb) wsHandleData(respRaw []byte) error {
|
|
var resp WsResponse
|
|
err := json.Unmarshal(respRaw, &resp)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
if resp.Status != "" {
|
|
if resp.Status == "0000" {
|
|
return nil
|
|
}
|
|
return fmt.Errorf("%s: %w",
|
|
resp.ResponseMessage,
|
|
stream.ErrSubscriptionFailure)
|
|
}
|
|
|
|
switch resp.Type {
|
|
case "ticker":
|
|
var tick WsTicker
|
|
err = json.Unmarshal(resp.Content, &tick)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
var lu time.Time
|
|
lu, err = time.ParseInLocation(tickerTimeLayout,
|
|
tick.Date+tick.Time,
|
|
location)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
b.Websocket.DataHandler <- &ticker.Price{
|
|
ExchangeName: b.Name,
|
|
AssetType: asset.Spot,
|
|
Last: tick.PreviousClosePrice,
|
|
Pair: tick.Symbol,
|
|
Open: tick.OpenPrice,
|
|
Close: tick.ClosePrice,
|
|
Low: tick.LowPrice,
|
|
High: tick.HighPrice,
|
|
QuoteVolume: tick.Value,
|
|
Volume: tick.Volume,
|
|
LastUpdated: lu,
|
|
}
|
|
case "transaction":
|
|
if !b.IsSaveTradeDataEnabled() {
|
|
return nil
|
|
}
|
|
|
|
var trades WsTransactions
|
|
err = json.Unmarshal(resp.Content, &trades)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
toBuffer := make([]trade.Data, len(trades.List))
|
|
var lu time.Time
|
|
for x := range trades.List {
|
|
lu, err = time.ParseInLocation(tradeTimeLayout,
|
|
trades.List[x].ContractTime,
|
|
location)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
toBuffer[x] = trade.Data{
|
|
Exchange: b.Name,
|
|
AssetType: asset.Spot,
|
|
CurrencyPair: trades.List[x].Symbol,
|
|
Timestamp: lu,
|
|
Price: trades.List[x].ContractPrice,
|
|
Amount: trades.List[x].ContractAmount,
|
|
}
|
|
}
|
|
|
|
err = b.AddTradesToBuffer(toBuffer...)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
case "orderbookdepth":
|
|
var orderbooks WsOrderbooks
|
|
err = json.Unmarshal(resp.Content, &orderbooks)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
init, err := b.UpdateLocalBuffer(&orderbooks)
|
|
if err != nil && !init {
|
|
return fmt.Errorf("%v - UpdateLocalCache error: %s", b.Name, err)
|
|
}
|
|
return nil
|
|
default:
|
|
return fmt.Errorf("unhandled response type %s", resp.Type)
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
// generateSubscriptions generates the default subscription set
|
|
func (b *Bithumb) generateSubscriptions() (subscription.List, error) {
|
|
var channels = []string{"ticker", "transaction", "orderbookdepth"}
|
|
var subscriptions subscription.List
|
|
pairs, err := b.GetEnabledPairs(asset.Spot)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
pFmt, err := b.GetPairFormat(asset.Spot, true)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
pairs = pairs.Format(pFmt)
|
|
|
|
for y := range channels {
|
|
subscriptions = append(subscriptions, &subscription.Subscription{
|
|
Channel: channels[y],
|
|
Pairs: pairs,
|
|
Asset: asset.Spot,
|
|
})
|
|
}
|
|
return subscriptions, nil
|
|
}
|
|
|
|
// Subscribe subscribes to a set of channels
|
|
func (b *Bithumb) Subscribe(channelsToSubscribe subscription.List) error {
|
|
var errs error
|
|
for _, s := range channelsToSubscribe {
|
|
req := &WsSubscribe{
|
|
Type: s.Channel,
|
|
Symbols: s.Pairs,
|
|
}
|
|
if s.Channel == "ticker" {
|
|
req.TickTypes = wsDefaultTickTypes
|
|
}
|
|
err := b.Websocket.Conn.SendJSONMessage(context.TODO(), request.Unset, req)
|
|
if err == nil {
|
|
err = b.Websocket.AddSuccessfulSubscriptions(b.Websocket.Conn, s)
|
|
}
|
|
if err != nil {
|
|
errs = common.AppendError(errs, err)
|
|
}
|
|
}
|
|
return errs
|
|
}
|