mirror of
https://github.com/d0zingcat/gocryptotrader.git
synced 2026-06-09 15:11:10 +00:00
Utilising authenticated websocket functions in exchange wrappers (#384)
* Basic concept commit * Initial changes to support bitfinex v2. Reverts linter changes as they suck. Exports bitfinex ws types * Adds ticker, trade and orderbook support * Candles sub that returns no data COMPLETE * Adds authenticated ws support * Adds the barebones endpoints to support * Adds more endpoints * Even more endpoints * minicommit to switch and test * All the interactive types * Adds support for simultaneous connections. Updates tests. Nothing is working * Successfully adds place order. Moves all authenticated endpoints to new switch case * Cancel order and modify order * Cancel all orders, cancel multi orders * Finalises implementation. Uses testMain * Adds WS wrapper support for some funcs * Fixing rebasing issues * Replaces use of currency as a variable. Updates a lot of coinut websocket auth endpoint stuff * Fixes some fun for loops with GetEnabledPairs * Fixes tests impacted by currency var change * Adds coinut support for WS functions. Replaces `order` vars with `ord`. Fixes some for loops too. Removes verbose from bitfinex * So many panics * I'm fixing a hole, where the panics get in, and stops my mind from wandering, where it will go * Moves func `CanUseAuthenticatedWebsocketEndpoint` to Websocket package as it fits better. Adds test coverage of `CanUseAuthenticatedWebsocketEndpoint` * Finishes up all of coinuts ws implementations. * GateIO implementation * Adds some helper funcs for types, sides and status. Adds support for huobi. Removes unnecessary type * Adds forgotten huobi endpoint * Fixes cancel order endpoint * go hates my formatting and so do I * The process to get authenticated kraken websocket to work. Uses testmain. Adds new auth channel, auth subscriptions, auth data handling. Not working yet * Finishes open orders handling * Mini update for status only updates * Fixes some kraken points * Finishes WS kraken since it doesn't work * Unfinished commit, cleaning up types * Finishes the const replacing * Fixes extra GetNAmes after rebase * An end to the cleanup. testmain for gateio * Adds ZB support * Bitfinex cleanup. Renamed func * Testmain-47s for everyone!!! yayaaaaaaa * Adds kraken websocket wrapper support * Fixes rebase issues * Fixes tests from rebase * Adds test for conversion. Fixes for loop. Updates test order pricing. Fixes some poor made tests. Adds proper error handling for ws responses instead of logging them. Fixed issue where commented code ruined kraken ws. * Fixes secret linting issues. Prioritises bitfinex channelID responses over authorised * Fixes sloppy error/var declarations * Fixes crazy bad logic where submit order errors weren't really considered. Parralols alphapoint/alphapoint_test.go. Removes buffer for multi-websocket comms channel. * Removal of inline string and removal of redundant nil checkerinos * Fixes err checks. Checks whether float has decimal. Fixes append. Drops omitempties. Parallel to some tests. Moves var declarations * Replaces my lazy sprintfs with strconv.FormatInt(time.Now().Unix(), 10) * Adds shiny new FullyMatched bool. Fixes coinbene buy sell consts * Fixes oopsie with coinbene const replacement * Fixes currency issue * Cleans up new places that use JSONDecode * Fixes huge panic bug from string int conversion. Adds large testtable for strings to order types * Fixes some more strconversion issues. Fixes table test var usage. Changes mapperino name * Added some new scenarios for number splitting * Fixes lint issues * negative num fix * Typo fix * Accuracy warning comment
This commit is contained in:
@@ -423,10 +423,10 @@ func (z *ZB) Withdraw(currency, address, safepassword string, amount, fees float
|
||||
|
||||
vals := url.Values{}
|
||||
vals.Set("accesskey", z.API.Credentials.Key)
|
||||
vals.Set("amount", fmt.Sprintf("%v", amount))
|
||||
vals.Set("amount", strconv.FormatFloat(amount, 'f', -1, 64))
|
||||
vals.Set("currency", currency)
|
||||
vals.Set("fees", fmt.Sprintf("%v", fees))
|
||||
vals.Set("itransfer", fmt.Sprintf("%v", itransfer))
|
||||
vals.Set("fees", strconv.FormatFloat(fees, 'f', -1, 64))
|
||||
vals.Set("itransfer", strconv.FormatBool(itransfer))
|
||||
vals.Set("method", "withdraw")
|
||||
vals.Set("recieveAddr", address)
|
||||
vals.Set("safePwd", safepassword)
|
||||
|
||||
@@ -3,7 +3,10 @@ package zb
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"strconv"
|
||||
"testing"
|
||||
|
||||
"github.com/gorilla/websocket"
|
||||
@@ -25,19 +28,16 @@ const (
|
||||
var z ZB
|
||||
var wsSetupRan bool
|
||||
|
||||
func TestSetDefaults(t *testing.T) {
|
||||
func TestMain(m *testing.M) {
|
||||
z.SetDefaults()
|
||||
}
|
||||
|
||||
func TestSetup(t *testing.T) {
|
||||
cfg := config.GetConfig()
|
||||
err := cfg.LoadConfig("../../testdata/configtest.json", true)
|
||||
if err != nil {
|
||||
t.Fatal("ZB load config error", err)
|
||||
log.Fatal("ZB load config error", err)
|
||||
}
|
||||
zbConfig, err := cfg.GetExchangeConfig("ZB")
|
||||
if err != nil {
|
||||
t.Fatal("ZB Setup() init error", err)
|
||||
log.Fatal("ZB Setup() init error", err)
|
||||
}
|
||||
zbConfig.API.AuthenticatedSupport = true
|
||||
zbConfig.API.AuthenticatedWebsocketSupport = true
|
||||
@@ -46,16 +46,16 @@ func TestSetup(t *testing.T) {
|
||||
|
||||
err = z.Setup(zbConfig)
|
||||
if err != nil {
|
||||
t.Fatal("ZB setup error", err)
|
||||
log.Fatal("ZB setup error", err)
|
||||
}
|
||||
|
||||
os.Exit(m.Run())
|
||||
}
|
||||
|
||||
func setupWsAuth(t *testing.T) {
|
||||
if wsSetupRan {
|
||||
return
|
||||
}
|
||||
z.SetDefaults()
|
||||
TestSetup(t)
|
||||
if !z.Websocket.IsEnabled() && !z.API.AuthenticatedWebsocketSupport || !areTestAPIKeysSet() || !canManipulateRealOrders {
|
||||
t.Skip(wshandler.WebsocketNotEnabled)
|
||||
}
|
||||
@@ -90,11 +90,9 @@ func TestSpotNewOrder(t *testing.T) {
|
||||
Amount: 0.01,
|
||||
Price: 10246.1,
|
||||
}
|
||||
orderid, err := z.SpotNewOrder(arg)
|
||||
_, err := z.SpotNewOrder(arg)
|
||||
if err != nil {
|
||||
t.Errorf("ZB SpotNewOrder: %s", err)
|
||||
} else {
|
||||
t.Log(orderid)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -182,7 +180,7 @@ func setFeeBuilder() *exchange.FeeBuilder {
|
||||
func TestGetFeeByTypeOfflineTradeFee(t *testing.T) {
|
||||
var feeBuilder = setFeeBuilder()
|
||||
z.GetFeeByType(feeBuilder)
|
||||
if apiKey == "" || apiSecret == "" {
|
||||
if !areTestAPIKeysSet() {
|
||||
if feeBuilder.FeeType != exchange.OfflineTradeFee {
|
||||
t.Errorf("Expected %v, received %v", exchange.OfflineTradeFee, feeBuilder.FeeType)
|
||||
}
|
||||
@@ -194,8 +192,6 @@ func TestGetFeeByTypeOfflineTradeFee(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestGetFee(t *testing.T) {
|
||||
z.SetDefaults()
|
||||
TestSetup(t)
|
||||
var feeBuilder = setFeeBuilder()
|
||||
|
||||
// CryptocurrencyTradeFee Basic
|
||||
@@ -272,20 +268,14 @@ func TestGetFee(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestFormatWithdrawPermissions(t *testing.T) {
|
||||
z.SetDefaults()
|
||||
expectedResult := exchange.AutoWithdrawCryptoText + " & " + exchange.NoFiatWithdrawalsText
|
||||
|
||||
withdrawPermissions := z.FormatWithdrawPermissions()
|
||||
|
||||
if withdrawPermissions != expectedResult {
|
||||
t.Errorf("Expected: %s, Received: %s", expectedResult, withdrawPermissions)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetActiveOrders(t *testing.T) {
|
||||
z.SetDefaults()
|
||||
TestSetup(t)
|
||||
|
||||
var getOrdersRequest = order.GetOrdersRequest{
|
||||
OrderType: order.AnyType,
|
||||
Currencies: []currency.Pair{currency.NewPair(currency.XRP,
|
||||
@@ -301,9 +291,6 @@ func TestGetActiveOrders(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestGetOrderHistory(t *testing.T) {
|
||||
z.SetDefaults()
|
||||
TestSetup(t)
|
||||
|
||||
var getOrdersRequest = order.GetOrdersRequest{
|
||||
OrderType: order.AnyType,
|
||||
OrderSide: order.Buy,
|
||||
@@ -326,9 +313,6 @@ func areTestAPIKeysSet() bool {
|
||||
}
|
||||
|
||||
func TestSubmitOrder(t *testing.T) {
|
||||
z.SetDefaults()
|
||||
TestSetup(t)
|
||||
|
||||
if areTestAPIKeysSet() && !canManipulateRealOrders {
|
||||
t.Skip(fmt.Sprintf("ApiKey: %s. Can place orders: %v",
|
||||
z.API.Credentials.Key,
|
||||
@@ -356,15 +340,11 @@ func TestSubmitOrder(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestCancelExchangeOrder(t *testing.T) {
|
||||
z.SetDefaults()
|
||||
TestSetup(t)
|
||||
|
||||
if areTestAPIKeysSet() && !canManipulateRealOrders {
|
||||
t.Skip("API keys set, canManipulateRealOrders false, skipping test")
|
||||
}
|
||||
|
||||
currencyPair := currency.NewPair(currency.XRP, currency.USDT)
|
||||
|
||||
var orderCancellation = &order.Cancel{
|
||||
OrderID: "1",
|
||||
WalletAddress: "1F5zVDgNjorJ51oGebSvNCrSAHpwGkUdDB",
|
||||
@@ -382,15 +362,11 @@ func TestCancelExchangeOrder(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestCancelAllExchangeOrders(t *testing.T) {
|
||||
z.SetDefaults()
|
||||
TestSetup(t)
|
||||
|
||||
if areTestAPIKeysSet() && !canManipulateRealOrders {
|
||||
t.Skip("API keys set, canManipulateRealOrders false, skipping test")
|
||||
}
|
||||
|
||||
currencyPair := currency.NewPair(currency.XRP, currency.USDT)
|
||||
|
||||
var orderCancellation = &order.Cancel{
|
||||
OrderID: "1",
|
||||
WalletAddress: "1F5zVDgNjorJ51oGebSvNCrSAHpwGkUdDB",
|
||||
@@ -427,6 +403,9 @@ func TestGetAccountInfo(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestModifyOrder(t *testing.T) {
|
||||
if areTestAPIKeysSet() && !canManipulateRealOrders {
|
||||
t.Skip("API keys set, canManipulateRealOrders false, skipping test")
|
||||
}
|
||||
_, err := z.ModifyOrder(&order.Modify{})
|
||||
if err == nil {
|
||||
t.Error("ModifyOrder() Expected error")
|
||||
@@ -434,8 +413,6 @@ func TestModifyOrder(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestWithdraw(t *testing.T) {
|
||||
z.SetDefaults()
|
||||
TestSetup(t)
|
||||
withdrawCryptoRequest := exchange.CryptoWithdrawRequest{
|
||||
GenericWithdrawRequestInfo: exchange.GenericWithdrawRequestInfo{
|
||||
Amount: -1,
|
||||
@@ -460,9 +437,6 @@ func TestWithdraw(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestWithdrawFiat(t *testing.T) {
|
||||
z.SetDefaults()
|
||||
TestSetup(t)
|
||||
|
||||
if areTestAPIKeysSet() && !canManipulateRealOrders {
|
||||
t.Skip("API keys set, canManipulateRealOrders false, skipping test")
|
||||
}
|
||||
@@ -475,9 +449,6 @@ func TestWithdrawFiat(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestWithdrawInternationalBank(t *testing.T) {
|
||||
z.SetDefaults()
|
||||
TestSetup(t)
|
||||
|
||||
if areTestAPIKeysSet() && !canManipulateRealOrders {
|
||||
t.Skip("API keys set, canManipulateRealOrders false, skipping test")
|
||||
}
|
||||
@@ -490,7 +461,7 @@ func TestWithdrawInternationalBank(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestGetDepositAddress(t *testing.T) {
|
||||
if apiKey != "" || apiSecret != "" {
|
||||
if areTestAPIKeysSet() {
|
||||
_, err := z.GetDepositAddress(currency.BTC, "")
|
||||
if err != nil {
|
||||
t.Error("GetDepositAddress() error PLEASE MAKE SURE YOU CREATE DEPOSIT ADDRESSES VIA ZB.COM",
|
||||
@@ -548,7 +519,7 @@ func TestWsCreateSuUserKey(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
userID := subUsers.Message[0].UserID
|
||||
_, err = z.wsCreateSubUserKey(true, true, true, true, "subu", fmt.Sprintf("%v", userID))
|
||||
_, err = z.wsCreateSubUserKey(true, true, true, true, "subu", strconv.FormatInt(userID, 10))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
@@ -16,7 +16,7 @@ type OrderbookResponse struct {
|
||||
|
||||
// AccountsResponseCoin holds the accounts coin details
|
||||
type AccountsResponseCoin struct {
|
||||
Freez string `json:"freez"` // 冻结资产
|
||||
Freeze string `json:"freez"` // 冻结资产
|
||||
EnName string `json:"enName"` // 币种英文名
|
||||
UnitDecimal int `json:"unitDecimal"` // 保留小数位
|
||||
UnName string `json:"cnName"` // 币种中文名
|
||||
@@ -44,6 +44,9 @@ type Order struct {
|
||||
TradeDate int `json:"trade_date"`
|
||||
TradeMoney float64 `json:"trade_money"`
|
||||
Type int64 `json:"type"`
|
||||
Fees float64 `json:"fees,omitempty"`
|
||||
TradePrice float64 `json:"trade_price,omitempty"`
|
||||
No int64 `json:"no,string,omitempty"`
|
||||
}
|
||||
|
||||
// AccountsResponse 用户基本信息
|
||||
|
||||
@@ -187,40 +187,6 @@ func (z *ZB) WsHandleData() {
|
||||
}
|
||||
}
|
||||
|
||||
var wsErrCodes = map[int64]string{
|
||||
1000: "Successful call",
|
||||
1001: "General error message",
|
||||
1002: "internal error",
|
||||
1003: "Verification failed",
|
||||
1004: "Financial security password lock",
|
||||
1005: "The fund security password is incorrect. Please confirm and re-enter.",
|
||||
1006: "Real-name certification is awaiting review or review",
|
||||
1007: "Channel is empty",
|
||||
1008: "Event is empty",
|
||||
1009: "This interface is being maintained",
|
||||
1011: "Not open yet",
|
||||
1012: "Insufficient permissions",
|
||||
1013: "Can not trade, if you have any questions, please contact online customer service",
|
||||
1014: "Cannot be sold during the pre-sale period",
|
||||
2002: "Insufficient balance in Bitcoin account",
|
||||
2003: "Insufficient balance of Litecoin account",
|
||||
2005: "Insufficient balance in Ethereum account",
|
||||
2006: "Insufficient balance in ETC currency account",
|
||||
2007: "Insufficient balance of BTS currency account",
|
||||
2008: "Insufficient balance in EOS currency account",
|
||||
2009: "Insufficient account balance",
|
||||
3001: "Pending order not found",
|
||||
3002: "Invalid amount",
|
||||
3003: "Invalid quantity",
|
||||
3004: "User does not exist",
|
||||
3005: "Invalid parameter",
|
||||
3006: "Invalid IP or inconsistent with the bound IP",
|
||||
3007: "Request time has expired",
|
||||
3008: "Transaction history not found",
|
||||
4001: "API interface is locked",
|
||||
4002: "Request too frequently",
|
||||
}
|
||||
|
||||
// GenerateDefaultSubscriptions Adds default subscriptions to websocket to be handled by ManageSubscriptions()
|
||||
func (z *ZB) GenerateDefaultSubscriptions() {
|
||||
var subscriptions []wshandler.WebsocketChannelSubscription
|
||||
|
||||
@@ -191,28 +191,12 @@ type WsGetOrderRequest struct {
|
||||
|
||||
// WsGetOrderResponse contains order data
|
||||
type WsGetOrderResponse struct {
|
||||
Message string `json:"message"`
|
||||
No int64 `json:"no,string"`
|
||||
Code int64 `json:"code"`
|
||||
Channel string `json:"channel"`
|
||||
Success bool `json:"success"`
|
||||
Data WsGetOrderResponseData `json:"data"`
|
||||
}
|
||||
|
||||
// WsGetOrderResponseData Detailed order data
|
||||
type WsGetOrderResponseData struct {
|
||||
Currency string `json:"currency"`
|
||||
Fees float64 `json:"fees"`
|
||||
ID string `json:"id"`
|
||||
Price float64 `json:"price"`
|
||||
Status int64 `json:"status"`
|
||||
TotalAmount float64 `json:"total_amount"`
|
||||
TradeAmount float64 `json:"trade_amount"`
|
||||
TradePrice float64 `json:"trade_price"`
|
||||
TradeDate int64 `json:"trade_date"`
|
||||
TradeMoney float64 `json:"trade_money"`
|
||||
Type int64 `json:"type"`
|
||||
No int64 `json:"no,string"`
|
||||
Message string `json:"message"`
|
||||
No int64 `json:"no,string"`
|
||||
Code int64 `json:"code"`
|
||||
Channel string `json:"channel"`
|
||||
Success bool `json:"success"`
|
||||
Data []Order `json:"data"`
|
||||
}
|
||||
|
||||
// WsGetOrdersRequest get more orders, with no orderID filtering
|
||||
@@ -228,12 +212,12 @@ type WsGetOrdersRequest struct {
|
||||
|
||||
// WsGetOrdersResponse contains orders data
|
||||
type WsGetOrdersResponse struct {
|
||||
Message string `json:"message"`
|
||||
No int64 `json:"no,string"`
|
||||
Code int64 `json:"code"`
|
||||
Channel string `json:"channel"`
|
||||
Success bool `json:"success"`
|
||||
Data []WsGetOrderResponseData `json:"data"`
|
||||
Message string `json:"message"`
|
||||
No int64 `json:"no,string"`
|
||||
Code int64 `json:"code"`
|
||||
Channel string `json:"channel"`
|
||||
Success bool `json:"success"`
|
||||
Data []Order `json:"data"`
|
||||
}
|
||||
|
||||
// WsGetOrdersIgnoreTradeTypeRequest ws request
|
||||
@@ -249,12 +233,12 @@ type WsGetOrdersIgnoreTradeTypeRequest struct {
|
||||
|
||||
// WsGetOrdersIgnoreTradeTypeResponse contains orders data
|
||||
type WsGetOrdersIgnoreTradeTypeResponse struct {
|
||||
Message string `json:"message"`
|
||||
No int64 `json:"no,string"`
|
||||
Code int64 `json:"code"`
|
||||
Channel string `json:"channel"`
|
||||
Success bool `json:"success"`
|
||||
Data []WsGetOrderResponseData `json:"data"`
|
||||
Message string `json:"message"`
|
||||
No int64 `json:"no,string"`
|
||||
Code int64 `json:"code"`
|
||||
Channel string `json:"channel"`
|
||||
Success bool `json:"success"`
|
||||
Data []Order `json:"data"`
|
||||
}
|
||||
|
||||
// WsGetAccountInfoResponse contains account data
|
||||
@@ -262,23 +246,44 @@ type WsGetAccountInfoResponse struct {
|
||||
Message string `json:"message"`
|
||||
No int64 `json:"no,string"`
|
||||
Data struct {
|
||||
Coins []struct {
|
||||
Freez float64 `json:"freez,string"`
|
||||
EnName string `json:"enName"`
|
||||
UnitDecimal int64 `json:"unitDecimal"`
|
||||
CnName string `json:"cnName"`
|
||||
UnitTag string `json:"unitTag"`
|
||||
Available float64 `json:"available,string"`
|
||||
Key string `json:"key"`
|
||||
} `json:"coins"`
|
||||
Base struct {
|
||||
Username string `json:"username"`
|
||||
TradePasswordEnabled bool `json:"trade_password_enabled"`
|
||||
AuthGoogleEnabled bool `json:"auth_google_enabled"`
|
||||
AuthMobileEnabled bool `json:"auth_mobile_enabled"`
|
||||
} `json:"base"`
|
||||
Coins []AccountsResponseCoin `json:"coins"`
|
||||
Base AccountsBaseResponse `json:"base"`
|
||||
} `json:"data"`
|
||||
Code int64 `json:"code"`
|
||||
Channel string `json:"channel"`
|
||||
Success bool `json:"success"`
|
||||
}
|
||||
|
||||
var wsErrCodes = map[int64]string{
|
||||
1000: "Successful call",
|
||||
1001: "General error message",
|
||||
1002: "internal error",
|
||||
1003: "Verification failed",
|
||||
1004: "Financial security password lock",
|
||||
1005: "The fund security password is incorrect. Please confirm and re-enter.",
|
||||
1006: "Real-name certification is awaiting review or review",
|
||||
1007: "Channel is empty",
|
||||
1008: "Event is empty",
|
||||
1009: "This interface is being maintained",
|
||||
1011: "Not open yet",
|
||||
1012: "Insufficient permissions",
|
||||
1013: "Can not trade, if you have any questions, please contact online customer service",
|
||||
1014: "Cannot be sold during the pre-sale period",
|
||||
2002: "Insufficient balance in Bitcoin account",
|
||||
2003: "Insufficient balance of Litecoin account",
|
||||
2005: "Insufficient balance in Ethereum account",
|
||||
2006: "Insufficient balance in ETC currency account",
|
||||
2007: "Insufficient balance of BTS currency account",
|
||||
2008: "Insufficient balance in EOS currency account",
|
||||
2009: "Insufficient account balance",
|
||||
3001: "Pending order not found",
|
||||
3002: "Invalid amount",
|
||||
3003: "Invalid quantity",
|
||||
3004: "User does not exist",
|
||||
3005: "Invalid parameter",
|
||||
3006: "Invalid IP or inconsistent with the bound IP",
|
||||
3007: "Request time has expired",
|
||||
3008: "Transaction history not found",
|
||||
4001: "API interface is locked",
|
||||
4002: "Request too frequently",
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ package zb
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
@@ -268,8 +269,9 @@ func (z *ZB) FetchOrderbook(p currency.Pair, assetType asset.Item) (orderbook.Ba
|
||||
// UpdateOrderbook updates and returns the orderbook for a currency pair
|
||||
func (z *ZB) UpdateOrderbook(p currency.Pair, assetType asset.Item) (orderbook.Base, error) {
|
||||
var orderBook orderbook.Base
|
||||
orderbookNew, err := z.GetOrderbook(z.FormatExchangeCurrency(p,
|
||||
assetType).String())
|
||||
curr := z.FormatExchangeCurrency(p, assetType).String()
|
||||
|
||||
orderbookNew, err := z.GetOrderbook(curr)
|
||||
if err != nil {
|
||||
return orderBook, err
|
||||
}
|
||||
@@ -304,25 +306,35 @@ func (z *ZB) UpdateOrderbook(p currency.Pair, assetType asset.Item) (orderbook.B
|
||||
// ZB exchange
|
||||
func (z *ZB) GetAccountInfo() (exchange.AccountInfo, error) {
|
||||
var info exchange.AccountInfo
|
||||
bal, err := z.GetAccountInformation()
|
||||
if err != nil {
|
||||
return info, err
|
||||
var balances []exchange.AccountCurrencyInfo
|
||||
var coins []AccountsResponseCoin
|
||||
if z.Websocket.CanUseAuthenticatedWebsocketForWrapper() {
|
||||
resp, err := z.wsGetAccountInfoRequest()
|
||||
if err != nil {
|
||||
return info, err
|
||||
}
|
||||
coins = resp.Data.Coins
|
||||
} else {
|
||||
bal, err := z.GetAccountInformation()
|
||||
if err != nil {
|
||||
return info, err
|
||||
}
|
||||
coins = bal.Result.Coins
|
||||
}
|
||||
|
||||
var balances []exchange.AccountCurrencyInfo
|
||||
for _, data := range bal.Result.Coins {
|
||||
hold, err := strconv.ParseFloat(data.Freez, 64)
|
||||
for i := range coins {
|
||||
hold, err := strconv.ParseFloat(coins[i].Freeze, 64)
|
||||
if err != nil {
|
||||
return info, err
|
||||
}
|
||||
|
||||
avail, err := strconv.ParseFloat(data.Available, 64)
|
||||
avail, err := strconv.ParseFloat(coins[i].Available, 64)
|
||||
if err != nil {
|
||||
return info, err
|
||||
}
|
||||
|
||||
balances = append(balances, exchange.AccountCurrencyInfo{
|
||||
CurrencyName: currency.NewCode(data.EnName),
|
||||
CurrencyName: currency.NewCode(coins[i].EnName),
|
||||
TotalValue: hold + avail,
|
||||
Hold: hold,
|
||||
})
|
||||
@@ -348,33 +360,53 @@ func (z *ZB) GetExchangeHistory(p currency.Pair, assetType asset.Item) ([]exchan
|
||||
}
|
||||
|
||||
// SubmitOrder submits a new order
|
||||
func (z *ZB) SubmitOrder(s *order.Submit) (order.SubmitResponse, error) {
|
||||
func (z *ZB) SubmitOrder(o *order.Submit) (order.SubmitResponse, error) {
|
||||
var submitOrderResponse order.SubmitResponse
|
||||
if err := s.Validate(); err != nil {
|
||||
err := o.Validate()
|
||||
if err != nil {
|
||||
return submitOrderResponse, err
|
||||
}
|
||||
|
||||
var oT SpotNewOrderRequestParamsType
|
||||
if s.OrderSide == order.Buy {
|
||||
oT = SpotNewOrderRequestParamsTypeBuy
|
||||
if z.Websocket.CanUseAuthenticatedWebsocketForWrapper() {
|
||||
var isBuyOrder int64
|
||||
if o.OrderSide == order.Buy {
|
||||
isBuyOrder = 1
|
||||
} else {
|
||||
isBuyOrder = 0
|
||||
}
|
||||
var response *WsSubmitOrderResponse
|
||||
response, err = z.wsSubmitOrder(o.Pair, o.Amount, o.Price, isBuyOrder)
|
||||
if err != nil {
|
||||
return submitOrderResponse, err
|
||||
}
|
||||
submitOrderResponse.OrderID = strconv.FormatInt(response.Data.EntrustID, 10)
|
||||
} else {
|
||||
oT = SpotNewOrderRequestParamsTypeSell
|
||||
}
|
||||
var oT SpotNewOrderRequestParamsType
|
||||
if o.OrderSide == order.Buy {
|
||||
oT = SpotNewOrderRequestParamsTypeBuy
|
||||
} else {
|
||||
oT = SpotNewOrderRequestParamsTypeSell
|
||||
}
|
||||
|
||||
var params = SpotNewOrderRequestParams{
|
||||
Amount: s.Amount,
|
||||
Price: s.Price,
|
||||
Symbol: s.Pair.Lower().String(),
|
||||
Type: oT,
|
||||
var params = SpotNewOrderRequestParams{
|
||||
Amount: o.Amount,
|
||||
Price: o.Price,
|
||||
Symbol: o.Pair.Lower().String(),
|
||||
Type: oT,
|
||||
}
|
||||
var response int64
|
||||
response, err = z.SpotNewOrder(params)
|
||||
if err != nil {
|
||||
return submitOrderResponse, err
|
||||
}
|
||||
if response > 0 {
|
||||
submitOrderResponse.OrderID = strconv.FormatInt(response, 10)
|
||||
}
|
||||
}
|
||||
response, err := z.SpotNewOrder(params)
|
||||
if response > 0 {
|
||||
submitOrderResponse.OrderID = strconv.FormatInt(response, 10)
|
||||
submitOrderResponse.IsOrderPlaced = true
|
||||
if o.OrderType == order.Market {
|
||||
submitOrderResponse.FullyMatched = true
|
||||
}
|
||||
if err == nil {
|
||||
submitOrderResponse.IsOrderPlaced = true
|
||||
}
|
||||
return submitOrderResponse, err
|
||||
return submitOrderResponse, nil
|
||||
}
|
||||
|
||||
// ModifyOrder will allow of changing orderbook placement and limit to
|
||||
@@ -389,8 +421,20 @@ func (z *ZB) CancelOrder(o *order.Cancel) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
curr := z.FormatExchangeCurrency(o.CurrencyPair, o.AssetType).String()
|
||||
return z.CancelExistingOrder(orderIDInt, curr)
|
||||
|
||||
if z.Websocket.CanUseAuthenticatedWebsocketForWrapper() {
|
||||
var response *WsCancelOrderResponse
|
||||
response, err = z.wsCancelOrder(o.CurrencyPair, orderIDInt)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !response.Success {
|
||||
return fmt.Errorf("%v - Could not cancel order %v", z.Name, o.OrderID)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
return z.CancelExistingOrder(orderIDInt, z.FormatExchangeCurrency(o.CurrencyPair,
|
||||
o.AssetType).String())
|
||||
}
|
||||
|
||||
// CancelAllOrders cancels all orders associated with a currency pair
|
||||
@@ -424,11 +468,12 @@ func (z *ZB) CancelAllOrders(_ *order.Cancel) (order.CancelAllResponse, error) {
|
||||
}
|
||||
|
||||
for i := range allOpenOrders {
|
||||
err := z.CancelExistingOrder(allOpenOrders[i].ID,
|
||||
allOpenOrders[i].Currency)
|
||||
err := z.CancelOrder(&order.Cancel{
|
||||
OrderID: strconv.FormatInt(allOpenOrders[i].ID, 10),
|
||||
CurrencyPair: currency.NewPairFromString(allOpenOrders[i].Currency),
|
||||
})
|
||||
if err != nil {
|
||||
ID := strconv.FormatInt(allOpenOrders[i].ID, 10)
|
||||
cancelAllOrdersResponse.Status[ID] = err.Error()
|
||||
cancelAllOrdersResponse.Status[strconv.FormatInt(allOpenOrders[i].ID, 10)] = err.Error()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -539,35 +584,45 @@ func (z *ZB) GetOrderHistory(req *order.GetOrdersRequest) ([]order.Detail, error
|
||||
if req.OrderSide == order.AnySide || req.OrderSide == "" {
|
||||
return nil, errors.New("specific order side is required")
|
||||
}
|
||||
|
||||
var allOrders []Order
|
||||
|
||||
var orders []order.Detail
|
||||
var side int64
|
||||
if req.OrderSide == order.Buy {
|
||||
side = 1
|
||||
}
|
||||
|
||||
for x := range req.Currencies {
|
||||
for y := int64(1); ; y++ {
|
||||
fPair := z.FormatExchangeCurrency(req.Currencies[x], asset.Spot).String()
|
||||
resp, err := z.GetOrders(fPair, y, side)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
if z.Websocket.CanUseAuthenticatedWebsocketForWrapper() {
|
||||
for x := range req.Currencies {
|
||||
for y := int64(1); ; y++ {
|
||||
resp, err := z.wsGetOrdersIgnoreTradeType(req.Currencies[x], y, 10)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
allOrders = append(allOrders, resp.Data...)
|
||||
if len(resp.Data) != 10 {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if len(resp) == 0 {
|
||||
break
|
||||
}
|
||||
|
||||
allOrders = append(allOrders, resp...)
|
||||
|
||||
if len(resp) != 10 {
|
||||
break
|
||||
}
|
||||
} else {
|
||||
if req.OrderSide == order.Buy {
|
||||
side = 1
|
||||
}
|
||||
for x := range req.Currencies {
|
||||
for y := int64(1); ; y++ {
|
||||
fPair := z.FormatExchangeCurrency(req.Currencies[x], asset.Spot).String()
|
||||
resp, err := z.GetOrders(fPair, y, side)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(resp) == 0 {
|
||||
break
|
||||
}
|
||||
allOrders = append(allOrders, resp...)
|
||||
if len(resp) != 10 {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var orders []order.Detail
|
||||
for i := range allOrders {
|
||||
symbol := currency.NewPairDelimiter(allOrders[i].Currency,
|
||||
z.GetPairFormat(asset.Spot, false).Delimiter)
|
||||
|
||||
Reference in New Issue
Block a user