Skip to content

Commit

Permalink
Getting closed orders implementation, fixed Binance MARKET order crea…
Browse files Browse the repository at this point in the history
…tion, expanded SubmitOrder response (thrasher-corp#572)

* GetClosedOrder implemented for Kraken and Binance, fixed Binance MARKET order creaton, added rate, fee and cost fileds on SubmitOrder responce

* return Trades on Binance SubmitOrder, new validation methods on Binance and kraken GetClosedOrderInfo

* removed the Binance extra method GetClosedOrder

* func description corrected

* removed price, fee and cost from SimulateOrder response, as we get all necessary info in response to calculate them on client side

* GetClosedOrder implementation moved to GetOrderInfo

* changed GetOrderInfo params

* removed Canceled order.Type used for Kraken

* update QueryOrder in gctscript

* add missed params to QueryOrder validator (gctscript)

* fixed testing issues

* GetClosedOrder implemented for Kraken and Binance, fixed Binance MARKET order creaton, added rate, fee and cost fileds on SubmitOrder responce

* return Trades on Binance SubmitOrder, new validation methods on Binance and kraken GetClosedOrderInfo

* removed the Binance extra method GetClosedOrder

* func description corrected

* removed price, fee and cost from SimulateOrder response, as we get all necessary info in response to calculate them on client side

* GetClosedOrder implementation moved to GetOrderInfo

* changed GetOrderInfo params

* removed Canceled order.Type used for Kraken

* update QueryOrder in gctscript

* add missed params to QueryOrder validator (gctscript)

* fixed testing issues

* pull previous changes

* linter issues fix

* updated query_order exmple in gctscript, fixed params check

* removed orderPair unnecessary conversion

Co-authored-by: Vazha Bezhanishvili <[email protected]>
  • Loading branch information
vazha and Vazha Bezhanishvili authored Oct 22, 2020
1 parent 4ccb495 commit fab9d93
Show file tree
Hide file tree
Showing 54 changed files with 2,360 additions and 2,146 deletions.
4 changes: 2 additions & 2 deletions cmd/exchange_template/wrapper_file.tmpl
Original file line number Diff line number Diff line change
Expand Up @@ -362,8 +362,8 @@ func ({{.Variable}} *{{.CapitalName}}) CancelAllOrders(orderCancellation *order.
return order.CancelAllResponse{}, common.ErrNotYetImplemented
}

// GetOrderInfo returns information on a current open order
func ({{.Variable}} *{{.CapitalName}}) GetOrderInfo(orderID string) (order.Detail, error) {
// GetOrderInfo returns order information based on order ID
func ({{.Variable}} *{{.CapitalName}}) GetOrderInfo(orderID string, pair currency.Pair, assetType asset.Item) (order.Detail, error) {
return order.Detail{}, common.ErrNotYetImplemented
}

Expand Down
2 changes: 1 addition & 1 deletion cmd/exchange_wrapper_coverage/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,7 @@ func testWrappers(e exchange.IBotExchange) []string {
funcs = append(funcs, "CancelAllOrders")
}

_, err = e.GetOrderInfo("1")
_, err = e.GetOrderInfo("1", p, assetType)
if err == common.ErrNotYetImplemented {
funcs = append(funcs, "GetOrderInfo")
}
Expand Down
2 changes: 1 addition & 1 deletion cmd/exchange_wrapper_issues/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -550,7 +550,7 @@ func testWrappers(e exchange.IBotExchange, base *exchange.Base, config *Config)
})

var r15 order.Detail
r15, err = e.GetOrderInfo(config.OrderSubmission.OrderID)
r15, err = e.GetOrderInfo(config.OrderSubmission.OrderID, p, assetTypes[i])
msg = ""
if err != nil {
msg = err.Error()
Expand Down
27 changes: 26 additions & 1 deletion cmd/gctcli/commands.go
Original file line number Diff line number Diff line change
Expand Up @@ -1231,7 +1231,7 @@ func getOrders(c *cli.Context) error {
var getOrderCommand = cli.Command{
Name: "getorder",
Usage: "gets the specified order info",
ArgsUsage: "<exchange> <order_id>",
ArgsUsage: "<exchange> <order_id> <pair>",
Action: getOrder,
Flags: []cli.Flag{
cli.StringFlag{
Expand All @@ -1242,6 +1242,10 @@ var getOrderCommand = cli.Command{
Name: "order_id",
Usage: "the order id to retrieve",
},
cli.StringFlag{
Name: "pair",
Usage: "the pair to retrieve",
},
},
}

Expand All @@ -1253,13 +1257,29 @@ func getOrder(c *cli.Context) error {

var exchangeName string
var orderID string
var currencyPair string

if c.IsSet("pair") {
currencyPair = c.String("pair")
} else {
currencyPair = c.Args().Get(2)
}

if c.IsSet("exchange") {
exchangeName = c.String("exchange")
} else {
exchangeName = c.Args().First()
}

if !validPair(currencyPair) {
return errInvalidPair
}

p, err := currency.NewPairDelimiter(currencyPair, pairDelimiter)
if err != nil {
return err
}

if !validExchange(exchangeName) {
return errInvalidExchange
}
Expand All @@ -1280,6 +1300,11 @@ func getOrder(c *cli.Context) error {
result, err := client.GetOrder(context.Background(), &gctrpc.GetOrderRequest{
Exchange: exchangeName,
OrderId: orderID,
Pair: &gctrpc.CurrencyPair{
Delimiter: p.Delimiter,
Base: p.Base.String(),
Quote: p.Quote.String(),
},
})
if err != nil {
return err
Expand Down
2 changes: 1 addition & 1 deletion engine/fake_exchange_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ func (h *FakePassingExchange) CancelOrder(_ *order.Cancel) error { ret
func (h *FakePassingExchange) CancelAllOrders(_ *order.Cancel) (order.CancelAllResponse, error) {
return order.CancelAllResponse{}, nil
}
func (h *FakePassingExchange) GetOrderInfo(_ string) (order.Detail, error) {
func (h *FakePassingExchange) GetOrderInfo(_ string, _ currency.Pair, _ asset.Item) (order.Detail, error) {
return order.Detail{}, nil
}
func (h *FakePassingExchange) GetDepositAddress(_ currency.Code, _ string) (string, error) {
Expand Down
22 changes: 21 additions & 1 deletion engine/rpcserver.go
Original file line number Diff line number Diff line change
Expand Up @@ -804,7 +804,14 @@ func (s *RPCServer) GetOrder(_ context.Context, r *gctrpc.GetOrderRequest) (*gct
if exch == nil {
return nil, errExchangeNotLoaded
}
result, err := exch.GetOrderInfo(r.OrderId)

pair := currency.Pair{
Delimiter: r.Pair.Delimiter,
Base: currency.NewCode(r.Pair.Base),
Quote: currency.NewCode(r.Pair.Quote),
}

result, err := exch.GetOrderInfo(r.OrderId, pair, "") // assetType will be implemented in the future
if err != nil {
return nil, fmt.Errorf("error whilst trying to retrieve info for order %s: %s", r.OrderId, err)
}
Expand Down Expand Up @@ -836,6 +843,8 @@ func (s *RPCServer) GetOrder(_ context.Context, r *gctrpc.GetOrderRequest) (*gct
OpenVolume: result.RemainingAmount,
Fee: result.Fee,
Trades: trades,
Cost: result.Cost,
UpdateTime: result.CloseTime.Unix(),
}, err
}

Expand Down Expand Up @@ -873,9 +882,20 @@ func (s *RPCServer) SubmitOrder(_ context.Context, r *gctrpc.SubmitOrderRequest)
return &gctrpc.SubmitOrderResponse{}, err
}

var trades []*gctrpc.Trades
for i := range resp.Trades {
trades = append(trades, &gctrpc.Trades{
Amount: resp.Trades[i].Amount,
Price: resp.Trades[i].Price,
Fee: resp.Trades[i].Fee,
FeeAsset: resp.Trades[i].FeeAsset,
})
}

return &gctrpc.SubmitOrderResponse{
OrderId: resp.OrderID,
OrderPlaced: resp.IsOrderPlaced,
Trades: trades,
}, err
}

Expand Down
4 changes: 2 additions & 2 deletions exchanges/alphapoint/alphapoint_wrapper.go
Original file line number Diff line number Diff line change
Expand Up @@ -269,8 +269,8 @@ func (a *Alphapoint) CancelAllOrders(orderCancellation *order.Cancel) (order.Can
a.CancelAllExistingOrders(orderCancellation.AccountID)
}

// GetOrderInfo returns information on a current open order
func (a *Alphapoint) GetOrderInfo(orderID string) (float64, error) {
// GetOrderInfo returns order information based on order ID
func (a *Alphapoint) GetOrderInfo(orderID string, pair currency.Pair, assetType asset.Item) (float64, error) {
orders, err := a.GetOrders()
if err != nil {
return 0, err
Expand Down
1 change: 1 addition & 0 deletions exchanges/binance/binance.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ const (
queryOrder = "/api/v3/order"
openOrders = "/api/v3/openOrders"
allOrders = "/api/v3/allOrders"
myTrades = "/api/v3/myTrades"

// Withdraw API endpoints
withdrawEndpoint = "/wapi/v3/withdraw.html"
Expand Down
36 changes: 20 additions & 16 deletions exchanges/binance/binance_types.go
Original file line number Diff line number Diff line change
Expand Up @@ -328,22 +328,26 @@ type CancelOrderResponse struct {

// QueryOrderData holds query order data
type QueryOrderData struct {
Code int `json:"code"`
Msg string `json:"msg"`
Symbol string `json:"symbol"`
OrderID int64 `json:"orderId"`
ClientOrderID string `json:"clientOrderId"`
Price float64 `json:"price,string"`
OrigQty float64 `json:"origQty,string"`
ExecutedQty float64 `json:"executedQty,string"`
Status string `json:"status"`
TimeInForce string `json:"timeInForce"`
Type string `json:"type"`
Side string `json:"side"`
StopPrice float64 `json:"stopPrice,string"`
IcebergQty float64 `json:"icebergQty,string"`
Time float64 `json:"time"`
IsWorking bool `json:"isWorking"`
Code int `json:"code"`
Msg string `json:"msg"`
Symbol string `json:"symbol"`
OrderID int64 `json:"orderId"`
ClientOrderID string `json:"clientOrderId"`
Price float64 `json:"price,string"`
OrigQty float64 `json:"origQty,string"`
ExecutedQty float64 `json:"executedQty,string"`
Status string `json:"status"`
TimeInForce string `json:"timeInForce"`
Type string `json:"type"`
Side string `json:"side"`
StopPrice float64 `json:"stopPrice,string"`
IcebergQty float64 `json:"icebergQty,string"`
Time float64 `json:"time"`
IsWorking bool `json:"isWorking"`
CummulativeQuoteQty float64 `json:"cummulativeQuoteQty,string"`
OrderListID int64 `json:"orderListId"`
OrigQuoteOrderQty float64 `json:"origQuoteOrderQty,string"`
UpdateTime int64 `json:"updateTime"`
}

// Balance holds query order data
Expand Down
86 changes: 79 additions & 7 deletions exchanges/binance/binance_wrapper.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"time"

"github.com/thrasher-corp/gocryptotrader/common"
"github.com/thrasher-corp/gocryptotrader/common/convert"
"github.com/thrasher-corp/gocryptotrader/config"
"github.com/thrasher-corp/gocryptotrader/currency"
exchange "github.com/thrasher-corp/gocryptotrader/exchanges"
Expand Down Expand Up @@ -513,9 +514,11 @@ func (b *Binance) SubmitOrder(s *order.Submit) (order.SubmitResponse, error) {
sideType = order.Sell.String()
}

timeInForce := BinanceRequestParamsTimeGTC
var requestParamsOrderType RequestParamsOrderType
switch s.Type {
case order.Market:
timeInForce = ""
requestParamsOrderType = BinanceRequestParamsOrderMarket
case order.Limit:
requestParamsOrderType = BinanceRequestParamsOrderLimit
Expand All @@ -530,13 +533,14 @@ func (b *Binance) SubmitOrder(s *order.Submit) (order.SubmitResponse, error) {
Price: s.Price,
Quantity: s.Amount,
TradeType: requestParamsOrderType,
TimeInForce: BinanceRequestParamsTimeGTC,
TimeInForce: timeInForce,
}

response, err := b.NewOrder(&orderRequest)
if err != nil {
return submitOrderResponse, err
}

if response.OrderID > 0 {
submitOrderResponse.OrderID = strconv.FormatInt(response.OrderID, 10)
}
Expand All @@ -545,6 +549,15 @@ func (b *Binance) SubmitOrder(s *order.Submit) (order.SubmitResponse, error) {
}
submitOrderResponse.IsOrderPlaced = true

for i := range response.Fills {
submitOrderResponse.Trades = append(submitOrderResponse.Trades, order.TradeHistory{
Price: response.Fills[i].Price,
Amount: response.Fills[i].Qty,
Fee: response.Fills[i].Commission,
FeeAsset: response.Fills[i].CommissionAsset,
})
}

return submitOrderResponse, nil
}

Expand Down Expand Up @@ -598,10 +611,63 @@ func (b *Binance) CancelAllOrders(_ *order.Cancel) (order.CancelAllResponse, err
return cancelAllOrdersResponse, nil
}

// GetOrderInfo returns information on a current open order
func (b *Binance) GetOrderInfo(orderID string) (order.Detail, error) {
var orderDetail order.Detail
return orderDetail, common.ErrNotYetImplemented
// GetOrderInfo returns order information based on order ID
func (b *Binance) GetOrderInfo(orderID string, pair currency.Pair, assetType asset.Item) (o order.Detail, err error) {
if assetType == "" {
assetType = asset.Spot
}

formattedPair, err := b.FormatExchangeCurrency(pair, assetType)
if err != nil {
return
}

orderIDInt64, err := convert.Int64FromString(orderID)
if err != nil {
return
}

resp, err := b.QueryOrder(formattedPair.String(), "", orderIDInt64)
if err != nil {
return
}

orderSide := order.Side(resp.Side)
orderDate, err := convert.TimeFromUnixTimestampFloat(resp.Time)
if err != nil {
return
}

orderCloseDate, err := convert.TimeFromUnixTimestampFloat(float64(resp.UpdateTime))
if err != nil {
return
}

status, err := order.StringToOrderStatus(resp.Status)
if err != nil {
return
}

orderType := order.Limit
if resp.Type == "MARKET" {
orderType = order.Market
}

return order.Detail{
Amount: resp.OrigQty,
Date: orderDate,
Exchange: b.Name,
ID: strconv.FormatInt(resp.OrderID, 10),
Side: orderSide,
Type: orderType,
Pair: formattedPair,
Cost: resp.CummulativeQuoteQty,
AssetType: assetType,
CloseTime: orderCloseDate,
Status: status,
Price: resp.Price,
ExecutedAmount: resp.ExecutedQty,
}, nil
}

// GetDepositAddress returns a deposit address for a specified currency
Expand Down Expand Up @@ -676,7 +742,10 @@ func (b *Binance) GetActiveOrders(req *order.GetOrdersRequest) ([]order.Detail,
for i := range resp {
orderSide := order.Side(strings.ToUpper(resp[i].Side))
orderType := order.Type(strings.ToUpper(resp[i].Type))
orderDate := time.Unix(0, int64(resp[i].Time)*int64(time.Millisecond))
orderDate, err := convert.TimeFromUnixTimestampFloat(resp[i].Time)
if err != nil {
return nil, err
}

pair, err := currency.NewPairFromString(resp[i].Symbol)
if err != nil {
Expand Down Expand Up @@ -730,7 +799,10 @@ func (b *Binance) GetOrderHistory(req *order.GetOrdersRequest) ([]order.Detail,
for i := range resp {
orderSide := order.Side(strings.ToUpper(resp[i].Side))
orderType := order.Type(strings.ToUpper(resp[i].Type))
orderDate := time.Unix(0, int64(resp[i].Time)*int64(time.Millisecond))
orderDate, err := convert.TimeFromUnixTimestampFloat(resp[i].Time)
if err != nil {
return nil, err
}
// New orders are covered in GetOpenOrders
if resp[i].Status == "NEW" {
continue
Expand Down
4 changes: 2 additions & 2 deletions exchanges/bitfinex/bitfinex_wrapper.go
Original file line number Diff line number Diff line change
Expand Up @@ -583,8 +583,8 @@ func (b *Bitfinex) CancelAllOrders(_ *order.Cancel) (order.CancelAllResponse, er
return order.CancelAllResponse{}, err
}

// GetOrderInfo returns information on a current open order
func (b *Bitfinex) GetOrderInfo(orderID string) (order.Detail, error) {
// GetOrderInfo returns order information based on order ID
func (b *Bitfinex) GetOrderInfo(orderID string, pair currency.Pair, assetType asset.Item) (order.Detail, error) {
var orderDetail order.Detail
return orderDetail, common.ErrNotYetImplemented
}
Expand Down
4 changes: 2 additions & 2 deletions exchanges/bitflyer/bitflyer_wrapper.go
Original file line number Diff line number Diff line change
Expand Up @@ -309,8 +309,8 @@ func (b *Bitflyer) CancelAllOrders(_ *order.Cancel) (order.CancelAllResponse, er
return order.CancelAllResponse{}, common.ErrNotYetImplemented
}

// GetOrderInfo returns information on a current open order
func (b *Bitflyer) GetOrderInfo(orderID string) (order.Detail, error) {
// GetOrderInfo returns order information based on order ID
func (b *Bitflyer) GetOrderInfo(orderID string, pair currency.Pair, assetType asset.Item) (order.Detail, error) {
var orderDetail order.Detail
return orderDetail, common.ErrNotYetImplemented
}
Expand Down
4 changes: 2 additions & 2 deletions exchanges/bithumb/bithumb_wrapper.go
Original file line number Diff line number Diff line change
Expand Up @@ -444,8 +444,8 @@ func (b *Bithumb) CancelAllOrders(orderCancellation *order.Cancel) (order.Cancel
return cancelAllOrdersResponse, nil
}

// GetOrderInfo returns information on a current open order
func (b *Bithumb) GetOrderInfo(orderID string) (order.Detail, error) {
// GetOrderInfo returns order information based on order ID
func (b *Bithumb) GetOrderInfo(orderID string, pair currency.Pair, assetType asset.Item) (order.Detail, error) {
var orderDetail order.Detail
return orderDetail, common.ErrNotYetImplemented
}
Expand Down
4 changes: 2 additions & 2 deletions exchanges/bitmex/bitmex_wrapper.go
Original file line number Diff line number Diff line change
Expand Up @@ -505,8 +505,8 @@ func (b *Bitmex) CancelAllOrders(_ *order.Cancel) (order.CancelAllResponse, erro
return cancelAllOrdersResponse, nil
}

// GetOrderInfo returns information on a current open order
func (b *Bitmex) GetOrderInfo(orderID string) (order.Detail, error) {
// GetOrderInfo returns order information based on order ID
func (b *Bitmex) GetOrderInfo(orderID string, pair currency.Pair, assetType asset.Item) (order.Detail, error) {
var orderDetail order.Detail
return orderDetail, common.ErrNotYetImplemented
}
Expand Down
Loading

0 comments on commit fab9d93

Please sign in to comment.