catws

package module
v0.0.0-...-6f81dac Latest Latest
Warning

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

Go to latest
Published: Dec 23, 2023 License: MIT Imports: 15 Imported by: 0

README

Coinbase Advanced Trade WebSocket (catws)

Go Report Card GitHub go.mod Go version GitHub Licence

This go package provides an easy accessible API for connecting and consuming the Coinbase Advanced Trade WebSocket.

See Advanced Trade WebSocket Overview for more details.

Installation

go get -u github.com/apperia-de/catws

Preparation

In order to subscribe to channels and consume data from the Coinbase Advanced Trade WebSocket, you need to create an API key first.

Please visit Creating Cloud API keys for details about creating an API key.

Example usage

package main

import (
	"fmt"
	"github.com/apperia-de/catws"
	"os"
	"os/signal"
	"time"
)

func main() {
	c := make(chan os.Signal, 1)
	signal.Notify(c, os.Interrupt)

	ws := catws.New(
		catws.WithCredentials("YOUR_COINBASE_API_KEY", "YOUR_COINBASE_API_SECRET"),
		catws.WithLogging(), // Enable logging.
		catws.WithSubscriptions(map[string][]string{ // Set default subscriptions -> will be also established after reconnect.
			catws.UserChannel:    nil,
			catws.CandlesChannel: {"BTC-EUR"},
		}),
		catws.WithMaxElapsedTime(time.Hour), // Retry reconnect with exponential backoff for at most 1hour before exiting the app.
	)
	// Subscribe to Ticker batch updates for some product ids
	ws.Subscribe(catws.TickerBatchChannel, []string{"BTC-EUR", "ETH-EUR", "XRP-EUR"}) // Will not be established after reconnect
	closeChan := make(chan struct{})

	go func() {
		for {
			select {
			//case m := <-ws.Channel.Heartbeat:
			//	fmt.Println(m)
			case m := <-ws.Channel.User:
				fmt.Println(m)
			case m := <-ws.Channel.Ticker:
				fmt.Println(m)
			case m := <-ws.Channel.Status:
				fmt.Println(m)
			case m := <-ws.Channel.MarketTrades:
				fmt.Println(m)
			case m := <-ws.Channel.Level2:
				fmt.Println(m)
			case <-closeChan:
				fmt.Println("shutdown go-routine...")
				return
			}
		}
	}()

	// Block until a signal is received. (CTRL-C)
	<-c
	closeChan <- struct{}{}
	fmt.Println("closing websocket...")
	if err := ws.CloseNormal(); err != nil {
		fmt.Println(err)
	}
}

Documentation

Index

Constants

View Source
const (
	AdvanceTradeWebsocketURL = "wss://advanced-trade-ws.coinbase.com"

	HeartbeatChannel    = "heartbeats"    // https://docs.cloud.coinbase.com/advanced-trade-api/docs/ws-channels#heartbeats-channel
	CandlesChannel      = "candles"       // https://docs.cloud.coinbase.com/advanced-trade-api/docs/ws-channels#candles-channel
	MarketTradesChannel = "market_trades" // https://docs.cloud.coinbase.com/advanced-trade-api/docs/ws-channels#market-trades-channel
	StatusChannel       = "status"        // https://docs.cloud.coinbase.com/advanced-trade-api/docs/ws-channels#status-channel
	TickerChannel       = "ticker"        // https://docs.cloud.coinbase.com/advanced-trade-api/docs/ws-channels#ticker-channel
	TickerBatchChannel  = "ticker_batch"  // https://docs.cloud.coinbase.com/advanced-trade-api/docs/ws-channels#ticker-batch-channel
	Level2Channel       = "level2"        // https://docs.cloud.coinbase.com/advanced-trade-api/docs/ws-channels#level2-channel
	UserChannel         = "user"          // https://docs.cloud.coinbase.com/advanced-trade-api/docs/ws-channels#user-channel

	SubscriptionsChannel = "subscriptions"

	ContextTimeout     = 5 * time.Second
	ContextReadTimeout = 10 * time.Second

	JWTAudience = "public_websocket_api"
	JWTIssuer   = "coinbase-cloud"
)

Variables

This section is empty.

Functions

This section is empty.

Types

type AdvancedTradeWS

type AdvancedTradeWS struct {
	Channel struct {
		Heartbeat    <-chan HeartbeatMessage
		Candles      <-chan CandlesMessage
		Status       <-chan StatusMessage
		MarketTrades <-chan MarketTradesMessage
		Ticker       <-chan TickerMessage
		Level2       <-chan Level2Message
		User         <-chan UserMessage
	}
	// contains filtered or unexported fields
}

func New

func New(opts ...Option) *AdvancedTradeWS

func (*AdvancedTradeWS) CloseNormal

func (ws *AdvancedTradeWS) CloseNormal() error

func (*AdvancedTradeWS) Connect

func (ws *AdvancedTradeWS) Connect() error

func (*AdvancedTradeWS) Subscribe

func (ws *AdvancedTradeWS) Subscribe(channel string, productIDs []string)

func (*AdvancedTradeWS) Unsubscribe

func (ws *AdvancedTradeWS) Unsubscribe(channel string, productIDs []string)

type CandlesMessage

type CandlesMessage struct {
	Message
	Events []struct {
		Type    string `json:"type"`
		Candles []struct {
			Start     string `json:"start"`
			High      string `json:"high"`
			Low       string `json:"low"`
			Open      string `json:"open"`
			Close     string `json:"close"`
			Volume    string `json:"volume"`
			ProductID string `json:"product_id"`
		} `json:"candles"`
	} `json:"events"`
}

CandlesMessage Response of the subscribe message

type HeartbeatMessage

type HeartbeatMessage struct {
	Message
	Events []struct {
		CurrentTime      string `json:"current_time"`
		HeartbeatCounter string `json:"heartbeat_counter"`
	} `json:"events"`
}

type Level2Message

type Level2Message struct {
	Message
	Events []struct {
		Type      string `json:"type"`
		ProductID string `json:"product_id"`
		Updates   []struct {
			Side        string    `json:"side"`
			EventTime   time.Time `json:"event_time"`
			PriceLevel  string    `json:"price_level"`
			NewQuantity string    `json:"new_quantity"`
		} `json:"updates"`
	} `json:"events"`
}

type MarketTradesMessage

type MarketTradesMessage struct {
	Message
	Events []struct {
		Type   string `json:"type"`
		Trades []struct {
			TradeID   string    `json:"trade_id"`
			ProductID string    `json:"product_id"`
			Price     string    `json:"price"`
			Size      string    `json:"size"`
			Side      string    `json:"side"`
			Time      time.Time `json:"time"`
		} `json:"trades"`
	} `json:"events"`
}

type Message

type Message struct {
	Channel     string    `json:"channel"`
	ClientID    string    `json:"client_id"`
	Timestamp   time.Time `json:"timestamp"`
	SequenceNum int       `json:"sequence_num"`
}

Message a Websocket message

type Option

type Option func(*AdvancedTradeWS)

func WithCredentials

func WithCredentials(apiKey, apiSecret string) Option

WithCredentials option provides the required apiKey and apiSecret of the coinbase user.

func WithLogging

func WithLogging() Option

WithLogging option enables package logging to stdErr (Default: logging to io.Discard)

func WithMaxElapsedTime

func WithMaxElapsedTime(maxElapsedTime time.Duration) Option

WithMaxElapsedTime sets the MaxElapsedTime after which the exponential backoff retries will finally stop trying to reconnect. Defaults to 15 minutes. Set to 0 in order to deactivate and let it retry forever.

func WithSubscriptions

func WithSubscriptions(s map[string][]string) Option

WithSubscriptions sets a combination of channel and productIDs the user wants to subscribe to.

func WithURL

func WithURL(url string) Option

WithURL allows changing the default coinbase websocket url

type StatusMessage

type StatusMessage struct {
	Message
	Events []struct {
		Type     string `json:"type"`
		Products []struct {
			ProductType    string `json:"product_type"`
			ID             string `json:"id"`
			BaseCurrency   string `json:"base_currency"`
			QuoteCurrency  string `json:"quote_currency"`
			BaseIncrement  string `json:"base_increment"`
			QuoteIncrement string `json:"quote_increment"`
			DisplayName    string `json:"display_name"`
			Status         string `json:"status"`
			StatusMessage  string `json:"status_message"`
			MinMarketFunds string `json:"min_market_funds"`
		} `json:"products"`
	} `json:"events"`
}

type SubscribeReq

type SubscribeReq struct {
	Type       string   `json:"type"`        // Type of the message
	ProductIds []string `json:"product_ids"` // List of product ids
	Channel    string   `json:"channel"`     // The name of the channel
	JWT        string   `json:"jwt"`         // Each JWT is valid for 2 minutes
	Timestamp  string   `json:"timestamp"`   // Current timestamp of the message as a unix integer
}

SubscribeReq Request of the subscribe message

type SubscriptionsMessage

type SubscriptionsMessage struct {
	Message
	Events []struct {
		Subscriptions map[string][]string `json:"subscriptions"`
	} `json:"events"`
}

SubscriptionsMessage Response of the subscribe message

type TickerMessage

type TickerMessage struct {
	Message
	Events []struct {
		Type    string `json:"type"`
		Tickers []struct {
			Type               string `json:"type"`
			ProductID          string `json:"product_id"`
			Price              string `json:"price"`
			Volume24H          string `json:"volume_24_h"`
			Low24H             string `json:"low_24_h"`
			High24H            string `json:"high_24_h"`
			Low52W             string `json:"low_52_w"`
			High52W            string `json:"high_52_w"`
			PricePercentChg24H string `json:"price_percent_chg_24_h"`
		} `json:"tickers"`
	} `json:"events"`
}

type UnsubscribeReq

type UnsubscribeReq struct {
	Type       string   `json:"type"`        // Type of the message
	ProductIds []string `json:"product_ids"` // List of product ids
	Channel    string   `json:"channel"`     // The name of the channel
	JWT        string   `json:"jwt"`         // Each JWT is valid for 2 minutes
	Timestamp  string   `json:"timestamp"`   // Current timestamp of the message as a unix integer
}

UnsubscribeReq Request of the unsubscribe message

type UserMessage

type UserMessage struct {
	Message
	Events []struct {
		Type   string `json:"type"`
		Orders []struct {
			OrderID            string    `json:"order_id"`
			ClientOrderID      string    `json:"client_order_id"`
			CumulativeQuantity string    `json:"cumulative_quantity"`
			LeavesQuantity     string    `json:"leaves_quantity"`
			AvgPrice           string    `json:"avg_price"`
			TotalFees          string    `json:"total_fees"`
			Status             string    `json:"status"`
			ProductID          string    `json:"product_id"`
			CreationTime       time.Time `json:"creation_time"`
			OrderSide          string    `json:"order_side"`
			OrderType          string    `json:"order_type"`
		} `json:"orders"`
	} `json:"events"`
}

UserMessage is the type of the user message which is returned if subscribed to "user" channel

func (UserMessage) String

func (m UserMessage) String() string

Jump to

Keyboard shortcuts

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