Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Okx: Fix sending trades to the websocket DataHandler #1833

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
73 changes: 73 additions & 0 deletions exchanges/okx/okx_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"fmt"
"log"
"os"
"sort"
"sync"
"testing"
"time"
Expand All @@ -30,6 +31,7 @@ import (
"github.com/thrasher-corp/gocryptotrader/exchanges/request"
"github.com/thrasher-corp/gocryptotrader/exchanges/sharedtestvalues"
"github.com/thrasher-corp/gocryptotrader/exchanges/subscription"
"github.com/thrasher-corp/gocryptotrader/exchanges/trade"
testexch "github.com/thrasher-corp/gocryptotrader/internal/testing/exchange"
testsubs "github.com/thrasher-corp/gocryptotrader/internal/testing/subscriptions"
"github.com/thrasher-corp/gocryptotrader/portfolio/withdraw"
Expand Down Expand Up @@ -4045,6 +4047,77 @@ func setupWS() {
}
}

func TestWSProcessTrades(t *testing.T) {
t.Parallel()

ok := new(Okx) //nolint:govet // Intentional shadow to avoid future copy/paste mistakes
require.NoError(t, testexch.Setup(ok), "Test instance Setup must not error")
assets, err := ok.getAssetsFromInstrumentID("BTC-USDT")
require.NoError(t, err, "getAssetsFromInstrumentID must not error")

p := currency.NewPairWithDelimiter("BTC", "USDT", currency.DashDelimiter)

for _, a := range assets {
err := ok.Websocket.AddSubscriptions(ok.Websocket.Conn, &subscription.Subscription{
Asset: a,
Pairs: currency.Pairs{p},
Channel: subscription.AllTradesChannel,
Key: fmt.Sprintf("%s-%s", p, a)})
require.NoError(t, err, "AddSubscriptions must not error")
}
testexch.FixtureToDataHandler(t, "testdata/wsAllTrades.json", ok.WsHandleData)

exp := []trade.Data{
{
Exchange: ok.Name,
CurrencyPair: p,
Timestamp: time.UnixMilli(1740394561685).UTC(),
Price: 95634.9,
Amount: 0.00011186,
Side: order.Buy,
TID: "674510826",
},
{
Exchange: ok.Name,
CurrencyPair: p,
Timestamp: time.UnixMilli(1740394561686).UTC(),
Price: 95635.3,
Amount: 0.00011194,
Side: order.Sell,
TID: "674510827",
},
}

total := len(assets) * len(exp)
require.Len(t, ok.Websocket.DataHandler, total, "Must see correct number of trades")

trades := make(map[asset.Item][]trade.Data)

for len(ok.Websocket.DataHandler) > 0 {
resp := <-ok.Websocket.DataHandler
switch v := resp.(type) {
case trade.Data:
trades[v.AssetType] = append(trades[v.AssetType], v)
case error:
t.Error(v)
default:
t.Errorf("Unexpected type in DataHandler: %T (%s)", v, v)
}
}

for _, assetType := range assets {
require.Len(t, trades[assetType], len(exp), "Should have received %d trades for asset %v", len(exp), assetType)
sort.Slice(trades[assetType], func(i, j int) bool {
return trades[assetType][i].TID < trades[assetType][j].TID
})
for i, trade := range trades[assetType] {
expected := exp[i]
expected.AssetType = assetType
require.Equal(t, expected, trade, "Trade %d (TID: %s) for asset %v should match expected data", i, trade.TID, assetType)
}
}
}

// ************************** Public Channel Subscriptions *****************************

func TestInstrumentsSubscription(t *testing.T) {
Expand Down
19 changes: 17 additions & 2 deletions exchanges/okx/okx_websocket.go
Original file line number Diff line number Diff line change
Expand Up @@ -1219,6 +1219,13 @@ func (ok *Okx) wsProcessTrades(data []byte) error {
if err != nil {
return err
}

saveTradeData := ok.IsSaveTradeDataEnabled()
tradeFeed := ok.IsTradeFeedEnabled()
if !saveTradeData && !tradeFeed {
return nil
}

var assets []asset.Item
if response.Argument.InstrumentType != "" {
assetType, err := assetTypeFromInstrumentType(response.Argument.InstrumentType)
Expand All @@ -1245,13 +1252,21 @@ func (ok *Okx) wsProcessTrades(data []byte) error {
CurrencyPair: pair,
Exchange: ok.Name,
Side: response.Data[i].Side,
Timestamp: response.Data[i].Timestamp.Time(),
Timestamp: response.Data[i].Timestamp.Time().UTC(),
TID: response.Data[i].TradeID,
Price: response.Data[i].Price.Float64(),
})
}
}
return trade.AddTradesToBuffer(trades...)
if tradeFeed {
for i := range trades {
ok.Websocket.DataHandler <- trades[i]
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

OOS: In trade.go under method Update we are passing the entire slice which can be updated to only send through individual updates. If you want to use this function to cut down on some code you are more than welcome. ok.Websocket.Trade.Update(...)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Will leave this out of this PR if that's ok

}
}
if saveTradeData {
return trade.AddTradesToBuffer(trades...)
}
return nil
}

// wsProcessOrders handles websocket order push data responses.
Expand Down
2 changes: 2 additions & 0 deletions exchanges/okx/testdata/wsAllTrades.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
{"arg":{"channel":"trades","instId":"BTC-USDT"},"data":[{"instId":"BTC-USDT","tradeId":"674510826","px":"95634.9","sz":"0.00011186","side":"buy","ts":"1740394561685","count":"1"}]}
{"arg":{"channel":"trades","instId":"BTC-USDT"},"data":[{"instId":"BTC-USDT","tradeId":"674510827","px":"95635.3","sz":"0.00011194","side":"sell","ts":"1740394561686","count":"1"}]}
2 changes: 1 addition & 1 deletion testdata/configtest.json
Original file line number Diff line number Diff line change
Expand Up @@ -2271,7 +2271,7 @@
"autoPairUpdates": true,
"websocketAPI": true,
"saveTradeData": false,
"tradeFeed": false,
"tradeFeed": true,
"fillsFeed": false
}
},
Expand Down
Loading