mirror of
https://github.com/d0zingcat/gocryptotrader.git
synced 2026-05-13 23:16:45 +00:00
* Currency: Variadic Pairs.Add This version of Pairs.Add is simpler and [more performant](https://gist.github.com/gbjk/06a1fc1832d04ee41213ca518938cf74) Behavioural difference: If there's nothing to add, the same slice is returned unaltered. This seems like good sauce * Currency: Variadic Remove * Common: Add Batch function * Common: Add common.SortStrings for stringers * Subscriptions: Add batching to templates * Subscriptions: Sort list of pairs * Kucoin: Switch to sub templating * Kucoin: Simplify channel prefix usage * Kucoin: Fix race on fetchedFuturesOrderbook * Subscriptions: Filter AssetPairs Now only the assetPairs relevant to the subscription are in the context * Subscriptions: Respect subscription Pairs * Subscriptions: Trim AssetSeparator early We want to trim before checking for "AssetSeparator vs All" because a template should be allowed to reuse a range template and generate just one trailing AssetSeparator whilst using a specific Asset * Kucoin: Fix empty margin asset added * Kucoin: Add Subscription batching Turns out that contary to the documentation, kucoin supports batching of all symbols and currencies * Kucoin: Fix checkSubscriptions and coverage * Subscriptions: Simplify error checking This reduces the complexity of error checking to just be "do we get the correct numbers". Fixes Asset.All with only one asset erroring on xpandPairs, because we trimmed the only asset separator, and then errored that we're not xpanding Assets and the asset on the sub is asset.All This use-case conflicted with commit 6bbd546d74, which required: ``` Subscriptions: Trim AssetSeparator early We want to trim before checking for "AssetSeparator vs All" because a template should be allowed to reuse a range template and generate just one trailing AssetSeparator whilst using a specific Asset ``` Now we set up the assets earlier, and we remove the check for xpandAssets, since the number of asset lines matching is all that matters. I've removed the asset tests for this, but they were correctly erroring on the number of asset lines instead. Everything hits coverage, as well. * Kucoin: Remove deprecated fundingBook endpoint * BTCMarkets: Use common.Batch
202 lines
6.0 KiB
Go
202 lines
6.0 KiB
Go
package subscription
|
|
|
|
import (
|
|
"bytes"
|
|
"errors"
|
|
"fmt"
|
|
"maps"
|
|
"slices"
|
|
"strconv"
|
|
"strings"
|
|
|
|
"github.com/thrasher-corp/gocryptotrader/common"
|
|
"github.com/thrasher-corp/gocryptotrader/exchanges/asset"
|
|
)
|
|
|
|
const (
|
|
deviceControl = "\x11"
|
|
groupSeparator = "\x1D"
|
|
recordSeparator = "\x1E"
|
|
)
|
|
|
|
var (
|
|
errInvalidAssetExpandPairs = errors.New("subscription template containing PairSeparator with must contain either specific Asset or AssetSeparator")
|
|
errAssetRecords = errors.New("subscription template did not generate the expected number of asset records")
|
|
errPairRecords = errors.New("subscription template did not generate the expected number of pair records")
|
|
errTooManyBatchSizePerAsset = errors.New("more than one BatchSize directive inside an AssetSeparator")
|
|
errAssetTemplateWithoutAll = errors.New("sub.Asset must be set to All if AssetSeparator is used in Channel template")
|
|
errNoTemplateContent = errors.New("subscription template did not generate content")
|
|
errInvalidTemplate = errors.New("GetSubscriptionTemplate did not return a template")
|
|
)
|
|
|
|
type tplCtx struct {
|
|
S *Subscription
|
|
AssetPairs assetPairs
|
|
PairSeparator string
|
|
AssetSeparator string
|
|
BatchSize string
|
|
}
|
|
|
|
// 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 (l List) ExpandTemplates(e iExchange) (List, error) {
|
|
if !slices.ContainsFunc(l, func(s *Subscription) bool { return s.QualifiedChannel == "" }) {
|
|
// Empty list, or already processed
|
|
return slices.Clone(l), nil
|
|
}
|
|
|
|
if !e.CanUseAuthenticatedWebsocketEndpoints() {
|
|
n := List{}
|
|
for _, s := range l {
|
|
if !s.Authenticated {
|
|
n = append(n, s)
|
|
}
|
|
}
|
|
l = n
|
|
}
|
|
|
|
ap, err := l.assetPairs(e)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
assets := make(asset.Items, 0, len(ap))
|
|
for k := range ap {
|
|
assets = append(assets, k)
|
|
}
|
|
slices.Sort(assets) // text/template ranges maps in sorted order
|
|
|
|
subs := List{}
|
|
for _, s := range l {
|
|
expanded, err2 := expandTemplate(e, s, maps.Clone(ap), assets)
|
|
if err2 != nil {
|
|
err = common.AppendError(err, fmt.Errorf("%s: %w", s, err2))
|
|
} else {
|
|
subs = append(subs, expanded...)
|
|
}
|
|
}
|
|
|
|
return subs, err
|
|
}
|
|
|
|
func expandTemplate(e iExchange, s *Subscription, ap assetPairs, assets asset.Items) (List, error) {
|
|
if s.QualifiedChannel != "" {
|
|
return List{s}, nil
|
|
}
|
|
|
|
t, err := e.GetSubscriptionTemplate(s)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if t == nil {
|
|
return nil, errInvalidTemplate
|
|
}
|
|
|
|
subCtx := &tplCtx{
|
|
S: s,
|
|
PairSeparator: recordSeparator,
|
|
AssetSeparator: groupSeparator,
|
|
BatchSize: deviceControl + "BS",
|
|
}
|
|
|
|
subs := List{}
|
|
|
|
switch s.Asset {
|
|
case asset.All:
|
|
subCtx.AssetPairs = ap
|
|
default:
|
|
// This deliberately includes asset.Empty to harmonise handling
|
|
subCtx.AssetPairs = assetPairs{
|
|
s.Asset: ap[s.Asset],
|
|
}
|
|
assets = asset.Items{s.Asset}
|
|
if s.Asset != asset.Empty && len(ap[s.Asset]) == 0 {
|
|
return List{}, nil // Nothing is enabled for this sub asset
|
|
}
|
|
}
|
|
|
|
if len(s.Pairs) != 0 {
|
|
for a, pairs := range subCtx.AssetPairs {
|
|
if err := pairs.ContainsAll(s.Pairs, true); err != nil { //nolint:govet // Shadow, or gocritic will complain sloppyReassign
|
|
return nil, err
|
|
}
|
|
subCtx.AssetPairs[a] = s.Pairs
|
|
}
|
|
}
|
|
|
|
buf := &bytes.Buffer{}
|
|
if err := t.Execute(buf, subCtx); err != nil { //nolint:govet // Shadow, or gocritic will complain sloppyReassign
|
|
return nil, err
|
|
}
|
|
|
|
out := strings.TrimSpace(buf.String())
|
|
|
|
// Remove a single trailing AssetSeparator; don't use a cutset to avoid removing 2 or more
|
|
out = strings.TrimSpace(strings.TrimSuffix(out, subCtx.AssetSeparator))
|
|
|
|
assetRecords := strings.Split(out, subCtx.AssetSeparator)
|
|
if len(assetRecords) != len(assets) {
|
|
return nil, fmt.Errorf("%w: Got %d; Expected %d", errAssetRecords, len(assetRecords), len(assets))
|
|
}
|
|
|
|
for i, assetChannels := range assetRecords {
|
|
a := assets[i]
|
|
pairs := subCtx.AssetPairs[a]
|
|
|
|
xpandPairs := strings.Contains(assetChannels, subCtx.PairSeparator)
|
|
|
|
/* Batching:
|
|
- We start by assuming we'll get 1 batch sized to contain all pairs. Maybe a comma-separated list, or just the asset name
|
|
- If a BatchSize directive is found, we expect it to come right at the end, and be followed by the batch size as a number
|
|
- We'll then split into N batches of that size
|
|
- If no batchSize was declared, but we saw a PairSeparator, then we expect to see one line per pair, so batchSize is 1
|
|
*/
|
|
batchSize := len(pairs)
|
|
if b := strings.Split(assetChannels, subCtx.BatchSize); len(b) > 2 {
|
|
return nil, fmt.Errorf("%w for %s", errTooManyBatchSizePerAsset, a)
|
|
} else if len(b) == 2 {
|
|
assetChannels = b[0]
|
|
if batchSize, err = strconv.Atoi(strings.TrimSpace(b[1])); err != nil {
|
|
return nil, fmt.Errorf("%s: %w", s, common.GetTypeAssertError("int", b[1], "batchSize"))
|
|
}
|
|
} else if xpandPairs {
|
|
batchSize = 1
|
|
}
|
|
|
|
// Trim space, then only one pair separator, then any more space.
|
|
assetChannels = strings.TrimSpace(strings.TrimSuffix(strings.TrimSpace(assetChannels), subCtx.PairSeparator))
|
|
|
|
if assetChannels == "" {
|
|
continue
|
|
}
|
|
|
|
batches := common.Batch(pairs, batchSize)
|
|
|
|
pairLines := strings.Split(assetChannels, subCtx.PairSeparator)
|
|
|
|
if s.Asset != asset.Empty && len(pairLines) != len(batches) {
|
|
// The number of lines we get generated must match the number of pair batches we expect
|
|
return nil, fmt.Errorf("%w for %s: Got %d; Expected %d", errPairRecords, a, len(pairLines), len(batches))
|
|
}
|
|
|
|
for j, channel := range pairLines {
|
|
c := s.Clone()
|
|
c.Asset = a
|
|
channel = strings.TrimSpace(channel)
|
|
if channel == "" {
|
|
return nil, fmt.Errorf("%w for %s: %s", errNoTemplateContent, a, s)
|
|
}
|
|
c.QualifiedChannel = channel
|
|
if s.Asset != asset.Empty {
|
|
c.Pairs = batches[j]
|
|
}
|
|
subs = append(subs, c)
|
|
}
|
|
}
|
|
|
|
return subs, nil
|
|
}
|