mirror of
https://github.com/d0zingcat/gocryptotrader.git
synced 2026-05-19 23:16:48 +00:00
* End of day commit moving packages and setting foundation into how trade processing will go * Conformity * tdd candle generation based on received trade data, renames orderbookbuffer back to buffer for now... * Formalises test functions and designs the trade processor * Theoretical amending old candles to allow any trades that were part of an old processed candle to be more accurate. Saving of candles will only occur on previous cycles, extending memory usage a bit longer * Figures out sqlboiler for sqlite. Updates websocket entries to process trade data * One more trade data * Adds more exchange support * Adds PSQL stuff * Begins creating sql implementation * End of day commit. Helper functions and understanding sql usage in GCT * Adds delete and cleans up table design * Finishes trades conceptually. Awaits candle data update in order to translate trades to candles * Initial handling of trades in coinbene * Proto * Fixing of some bugs, attempting to address coinbene asset type ws issues * Fixes up coinbene websocket implementation for the most part * finalises coinbene websocket implementation. Adds new ability to parse currencies without a delimiter * Implements rpc commands and adds testing * updates the following to be compatible with trade data update: Theoretical amending old candles to allow any trades that were part of an old processed candle to be more accurate. Saving of candles will only occur on previous cycles, extending memory usage a bit longer * Changes trade to be its own entity rather than attached to a websocket. * Adds coverage to trades. Changes signature of `AddTradesToBuffer` to return error. Now automatically shuts down without need for channel listening. Will automatically start up again if it gets data * Implements trade fetching at the wrapper level for a bunch of exchanges. Adds trade id to script updoot. Probably breaking change * Implements trade fetching for all wrappers hurray hurrah. Updates all the tests * Adds new interface func to get recent trades. Ensures GetExchangeHistory continues until conditions are met * Adds new readme, tests all new wrapper endpoints, updates exchange_wrapper_issues to test new endpoints. Updates exchange_wrapper_coverage with new coverage... Fixes lame bug causing wrapper tests to fail from being poorly setup. Adds loopy loop to ensure that all data is captured when requesting exchange history * Bugfix on psql migrations. Rebases latest changes, updates table design to use base and quote, updates trades to use exchange_name_id * Adds new config field for saving trades to the database per exchange. Now exits trade processing when trade saving is not enabled. Similarly for wrapper, does not save if not enabled * Minor bitfinex trade fixes. continues on buffer processing errors, now saves transactionid to the db * Adds support for generating candles from candlesextended. May extend it further, idk * Updates trade candles to be able to fill missing data with trades. Adds more tests. Also does a thing where you can forcefully override a candle based on internal trade data instead of API data * Fixes bug where force deletions did not follow up with insertions. Adds force to candle commands * Fixes specific exchange based issues. Extends recent trades to 24 hours where possible * Fixes issue with saved tests. Fixes tests for trades. Adds parallel to tests. Pre-fixes people's nits * Adds new GRPC functions to find out what data is missing from trades and candles. Fixes some assumptions from missing period code. * Adds unique constraint. Fixes up niggling issues for wrappers and websockets * Fixes issues with using unix times in the database trying to retrieve data via the CLI. Reduces save time to 15 seconds * Updates trades to use timestamps instead of int64 unix * Adds missing FTX wrapper implementation. Regens docs * Linting the linters. Updating readme * Adds new command to set whether an exchange can process trades * Doc update * Adds recent trades and historic trade endpoints to grpc * formats pair_test.go to appease linter gods * Addresses data race. Removes logging of missing intervals on unrelated function (now that it has its own rpc command). The buffer time isnt customisable, but I don't feel it needs to be at a config level at all really. * Fixes a few niterinos regarding spacing, type conversion, a weird Bitmex 0 trade value error, unsubscriptions and cli command references * Reduces map lookups. Adds base func and moves wrappers to use it * Uses better currency formatter. Adds time based validation to trade history. Reverts configtest.json * Reverts config and updates test names. Also WAYYYYY LESS SPAMMY * oopsie doopsie missed a whoopsie * mint flavoured lint * Fixes issues caused by rebase * Fixes issue with timestamps not converting properly from command to RPCServer. Adds new error type. Adds shorthand entries to some commands. Removes os.Exit from tests. Makes Gemini test rolling. Adds enabled exchange check to RPC function. Escapes timestamp on bitstamp. Renames var * fixes whoopsie oopsie doopsie I forgot to remove code shoopsie * missed a line * 🎉 🎉 :tada:Breaks everything in an end of day commit 🎉 🎉 🎉 * Modifies function 'createlocaloffset' to return a string instead. Uses strings for all time based start and end commands. Uses UTC times in RPC server and updates SQLITE to use formatted time based queries * Adds concurrency-safe way of changing SaveTradeData and checking it. Fixes embarrassing typo * End of day fix, adds bitfinex update to loop until either the return trades shows no new dates, or meets specifications. Fixes egregious typo * Improves testing and handling of historical trades function * Fixes tests after latest changes * Fix potential fatal err now that db is enabled in test config now * Fixes up some database settings to use a local engine instead of global var * DELICIOUS LINT CHOCOLATE FIXES * Fixes data race by slashing competitor's tyres * Adds mock test fixes to allow for live and stored data test * Removes verbosity in engine level tests. Adds new timezone format to highlight the timezone for RPC functions. Removes reference to Preix index fund * Oopsie doopsie, fixed a whoopsie * Loggers can no longer do data drag races on my lawn 👴 * Removes bad lock * Addresses command nits. End of day conceptual commit, trying to calculate spans of time in the context of missing periods. Tests will fail * Adds new stream response for retrieving trade history as it can take time to do. Unsuccessfully attempts to simplify time range calculation for missing trades response * Adds new timeperiods package to calculate time periods, time ranges and whether data is in those ranges. Removes kline basic implementation of same concept * Fixes lint issues. Fixes test. Moves trade cli commands to their own trade subcommands * Updates lakebtc to no longer have gethistorictrades as it is unsupported. Adds more validation to rpc functions * Removes requirement to have trades when testing trade wrapper functions. Doesn't really prove it works if there are no trades for a given currency in a time period. * Addresses nits, runs linting fix and ensures a test is consistent * Fix merge issues * Moves sort to timeperiods. Adds test coverage. Fixes typo * Removes log package in CLI * Fixes `GetTrades` url * Reorders all instances of validation occuring after settingup RPC connection * Fixes test to ensure that it is setup before testing that it is setup * Fixed issue with bool retrieval. Removes double append * Fixes Binance times, fixes bitfinex sell sides, fixes huobi times, sorts all responses * Fixes poloniex trade id consistency. Makes recent trade for poloniex consistent with others (15 minutes). Fixes coinbene. Fixes localbitcoins to use quote currency. Fixes coinut times. Updates huobi trade id, saves okgroup trades. Fixes bid and ask to buy and sell * Removes websocket trades for lakebtc as it did not meet our requirements for processing. Adds new constraints to the database to ensure we have uniqueness on trades where ID doesn't exist and doesn't trigger errors for trades where the tid does * Fixes migration for postgres to downscale properly * Really really fixes the psql index changes * Fixes broken tests * Now with working tests and no pocket lint * Makes the side column nullable with no more constraint for it. adds migrations and runs generation. comments lakebtc * Lint & Sprüngli * Updates zb to use more appropriate side * Fixes oopsie * Attempts to address a data race from globals * Fixes build * Fixes missed regen rpc files * Updates readme to point to trade readme. Fixes exchange_wrapper_coverage wrapper count and untested panics, tests bitfinex funding pair test for `fUSD`, adds shiny new param `tradeprocessinginterval` * mint flavoured lint * Uses the real default to set the default value by default * Fixes some extra tests surrounding email sending and number incompatibility * Reverts test config * re-adds gom2/usdt currency * Fixes typo, don't look! * Fixes minor codelingo pickups * Adds more precision to handling of trade data from Kraken. Expands test * interface christmas tree * lint
446 lines
14 KiB
Go
446 lines
14 KiB
Go
package zb
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"net/http"
|
|
"net/url"
|
|
"strconv"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/thrasher-corp/gocryptotrader/common/convert"
|
|
"github.com/thrasher-corp/gocryptotrader/common/crypto"
|
|
"github.com/thrasher-corp/gocryptotrader/currency"
|
|
exchange "github.com/thrasher-corp/gocryptotrader/exchanges"
|
|
"github.com/thrasher-corp/gocryptotrader/exchanges/request"
|
|
)
|
|
|
|
const (
|
|
zbTradeURL = "http://api.zb.live"
|
|
zbMarketURL = "https://trade.zb.live/api"
|
|
zbAPIVersion = "v1"
|
|
zbData = "data"
|
|
zbAccountInfo = "getAccountInfo"
|
|
zbMarkets = "markets"
|
|
zbKline = "kline"
|
|
zbOrder = "order"
|
|
zbCancelOrder = "cancelOrder"
|
|
zbTicker = "ticker"
|
|
zbTrades = "trades"
|
|
zbTickers = "allTicker"
|
|
zbDepth = "depth"
|
|
zbUnfinishedOrdersIgnoreTradeType = "getUnfinishedOrdersIgnoreTradeType"
|
|
zbGetOrdersGet = "getOrders"
|
|
zbWithdraw = "withdraw"
|
|
zbDepositAddress = "getUserAddress"
|
|
)
|
|
|
|
// ZB is the overarching type across this package
|
|
// 47.91.169.147 api.zb.com
|
|
// 47.52.55.212 trade.zb.com
|
|
type ZB struct {
|
|
exchange.Base
|
|
}
|
|
|
|
// SpotNewOrder submits an order to ZB
|
|
func (z *ZB) SpotNewOrder(arg SpotNewOrderRequestParams) (int64, error) {
|
|
var result SpotNewOrderResponse
|
|
|
|
vals := url.Values{}
|
|
vals.Set("accesskey", z.API.Credentials.Key)
|
|
vals.Set("method", "order")
|
|
vals.Set("amount", strconv.FormatFloat(arg.Amount, 'f', -1, 64))
|
|
vals.Set("currency", arg.Symbol)
|
|
vals.Set("price", strconv.FormatFloat(arg.Price, 'f', -1, 64))
|
|
vals.Set("tradeType", string(arg.Type))
|
|
|
|
err := z.SendAuthenticatedHTTPRequest(http.MethodGet, vals, &result, request.Auth)
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
if result.Code != 1000 {
|
|
return 0, fmt.Errorf("unsuccessful new order, message: %s code: %d", result.Message, result.Code)
|
|
}
|
|
newOrderID, err := strconv.ParseInt(result.ID, 10, 64)
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
return newOrderID, nil
|
|
}
|
|
|
|
// CancelExistingOrder cancels an order
|
|
func (z *ZB) CancelExistingOrder(orderID int64, symbol string) error {
|
|
type response struct {
|
|
Code int `json:"code"` // Result code
|
|
Message string `json:"message"` // Result Message
|
|
}
|
|
|
|
vals := url.Values{}
|
|
vals.Set("accesskey", z.API.Credentials.Key)
|
|
vals.Set("method", "cancelOrder")
|
|
vals.Set("id", strconv.FormatInt(orderID, 10))
|
|
vals.Set("currency", symbol)
|
|
|
|
var result response
|
|
err := z.SendAuthenticatedHTTPRequest(http.MethodGet, vals, &result, request.Auth)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
if result.Code != 1000 {
|
|
return errors.New(result.Message)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// GetAccountInformation returns account information including coin information
|
|
// and pricing
|
|
func (z *ZB) GetAccountInformation() (AccountsResponse, error) {
|
|
var result AccountsResponse
|
|
|
|
vals := url.Values{}
|
|
vals.Set("accesskey", z.API.Credentials.Key)
|
|
vals.Set("method", "getAccountInfo")
|
|
|
|
return result, z.SendAuthenticatedHTTPRequest(http.MethodGet, vals, &result, request.Auth)
|
|
}
|
|
|
|
// GetUnfinishedOrdersIgnoreTradeType returns unfinished orders
|
|
func (z *ZB) GetUnfinishedOrdersIgnoreTradeType(currency string, pageindex, pagesize int64) ([]Order, error) {
|
|
var result []Order
|
|
vals := url.Values{}
|
|
vals.Set("accesskey", z.API.Credentials.Key)
|
|
vals.Set("method", zbUnfinishedOrdersIgnoreTradeType)
|
|
vals.Set("currency", currency)
|
|
vals.Set("pageIndex", strconv.FormatInt(pageindex, 10))
|
|
vals.Set("pageSize", strconv.FormatInt(pagesize, 10))
|
|
|
|
err := z.SendAuthenticatedHTTPRequest(http.MethodGet, vals, &result, request.Auth)
|
|
return result, err
|
|
}
|
|
|
|
// GetOrders returns finished orders
|
|
func (z *ZB) GetOrders(currency string, pageindex, side int64) ([]Order, error) {
|
|
var response []Order
|
|
vals := url.Values{}
|
|
vals.Set("accesskey", z.API.Credentials.Key)
|
|
vals.Set("method", zbGetOrdersGet)
|
|
vals.Set("currency", currency)
|
|
vals.Set("pageIndex", strconv.FormatInt(pageindex, 10))
|
|
vals.Set("tradeType", strconv.FormatInt(side, 10))
|
|
return response, z.SendAuthenticatedHTTPRequest(http.MethodGet, vals, &response, request.Auth)
|
|
}
|
|
|
|
// GetMarkets returns market information including pricing, symbols and
|
|
// each symbols decimal precision
|
|
func (z *ZB) GetMarkets() (map[string]MarketResponseItem, error) {
|
|
endpoint := fmt.Sprintf("%s/%s/%s/%s", z.API.Endpoints.URL, zbData, zbAPIVersion, zbMarkets)
|
|
|
|
var res map[string]MarketResponseItem
|
|
err := z.SendHTTPRequest(endpoint, &res, request.UnAuth)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return res, nil
|
|
}
|
|
|
|
// GetLatestSpotPrice returns latest spot price of symbol
|
|
//
|
|
// symbol: string of currency pair
|
|
// 获取最新价格
|
|
func (z *ZB) GetLatestSpotPrice(symbol string) (float64, error) {
|
|
res, err := z.GetTicker(symbol)
|
|
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
|
|
return res.Ticker.Last, nil
|
|
}
|
|
|
|
// GetTicker returns a ticker for a given symbol
|
|
func (z *ZB) GetTicker(symbol string) (TickerResponse, error) {
|
|
urlPath := fmt.Sprintf("%s/%s/%s/%s?market=%s", z.API.Endpoints.URL, zbData, zbAPIVersion, zbTicker, symbol)
|
|
var res TickerResponse
|
|
err := z.SendHTTPRequest(urlPath, &res, request.UnAuth)
|
|
return res, err
|
|
}
|
|
|
|
// GetTicker returns a ticker for a given symbol
|
|
func (z *ZB) GetTrades(symbol string) (TradeHistory, error) {
|
|
urlPath := fmt.Sprintf("%s/%s/%s/%s?market=%s", z.API.Endpoints.URL, zbData, zbAPIVersion, zbTrades, symbol)
|
|
var res TradeHistory
|
|
err := z.SendHTTPRequest(urlPath, &res, request.UnAuth)
|
|
return res, err
|
|
}
|
|
|
|
// GetTickers returns ticker data for all supported symbols
|
|
func (z *ZB) GetTickers() (map[string]TickerChildResponse, error) {
|
|
urlPath := fmt.Sprintf("%s/%s/%s/%s", z.API.Endpoints.URL, zbData, zbAPIVersion, zbTickers)
|
|
resp := make(map[string]TickerChildResponse)
|
|
err := z.SendHTTPRequest(urlPath, &resp, request.UnAuth)
|
|
return resp, err
|
|
}
|
|
|
|
// GetOrderbook returns the orderbook for a given symbol
|
|
func (z *ZB) GetOrderbook(symbol string) (OrderbookResponse, error) {
|
|
urlPath := fmt.Sprintf("%s/%s/%s/%s?market=%s", z.API.Endpoints.URL, zbData, zbAPIVersion, zbDepth, symbol)
|
|
var res OrderbookResponse
|
|
|
|
err := z.SendHTTPRequest(urlPath, &res, request.UnAuth)
|
|
if err != nil {
|
|
return res, err
|
|
}
|
|
|
|
if len(res.Asks) == 0 {
|
|
return res, fmt.Errorf("ZB GetOrderbook asks is empty")
|
|
}
|
|
|
|
if len(res.Bids) == 0 {
|
|
return res, fmt.Errorf("ZB GetOrderbook bids is empty")
|
|
}
|
|
|
|
// reverse asks data
|
|
var data [][]float64
|
|
for x := len(res.Asks); x > 0; x-- {
|
|
data = append(data, res.Asks[x-1])
|
|
}
|
|
|
|
res.Asks = data
|
|
return res, nil
|
|
}
|
|
|
|
// GetSpotKline returns Kline data
|
|
func (z *ZB) GetSpotKline(arg KlinesRequestParams) (KLineResponse, error) {
|
|
vals := url.Values{}
|
|
vals.Set("type", arg.Type)
|
|
vals.Set("market", arg.Symbol)
|
|
if arg.Since > 0 {
|
|
vals.Set("since", strconv.FormatInt(arg.Since, 10))
|
|
}
|
|
if arg.Size != 0 {
|
|
vals.Set("size", fmt.Sprintf("%d", arg.Size))
|
|
}
|
|
|
|
urlPath := fmt.Sprintf("%s/%s/%s/%s?%s", z.API.Endpoints.URL, zbData, zbAPIVersion, zbKline, vals.Encode())
|
|
|
|
var res KLineResponse
|
|
var rawKlines map[string]interface{}
|
|
err := z.SendHTTPRequest(urlPath, &rawKlines, klineFunc)
|
|
if err != nil {
|
|
return res, err
|
|
}
|
|
if rawKlines == nil || rawKlines["symbol"] == nil {
|
|
return res, errors.New("zb GetSpotKline rawKlines is nil")
|
|
}
|
|
|
|
res.Symbol = rawKlines["symbol"].(string)
|
|
res.MoneyType = rawKlines["moneyType"].(string)
|
|
|
|
rawKlineDatasString, _ := json.Marshal(rawKlines["data"].([]interface{}))
|
|
var rawKlineDatas [][]interface{}
|
|
if err := json.Unmarshal(rawKlineDatasString, &rawKlineDatas); err != nil {
|
|
return res, errors.New("zb rawKlines unmarshal failed")
|
|
}
|
|
for _, k := range rawKlineDatas {
|
|
ot, err := convert.TimeFromUnixTimestampFloat(k[0])
|
|
if err != nil {
|
|
return res, errors.New("zb cannot parse Kline.OpenTime")
|
|
}
|
|
res.Data = append(res.Data, &KLineResponseData{
|
|
ID: k[0].(float64),
|
|
KlineTime: ot,
|
|
Open: k[1].(float64),
|
|
High: k[2].(float64),
|
|
Low: k[3].(float64),
|
|
Close: k[4].(float64),
|
|
Volume: k[5].(float64),
|
|
})
|
|
}
|
|
|
|
return res, nil
|
|
}
|
|
|
|
// GetCryptoAddress fetches and returns the deposit address
|
|
// NOTE - PLEASE BE AWARE THAT YOU NEED TO GENERATE A DEPOSIT ADDRESS VIA
|
|
// LOGGING IN AND NOT BY USING THIS ENDPOINT OTHERWISE THIS WILL GIVE YOU A
|
|
// GENERAL ERROR RESPONSE.
|
|
func (z *ZB) GetCryptoAddress(currency currency.Code) (UserAddress, error) {
|
|
var resp UserAddress
|
|
|
|
vals := url.Values{}
|
|
vals.Set("method", zbDepositAddress)
|
|
vals.Set("currency", currency.Lower().String())
|
|
|
|
return resp,
|
|
z.SendAuthenticatedHTTPRequest(http.MethodGet, vals, &resp, request.Auth)
|
|
}
|
|
|
|
// SendHTTPRequest sends an unauthenticated HTTP request
|
|
func (z *ZB) SendHTTPRequest(path string, result interface{}, f request.EndpointLimit) error {
|
|
return z.SendPayload(context.Background(), &request.Item{
|
|
Method: http.MethodGet,
|
|
Path: path,
|
|
Result: result,
|
|
Verbose: z.Verbose,
|
|
HTTPDebugging: z.HTTPDebugging,
|
|
HTTPRecording: z.HTTPRecording,
|
|
Endpoint: f,
|
|
})
|
|
}
|
|
|
|
// SendAuthenticatedHTTPRequest sends authenticated requests to the zb API
|
|
func (z *ZB) SendAuthenticatedHTTPRequest(httpMethod string, params url.Values, result interface{}, f request.EndpointLimit) error {
|
|
if !z.AllowAuthenticatedRequest() {
|
|
return fmt.Errorf(exchange.WarningAuthenticatedRequestWithoutCredentialsSet, z.Name)
|
|
}
|
|
|
|
params.Set("accesskey", z.API.Credentials.Key)
|
|
|
|
hmac := crypto.GetHMAC(crypto.HashMD5,
|
|
[]byte(params.Encode()),
|
|
[]byte(crypto.Sha1ToHex(z.API.Credentials.Secret)))
|
|
|
|
now := time.Now()
|
|
params.Set("reqTime", fmt.Sprintf("%d", convert.UnixMillis(now)))
|
|
params.Set("sign", fmt.Sprintf("%x", hmac))
|
|
|
|
urlPath := fmt.Sprintf("%s/%s?%s",
|
|
z.API.Endpoints.URLSecondary,
|
|
params.Get("method"),
|
|
params.Encode())
|
|
|
|
var intermediary json.RawMessage
|
|
|
|
errCap := struct {
|
|
Code int64 `json:"code"`
|
|
Message string `json:"message"`
|
|
}{}
|
|
|
|
// Expiry of timestamp doesn't appear to be documented, so making a reasonable assumption
|
|
ctx, cancel := context.WithDeadline(context.Background(), now.Add(15*time.Second))
|
|
defer cancel()
|
|
err := z.SendPayload(ctx, &request.Item{
|
|
Method: httpMethod,
|
|
Path: urlPath,
|
|
Body: strings.NewReader(""),
|
|
Result: &intermediary,
|
|
AuthRequest: true,
|
|
Verbose: z.Verbose,
|
|
HTTPDebugging: z.HTTPDebugging,
|
|
HTTPRecording: z.HTTPRecording,
|
|
Endpoint: f,
|
|
})
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
err = json.Unmarshal(intermediary, &errCap)
|
|
if err == nil {
|
|
if errCap.Code > 1000 {
|
|
return fmt.Errorf("sendAuthenticatedHTTPRequest error code: %d message %s",
|
|
errCap.Code,
|
|
errorCode[errCap.Code])
|
|
}
|
|
}
|
|
|
|
return json.Unmarshal(intermediary, result)
|
|
}
|
|
|
|
// GetFee returns an estimate of fee based on type of transaction
|
|
func (z *ZB) GetFee(feeBuilder *exchange.FeeBuilder) (float64, error) {
|
|
var fee float64
|
|
switch feeBuilder.FeeType {
|
|
case exchange.CryptocurrencyTradeFee:
|
|
fee = calculateTradingFee(feeBuilder.PurchasePrice, feeBuilder.Amount)
|
|
case exchange.CryptocurrencyWithdrawalFee:
|
|
fee = getWithdrawalFee(feeBuilder.Pair.Base)
|
|
case exchange.OfflineTradeFee:
|
|
fee = getOfflineTradeFee(feeBuilder.PurchasePrice, feeBuilder.Amount)
|
|
}
|
|
if fee < 0 {
|
|
fee = 0
|
|
}
|
|
|
|
return fee, nil
|
|
}
|
|
|
|
// getOfflineTradeFee calculates the worst case-scenario trading fee
|
|
func getOfflineTradeFee(price, amount float64) float64 {
|
|
return 0.002 * price * amount
|
|
}
|
|
|
|
func calculateTradingFee(purchasePrice, amount float64) (fee float64) {
|
|
fee = 0.002
|
|
return fee * amount * purchasePrice
|
|
}
|
|
|
|
func getWithdrawalFee(c currency.Code) float64 {
|
|
return WithdrawalFees[c]
|
|
}
|
|
|
|
var errorCode = 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",
|
|
1009: "This interface is being maintained",
|
|
1010: "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",
|
|
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",
|
|
}
|
|
|
|
// Withdraw transfers funds
|
|
func (z *ZB) Withdraw(currency, address, safepassword string, amount, fees float64, itransfer bool) (string, error) {
|
|
type response struct {
|
|
Code int `json:"code"` // Result code
|
|
Message string `json:"message"` // Result Message
|
|
ID string `json:"id"` // Withdrawal ID
|
|
}
|
|
|
|
vals := url.Values{}
|
|
vals.Set("accesskey", z.API.Credentials.Key)
|
|
vals.Set("amount", strconv.FormatFloat(amount, 'f', -1, 64))
|
|
vals.Set("currency", currency)
|
|
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)
|
|
|
|
var resp response
|
|
err := z.SendAuthenticatedHTTPRequest(http.MethodGet, vals, &resp, request.Auth)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
if resp.Code != 1000 {
|
|
return "", errors.New(resp.Message)
|
|
}
|
|
|
|
return resp.ID, nil
|
|
}
|