Skip to content

Commit

Permalink
feat: integrate cancel replace order on binance and binance us
Browse files Browse the repository at this point in the history
  • Loading branch information
ilhamosaurus committed Dec 11, 2024
1 parent 6c55042 commit 9961d24
Show file tree
Hide file tree
Showing 12 changed files with 470 additions and 101 deletions.
65 changes: 56 additions & 9 deletions exchanges/binance/binance.go
Original file line number Diff line number Diff line change
Expand Up @@ -59,12 +59,13 @@ const (
marginInterestHistory = "/sapi/v1/margin/interestHistory"

// Authenticated endpoints
newOrderTest = "/api/v3/order/test"
orderEndpoint = "/api/v3/order"
openOrders = "/api/v3/openOrders"
allOrders = "/api/v3/allOrders"
accountInfo = "/api/v3/account"
marginAccountInfo = "/sapi/v1/margin/account"
newOrderTest = "/api/v3/order/test"
orderEndpoint = "/api/v3/order"
openOrders = "/api/v3/openOrders"
allOrders = "/api/v3/allOrders"
accountInfo = "/api/v3/account"
marginAccountInfo = "/sapi/v1/margin/account"
cancelReplaceOrder = "/api/v3/order/cancelReplace"

// Wallet endpoints
allCoinsInfo = "/sapi/v1/capital/config/getall"
Expand Down Expand Up @@ -661,6 +662,49 @@ func (b *Binance) CancelExistingOrder(ctx context.Context, symbol currency.Pair,
return resp, b.SendAuthHTTPRequest(ctx, exchange.RestSpotSupplementary, http.MethodDelete, orderEndpoint, params, spotOrderRate, &resp)
}

func (b *Binance) CancelReplaceOrder(ctx context.Context, m *CancelReplaceOrderRequest, resp *CancelReplaceOrderResponse) error {
params := url.Values{}
symbol, err := b.FormatSymbol(m.Symbol, asset.Spot)
if err != nil {
return err
}

params.Set("symbol", symbol)
params.Set("side", m.Side)
params.Set("type", string(m.OrderType))
params.Set("cancelReplaceMode", string(m.CancelReplaceMode))

if m.QuoteOrderQty > 0 {
params.Set("quoteOrderQty", strconv.FormatFloat(m.QuoteOrderQty, 'f', -1, 64))
} else {
params.Set("quantity", strconv.FormatFloat(m.Quantity, 'f', -1, 64))
}
if m.OrderType == BinanceRequestParamsOrderLimit {
params.Set("price", strconv.FormatFloat(m.Price, 'f', -1, 64))
}
if m.TimeInForce != "" {
params.Set("timeInForce", m.TimeInForce)
}
if m.CancelNewClientOrderID != "" {
params.Set("cancelNewClientOrderId", m.CancelNewClientOrderID)
}
if m.CancelOrigClientOrderID != "" {
params.Set("cancelOrigClientOrderId", m.CancelOrigClientOrderID)
}
if m.CancelOrderID != "" {
params.Set("cancelOrderId", m.CancelOrderID)
}

if m.StopPrice != 0 {
params.Set("stopPrice", strconv.FormatFloat(m.StopPrice, 'f', -1, 64))
}

if err := b.SendAuthHTTPRequest(ctx, exchange.RestSpotSupplementary, http.MethodPost, cancelReplaceOrder, params, spotOrderRate, &resp); err != nil {
return err
}
return nil
}

// OpenOrders Current open orders. Get all open orders on a symbol.
// Careful when accessing this with no symbol: The number of requests counted
// against the rate limiter is significantly higher
Expand Down Expand Up @@ -807,7 +851,8 @@ func (b *Binance) SendHTTPRequest(ctx context.Context, ePath exchange.URL, path
Result: result,
Verbose: b.Verbose,
HTTPDebugging: b.HTTPDebugging,
HTTPRecording: b.HTTPRecording}
HTTPRecording: b.HTTPRecording,
}

return b.SendPayload(ctx, f, func() (*request.Item, error) {
return item, nil
Expand Down Expand Up @@ -836,7 +881,8 @@ func (b *Binance) SendAPIKeyHTTPRequest(ctx context.Context, ePath exchange.URL,
Result: result,
Verbose: b.Verbose,
HTTPDebugging: b.HTTPDebugging,
HTTPRecording: b.HTTPRecording}
HTTPRecording: b.HTTPRecording,
}

return b.SendPayload(ctx, f, func() (*request.Item, error) {
return item, nil
Expand Down Expand Up @@ -887,7 +933,8 @@ func (b *Binance) SendAuthHTTPRequest(ctx context.Context, ePath exchange.URL, m
Result: &interim,
Verbose: b.Verbose,
HTTPDebugging: b.HTTPDebugging,
HTTPRecording: b.HTTPRecording}, nil
HTTPRecording: b.HTTPRecording,
}, nil
}, request.AuthenticatedRequest)
if err != nil {
return err
Expand Down
57 changes: 57 additions & 0 deletions exchanges/binance/binance_types.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,13 @@ const (
maxNumAlgoOrdersFilter filterType = "MAX_NUM_ALGO_ORDERS"
)

type cancelReplaceMode string

const (
stopOnFailure cancelReplaceMode = "STOP_ON_FAILURE"
allowFailure cancelReplaceMode = "ALLOW_FAILURE"
)

// ExchangeInfo holds the full exchange information type
type ExchangeInfo struct {
Code int `json:"code"`
Expand Down Expand Up @@ -412,6 +419,32 @@ type NewOrderResponse struct {
} `json:"fills"`
}

type OrderResponse struct {
Symbol string `json:"symbol"`
OrigClientOrderID string `json:"origClientOrderId"`
OrderID int64 `json:"orderId"`
OrderListID int64 `json:"orderListId"`
ClientOrderID string `json:"clientOrderId"`
TransactionTime int64 `json:"transactTime"`
Price float64 `json:"price,string"`
OrigQty float64 `json:"origQty,string"`
ExecutedQty float64 `json:"executedQty,string"`
OrigQuoteOrderQty float64 `json:"origQuoteOrderQty,string"`
// The cumulative amount of the quote that has been spent (with a BUY order) or received (with a SELL order).
CumulativeQuoteQty float64 `json:"cummulativeQuoteQty,string"`
Status string `json:"status"`
TimeInForce string `json:"timeInForce"`
Type string `json:"type"`
Side string `json:"side"`
SelfTradePrevention string `json:"selfTradePreventionMode"`
Fills []struct {
Price float64 `json:"price,string"`
Qty float64 `json:"qty,string"`
Commission float64 `json:"commission,string"`
CommissionAsset string `json:"commissionAsset"`
} `json:"fills"`
}

// CancelOrderResponse is the return structured response from the exchange
type CancelOrderResponse struct {
Symbol string `json:"symbol"`
Expand All @@ -420,6 +453,30 @@ type CancelOrderResponse struct {
ClientOrderID string `json:"clientOrderId"`
}

type CancelReplaceOrderRequest struct {
Symbol currency.Pair `json:"symbol"`
Side string `json:"side"`
OrderType RequestParamsOrderType `json:"type"`
CancelReplaceMode cancelReplaceMode `json:"cancelReplaceMode"`
TimeInForce string `json:"timeInForce"`
Quantity float64 `json:"quantity"`
QuoteOrderQty float64 `json:"quoteOrderQty"`
Price float64 `json:"price"`
StopPrice float64 `json:"stopPrice"`
CancelNewClientOrderID string `json:"cancelNewClientOrderId"`
CancelOrigClientOrderID string `json:"cancelOrigClientOrderId"`
CancelOrderID string `json:"cancelOrderId"`
}

type CancelReplaceOrderResponse struct {
Code int `json:"code"`
Msg string `json:"msg"`
CancelResult string `json:"cancelResult"`
NewOrderResult string `json:"newOrderResult"`
CancelResponse OrderResponse `json:"cancelResponse"`
NewOrderResponse OrderResponse `json:"newOrderResponse"`
}

// QueryOrderData holds query order data
type QueryOrderData struct {
Code int `json:"code"`
Expand Down
9 changes: 5 additions & 4 deletions exchanges/binance/binance_ufutures.go
Original file line number Diff line number Diff line change
Expand Up @@ -676,7 +676,7 @@ func (b *Binance) UFuturesNewOrder(ctx context.Context, data *UFuturesNewOrderRe
if data.Quantity != 0 {
params.Set("quantity", strconv.FormatFloat(data.Quantity, 'f', -1, 64))
}
if data.Price != 0 {
if data.Price != 0 && data.OrderType != "MARKET" {
params.Set("price", strconv.FormatFloat(data.Price, 'f', -1, 64))
}
if data.StopPrice != 0 {
Expand All @@ -691,6 +691,7 @@ func (b *Binance) UFuturesNewOrder(ctx context.Context, data *UFuturesNewOrderRe
if err := b.SendAuthHTTPRequest(ctx, exchange.RestUSDTMargined, http.MethodPost, ufuturesOrder, params, uFuturesOrdersDefaultRate, &resp); err != nil {
return resp, err
}
log.Printf("Binance futures new order id: %+v", resp)
return resp, nil
}

Expand Down Expand Up @@ -776,7 +777,7 @@ func (b *Binance) UModifyOrder(ctx context.Context, m *UFuturesModifyOrderReques
if err := b.SendAuthHTTPRequest(ctx, exchange.RestUSDTMargined, http.MethodPut, ufuturesOrder, params, uFuturesOrdersDefaultRate, &resp); err != nil {
return resp, err
}

log.Printf("Binance futures modify order id: %+v", resp)
return resp, nil
}

Expand All @@ -792,11 +793,11 @@ func (b *Binance) UCancelOrder(ctx context.Context, symbol currency.Pair, orderI
if orderID != "" {
params.Set("orderId", orderID)
}
log.Printf("Binance futures cancel order id: %s", orderID)

if cliOrderID != "" {
params.Set("origClientOrderId", cliOrderID)
}
log.Printf("Binance futures cancel params: %+v", params)

return resp, b.SendAuthHTTPRequest(ctx, exchange.RestUSDTMargined, http.MethodDelete, ufuturesOrder, params, uFuturesOrdersDefaultRate, &resp)
}

Expand Down
Loading

0 comments on commit 9961d24

Please sign in to comment.