Files
gocryptotrader/exchanges/okcoin/okcoin_ws_trade.go
Gareth Kirwan 52c6b3bf0b Websocket: Various refactors and test improvements (#1466)
* Websocket: Remove IsInit and simplify SetProxyAddress

IsInit was basically the same as IsConnected.
Any time Connect was called both would be set to true.
Any time we had a disconnect they'd both be set to false
Shutdown() incorrectly didn't setInit(false)

SetProxyAddress simplified to only reconnect a connected Websocket.
Any other state means it hasn't been Connected, or it's about to
reconnect anyway.
There's no handling for IsConnecting previously, either, so I've wrapped
that behind the main mutex.

* Websocket: Expand and Assertify tests

* Websocket: Simplify state transistions

* Websocket: Simplify Connecting/Connected state

* Websocket: Tests and errors for websocket

* Websocket: Make WebsocketNotEnabled a real error

This allows for testing and avoids the repetition.
If each returned error is a error.New() you can never use errors.Is()

* Websocket: Add more testable errors

* Websocket: Improve GenerateMessageID test

Testing just the last id doesn't feel very robust

* Websocket: Protect Setup() from races

* Websocket: Use atomics instead of mutex

This was spurred by looking at the setState call in trafficMonitor and
the effect on blocking and efficiency.
With the new atomic types in Go 1.19, and the small types in use here,
atomics should be safe for our usage. bools should be truly atomic,
and uint32 is atomic when the accepted value range is less than one byte/uint8 since
that can be written atomicly by concurrent processors.
Maybe that's not even a factor any more, however we don't even have to worry enough to check.

* Websocket: Fix and simplify traffic monitor

trafficMonitor had a check throttle at the end of the for loop to stop it just gobbling the (blocking) trafficAlert channel non-stop.
That makes sense, except that nothing is sent to the trafficAlert channel if there's no listener.
So that means that it's out by one second on the trafficAlert, because any traffic received during the pause is doesn't try to send a traffic alert.

The unstopped timer is deliberately leaked for later GC when shutdown.
It won't delay/block anything, and it's a trivial memory leak during an infrequent event.

Deliberately Choosing to recreate the timer each time instead of using Stop, drain and reset

* Websocket: Split traficMonitor test on behaviours

* Websocket: Remove trafficMonitor connected status

trafficMonitor does not need to set the connection to be connected.
Connect() does that. Anything after that should result in a full
shutdown and restart. It can't and shouldn't become connected
unexpectedly, and this is most likely a race anyway.

Also dropped trafficCheckInterval to 100ms to mitigate races of traffic
alerts being buffered for too long.

* Websocket: Set disconnected earlier in Shutdown

This caused a possible race where state is still connected, but we start
to trigger interested actors via ShutdownC and Wait.
They may check state and then call Shutdown again, such as
trafficMonitor

* Websocket: Wait 5s for slow tests to pass traffic draining

Keep getting failures upstream on test rigs.
Think they can be very contended, so this pushes the boundary right out
to 5s
2024-02-23 18:39:25 +11:00

184 lines
5.6 KiB
Go

package okcoin
import (
"encoding/json"
"errors"
"fmt"
"reflect"
"strconv"
"github.com/thrasher-corp/gocryptotrader/exchanges/stream"
)
// WsPlaceOrder place trade order through the websocket channel.
func (o *Okcoin) WsPlaceOrder(arg *PlaceTradeOrderParam) (*TradeOrderResponse, error) {
err := arg.validateTradeOrderParameter()
if err != nil {
return nil, err
}
var resp []TradeOrderResponse
err = o.SendWebsocketRequest("order", arg, &resp, true)
if err != nil {
return nil, err
}
if len(resp) == 0 {
return nil, errNoValidResponseFromServer
}
if resp[0].SCode != "0" {
return nil, fmt.Errorf("code: %s msg: %s", resp[0].SCode, resp[0].SMsg)
}
return &resp[0], nil
}
// WsPlaceMultipleOrder place orders in batches through the websocket stream. Maximum 20 orders can be placed per request. Request parameters should be passed in the form of an array.
func (o *Okcoin) WsPlaceMultipleOrder(args []PlaceTradeOrderParam) ([]TradeOrderResponse, error) {
var err error
if len(args) == 0 {
return nil, fmt.Errorf("%w, 0 length place order requests", errNilArgument)
}
for x := range args {
err = args[x].validateTradeOrderParameter()
if err != nil {
return nil, err
}
}
var resp []TradeOrderResponse
return resp, o.SendWebsocketRequest("batch-orders", args, &resp, true)
}
// WsCancelTradeOrder cancels a single trade order through the websocket stream.
func (o *Okcoin) WsCancelTradeOrder(arg *CancelTradeOrderRequest) (*TradeOrderResponse, error) {
if arg == nil {
return nil, errNilArgument
}
if arg.InstrumentID == "" {
return nil, errMissingInstrumentID
}
if arg.OrderID == "" && arg.ClientOrderID == "" {
return nil, errOrderIDOrClientOrderIDRequired
}
var resp []TradeOrderResponse
err := o.SendWebsocketRequest("cancel-order", &arg, &resp, true)
if err != nil {
return nil, err
}
if len(resp) == 0 {
return nil, errNoValidResponseFromServer
}
if resp[0].SCode != "0" {
return nil, fmt.Errorf("code: %s msg: %s", resp[0].SCode, resp[0].SMsg)
}
return &resp[0], nil
}
// WsCancelMultipleOrders cancel incomplete orders in batches through the websocket stream. Maximum 20 orders can be canceled per request.
// Request parameters should be passed in the form of an array.
func (o *Okcoin) WsCancelMultipleOrders(args []CancelTradeOrderRequest) ([]TradeOrderResponse, error) {
var err error
if len(args) == 0 {
return nil, fmt.Errorf("%w, 0 length place order requests", errNilArgument)
}
for x := range args {
err = args[x].validate()
if err != nil {
return nil, err
}
}
var resp []TradeOrderResponse
return resp, o.SendWebsocketRequest("batch-cancel-orders", args, &resp, true)
}
// WsAmendOrder amends an incomplete order through the websocket connection
func (o *Okcoin) WsAmendOrder(arg *AmendTradeOrderRequestParam) (*AmendTradeOrderResponse, error) {
err := arg.validate()
if err != nil {
return nil, err
}
var resp []AmendTradeOrderResponse
err = o.SendWebsocketRequest("amend-order", &arg, &resp, true)
if err != nil {
if len(resp) > 0 && resp[0].StatusCode != "0" && resp[0].StatusCode != "" {
return nil, fmt.Errorf("%w, code: %s msg: %s", err, resp[0].StatusCode, resp[0].StatusMessage)
}
return nil, err
}
if len(resp) == 0 {
return nil, errNoValidResponseFromServer
}
if resp[0].StatusCode != "0" {
return nil, fmt.Errorf("code: %s msg: %s", resp[0].StatusCode, resp[0].StatusMessage)
}
return &resp[0], nil
}
// WsAmendMultipleOrder amends multiple trade orders.
func (o *Okcoin) WsAmendMultipleOrder(args []AmendTradeOrderRequestParam) ([]AmendTradeOrderResponse, error) {
if len(args) == 0 {
return nil, fmt.Errorf("%w, please provide at least one trade order amendment request", errNilArgument)
}
for x := range args {
err := args[x].validate()
if err != nil {
return nil, err
}
}
var resp []AmendTradeOrderResponse
return resp, o.SendWebsocketRequest("batch-amend-orders", args, &resp, true)
}
// SendWebsocketRequest send a request through the websocket connection.
func (o *Okcoin) SendWebsocketRequest(operation string, data, result interface{}, authenticated bool) error {
switch {
case !o.Websocket.IsEnabled():
return stream.ErrWebsocketNotEnabled
case !o.Websocket.IsConnected():
return stream.ErrNotConnected
case !o.Websocket.CanUseAuthenticatedEndpoints() && authenticated:
return errors.New("websocket connection not authenticated")
}
req := &struct {
ID string `json:"id"`
Operation string `json:"op"`
Arguments interface{} `json:"args"`
}{
ID: strconv.FormatInt(o.Websocket.Conn.GenerateMessageID(false), 10),
Operation: operation,
}
if reflect.TypeOf(data).Kind() == reflect.Slice {
req.Arguments = data
} else {
req.Arguments = []interface{}{data}
}
var byteData []byte
var err error
// TODO: ratelimits for websocket
if authenticated {
byteData, err = o.Websocket.AuthConn.SendMessageReturnResponse(req.ID, req)
} else {
byteData, err = o.Websocket.Conn.SendMessageReturnResponse(req.ID, req)
}
if err != nil {
return err
}
response := struct {
ID string `json:"id"`
Operation string `json:"op"`
Data interface{} `json:"data"`
Code string `json:"code"`
Message string `json:"msg"`
}{
Data: &result,
}
err = json.Unmarshal(byteData, &response)
if err != nil {
return err
}
if response.Code != "" && response.Code != "0" && response.Code != "1" && response.Code != "2" {
if response.Message == "" {
response.Message = websocketErrorCodes[response.Code]
}
return fmt.Errorf("%s websocket error code: %s message: %s", o.Name, response.Code, response.Message)
}
return nil
}