mirror of
https://github.com/d0zingcat/gocryptotrader.git
synced 2026-05-21 07:26: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 * stream match update * update tests * linter: fix * glorious: nits + handle context cancellations * 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. * glorious: whooops * gk: nits * Leak issue and edge case * Websocket: Add SendMessageReturnResponses * whooooooopsie * gk: nitssssss * Update exchanges/stream/stream_match.go Co-authored-by: Gareth Kirwan <gbjkirwan@gmail.com> * Update exchanges/stream/stream_match_test.go Co-authored-by: Gareth Kirwan <gbjkirwan@gmail.com> * linter: appease the linter gods * gk: nits * gk: drain brain * started * more changes before merge match pr * gateio: still building out * gateio: finish spot * fix up tests in gateio * Add tests for stream package * rm unused field * glorious: nits * rn files, specifically set function names to asset and offload routing to websocket type. * linter: fix * Add futures websocket request support * gateio: integrate with IBOTExchange (cherry pick my nose) * linter: fix * glorious: nits * add counter and update gateio * fix collision issue * 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 * upgrade to upstream merge * 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 * Set correct price * 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 * fix ID bug, why I do this, I don't know. * glorious: panix * linter: things * whoops * dont need to make consecutive Unix() calls * websocket: fix potential panic on error and no responses and adding waitForResponses * rm json parser and handle in json package instead * in favour of json package unmarshalling * linter: fix * linter: fix again * * change field name OutboundRequestSignature to WrapperDefinedConnectionSignature for agnostic inbound and outbound connections. * change method name GetOutboundConnection to GetConnection for agnostic inbound and outbound connections. * drop outbound field map for improved performance just using a range and field check (less complex as well) * change field name connections to connectionToWrapper for better clarity * spells and magic and wands * glorious: nits * comparable check for signature * mv err var * glorious: nits and stuff * attempt to fix race * glorious: nits * gk: nits; engine log cleanup * gk: nits; OCD * gk: nits; move function change file names * gk: nits; 🚀 * gk: nits; convert variadic function and message inspection to interface and include a specific function for that handling so as to not need nil on every call * gk: nits; continued * gk: engine nits; rm loaded exchange * gk: nits; drop WebsocketLoginResponse * stream: Add match method EnsureMatchWithData * gk: nits; rn Inspect to IsFinal * gk: nits; rn to MessageFilter * linter: fix * gateio: update rate limit definitions (cherry-pick) * Add test and missing * Shared REST rate limit definitions with Websocket service, set lookup item to nil for systems that do not require rate limiting; add glorious nit * integrate rate limits for websocket trading spot * conform to match upstream changes * standardise names to upstream style * fix wrapper standards test when sending a auth request through a websocket connection * whoops * Update exchanges/gateio/gateio_types.go Co-authored-by: Scott <gloriousCode@users.noreply.github.com> * glorious: nits * linter: fix * linter: overload * whoops * spelling fixes on recent merge * glorious: nits * linter: fix? * glorious: nits * gk: assert errors touched * gk: unexport derive functions * gk: nitssssssss * fix test * gk: nitters v1 * gk: http status * gk/nits: Add getAssetFromFuturesPair * gk: nits single response when submitting * gk: new pair with delimiter in tests * gk: param update slice to slice of pointers * gk: add asset type in params, includes t.Context() for tests * linter: fix * linter: fix * fix merge whoopsie * glorious: nits * gk: nit * shift over to websocket package error * internal/exchange/websocket -> exchange/websocket * PEAK OCD! * appease the OCD gods * thrasher: nits --------- Co-authored-by: shazbert <ryan.oharareid@thrasher.io> Co-authored-by: Gareth Kirwan <gbjkirwan@gmail.com> Co-authored-by: Scott <gloriousCode@users.noreply.github.com>
689 lines
21 KiB
Go
689 lines
21 KiB
Go
package gateio
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"net/http"
|
|
"strconv"
|
|
"strings"
|
|
"time"
|
|
|
|
gws "github.com/gorilla/websocket"
|
|
"github.com/thrasher-corp/gocryptotrader/currency"
|
|
"github.com/thrasher-corp/gocryptotrader/encoding/json"
|
|
"github.com/thrasher-corp/gocryptotrader/exchange/websocket"
|
|
"github.com/thrasher-corp/gocryptotrader/exchanges/account"
|
|
"github.com/thrasher-corp/gocryptotrader/exchanges/asset"
|
|
"github.com/thrasher-corp/gocryptotrader/exchanges/fill"
|
|
"github.com/thrasher-corp/gocryptotrader/exchanges/kline"
|
|
"github.com/thrasher-corp/gocryptotrader/exchanges/order"
|
|
"github.com/thrasher-corp/gocryptotrader/exchanges/orderbook"
|
|
"github.com/thrasher-corp/gocryptotrader/exchanges/subscription"
|
|
"github.com/thrasher-corp/gocryptotrader/exchanges/ticker"
|
|
"github.com/thrasher-corp/gocryptotrader/exchanges/trade"
|
|
"github.com/thrasher-corp/gocryptotrader/log"
|
|
)
|
|
|
|
const (
|
|
optionsWebsocketURL = "wss://op-ws.gateio.live/v4/ws"
|
|
optionsWebsocketTestnetURL = "wss://op-ws-testnet.gateio.live/v4/ws"
|
|
|
|
// channels
|
|
optionsPingChannel = "options.ping"
|
|
optionsContractTickersChannel = "options.contract_tickers"
|
|
optionsUnderlyingTickersChannel = "options.ul_tickers"
|
|
optionsTradesChannel = "options.trades"
|
|
optionsUnderlyingTradesChannel = "options.ul_trades"
|
|
optionsUnderlyingPriceChannel = "options.ul_price"
|
|
optionsMarkPriceChannel = "options.mark_price"
|
|
optionsSettlementChannel = "options.settlements"
|
|
optionsContractsChannel = "options.contracts"
|
|
optionsContractCandlesticksChannel = "options.contract_candlesticks"
|
|
optionsUnderlyingCandlesticksChannel = "options.ul_candlesticks"
|
|
optionsOrderbookChannel = "options.order_book"
|
|
optionsOrderbookTickerChannel = "options.book_ticker"
|
|
optionsOrderbookUpdateChannel = "options.order_book_update"
|
|
optionsOrdersChannel = "options.orders"
|
|
optionsUserTradesChannel = "options.usertrades"
|
|
optionsLiquidatesChannel = "options.liquidates"
|
|
optionsUserSettlementChannel = "options.user_settlements"
|
|
optionsPositionCloseChannel = "options.position_closes"
|
|
optionsBalancesChannel = "options.balances"
|
|
optionsPositionsChannel = "options.positions"
|
|
)
|
|
|
|
var defaultOptionsSubscriptions = []string{
|
|
optionsContractTickersChannel,
|
|
optionsUnderlyingTickersChannel,
|
|
optionsTradesChannel,
|
|
optionsUnderlyingTradesChannel,
|
|
optionsContractCandlesticksChannel,
|
|
optionsUnderlyingCandlesticksChannel,
|
|
optionsOrderbookChannel,
|
|
optionsOrderbookUpdateChannel,
|
|
}
|
|
|
|
var fetchedOptionsCurrencyPairSnapshotOrderbook = make(map[string]bool)
|
|
|
|
// WsOptionsConnect initiates a websocket connection to options websocket endpoints.
|
|
func (g *Gateio) WsOptionsConnect(ctx context.Context, conn websocket.Connection) error {
|
|
err := g.CurrencyPairs.IsAssetEnabled(asset.Options)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
err = conn.DialContext(ctx, &gws.Dialer{}, http.Header{})
|
|
if err != nil {
|
|
return err
|
|
}
|
|
pingMessage, err := json.Marshal(WsInput{
|
|
ID: conn.GenerateMessageID(false),
|
|
Time: time.Now().Unix(), // TODO: Func for dynamic time as this will be the same time for every ping message.
|
|
Channel: optionsPingChannel,
|
|
})
|
|
if err != nil {
|
|
return err
|
|
}
|
|
conn.SetupPingHandler(websocketRateLimitNotNeededEPL, websocket.PingHandler{
|
|
Websocket: true,
|
|
Delay: time.Second * 5,
|
|
MessageType: gws.PingMessage,
|
|
Message: pingMessage,
|
|
})
|
|
return nil
|
|
}
|
|
|
|
// GenerateOptionsDefaultSubscriptions generates list of channel subscriptions for options asset type.
|
|
func (g *Gateio) GenerateOptionsDefaultSubscriptions() (subscription.List, error) {
|
|
channelsToSubscribe := defaultOptionsSubscriptions
|
|
var userID int64
|
|
if g.Websocket.CanUseAuthenticatedEndpoints() {
|
|
var err error
|
|
_, err = g.GetCredentials(context.TODO())
|
|
if err != nil {
|
|
g.Websocket.SetCanUseAuthenticatedEndpoints(false)
|
|
goto getEnabledPairs
|
|
}
|
|
response, err := g.GetSubAccountBalances(context.Background(), "")
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if len(response) != 0 {
|
|
channelsToSubscribe = append(channelsToSubscribe,
|
|
optionsUserTradesChannel,
|
|
optionsBalancesChannel,
|
|
)
|
|
userID = response[0].UserID
|
|
} else if g.Verbose {
|
|
log.Errorf(log.ExchangeSys, "no subaccount found for authenticated options channel subscriptions")
|
|
}
|
|
}
|
|
|
|
getEnabledPairs:
|
|
|
|
pairs, err := g.GetEnabledPairs(asset.Options)
|
|
if err != nil {
|
|
if errors.Is(err, asset.ErrNotEnabled) {
|
|
return nil, nil // no enabled pairs, subscriptions require an associated pair.
|
|
}
|
|
return nil, err
|
|
}
|
|
|
|
var subscriptions subscription.List
|
|
for i := range channelsToSubscribe {
|
|
for j := range pairs {
|
|
params := make(map[string]any)
|
|
switch channelsToSubscribe[i] {
|
|
case optionsOrderbookChannel:
|
|
params["accuracy"] = "0"
|
|
params["level"] = "20"
|
|
case optionsContractCandlesticksChannel, optionsUnderlyingCandlesticksChannel:
|
|
params["interval"] = kline.FiveMin
|
|
case optionsOrderbookUpdateChannel:
|
|
params["interval"] = kline.ThousandMilliseconds
|
|
params["level"] = "20"
|
|
case optionsOrdersChannel,
|
|
optionsUserTradesChannel,
|
|
optionsLiquidatesChannel,
|
|
optionsUserSettlementChannel,
|
|
optionsPositionCloseChannel,
|
|
optionsBalancesChannel,
|
|
optionsPositionsChannel:
|
|
if userID == 0 {
|
|
continue
|
|
}
|
|
params["user_id"] = userID
|
|
}
|
|
fPair, err := g.FormatExchangeCurrency(pairs[j], asset.Options)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
subscriptions = append(subscriptions, &subscription.Subscription{
|
|
Channel: channelsToSubscribe[i],
|
|
Pairs: currency.Pairs{fPair.Upper()},
|
|
Params: params,
|
|
Asset: asset.Options,
|
|
})
|
|
}
|
|
}
|
|
return subscriptions, nil
|
|
}
|
|
|
|
func (g *Gateio) generateOptionsPayload(ctx context.Context, conn websocket.Connection, event string, channelsToSubscribe subscription.List) ([]WsInput, error) {
|
|
if len(channelsToSubscribe) == 0 {
|
|
return nil, errors.New("cannot generate payload, no channels supplied")
|
|
}
|
|
var err error
|
|
var intervalString string
|
|
payloads := make([]WsInput, len(channelsToSubscribe))
|
|
for i := range channelsToSubscribe {
|
|
if len(channelsToSubscribe[i].Pairs) != 1 {
|
|
return nil, subscription.ErrNotSinglePair
|
|
}
|
|
var auth *WsAuthInput
|
|
timestamp := time.Now()
|
|
var params []string
|
|
switch channelsToSubscribe[i].Channel {
|
|
case optionsUnderlyingTickersChannel,
|
|
optionsUnderlyingTradesChannel,
|
|
optionsUnderlyingPriceChannel,
|
|
optionsUnderlyingCandlesticksChannel:
|
|
var uly currency.Pair
|
|
uly, err = g.GetUnderlyingFromCurrencyPair(channelsToSubscribe[i].Pairs[0])
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
params = append(params, uly.String())
|
|
case optionsBalancesChannel:
|
|
// options.balance channel does not require underlying or contract
|
|
default:
|
|
channelsToSubscribe[i].Pairs[0].Delimiter = currency.UnderscoreDelimiter
|
|
params = append(params, channelsToSubscribe[i].Pairs[0].String())
|
|
}
|
|
switch channelsToSubscribe[i].Channel {
|
|
case optionsOrderbookChannel:
|
|
accuracy, ok := channelsToSubscribe[i].Params["accuracy"].(string)
|
|
if !ok {
|
|
return nil, fmt.Errorf("%w, invalid options orderbook accuracy", orderbook.ErrOrderbookInvalid)
|
|
}
|
|
level, ok := channelsToSubscribe[i].Params["level"].(string)
|
|
if !ok {
|
|
return nil, fmt.Errorf("%w, invalid options orderbook level", orderbook.ErrOrderbookInvalid)
|
|
}
|
|
params = append(
|
|
params,
|
|
level,
|
|
accuracy,
|
|
)
|
|
case optionsUserTradesChannel,
|
|
optionsBalancesChannel,
|
|
optionsOrdersChannel,
|
|
optionsLiquidatesChannel,
|
|
optionsUserSettlementChannel,
|
|
optionsPositionCloseChannel,
|
|
optionsPositionsChannel:
|
|
userID, ok := channelsToSubscribe[i].Params["user_id"].(int64)
|
|
if !ok {
|
|
continue
|
|
}
|
|
params = append([]string{strconv.FormatInt(userID, 10)}, params...)
|
|
var creds *account.Credentials
|
|
creds, err = g.GetCredentials(ctx)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
var sigTemp string
|
|
sigTemp, err = g.generateWsSignature(creds.Secret, event, channelsToSubscribe[i].Channel, timestamp.Unix())
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
auth = &WsAuthInput{
|
|
Method: "api_key",
|
|
Key: creds.Key,
|
|
Sign: sigTemp,
|
|
}
|
|
case optionsOrderbookUpdateChannel:
|
|
interval, ok := channelsToSubscribe[i].Params["interval"].(kline.Interval)
|
|
if !ok {
|
|
return nil, fmt.Errorf("%w, missing options orderbook interval", orderbook.ErrOrderbookInvalid)
|
|
}
|
|
intervalString, err = g.GetIntervalString(interval)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
params = append(params,
|
|
intervalString)
|
|
if value, ok := channelsToSubscribe[i].Params["level"].(int); ok {
|
|
params = append(params, strconv.Itoa(value))
|
|
}
|
|
case optionsContractCandlesticksChannel,
|
|
optionsUnderlyingCandlesticksChannel:
|
|
interval, ok := channelsToSubscribe[i].Params["interval"].(kline.Interval)
|
|
if !ok {
|
|
return nil, errors.New("missing options underlying candlesticks interval")
|
|
}
|
|
intervalString, err = g.GetIntervalString(interval)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
params = append(
|
|
[]string{intervalString},
|
|
params...)
|
|
}
|
|
payloads[i] = WsInput{
|
|
ID: conn.GenerateMessageID(false),
|
|
Event: event,
|
|
Channel: channelsToSubscribe[i].Channel,
|
|
Payload: params,
|
|
Auth: auth,
|
|
Time: timestamp.Unix(),
|
|
}
|
|
}
|
|
return payloads, nil
|
|
}
|
|
|
|
// OptionsSubscribe sends a websocket message to stop receiving data for asset type options
|
|
func (g *Gateio) OptionsSubscribe(ctx context.Context, conn websocket.Connection, channelsToUnsubscribe subscription.List) error {
|
|
return g.handleSubscription(ctx, conn, subscribeEvent, channelsToUnsubscribe, g.generateOptionsPayload)
|
|
}
|
|
|
|
// OptionsUnsubscribe sends a websocket message to stop receiving data for asset type options
|
|
func (g *Gateio) OptionsUnsubscribe(ctx context.Context, conn websocket.Connection, channelsToUnsubscribe subscription.List) error {
|
|
return g.handleSubscription(ctx, conn, unsubscribeEvent, channelsToUnsubscribe, g.generateOptionsPayload)
|
|
}
|
|
|
|
// WsHandleOptionsData handles options websocket data
|
|
func (g *Gateio) WsHandleOptionsData(_ context.Context, respRaw []byte) error {
|
|
push, err := parseWSHeader(respRaw)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
if push.Event == subscribeEvent || push.Event == unsubscribeEvent {
|
|
return g.Websocket.Match.RequireMatchWithData(push.ID, respRaw)
|
|
}
|
|
|
|
switch push.Channel {
|
|
case optionsContractTickersChannel:
|
|
return g.processOptionsContractTickers(push.Result)
|
|
case optionsUnderlyingTickersChannel:
|
|
return g.processOptionsUnderlyingTicker(push.Result)
|
|
case optionsTradesChannel,
|
|
optionsUnderlyingTradesChannel:
|
|
return g.processOptionsTradesPushData(respRaw)
|
|
case optionsUnderlyingPriceChannel:
|
|
return g.processOptionsUnderlyingPricePushData(push.Result)
|
|
case optionsMarkPriceChannel:
|
|
return g.processOptionsMarkPrice(push.Result)
|
|
case optionsSettlementChannel:
|
|
return g.processOptionsSettlementPushData(push.Result)
|
|
case optionsContractsChannel:
|
|
return g.processOptionsContractPushData(push.Result)
|
|
case optionsContractCandlesticksChannel,
|
|
optionsUnderlyingCandlesticksChannel:
|
|
return g.processOptionsCandlestickPushData(respRaw)
|
|
case optionsOrderbookChannel:
|
|
return g.processOptionsOrderbookSnapshotPushData(push.Event, push.Result, push.Time)
|
|
case optionsOrderbookTickerChannel:
|
|
return g.processOrderbookTickerPushData(respRaw)
|
|
case optionsOrderbookUpdateChannel:
|
|
return g.processFuturesAndOptionsOrderbookUpdate(push.Result, asset.Options)
|
|
case optionsOrdersChannel:
|
|
return g.processOptionsOrderPushData(respRaw)
|
|
case optionsUserTradesChannel:
|
|
return g.processOptionsUserTradesPushData(respRaw)
|
|
case optionsLiquidatesChannel:
|
|
return g.processOptionsLiquidatesPushData(respRaw)
|
|
case optionsUserSettlementChannel:
|
|
return g.processOptionsUsersPersonalSettlementsPushData(respRaw)
|
|
case optionsPositionCloseChannel:
|
|
return g.processPositionCloseData(respRaw)
|
|
case optionsBalancesChannel:
|
|
return g.processBalancePushData(respRaw, asset.Options)
|
|
case optionsPositionsChannel:
|
|
return g.processOptionsPositionPushData(respRaw)
|
|
default:
|
|
g.Websocket.DataHandler <- websocket.UnhandledMessageWarning{
|
|
Message: g.Name + websocket.UnhandledMessage + string(respRaw),
|
|
}
|
|
return errors.New(websocket.UnhandledMessage)
|
|
}
|
|
}
|
|
|
|
func (g *Gateio) processOptionsContractTickers(incoming []byte) error {
|
|
var data OptionsTicker
|
|
err := json.Unmarshal(incoming, &data)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
g.Websocket.DataHandler <- &ticker.Price{
|
|
Pair: data.Name,
|
|
Last: data.LastPrice.Float64(),
|
|
Bid: data.Bid1Price.Float64(),
|
|
Ask: data.Ask1Price.Float64(),
|
|
AskSize: data.Ask1Size,
|
|
BidSize: data.Bid1Size,
|
|
ExchangeName: g.Name,
|
|
AssetType: asset.Options,
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (g *Gateio) processOptionsUnderlyingTicker(incoming []byte) error {
|
|
var data WsOptionUnderlyingTicker
|
|
err := json.Unmarshal(incoming, &data)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
g.Websocket.DataHandler <- &data
|
|
return nil
|
|
}
|
|
|
|
func (g *Gateio) processOptionsTradesPushData(data []byte) error {
|
|
saveTradeData := g.IsSaveTradeDataEnabled()
|
|
if !saveTradeData &&
|
|
!g.IsTradeFeedEnabled() {
|
|
return nil
|
|
}
|
|
resp := struct {
|
|
Time int64 `json:"time"`
|
|
Channel string `json:"channel"`
|
|
Event string `json:"event"`
|
|
Result []WsOptionsTrades `json:"result"`
|
|
}{}
|
|
err := json.Unmarshal(data, &resp)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
trades := make([]trade.Data, len(resp.Result))
|
|
for x := range resp.Result {
|
|
trades[x] = trade.Data{
|
|
Timestamp: resp.Result[x].CreateTime.Time(),
|
|
CurrencyPair: resp.Result[x].Contract,
|
|
AssetType: asset.Options,
|
|
Exchange: g.Name,
|
|
Price: resp.Result[x].Price,
|
|
Amount: resp.Result[x].Size,
|
|
TID: strconv.FormatInt(resp.Result[x].ID, 10),
|
|
}
|
|
}
|
|
return g.Websocket.Trade.Update(saveTradeData, trades...)
|
|
}
|
|
|
|
func (g *Gateio) processOptionsUnderlyingPricePushData(incoming []byte) error {
|
|
var data WsOptionsUnderlyingPrice
|
|
err := json.Unmarshal(incoming, &data)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
g.Websocket.DataHandler <- &data
|
|
return nil
|
|
}
|
|
|
|
func (g *Gateio) processOptionsMarkPrice(incoming []byte) error {
|
|
var data WsOptionsMarkPrice
|
|
err := json.Unmarshal(incoming, &data)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
g.Websocket.DataHandler <- &data
|
|
return nil
|
|
}
|
|
|
|
func (g *Gateio) processOptionsSettlementPushData(incoming []byte) error {
|
|
var data WsOptionsSettlement
|
|
err := json.Unmarshal(incoming, &data)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
g.Websocket.DataHandler <- &data
|
|
return nil
|
|
}
|
|
|
|
func (g *Gateio) processOptionsContractPushData(incoming []byte) error {
|
|
var data WsOptionsContract
|
|
err := json.Unmarshal(incoming, &data)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
g.Websocket.DataHandler <- &data
|
|
return nil
|
|
}
|
|
|
|
func (g *Gateio) processOptionsCandlestickPushData(data []byte) error {
|
|
resp := struct {
|
|
Time int64 `json:"time"`
|
|
Channel string `json:"channel"`
|
|
Event string `json:"event"`
|
|
Result []WsOptionsContractCandlestick `json:"result"`
|
|
}{}
|
|
err := json.Unmarshal(data, &resp)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
klineDatas := make([]websocket.KlineData, len(resp.Result))
|
|
for x := range resp.Result {
|
|
icp := strings.Split(resp.Result[x].NameOfSubscription, currency.UnderscoreDelimiter)
|
|
if len(icp) < 3 {
|
|
return errors.New("malformed options candlestick websocket push data")
|
|
}
|
|
currencyPair, err := currency.NewPairFromString(strings.Join(icp[1:], currency.UnderscoreDelimiter))
|
|
if err != nil {
|
|
return err
|
|
}
|
|
klineDatas[x] = websocket.KlineData{
|
|
Pair: currencyPair,
|
|
AssetType: asset.Options,
|
|
Exchange: g.Name,
|
|
StartTime: resp.Result[x].Timestamp.Time(),
|
|
Interval: icp[0],
|
|
OpenPrice: resp.Result[x].OpenPrice.Float64(),
|
|
ClosePrice: resp.Result[x].ClosePrice.Float64(),
|
|
HighPrice: resp.Result[x].HighestPrice.Float64(),
|
|
LowPrice: resp.Result[x].LowestPrice.Float64(),
|
|
Volume: resp.Result[x].Amount.Float64(),
|
|
}
|
|
}
|
|
g.Websocket.DataHandler <- klineDatas
|
|
return nil
|
|
}
|
|
|
|
func (g *Gateio) processOrderbookTickerPushData(incoming []byte) error {
|
|
var data WsOptionsOrderbookTicker
|
|
err := json.Unmarshal(incoming, &data)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
g.Websocket.DataHandler <- &data
|
|
return nil
|
|
}
|
|
|
|
func (g *Gateio) processOptionsOrderbookSnapshotPushData(event string, incoming []byte, updatePushedAt time.Time) error {
|
|
if event == "all" {
|
|
var data WsOptionsOrderbookSnapshot
|
|
err := json.Unmarshal(incoming, &data)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
base := orderbook.Base{
|
|
Asset: asset.Options,
|
|
Exchange: g.Name,
|
|
Pair: data.Contract,
|
|
LastUpdated: data.Timestamp.Time(),
|
|
UpdatePushedAt: updatePushedAt,
|
|
VerifyOrderbook: g.CanVerifyOrderbook,
|
|
}
|
|
base.Asks = make([]orderbook.Tranche, len(data.Asks))
|
|
for x := range data.Asks {
|
|
base.Asks[x].Amount = data.Asks[x].Size
|
|
base.Asks[x].Price = data.Asks[x].Price.Float64()
|
|
}
|
|
base.Bids = make([]orderbook.Tranche, len(data.Bids))
|
|
for x := range data.Bids {
|
|
base.Bids[x].Amount = data.Bids[x].Size
|
|
base.Bids[x].Price = data.Bids[x].Price.Float64()
|
|
}
|
|
return g.Websocket.Orderbook.LoadSnapshot(&base)
|
|
}
|
|
var data []WsFuturesOrderbookUpdateEvent
|
|
err := json.Unmarshal(incoming, &data)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
dataMap := map[string][2][]orderbook.Tranche{}
|
|
for x := range data {
|
|
ab, ok := dataMap[data[x].CurrencyPair]
|
|
if !ok {
|
|
ab = [2][]orderbook.Tranche{}
|
|
}
|
|
if data[x].Amount > 0 {
|
|
ab[1] = append(ab[1], orderbook.Tranche{
|
|
Price: data[x].Price.Float64(), Amount: data[x].Amount,
|
|
})
|
|
} else {
|
|
ab[0] = append(ab[0], orderbook.Tranche{
|
|
Price: data[x].Price.Float64(), Amount: -data[x].Amount,
|
|
})
|
|
}
|
|
if !ok {
|
|
dataMap[data[x].CurrencyPair] = ab
|
|
}
|
|
}
|
|
if len(dataMap) == 0 {
|
|
return errors.New("missing orderbook ask and bid data")
|
|
}
|
|
for key, ab := range dataMap {
|
|
currencyPair, err := currency.NewPairFromString(key)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
err = g.Websocket.Orderbook.LoadSnapshot(&orderbook.Base{
|
|
Asks: ab[0],
|
|
Bids: ab[1],
|
|
Asset: asset.Options,
|
|
Exchange: g.Name,
|
|
Pair: currencyPair,
|
|
LastUpdated: updatePushedAt,
|
|
UpdatePushedAt: updatePushedAt,
|
|
VerifyOrderbook: g.CanVerifyOrderbook,
|
|
})
|
|
if err != nil {
|
|
return err
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (g *Gateio) processOptionsOrderPushData(data []byte) error {
|
|
resp := struct {
|
|
Time int64 `json:"time"`
|
|
Channel string `json:"channel"`
|
|
Event string `json:"event"`
|
|
Result []WsOptionsOrder `json:"result"`
|
|
}{}
|
|
err := json.Unmarshal(data, &resp)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
orderDetails := make([]order.Detail, len(resp.Result))
|
|
for x := range resp.Result {
|
|
status, err := order.StringToOrderStatus(func() string {
|
|
if resp.Result[x].Status == "finished" {
|
|
return "cancelled"
|
|
}
|
|
return resp.Result[x].Status
|
|
}())
|
|
if err != nil {
|
|
return err
|
|
}
|
|
orderDetails[x] = order.Detail{
|
|
Amount: resp.Result[x].Size,
|
|
Exchange: g.Name,
|
|
OrderID: strconv.FormatInt(resp.Result[x].ID, 10),
|
|
Status: status,
|
|
Pair: resp.Result[x].Contract,
|
|
Date: resp.Result[x].CreationTime.Time(),
|
|
ExecutedAmount: resp.Result[x].Size - resp.Result[x].Left,
|
|
Price: resp.Result[x].Price,
|
|
AssetType: asset.Options,
|
|
AccountID: resp.Result[x].User,
|
|
}
|
|
}
|
|
g.Websocket.DataHandler <- orderDetails
|
|
return nil
|
|
}
|
|
|
|
func (g *Gateio) processOptionsUserTradesPushData(data []byte) error {
|
|
if !g.IsFillsFeedEnabled() {
|
|
return nil
|
|
}
|
|
resp := struct {
|
|
Time int64 `json:"time"`
|
|
Channel string `json:"channel"`
|
|
Event string `json:"event"`
|
|
Result []WsOptionsUserTrade `json:"result"`
|
|
}{}
|
|
err := json.Unmarshal(data, &resp)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
fills := make([]fill.Data, len(resp.Result))
|
|
for x := range resp.Result {
|
|
fills[x] = fill.Data{
|
|
Timestamp: resp.Result[x].CreateTime.Time(),
|
|
Exchange: g.Name,
|
|
CurrencyPair: resp.Result[x].Contract,
|
|
OrderID: resp.Result[x].OrderID,
|
|
TradeID: resp.Result[x].ID,
|
|
Price: resp.Result[x].Price.Float64(),
|
|
Amount: resp.Result[x].Size,
|
|
}
|
|
}
|
|
return g.Websocket.Fills.Update(fills...)
|
|
}
|
|
|
|
func (g *Gateio) processOptionsLiquidatesPushData(data []byte) error {
|
|
resp := struct {
|
|
Time int64 `json:"time"`
|
|
Channel string `json:"channel"`
|
|
Event string `json:"event"`
|
|
Result []WsOptionsLiquidates `json:"result"`
|
|
}{}
|
|
err := json.Unmarshal(data, &resp)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
g.Websocket.DataHandler <- &resp
|
|
return nil
|
|
}
|
|
|
|
func (g *Gateio) processOptionsUsersPersonalSettlementsPushData(data []byte) error {
|
|
resp := struct {
|
|
Time int64 `json:"time"`
|
|
Channel string `json:"channel"`
|
|
Event string `json:"event"`
|
|
Result []WsOptionsUserSettlement `json:"result"`
|
|
}{}
|
|
err := json.Unmarshal(data, &resp)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
g.Websocket.DataHandler <- &resp
|
|
return nil
|
|
}
|
|
|
|
func (g *Gateio) processOptionsPositionPushData(data []byte) error {
|
|
resp := struct {
|
|
Time int64 `json:"time"`
|
|
Channel string `json:"channel"`
|
|
Event string `json:"event"`
|
|
Result []WsOptionsPosition `json:"result"`
|
|
}{}
|
|
err := json.Unmarshal(data, &resp)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
g.Websocket.DataHandler <- &resp
|
|
return nil
|
|
}
|