Coinbase: Update exchange implementation (#1480)

* Slight enhance of Coinbase tests

Continual enhance of Coinbase tests

The revamp continues

Oh jeez the Orderbook part's unfinished don't look

Coinbase revamp, Orderbook still unfinished

* Coinbase revamp; CreateReport is still WIP

* More coinbase improvements; onto sandbox testing

* Coinbase revamp continues

* Coinbase revamp continues

* Coinbasepro revamp is ceaseless

* Coinbase revamp, starting on advanced trade API

* Coinbase Advanced Trade Starts in Ernest

V3 done, onto V2

Coinbase revamp nears completion

Coinbase revamp nears completion

Test commit should fail

Coinbase revamp nears completion

* Coinbase revamp stage wrapper

* Coinbase wrapper coherence continues

* Coinbase wrapper continues writhing

* Coinbase wrapper & codebase cleanup

* Coinbase updates & wrap progress

* More Coinbase wrapper progress

* Wrapper is wrapped, kinda

* Test & type checking

* Coinbase REST revamp finished

* Post-merge fix

* WS revamp begins

* WS Main Revamp Done?

* CB websocket tidying up

* Coinbase WS wrapperupperer

* Coinbase revamp done??

* Linter progress

* Continued lint cleanup

* Further lint cleanup

* Increased lint coverage

* Does this fix all sloppy reassigns & shadowing?

* Undoing retry policy change

* Documentation regeneration

* Coinbase code improvements

* Providing warning about known issue

* Updating an error to new format

* Making gocritic happy

* Review adherence

* Endpoints moved to V3 & nil pointer fixes

* Removing seemingly superfluous constant

* Glorious improvements

* Removing unused error

* Partial public endpoint addition

* Slight improvements

* Wrapper improvements; still a few errors left in other packages

* A lil Coinbase progress

* Json cleaning

* Lint appeasement

* Config repair

* Config fix (real)

* Little fix

* New public endpoint incorporation

* Additional fixes

* Improvements & Appeasements

* LineSaver

* Additional fixes

* Another fix

* Fixing picked nits

* Quick fixies

* Lil fixes

* Subscriptions: Add List.Enabled

* CoinbasePro: Add subscription templating

* fixup! CoinbasePro: Add subscription templating

* fixup! CoinbasePro: Add subscription templating

* Comment fix

* Subsequent fixes

* Issues hopefully fixed

* Lint fix

* Glorious fixes

* Json formatting

* ShazNits

* (L/N)i(n/)t

* Adding a test

* Tiny test improvement

* Template patch testing

* Fixes

* Further shaznits

* Lint nit

* JWT move and other fixes

* Small nits

* Shaznit, singular

* Post-merge fix

* Post-merge fixes

* Typo fix

* Some glorious nits

* Required changes

* Stop going

* Alias attempt

* Alias fix & test cleanup

* Test fix

* GetDepositAddress logic improvement

* Status update: Fixed

* Lint fix

* Happy birthday to PR 1480

* Cleanups

* Necessary nit corrections

* Fixing sillybug

* As per request

* Programming progress

* Order fixes

* Further fixies

* Test fix

* Pre-merge fixes

* More shaznits

* Context

* Sonic error handling

* Import fix

* Better Sonic error handling

* Perfect Sonic error handling?

* F purge

* Coinbase improvements

* API Update Conformity

* Coinbase continuation

* Coinbase order improvements

* Coinbase order improvements

* CreateOrderConfig improvements

* Managing API updates

* Coinbase API update progression

* jwt rename

* Comment link fix

* Coinbase v2 cleanup

* Post-merge fixes

* Review fixes

* GK's suggestions

* Linter fix

* Minor gbjk fixes

* Nit fixes

* Merge fix

* Lint fixes

* Coinbase rename stage 1

* Coinbase rename stage 2

* Coinbase rename stage 3

* Coinbase rename stage 4

* Coinbase rename final fix

* Coinbase: PoC on converting to request structs

* Applying requested changes

* Many review fixes, handled

* Thrashed by nits

* More minor modifications

* The last nit!?

---------

Co-authored-by: Gareth Kirwan <gbjkirwan@gmail.com>
This commit is contained in:
cranktakular
2025-09-16 13:37:00 +10:00
committed by GitHub
parent d957ddae62
commit fd9aaf00a2
78 changed files with 8850 additions and 3937 deletions

View File

@@ -38,7 +38,7 @@ func TestSubmitValidate(t *testing.T) {
Submit: nil,
}, // nil struct
{
ExpectedErr: errExchangeNameUnset,
ExpectedErr: common.ErrExchangeNameNotSet,
Submit: &Submit{},
}, // empty exchange
{
@@ -831,7 +831,7 @@ func TestStringToOrderType(t *testing.T) {
{"mMp", MarketMakerProtection, nil},
{"tWaP", TWAP, nil},
{"TWAP", TWAP, nil},
{"woahMan", UnknownType, errUnrecognisedOrderType},
{"woahMan", UnknownType, ErrUnrecognisedOrderType},
{"chase", Chase, nil},
{"MOVE_ORDER_STOP", TrailingStop, nil},
{"mOVe_OrdeR_StoP", TrailingStop, nil},
@@ -842,6 +842,8 @@ func TestStringToOrderType(t *testing.T) {
{"Take ProfIt", TakeProfit, nil},
{"TAKE PROFIT MARkEt", TakeProfitMarket, nil},
{"TAKE_PROFIT_MARkEt", TakeProfitMarket, nil},
{"brAcket", Bracket, nil},
{"TRIGGER_bracket", Bracket, nil},
{"optimal_limit", OptimalLimit, nil},
{"OPTIMAL_LIMIT", OptimalLimit, nil},
}
@@ -1135,7 +1137,7 @@ func TestValidationOnOrderTypes(t *testing.T) {
getOrders.Side = AnySide
err = getOrders.Validate()
require.ErrorIs(t, err, errUnrecognisedOrderType)
require.ErrorIs(t, err, ErrUnrecognisedOrderType)
errTestError := errors.New("test error")
getOrders.Type = AnyType
@@ -1743,6 +1745,6 @@ func TestMarshalOrder(t *testing.T) {
}
j, err := json.Marshal(orderSubmit)
require.NoError(t, err, "Marshal must not error")
exp := []byte(`{"Exchange":"test","Type":4,"Side":"BUY","Pair":"BTC-USDT","AssetType":"spot","TimeInForce":"","ReduceOnly":false,"Leverage":0,"Price":1000,"Amount":1,"QuoteAmount":0,"TriggerPrice":0,"TriggerPriceType":0,"ClientID":"","ClientOrderID":"","AutoBorrow":false,"MarginType":"multi","RetrieveFees":false,"RetrieveFeeDelay":0,"RiskManagementModes":{"Mode":"","TakeProfit":{"Enabled":false,"TriggerPriceType":0,"Price":0,"LimitPrice":0,"OrderType":0},"StopLoss":{"Enabled":false,"TriggerPriceType":0,"Price":0,"LimitPrice":0,"OrderType":0},"StopEntry":{"Enabled":false,"TriggerPriceType":0,"Price":0,"LimitPrice":0,"OrderType":0}},"Hidden":false,"Iceberg":false,"TrackingMode":0,"TrackingValue":0}`)
exp := []byte(`{"Exchange":"test","Type":4,"Side":"BUY","Pair":"BTC-USDT","AssetType":"spot","TimeInForce":"","ReduceOnly":false,"Leverage":0,"Price":1000,"Amount":1,"QuoteAmount":0,"TriggerPrice":0,"TriggerPriceType":0,"ClientID":"","ClientOrderID":"","AutoBorrow":false,"MarginType":"multi","RetrieveFees":false,"RetrieveFeeDelay":0,"RiskManagementModes":{"Mode":"","TakeProfit":{"Enabled":false,"TriggerPriceType":0,"Price":0,"LimitPrice":0,"OrderType":0},"StopLoss":{"Enabled":false,"TriggerPriceType":0,"Price":0,"LimitPrice":0,"OrderType":0},"StopEntry":{"Enabled":false,"TriggerPriceType":0,"Price":0,"LimitPrice":0,"OrderType":0}},"Hidden":false,"Iceberg":false,"EndTime":"0001-01-01T00:00:00Z","StopDirection":false,"TrackingMode":0,"TrackingValue":0,"RFQDisabled":false}`)
assert.Equal(t, exp, j)
}

View File

@@ -28,6 +28,7 @@ var (
ErrSubmitLeverageNotSupported = errors.New("leverage is not supported via order submission")
ErrClientOrderIDNotSupported = errors.New("client order id not supported")
ErrUnsupportedOrderType = errors.New("unsupported order type")
ErrUnsupportedStatusType = errors.New("unsupported status type")
// ErrNoRates is returned when no margin rates are returned when they are expected
ErrNoRates = errors.New("no rates")
ErrCannotLiquidate = errors.New("cannot liquidate position")
@@ -93,10 +94,18 @@ type Submit struct {
// Iceberg specifies whether or not only visible portions of orders are shown in iceberg orders
Iceberg bool
// EndTime is the moment which a good til date order is valid until
EndTime time.Time
// StopDirection is the direction from which the stop order will trigger
StopDirection StopDirection
// TrackingMode specifies the way trailing stop and chase orders follow the market price or ask/bid prices.
// See: https://www.okx.com/docs-v5/en/#order-book-trading-algo-trading-post-place-algo-order
TrackingMode TrackingMode
TrackingValue float64
// RFQDisabled, when set, attempts to route the order to the exchange CLOB. Currently only supported by Coinbase
RFQDisabled bool
}
// SubmitResponse is what is returned after submitting an order to an exchange
@@ -375,6 +384,7 @@ const (
StopLimit = Stop | Limit
StopMarket = Stop | Market
TakeProfitMarket = TakeProfit | Market
Bracket = Stop | TakeProfit
)
// order-type string representations
@@ -396,9 +406,31 @@ const (
orderOCO = "OCO"
orderOptimalLimit = "OPTIMAL_LIMIT"
orderMarketMakerProtection = "MMP"
orderBracket = "BRACKET"
orderAnyType = "ANY"
)
// AllOrderTypes collects all order types for easy and consistent comparisons
var AllOrderTypes = Limit |
Market |
Stop |
StopLimit |
StopMarket |
TakeProfit |
TakeProfitMarket |
TrailingStop |
IOS |
AnyType |
Liquidation |
Trigger |
OCO |
ConditionalStop |
TWAP |
Chase |
OptimalLimit |
MarketMakerProtection |
Bracket
// Side enforces a standard for order sides across the code base
type Side uint32
@@ -453,6 +485,17 @@ type ClassificationError struct {
// MultiOrderRequest.
type FilteredOrders []Detail
// StopDirection is the direction from which the stop order will trigger; Up will have the order trigger
// when the last trade price goes above the TriggerPrice; Down will have the order trigger when the
// last trade price goes below the TriggerPrice
type StopDirection bool
// StopDirection types
const (
StopUp StopDirection = true
StopDown StopDirection = false
)
// RiskManagement represents a risk management detail information.
type RiskManagement struct {
Enabled bool

View File

@@ -40,12 +40,11 @@ var (
ErrAmountMustBeSet = errors.New("amount must be set")
ErrClientOrderIDMustBeSet = errors.New("client order ID must be set")
ErrUnknownSubmissionAmountType = errors.New("unknown submission amount type")
ErrUnrecognisedOrderType = errors.New("unrecognised order type")
)
var (
errUnrecognisedOrderType = errors.New("unrecognised order type")
errUnrecognisedOrderStatus = errors.New("unrecognised order status")
errExchangeNameUnset = errors.New("exchange name unset")
errOrderSubmitIsNil = errors.New("order submit is nil")
errOrderSubmitResponseIsNil = errors.New("order submit response is nil")
errOrderDetailIsNil = errors.New("order detail is nil")
@@ -64,7 +63,7 @@ func (s *Submit) Validate(requirements protocol.TradingRequirements, opt ...vali
}
if s.Exchange == "" {
return errExchangeNameUnset
return common.ErrExchangeNameNotSet
}
if s.Pair.IsEmpty() {
@@ -83,7 +82,7 @@ func (s *Submit) Validate(requirements protocol.TradingRequirements, opt ...vali
return fmt.Errorf("%w %v", ErrSideIsInvalid, s.Side)
}
if s.Type != Market && s.Type != Limit {
if AllOrderTypes&s.Type != s.Type || s.Type == UnknownType {
return ErrTypeIsInvalid
}
@@ -697,6 +696,8 @@ func (t Type) String() string {
return orderTrigger
case OCO:
return orderOCO
case Bracket:
return orderBracket
case OptimalLimit:
return orderOptimalLimit
case MarketMakerProtection:
@@ -1136,8 +1137,10 @@ func StringToOrderType(oType string) (Type, error) {
return TakeProfit, nil
case orderLiquidation:
return Liquidation, nil
case orderBracket, "TRIGGER_BRACKET":
return Bracket, nil
default:
return UnknownType, fmt.Errorf("'%v' %w", oType, errUnrecognisedOrderType)
return UnknownType, fmt.Errorf("'%v' %w", oType, ErrUnrecognisedOrderType)
}
}
@@ -1263,7 +1266,7 @@ func (g *MultiOrderRequest) Validate(opt ...validate.Checker) error {
}
if g.Type == UnknownType {
return errUnrecognisedOrderType
return ErrUnrecognisedOrderType
}
var errs error

View File

@@ -13,7 +13,7 @@ var (
)
// TimeInForce enforces a standard for time-in-force values across the code base.
type TimeInForce uint8
type TimeInForce uint16
// TimeInForce types
const (
@@ -25,8 +25,9 @@ const (
FillOrKill
ImmediateOrCancel
PostOnly
StopOrReduce
supportedTimeInForceFlag = GoodTillCancel | GoodTillDay | GoodTillTime | GoodTillCrossing | FillOrKill | ImmediateOrCancel | PostOnly
supportedTimeInForceFlag = GoodTillCancel | GoodTillDay | GoodTillTime | GoodTillCrossing | FillOrKill | ImmediateOrCancel | PostOnly | StopOrReduce
)
// time-in-force string representations
@@ -38,6 +39,7 @@ const (
fokStr = "FOK"
iocStr = "IOC"
postonlyStr = "POSTONLY"
sorStr = "SOR"
)
// Is checks to see if the enum contains the flag
@@ -64,6 +66,8 @@ func StringToTimeInForce(timeInForce string) (TimeInForce, error) {
result = FillOrKill
case "POC", "POST_ONLY", "PENDINGORCANCEL", postonlyStr:
result = PostOnly
case "STOPORREDUCE", "STOP_OR_REDUCE", sorStr:
result = StopOrReduce
}
if result == UnknownTIF && timeInForce != "" {
return UnknownTIF, fmt.Errorf("%w: tif=%s", ErrInvalidTimeInForce, timeInForce)
@@ -111,6 +115,9 @@ func (t TimeInForce) String() string {
if t.Is(PostOnly) {
tifStrings = append(tifStrings, postonlyStr)
}
if t.Is(StopOrReduce) {
tifStrings = append(tifStrings, sorStr)
}
if len(tifStrings) == 0 {
return "UNKNOWN"
}

View File

@@ -22,6 +22,7 @@ func TestTimeInForceIs(t *testing.T) {
FillOrKill: {FillOrKill},
PostOnly: {PostOnly},
GoodTillCrossing: {GoodTillCrossing},
StopOrReduce: {StopOrReduce},
}
for tif, exps := range tifValuesMap {
for _, v := range exps {
@@ -49,6 +50,7 @@ func TestIsValid(t *testing.T) {
GoodTillDay | PostOnly: true,
GoodTillCrossing | PostOnly: true,
GoodTillCancel | PostOnly: true,
StopOrReduce: true,
UnknownTIF: true,
}
for tif, value := range timeInForceValidityMap {
@@ -80,6 +82,8 @@ var timeInForceStringToValueMap = map[string]struct {
"GTX": {TIF: GoodTillCrossing},
"GOOD_TILL_CROSSING": {TIF: GoodTillCrossing},
"Good Til crossing": {TIF: GoodTillCrossing},
"sor": {TIF: StopOrReduce},
"STOP_OR_REDUCE": {TIF: StopOrReduce},
"abcdfeg": {TIF: UnknownTIF, Error: ErrInvalidTimeInForce},
}
@@ -113,6 +117,7 @@ func TestString(t *testing.T) {
GoodTillTime | PostOnly: "GTT,POSTONLY",
GoodTillDay | PostOnly: "GTD,POSTONLY",
FillOrKill | ImmediateOrCancel: "IOC,FOK",
StopOrReduce: "SOR",
TimeInForce(1): "UNKNOWN",
}
for x := range valMap {
@@ -125,9 +130,9 @@ func TestUnmarshalJSON(t *testing.T) {
t.Parallel()
targets := []TimeInForce{
GoodTillCancel | PostOnly | ImmediateOrCancel, GoodTillCancel | PostOnly, GoodTillCancel, UnknownTIF, PostOnly | ImmediateOrCancel,
GoodTillCancel, GoodTillCancel, PostOnly, PostOnly, ImmediateOrCancel, GoodTillDay, GoodTillDay, GoodTillTime, FillOrKill, FillOrKill,
GoodTillCancel, GoodTillCancel, PostOnly, PostOnly, ImmediateOrCancel, GoodTillDay, GoodTillDay, GoodTillTime, FillOrKill, FillOrKill, StopOrReduce,
}
data := []byte(`{"tifs": ["GTC,POSTONLY,IOC", "GTC,POSTONLY", "GTC", "", "POSTONLY,IOC", "GoodTilCancel", "GoodTILLCANCEL", "POST_ONLY", "POC","IOC", "GTD", "gtd","gtt", "fok", "fillOrKill"]}`)
data := []byte(`{"tifs": ["GTC,POSTONLY,IOC", "GTC,POSTONLY", "GTC", "", "POSTONLY,IOC", "GoodTilCancel", "GoodTILLCANCEL", "POST_ONLY", "POC","IOC", "GTD", "gtd","gtt", "fok", "fillOrKill", "SOR"]}`)
target := &struct {
TIFs []TimeInForce `json:"tifs"`
}{}
@@ -135,7 +140,7 @@ func TestUnmarshalJSON(t *testing.T) {
require.NoError(t, err)
require.Equal(t, targets, target.TIFs)
data = []byte(`{"tifs": ["abcd,POSTONLY,IOC", "GTC,POSTONLY", "GTC", "", "POSTONLY,IOC", "GoodTilCancel", "GoodTILLCANCEL", "POST_ONLY", "POC","IOC", "GTD", "gtd","gtt", "fok", "fillOrKill"]}`)
data = []byte(`{"tifs": ["abcd,POSTONLY,IOC", "GTC,POSTONLY", "GTC", "", "POSTONLY,IOC", "GoodTilCancel", "GoodTILLCANCEL", "POST_ONLY", "POC","IOC", "GTD", "gtd","gtt", "fok", "fillOrKill", "SOR"]}`)
target = &struct {
TIFs []TimeInForce `json:"tifs"`
}{}