GetActiveOrders/GetOrderHistory wrapper implementation (#239)

* Adds signature to all exchange wrappers

* Adds funky new OrderHistoryRequest type. Updates signature for GetOrderHistory to use funky new type. Adds tests for GetOrderHistory on all exchanges. Implements GetOrderHistory for ANX

* Fixes alphapoint, bitstamp, itbit, zb tests. Adds exchange functions FilterOrdersByStatusAndType, FilterOrdersByTickRange, FilterOrdersByCurrencies to easily filter returned orders. Adds tests for filters. Implements GetOrderHistory wrapper for Binance, bitfinex, bithumb, bitmex. Adds new filter funcs to implementations.

* Adds bitstamp wrapper support

* Splits up GetOrderHistory into GetOpenOrders and GetOrderHistory wraapper functions to distinguish between active and past. Renames exchange.GetOrderHistoryRequest to exchange.GetOrdersRequest. Renames any API exchange method named GetOpenOrders to GetActiveOrders. Adds test function TestGetOpenOrders for each exchange

* Reimplements the split GetOrders and GetOrderHistory for alphapoint, anx, binance, bitfinex, bithumb, bitmex, bitstamp and bittrex. Renames orderType, orderStatus constants. Adds new exchange.FilterOrdersBySide and exchange.FilterOrdersByType and removes old exchange.FilterOrdersByStatusAndType.

* Changes orderHistoryRequest to use currencypair array instead of strings, also adds fees and trade breakdown. Removes if statement preventing ANX/BTCMarkets testing. Implements Active order + Order history retrieval for Bittrex and BTCMarkets.

* Adds support for coinut and coinbasepro

* Adds Exmo support

* Adds GateIO support

* Adds Gemini support

* Adds hitbtc, huobi, hadax,  itbit, kraken support for open orders & order history. Fixes switch case break and fallthroughs. Adds filtering to gateio and gemini results

* Adds support for LakeBTC, Liqui, Localbitcoin, OKCoin, OKEX

* Adds poloniex support

* Adds Wex support

* Adds Yobit support. Updates Wex support

* Adds ZB support. Removes ArrangeActAssert from tests

* Changes baseCurrency + quoteCurrency exchange.OrderDetail properties to a pair.CurrencyPair. Adds exchange name to all implementations. Fixes EXMO TestSetup

* Removes verbose setting from tests as verbosity increases the amount of noise return when testing. Noise is only helpful when debugging tests to get more helpful information to resolve the issue and so it is unnecessary to have such lengthy output when testing in bulk or via Travis CI. This commit therefore improves readability when there are no issues

* Fixes issue where gemini test sandbox api url was overridden. Handles blank response from Gemini

* Fixes verbose typo

* Removes spacing for old act assert test comments. Limits previous infinite loop to 10

* Fixes issue with filtering where orderside is never specified

* Uses proper capitalisation for ServerOrderID and OpenOrders. Reverts commenting out orde_id param for bithumb.GetOrderDetails. Removes unnecessary int logic

* Removes JSON ID fields. Uses map where appropriate for exchange order side/type. Updates OrderDetail/GetOrdersRequest type to use time fields. Remvoes comments. Removes inappropriate variable name. Adds AccountID field for alphapoint. Fixes log message formatting. Lowers errorfs to warnfs for time conversion

* Adds missed files

* Removes blank line

* Adds sorting options for orders. Adds concurrency warnings in comments. Adds test for NewCurrencyPairWithDelimiter. Removes (e *Base) from filter funcs. Updates references to filter funcs

* Fixes rebase issues. Condenses append loops.

* Fixes more receive typos. Removes some inline strings. Adds AskOrderSide and BidOrderSide. Removes hypothetical infinite loop

* Fixes issue where allTrades wasn't used in loop. Fixes assignment/typing issues

* Fixes formatting
This commit is contained in:
Scott
2019-02-05 10:44:05 +11:00
committed by Adrian Gallagher
parent 82a622294c
commit 978b91a692
105 changed files with 4797 additions and 765 deletions

View File

@@ -31,6 +31,7 @@ const (
gateioCancelAllOrders = "private/cancelAllOrders"
gateioWithdraw = "private/withdraw"
gateioOpenOrders = "private/openOrders"
gateioTradeHistory = "private/tradeHistory"
gateioDepositAddress = "private/depositAddress"
gateioTicker = "ticker"
gateioTickers = "tickers"
@@ -428,8 +429,7 @@ func (g *Gateio) CancelAllExistingOrders(orderType int64, symbol string) error {
return nil
}
//
// GetOpenOrders retrieves all orders with an optional symbol filter
// GetOpenOrders retrieves all open orders with an optional symbol filter
func (g *Gateio) GetOpenOrders(symbol string) (OpenOrdersResponse, error) {
var params string
var result OpenOrdersResponse
@@ -450,6 +450,24 @@ func (g *Gateio) GetOpenOrders(symbol string) (OpenOrdersResponse, error) {
return result, nil
}
// GetTradeHistory retrieves all orders with an optional symbol filter
func (g *Gateio) GetTradeHistory(symbol string) (TradHistoryResponse, error) {
var params string
var result TradHistoryResponse
params = fmt.Sprintf("currencyPair=%s", symbol)
err := g.SendAuthenticatedHTTPRequest("POST", gateioTradeHistory, params, &result)
if err != nil {
return result, err
}
if result.Code > 0 {
return result, fmt.Errorf("code:%d message:%s", result.Code, result.Message)
}
return result, nil
}
// SendAuthenticatedHTTPRequest sends authenticated requests to the Gateio API
// To use this you must setup an APIKey and APISecret from the exchange
func (g *Gateio) SendAuthenticatedHTTPRequest(method, endpoint, param string, result interface{}) error {

View File

@@ -31,7 +31,6 @@ func TestSetup(t *testing.T) {
if err != nil {
t.Error("Test Failed - GateIO Setup() init error")
}
gateioConfig.AuthenticatedAPISupport = true
gateioConfig.APIKey = apiKey
gateioConfig.APISecret = apiSecret
@@ -240,17 +239,52 @@ func TestGetFee(t *testing.T) {
}
func TestFormatWithdrawPermissions(t *testing.T) {
// Arrange
g.SetDefaults()
expectedResult := exchange.AutoWithdrawCryptoText + " & " + exchange.NoFiatWithdrawalsText
// Act
withdrawPermissions := g.FormatWithdrawPermissions()
// Assert
if withdrawPermissions != expectedResult {
t.Errorf("Expected: %s, Received: %s", expectedResult, withdrawPermissions)
}
}
func TestGetActiveOrders(t *testing.T) {
g.SetDefaults()
TestSetup(t)
var getOrdersRequest = exchange.GetOrdersRequest{
OrderType: exchange.AnyOrderType,
}
_, err := g.GetActiveOrders(getOrdersRequest)
if areTestAPIKeysSet() && err != nil {
t.Errorf("Could not get open orders: %s", err)
} else if !areTestAPIKeysSet() && err == nil {
t.Error("Expecting an error when no keys are set")
}
}
func TestGetOrderHistory(t *testing.T) {
g.SetDefaults()
TestSetup(t)
var getOrdersRequest = exchange.GetOrdersRequest{
OrderType: exchange.AnyOrderType,
}
currPair := pair.NewCurrencyPair(symbol.LTC, symbol.BTC)
currPair.Delimiter = "_"
getOrdersRequest.Currencies = []pair.CurrencyPair{currPair}
_, err := g.GetOrderHistory(getOrdersRequest)
if areTestAPIKeysSet() && err != nil {
t.Errorf("Could not get order history: %s", err)
} else if !areTestAPIKeysSet() && err == nil {
t.Error("Expecting an error when no keys are set")
}
}
// Any tests below this line have the ability to impact your orders on the exchange. Enable canManipulateRealOrders to run them
// ----------------------------------------------------------------------------------------------------------------------------
func areTestAPIKeysSet() bool {
@@ -274,7 +308,7 @@ func TestSubmitOrder(t *testing.T) {
FirstCurrency: symbol.LTC,
SecondCurrency: symbol.BTC,
}
response, err := g.SubmitOrder(p, exchange.Buy, exchange.Market, 1, 10, "1234234")
response, err := g.SubmitOrder(p, exchange.BuyOrderSide, exchange.MarketOrderType, 1, 10, "1234234")
if areTestAPIKeysSet() && (err != nil || !response.IsOrderPlaced) {
t.Errorf("Order failed to be placed: %v", err)
} else if !areTestAPIKeysSet() && err == nil {
@@ -283,7 +317,6 @@ func TestSubmitOrder(t *testing.T) {
}
func TestCancelExchangeOrder(t *testing.T) {
// Arrange
g.SetDefaults()
TestSetup(t)
@@ -300,12 +333,9 @@ func TestCancelExchangeOrder(t *testing.T) {
CurrencyPair: currencyPair,
}
// Act
err := g.CancelOrder(orderCancellation)
// Assert
if !areTestAPIKeysSet() && err == nil {
t.Errorf("Expecting an error when no keys are set: %v", err)
t.Error("Expecting an error when no keys are set")
}
if areTestAPIKeysSet() && err != nil {
t.Errorf("Could not cancel orders: %v", err)
@@ -313,7 +343,6 @@ func TestCancelExchangeOrder(t *testing.T) {
}
func TestCancelAllExchangeOrders(t *testing.T) {
// Arrange
g.SetDefaults()
TestSetup(t)
@@ -330,12 +359,10 @@ func TestCancelAllExchangeOrders(t *testing.T) {
CurrencyPair: currencyPair,
}
// Act
resp, err := g.CancelAllOrders(orderCancellation)
// Assert
if !areTestAPIKeysSet() && err == nil {
t.Errorf("Expecting an error when no keys are set: %v", err)
t.Error("Expecting an error when no keys are set")
}
if areTestAPIKeysSet() && err != nil {
t.Errorf("Could not cancel orders: %v", err)
@@ -383,7 +410,7 @@ func TestWithdraw(t *testing.T) {
_, err := g.WithdrawCryptocurrencyFunds(withdrawCryptoRequest)
if !areTestAPIKeysSet() && err == nil {
t.Errorf("Expecting an error when no keys are set: %v", err)
t.Error("Expecting an error when no keys are set")
}
if areTestAPIKeysSet() && err != nil {
t.Errorf("Withdraw failed to be placed: %v", err)

View File

@@ -142,20 +142,41 @@ type OpenOrdersResponse struct {
// OpenOrder details each open order
type OpenOrder struct {
Amount string `json:"amount"`
Amount float64 `json:"amount,string"`
CurrencyPair string `json:"currencyPair"`
FilledAmount int `json:"filledAmount"`
FilledRate int `json:"filledRate"`
InitialAmount string `json:"initialAmount"`
FilledAmount float64 `json:"filledAmount,string"`
FilledRate float64 `json:"filledRate"`
InitialAmount float64 `json:"initialAmount"`
InitialRate float64 `json:"initialRate"`
OrderNumber string `json:"orderNumber"`
Rate float64 `json:"rate"`
Status string `json:"status"`
Timestamp string `json:"timestamp"`
Total string `json:"total"`
Timestamp int64 `json:"timestamp"`
Total float64 `json:"total,string"`
Type string `json:"type"`
}
// TradHistoryResponse The full response for retrieving all user trade history
type TradHistoryResponse struct {
Code int `json:"code,omitempty"`
Elapsed string `json:"elapsed,omitempty"`
Message string `json:"message"`
Trades []TradesResponse `json:"trades"`
Result string `json:"result"`
}
// TradesResponse details trade history
type TradesResponse struct {
ID string `json:"id"`
OrderID string `json:"orderid"`
Pair string `json:"pair"`
Type string `json:"type"`
Rate float64 `json:"rate,string"`
Amount float64 `json:"amount,string"`
Time string `json:"time"`
TimeUnix int64 `json:"time_unix,string"`
}
// WithdrawalFees the large list of predefined withdrawal fees
// Prone to change
var WithdrawalFees = map[string]float64{

View File

@@ -4,6 +4,7 @@ import (
"errors"
"fmt"
"strconv"
"strings"
"sync"
"time"
@@ -191,7 +192,7 @@ func (g *Gateio) SubmitOrder(p pair.CurrencyPair, side exchange.OrderSide, order
var submitOrderResponse exchange.SubmitOrderResponse
var orderTypeFormat SpotNewOrderRequestParamsType
if side == exchange.Buy {
if side == exchange.BuyOrderSide {
orderTypeFormat = SpotNewOrderRequestParamsTypeBuy
} else {
orderTypeFormat = SpotNewOrderRequestParamsTypeSell
@@ -319,3 +320,77 @@ func (g *Gateio) GetFeeByType(feeBuilder exchange.FeeBuilder) (float64, error) {
func (g *Gateio) GetWithdrawCapabilities() uint32 {
return g.GetWithdrawPermissions()
}
// GetActiveOrders retrieves any orders that are active/open
func (g *Gateio) GetActiveOrders(getOrdersRequest exchange.GetOrdersRequest) ([]exchange.OrderDetail, error) {
var currPair string
if len(getOrdersRequest.Currencies) == 1 {
currPair = getOrdersRequest.Currencies[0].Pair().String()
}
resp, err := g.GetOpenOrders(currPair)
if err != nil {
return nil, err
}
var orders []exchange.OrderDetail
for _, order := range resp.Orders {
if order.Status != "open" {
continue
}
symbol := pair.NewCurrencyPairDelimiter(order.CurrencyPair, g.ConfigCurrencyPairFormat.Delimiter)
side := exchange.OrderSide(strings.ToUpper(order.Type))
orderDate := time.Unix(order.Timestamp, 0)
orders = append(orders, exchange.OrderDetail{
ID: order.OrderNumber,
Amount: order.Amount,
Price: order.Rate,
RemainingAmount: order.FilledAmount,
OrderDate: orderDate,
OrderSide: side,
Exchange: g.Name,
CurrencyPair: symbol,
})
}
exchange.FilterOrdersByTickRange(&orders, getOrdersRequest.StartTicks, getOrdersRequest.EndTicks)
exchange.FilterOrdersBySide(&orders, getOrdersRequest.OrderSide)
return orders, nil
}
// GetOrderHistory retrieves account order information
// Can Limit response to specific order status
func (g *Gateio) GetOrderHistory(getOrdersRequest exchange.GetOrdersRequest) ([]exchange.OrderDetail, error) {
var trades []TradesResponse
for _, currency := range getOrdersRequest.Currencies {
resp, err := g.GetTradeHistory(currency.Pair().String())
if err != nil {
return nil, err
}
trades = append(trades, resp.Trades...)
}
var orders []exchange.OrderDetail
for _, trade := range trades {
symbol := pair.NewCurrencyPairDelimiter(trade.Pair, g.ConfigCurrencyPairFormat.Delimiter)
side := exchange.OrderSide(strings.ToUpper(trade.Type))
orderDate := time.Unix(trade.TimeUnix, 0)
orders = append(orders, exchange.OrderDetail{
ID: trade.OrderID,
Amount: trade.Amount,
Price: trade.Rate,
OrderDate: orderDate,
OrderSide: side,
Exchange: g.Name,
CurrencyPair: symbol,
})
}
exchange.FilterOrdersByTickRange(&orders, getOrdersRequest.StartTicks, getOrdersRequest.EndTicks)
exchange.FilterOrdersBySide(&orders, getOrdersRequest.OrderSide)
return orders, nil
}