Skip to content

Commit

Permalink
GetActiveOrders/GetOrderHistory wrapper implementation (thrasher-corp…
Browse files Browse the repository at this point in the history
…#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
  • Loading branch information
gloriousCode authored and thrasher- committed Feb 4, 2019
1 parent 82a6222 commit 978b91a
Show file tree
Hide file tree
Showing 105 changed files with 4,797 additions and 765 deletions.
2 changes: 0 additions & 2 deletions communications/slack/slack_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,6 @@ func TestBuildURL(t *testing.T) {
}

func TestGetChannelsString(t *testing.T) {

s.Details.Channels = append(s.Details.Channels, struct {
Created int `json:"created"`
Creator string `json:"creator"`
Expand Down Expand Up @@ -315,7 +314,6 @@ func TestHandleHelloResponse(t *testing.T) {
}

func TestHandleReconnectResponse(t *testing.T) {

err := s.handleReconnectResponse([]byte(`{"malformedjson}`))
if err == nil {
t.Error("test failed - slack handleReconnectResponse(), unmarshalled malformed json")
Expand Down
9 changes: 9 additions & 0 deletions currency/pair/pair.go
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,15 @@ func NewCurrencyPair(firstCurrency, secondCurrency string) CurrencyPair {
}
}

// NewCurrencyPairWithDelimiter returns a CurrencyPair with a delimiter
func NewCurrencyPairWithDelimiter(firstCurrency, secondCurrency, delimiter string) CurrencyPair {
return CurrencyPair{
FirstCurrency: CurrencyItem(firstCurrency),
SecondCurrency: CurrencyItem(secondCurrency),
Delimiter: delimiter,
}
}

// NewCurrencyPairFromIndex returns a CurrencyPair via a currency string and
// specific index
func NewCurrencyPairFromIndex(currency, index string) CurrencyPair {
Expand Down
23 changes: 23 additions & 0 deletions currency/pair/pair_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,29 @@ func TestNewCurrencyPair(t *testing.T) {
}
}

func TestNewCurrencyPairWithDelimiter(t *testing.T) {
t.Parallel()
pair := NewCurrencyPairWithDelimiter("BTC", "USD", "-test-")
actual := pair.Pair()
expected := CurrencyItem("BTC-test-USD")
if actual != expected {
t.Errorf(
"Test failed. Pair(): %s was not equal to expected value: %s",
actual, expected,
)
}

pair = NewCurrencyPairWithDelimiter("BTC", "USD", "")
actual = pair.Pair()
expected = CurrencyItem("BTCUSD")
if actual != expected {
t.Errorf(
"Test failed. Pair(): %s was not equal to expected value: %s",
actual, expected,
)
}
}

func TestNewCurrencyPairDelimiter(t *testing.T) {
t.Parallel()
pair := NewCurrencyPairDelimiter("BTC-USD", "-")
Expand Down
2 changes: 1 addition & 1 deletion exchanges/alphapoint/alphapoint.go
Original file line number Diff line number Diff line change
Expand Up @@ -361,7 +361,7 @@ func (a *Alphapoint) WithdrawCoins(symbol, product, address string, amount float
}

func (a *Alphapoint) convertOrderTypeToOrderTypeNumber(orderType string) (orderTypeNumber int64) {
if orderType == exchange.Market.ToString() {
if orderType == exchange.MarketOrderType.ToString() {
orderTypeNumber = 1
}

Expand Down
56 changes: 41 additions & 15 deletions exchanges/alphapoint/alphapoint_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -413,7 +413,7 @@ func TestCreateOrder(t *testing.T) {
return
}

_, err := a.CreateOrder("", "", exchange.Market.ToString(), 0.01, 0)
_, err := a.CreateOrder("", "", exchange.MarketOrderType.ToString(), 0.01, 0)
if err == nil {
t.Error("Test Failed - GetUserInfo() error")
}
Expand Down Expand Up @@ -480,18 +480,49 @@ func TestGetOrderFee(t *testing.T) {
}

func TestFormatWithdrawPermissions(t *testing.T) {
// Arrange
a := &Alphapoint{}
a.SetDefaults()
expectedResult := exchange.AutoWithdrawCryptoWithAPIPermissionText + " & " + exchange.WithdrawCryptoWith2FAText + " & " + exchange.NoFiatWithdrawalsText
// Act

withdrawPermissions := a.FormatWithdrawPermissions()
// Assert

if withdrawPermissions != expectedResult {
t.Errorf("Expected: %s, Received: %s", expectedResult, withdrawPermissions)
}
}

func TestGetActiveOrders(t *testing.T) {
a := &Alphapoint{}
a.SetDefaults()

var getOrdersRequest = exchange.GetOrdersRequest{
OrderType: exchange.AnyOrderType,
}

_, err := a.GetActiveOrders(getOrdersRequest)
if areTestAPIKeysSet(a) && err != nil {
t.Errorf("Could not get open orders: %s", err)
} else if !areTestAPIKeysSet(a) && err == nil {
t.Error("Expecting an error when no keys are set")
}
}

func TestGetOrderHistory(t *testing.T) {
a := &Alphapoint{}
a.SetDefaults()

var getOrdersRequest = exchange.GetOrdersRequest{
OrderType: exchange.AnyOrderType,
}

_, err := a.GetOrderHistory(getOrdersRequest)
if areTestAPIKeysSet(a) && err != nil {
t.Errorf("Could not get order history: %s", err)
} else if !areTestAPIKeysSet(a) && 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
// ----------------------------------------------------------------------------------------------------------------------------

Expand All @@ -515,9 +546,9 @@ func TestSubmitOrder(t *testing.T) {
FirstCurrency: symbol.BTC,
SecondCurrency: symbol.USD,
}
response, err := a.SubmitOrder(p, exchange.Buy, exchange.Market, 1, 1, "clientId")
response, err := a.SubmitOrder(p, exchange.BuyOrderSide, exchange.MarketOrderType, 1, 1, "clientId")
if !areTestAPIKeysSet(a) && 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(a) && err != nil {
t.Errorf("Withdraw failed to be placed: %v", err)
Expand All @@ -529,7 +560,6 @@ func TestSubmitOrder(t *testing.T) {
}

func TestCancelExchangeOrder(t *testing.T) {
// Arrange
a := &Alphapoint{}
a.SetDefaults()

Expand All @@ -545,20 +575,17 @@ func TestCancelExchangeOrder(t *testing.T) {
AccountID: "1",
CurrencyPair: currencyPair,
}
// Act
err := a.CancelOrder(orderCancellation)

// Assert
err := a.CancelOrder(orderCancellation)
if !areTestAPIKeysSet(a) && 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(a) && err != nil {
t.Errorf("Withdraw failed to be placed: %v", err)
}
}

func TestCancelAllExchangeOrders(t *testing.T) {
// Arrange
a := &Alphapoint{}
a.SetDefaults()

Expand All @@ -574,12 +601,11 @@ func TestCancelAllExchangeOrders(t *testing.T) {
AccountID: "1",
CurrencyPair: currencyPair,
}
// Act

resp, err := a.CancelAllOrders(orderCancellation)

// Assert
if !areTestAPIKeysSet(a) && 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(a) && err != nil {
t.Errorf("Withdraw failed to be placed: %v", err)
Expand Down
34 changes: 26 additions & 8 deletions exchanges/alphapoint/alphapoint_types.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package alphapoint

import exchange "github.com/thrasher-/gocryptotrader/exchanges"

// Response contains general responses from the exchange
type Response struct {
IsAccepted bool `json:"isAccepted"`
Expand Down Expand Up @@ -144,19 +146,21 @@ type AccountInfo struct {

// Order is a generalised order type
type Order struct {
Serverorderid int `json:"ServerOrderId"`
AccountID int `json:"AccountId"`
Price int `json:"Price"`
QtyTotal int `json:"QtyTotal"`
QtyRemaining int `json:"QtyRemaining"`
ReceiveTime int64 `json:"ReceiveTime"`
Side int `json:"Side"`
ServerOrderID int `json:"ServerOrderId"`
AccountID int `json:"AccountId"`
Price float64 `json:"Price"`
QtyTotal float64 `json:"QtyTotal"`
QtyRemaining float64 `json:"QtyRemaining"`
ReceiveTime int64 `json:"ReceiveTime"`
Side int64 `json:"Side"`
State int `json:"orderState"`
OrderType int `json:"orderType"`
}

// OpenOrders holds the full range of orders by instrument
type OpenOrders struct {
Instrument string `json:"ins"`
Openorders []Order `json:"openOrders"`
OpenOrders []Order `json:"openOrders"`
}

// OrderInfo holds all open orders across the entire range of all instruments
Expand Down Expand Up @@ -192,3 +196,17 @@ type WebsocketTicker struct {
BuyOrderCount int `json:"buyOrderCount"`
SellOrderCount int `json:"sellOrderCount"`
}

// orderSideMap holds order type info based on Alphapoint data
var orderSideMap = map[int64]exchange.OrderSide{
1: exchange.BuyOrderSide,
2: exchange.SellOrderSide,
}

// orderTypeMap holds order type info based on Alphapoint data
var orderTypeMap = map[int]exchange.OrderType{
1: exchange.MarketOrderType,
2: exchange.LimitOrderType,
3: exchange.StopOrderType,
6: exchange.TrailingStopOrderType,
}
92 changes: 89 additions & 3 deletions exchanges/alphapoint/alphapoint_wrapper.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"errors"
"fmt"
"strconv"
"time"

"github.com/thrasher-/gocryptotrader/common"
"github.com/thrasher-/gocryptotrader/currency/pair"
Expand Down Expand Up @@ -161,9 +162,9 @@ func (a *Alphapoint) GetOrderInfo(orderID int64) (float64, error) {
}

for x := range orders {
for y := range orders[x].Openorders {
if int64(orders[x].Openorders[y].Serverorderid) == orderID {
return float64(orders[x].Openorders[y].QtyRemaining), nil
for y := range orders[x].OpenOrders {
if int64(orders[x].OpenOrders[y].ServerOrderID) == orderID {
return float64(orders[x].OpenOrders[y].QtyRemaining), nil
}
}
}
Expand Down Expand Up @@ -216,3 +217,88 @@ func (a *Alphapoint) GetFeeByType(feeBuilder exchange.FeeBuilder) (float64, erro
func (a *Alphapoint) GetWithdrawCapabilities() uint32 {
return a.GetWithdrawPermissions()
}

// GetActiveOrders retrieves any orders that are active/open
// This function is not concurrency safe due to orderSide/orderType maps
func (a *Alphapoint) GetActiveOrders(getOrdersRequest exchange.GetOrdersRequest) ([]exchange.OrderDetail, error) {
resp, err := a.GetOrders()
if err != nil {
return nil, err
}

var orders []exchange.OrderDetail
for x := range resp {
for _, order := range resp[x].OpenOrders {
if order.State != 1 {
continue
}

orderDetail := exchange.OrderDetail{
Amount: float64(order.QtyTotal),
Exchange: a.Name,
AccountID: fmt.Sprintf("%v", order.AccountID),
ID: fmt.Sprintf("%v", order.ServerOrderID),
Price: float64(order.Price),
RemainingAmount: float64(order.QtyRemaining),
}

orderDetail.OrderSide = orderSideMap[order.Side]
orderDetail.OrderDate = time.Unix(order.ReceiveTime, 0)
orderDetail.OrderType = orderTypeMap[order.OrderType]
if orderDetail.OrderType == "" {
orderDetail.OrderType = exchange.UnknownOrderType
}

orders = append(orders, orderDetail)
}
}

exchange.FilterOrdersByType(&orders, getOrdersRequest.OrderType)
exchange.FilterOrdersBySide(&orders, getOrdersRequest.OrderSide)
exchange.FilterOrdersByTickRange(&orders, getOrdersRequest.StartTicks, getOrdersRequest.EndTicks)

return orders, nil
}

// GetOrderHistory retrieves account order information
// Can Limit response to specific order status
// This function is not concurrency safe due to orderSide/orderType maps
func (a *Alphapoint) GetOrderHistory(getOrdersRequest exchange.GetOrdersRequest) ([]exchange.OrderDetail, error) {
resp, err := a.GetOrders()
if err != nil {
return nil, err
}

var orders []exchange.OrderDetail
for x := range resp {
for _, order := range resp[x].OpenOrders {
if order.State == 1 {
continue
}

orderDetail := exchange.OrderDetail{
Amount: float64(order.QtyTotal),
AccountID: fmt.Sprintf("%v", order.AccountID),
Exchange: a.Name,
ID: fmt.Sprintf("%v", order.ServerOrderID),
Price: float64(order.Price),
RemainingAmount: float64(order.QtyRemaining),
}

orderDetail.OrderSide = orderSideMap[order.Side]
orderDetail.OrderDate = time.Unix(order.ReceiveTime, 0)
orderDetail.OrderType = orderTypeMap[order.OrderType]
if orderDetail.OrderType == "" {
orderDetail.OrderType = exchange.UnknownOrderType
}

orders = append(orders, orderDetail)
}
}

exchange.FilterOrdersByType(&orders, getOrdersRequest.OrderType)
exchange.FilterOrdersBySide(&orders, getOrdersRequest.OrderSide)
exchange.FilterOrdersByTickRange(&orders, getOrdersRequest.StartTicks, getOrdersRequest.EndTicks)

return orders, nil
}
Loading

0 comments on commit 978b91a

Please sign in to comment.