subscription

package
v0.0.0-...-9d0796a Latest Latest
Warning

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

Go to latest
Published: Dec 9, 2024 License: MIT Imports: 13 Imported by: 0

README

GoCryptoTrader package Subscription

Build Status Software License GoDoc Coverage Status Go Report Card

This subscription package is part of the GoCryptoTrader codebase.

This is still in active development

You can track ideas, planned features and what's in progress on our GoCryptoTrader Kanban board.

Join our slack to discuss all things related to GoCryptoTrader! GoCryptoTrader Slack

Exchange Subscriptions

Exchange Subscriptions are streams of data delivered via websocket.

GoCryptoTrader engine will subscribe automatically to configured channels. A subset of exchanges currently support user configured channels, with the remaining using hardcoded defaults. See configuration Features.Subscriptions for whether an exchange is configurable.

Templating

Exchange Contributors should implement GetSubscriptionTemplate to return a text/template Template.

Exchanges are free to implement template caching, a map or a mono-template, inline or file templates.

The template is provided with a single context structure:

  S              *subscription.Subscription
  AssetPairs     map[asset.Item]currency.Pairs
  AssetSeparator string
  PairSeparator  string
  BatchSize      string

Subscriptions may fan out many channels for assets and pairs, to support exchanges which require individual subscriptions.
To allow the template to communicate how to handle its output it should use the provided directives:

  • AssetSeparator should be added at the end of each section related to assets
  • PairSeparator should be added at the end of each pair
  • BatchSize should be added with a number directly before AssetSeparator to indicate pairs have been batched

Example:

{{- range $asset, $pairs := $.AssetPairs }}
    {{- range $b := batch $pairs 30 -}}
        {{- $.S.Channel -}} : {{- $b.Join -}}
        {{ $.PairSeparator }}
    {{- end -}}
    {{- $.BatchSize -}} 30
    {{- $.AssetSeparator }}
{{- end }}

Assets and pairs should be output in the sequence in AssetPairs since text/template range function uses an sorted order for map keys.

Template functions may modify AssetPairs to update the subscription's pairs, e.g. Filtering out margin pairs already in spot subscription.

We use separators like this because it allows mono-templates to decide at runtime whether to fan out.

See exchanges/subscription/testdata/subscriptions.tmpl for an example mono-template showcasing various features.

Templates do not need to worry about joining around separators; Trailing separators will be stripped automatically.

Template functions should panic to handle errors. They are caught by text/template and turned into errors for use in subscription.expandTemplate.

Contribution

Please feel free to submit any pull requests or suggest any desired features to be added.

When submitting a PR, please abide by our coding guidelines:

  • Code must adhere to the official Go formatting guidelines (i.e. uses gofmt).
  • Code must be documented adhering to the official Go commentary guidelines.
  • Code must adhere to our coding style.
  • Pull requests need to be based on and opened against the master branch.

Donations

If this framework helped you in any way, or you would like to support the developers working on it, please donate Bitcoin to:

bc1qk0jareu4jytc0cfrhr5wgshsq8282awpavfahc

Documentation

Index

Constants

View Source
const (
	TickerChannel    = "ticker"
	OrderbookChannel = "orderbook"
	CandlesChannel   = "candles"
	AllOrdersChannel = "allOrders"
	AllTradesChannel = "allTrades"
	MyTradesChannel  = "myTrades"
	MyOrdersChannel  = "myOrders"
	MyWalletChannel  = "myWallet"
	MyAccountChannel = "myAccount"
	HeartbeatChannel = "heartbeat"
)

Channel constants

Variables

View Source
var (
	ErrNotFound             = errors.New("subscription not found")
	ErrNotSinglePair        = errors.New("only single pair subscriptions expected")
	ErrBatchingNotSupported = errors.New("subscription batching not supported")
	ErrInStateAlready       = errors.New("subscription already in state")
	ErrInvalidState         = errors.New("invalid subscription state")
	ErrDuplicate            = errors.New("duplicate subscription")
	ErrUseConstChannelName  = errors.New("must use standard channel name constants")
	ErrNotSupported         = errors.New("subscription channel not supported")
)

Public errors

Functions

This section is empty.

Types

type ExactKey

type ExactKey struct {
	*Subscription
}

ExactKey is key type for subscriptions where all the pairs in a Subscription must match exactly

func (ExactKey) GetSubscription

func (k ExactKey) GetSubscription() *Subscription

GetSubscription returns the underlying subscription

func (ExactKey) Match

func (k ExactKey) Match(eachKey MatchableKey) bool

Match implements MatchableKey Returns true if the key fields exactly matches the subscription, including all Pairs Does not check QualifiedChannel or Params

func (ExactKey) String

func (k ExactKey) String() string

String implements Stringer; returns the Asset, Channel and Pairs Does not provide concurrency protection on the subscription it points to

type IgnoringAssetKey

type IgnoringAssetKey struct {
	*Subscription
}

IgnoringAssetKey is a key type for finding subscriptions to group together for requests

func (IgnoringAssetKey) GetSubscription

func (k IgnoringAssetKey) GetSubscription() *Subscription

GetSubscription returns the underlying subscription

func (IgnoringAssetKey) Match

func (k IgnoringAssetKey) Match(eachKey MatchableKey) bool

Match implements MatchableKey

func (IgnoringAssetKey) String

func (k IgnoringAssetKey) String() string

String implements Stringer; returns the asset and Channel name but no pairs

type IgnoringPairsKey

type IgnoringPairsKey struct {
	*Subscription
}

IgnoringPairsKey is a key type for finding subscriptions to group together for requests

func (IgnoringPairsKey) GetSubscription

func (k IgnoringPairsKey) GetSubscription() *Subscription

GetSubscription returns the underlying subscription

func (IgnoringPairsKey) Match

func (k IgnoringPairsKey) Match(eachKey MatchableKey) bool

Match implements MatchableKey

func (IgnoringPairsKey) String

func (k IgnoringPairsKey) String() string

String implements Stringer; returns the asset and Channel name but no pairs

type List

type List []*Subscription

List is a container of subscription pointers

func (List) Clone

func (l List) Clone() List

Clone returns a deep clone of the List

func (List) Enabled

func (l List) Enabled() List

Enabled returns a new list of only enabled subscriptions

func (List) ExpandTemplates

func (l List) ExpandTemplates(e iExchange) (List, error)

ExpandTemplates returns a list of Subscriptions with Template expanded May be called on already expanded subscriptions: Passes $s through unprocessed if QualifiedChannel is already populated Calls e.GetSubscriptionTemplate to find a template for each subscription Filters out Authenticated subscriptions if !e.CanUseAuthenticatedEndpoints See README.md for more details

func (List) GroupByPairs

func (l List) GroupByPairs() []List

GroupByPairs groups subscriptions which have the same Pairs

func (List) GroupPairs

func (l List) GroupPairs() (n List)

GroupPairs groups subscriptions which are identical apart from the Pairs The returned List contains cloned Subscriptions, and the original Subscriptions are left alone

func (List) Private

func (l List) Private() List

Private returns only subscriptions which require authentication

func (List) Public

func (l List) Public() List

Public returns only subscriptions which do not require authentication

func (List) QualifiedChannels

func (l List) QualifiedChannels() []string

QualifiedChannels returns a sorted list of all the qualified Channels in the list

func (List) SetStates

func (l List) SetStates(state State) error

SetStates sets the state for all the subs in a list Errors are collected for any subscriptions already in the state On error all changes are reverted

func (List) Strings

func (l List) Strings() []string

Strings returns a sorted slice of subscriptions

type MatchableKey

type MatchableKey interface {
	Match(MatchableKey) bool
	GetSubscription() *Subscription
	String() string
}

MatchableKey interface should be implemented by Key types which want a more complex matching than a simple key equality check The Subscription method allows keys to compare against keys of other types

type State

type State uint8

State tracks the status of a subscription channel

const (
	InactiveState State = iota
	SubscribingState
	SubscribedState
	ResubscribingState
	UnsubscribingState
	UnsubscribedState
)

State constants

type Store

type Store struct {
	// contains filtered or unexported fields
}

Store is a container of subscription pointers

func NewStore

func NewStore() *Store

NewStore creates a ready to use store and should always be used

func NewStoreFromList

func NewStoreFromList(l List) (*Store, error)

NewStoreFromList creates a Store from a List

func (*Store) Add

func (s *Store) Add(sub *Subscription) error

Add adds a subscription to the store Key can be already set; if omitted EnsureKeyed will be used Errors if it already exists

func (*Store) Clear

func (s *Store) Clear()

Clear empties the subscription store

func (*Store) Diff

func (s *Store) Diff(compare List) (added, removed List)

Diff returns a list of the added and missing subs from a new list The store Diff is invoked upon is read-lock protected The new store is assumed to be a new instance and enjoys no locking protection

func (*Store) Get

func (s *Store) Get(key any) *Subscription

Get returns a pointer to a subscription or nil if not found If the key passed in is a Subscription then its Key will be used; which may be a pointer to itself. If key implements MatchableKey then key.Match will be used; Note that *Subscription implements MatchableKey

func (*Store) Len

func (s *Store) Len() int

Len returns the number of subscriptions

func (*Store) List

func (s *Store) List() List

List returns a slice of Subscriptions pointers

func (*Store) Remove

func (s *Store) Remove(key any) error

Remove removes a subscription from the store If the key passed in is a Subscription then its Key will be used; which may be a pointer to itself. If key implements MatchableKey then key.Match will be used; Note that *Subscription implements MatchableKey

type Subscription

type Subscription struct {
	Enabled          bool           `json:"enabled"`
	Key              any            `json:"-"`
	Channel          string         `json:"channel,omitempty"`
	Pairs            currency.Pairs `json:"pairs,omitempty"`
	Asset            asset.Item     `json:"asset,omitempty"`
	Params           map[string]any `json:"params,omitempty"`
	Interval         kline.Interval `json:"interval,omitempty"`
	Levels           int            `json:"levels,omitempty"`
	Authenticated    bool           `json:"authenticated,omitempty"`
	QualifiedChannel string         `json:"-"`
	// contains filtered or unexported fields
}

Subscription container for streaming subscriptions

func (*Subscription) AddPairs

func (s *Subscription) AddPairs(pairs ...currency.Pair)

AddPairs does what it says on the tin safely for concurrency

func (*Subscription) Clone

func (s *Subscription) Clone() *Subscription

Clone returns a copy of a subscription Key is set to nil, because most Key types contain a pointer to the subscription, and because the clone isn't added to the store yet QualifiedChannel is not copied because it's expected that the contributing fields will be changed Users should allow a default key to be assigned on AddSubscription or can SetKey as necessary

func (*Subscription) EnsureKeyed

func (s *Subscription) EnsureKeyed() any

EnsureKeyed returns the subscription key If no key exists then ExactKey will be used

func (*Subscription) SetKey

func (s *Subscription) SetKey(key any)

SetKey does what it says on the tin safely for concurrency

func (*Subscription) SetPairs

func (s *Subscription) SetPairs(pairs currency.Pairs)

SetPairs does what it says on the tin safely for concurrency

func (*Subscription) SetState

func (s *Subscription) SetState(state State) error

SetState sets the subscription state Errors if already in that state or the new state is not valid

func (*Subscription) State

func (s *Subscription) State() State

State returns the subscription state

func (*Subscription) String

func (s *Subscription) String() string

String implements Stringer, and aims to informatively and uniquely identify a subscription for errors and information returns a string of the subscription key by delegating to MatchableKey.String() when possible If the key is not a MatchableKey then both the key and an ExactKey.String() will be returned; e.g. 1137: spot MyTrades

Jump to

Keyboard shortcuts

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