mirror of
https://github.com/d0zingcat/gocryptotrader.git
synced 2026-06-05 07:26:47 +00:00
* Initial changes, removing exchange name as an arg and puts it in the pointer struct. Adds case to ws routines * Adds CancelAllOrders func, adds GetByExchangeAndID. Adds modify handler in routines.go * initial poor attempts to have bitmex work with new datahandler handlers. fixes ordersides * bitmex Completes new order * Better bitmex handling, but not complete. Begins a gargantuan task of unifying order data structs. Sometimes an order update will contain lot's of information, so its best to be able to update all fields of our orders, rather than just an arbitrary subset. As a result, everything will be broken for the foreseeable future :glitch_crab: * Removes old order handler which did nothing. Updates order properties for everything everywhere - now consistent. Changes order status. Adds asset type and wallet address to all order types * Adds order updater to update only relevant fields since the object is generic, we don't know what fields are passed from what exchanges. Adds "lastupdated" field to order.Detail. Expands order cancellation for engine orders. * Ensures that new orders are added to the ordermanager's order store. Saaa many comments. Internalises orderStore get func. Adds internalOrderID to orderdetail and adds websocket support for it * Fixes a cancelAllOrders oopsie doopsie * Adds potential func to update orderdetails from an orderdetail struct. Unsure if will keep. * Begins btcmarkets implementation. Expands order "stringToOrder" funcs to allow for some more flexible string coversions. Removes order.Submit via websocket as it would cause unlimited order place issues :D * Finishes btc markets without testing * Adds untested ws auth func to btse * Finises btse, fixes btcmarkets bug * Adds coinbasepro support * Fixes a few more fields in coinbase pro and readds the extra subs * Begins work on coinbene. Plus theyve added a new ws connection yeee * Wasted a bunch of time adding support to an additional websocket that isn't needed ;_; Fixed a bug in coinbasepro. Fully kitted out coinbene support. Updates order types with all fields * Removes extra websocket connection ;_; * Finishes gemini. Fixes order side unknown * Adds okgroup support. Moves byte reading to another function to allow for unit testing. Updates routines to use pointers. Updates date update handling for order details * Finishes order data for okgroup websocket, but starts the STRANGE process of converting all other websocket endpoints to be a little less silly * Cleans up okroup websocket implementation. Fixes bug in Gemini * Adds poloniex support. Updates ws order handling * new bitmex support. Adds some tests now that its all in its own func. Fixes poloniex bug * Begins work on authenticated binance websocket * Attempts to track user data via binance websocket * Maybe finishes Binance websocket support * Begins adding test coverage to orders.go. Updates names of script properties to match updated * Begins an experiment with code coverage. Fixes more rebase issues * Completes orders coverage. Botches a few other things though. Fixes more scripting stuff * All tests in engine package pass * Adds some loevely routine tests * Moves ordermanager to test Bot ordermanager Adds lovely routine tests to ensure things that get sent to be handled the data handler are handled by the data handler by handling them * Replaces "wsHandleData" with "wsReadData" as that's what its going to do now. * Splits all wsHandleData into wsReadData and wsHandleData to allow for easy testing via sending []byte json examples to test proper functionality. Breaks so many tests * Fixes majority of test issues. But data races which are tough on the engine package * "Fixes" test by removing shutdown test. It interferes with too many things. Requires some thought * Tests all the binance websocket points * Adds better bitfinex websocket support. * Adds testing for bitfinex, bitstamp and btcmarkets. Fixes websocket bugs encountered * Adds BTSE ws tests. Fixes bugs in ws * Adds coinbase pro tests. Fixes any issues * Coinbene tests * Starts to handle coinut. Runs into a problem conceptually regarding websocket roundtrip and orders. Both events need to happen without impacting eachother/racing * Addresses a data race issue regarding websocket and bot order management submission - order submission locks at an earlier point to prevent routines.go from creating an order before order submission creates it. Updates rpcserver to use order management bot to submit orders. * Finishes the hectic coinut testing * Adds tests for gateio * Fixes rebase issues. Updates tests to work without being overloaded * Begins testing of gemini. fixes up minor issues * ginishes gemini tests and fixes * Adds hitbtc tests. Fixes all the many issues with hitbtc websocket * Adds remaining tests. Increases default test channel limit again * Begins work towards huobi tests * Finishes huobi tests * Fixed all mythical rebase adventures * Begins kraken transformation * Finishes kraken. Fixes coinbene leverage now that its changed * Begins okgroup testing * Adds okgroup ws tests * Does some poloniex * Fixes basic curreny issue by extracting to func * Begins redesign of poloniex websocket datahandling. Completes authenticated handling, now onto unauth * Finishes poloniex revision * Finishes ZB additions * Fixes data races * Fixes rebase issues. Fixes bad kraken logic * Fixes after reviewing code * lint everywhere * Fixes lingering lints * lint * Adds test coverage to order detail and modify updating * Fixes linting * Fixes huge int, fixes date tests * Adds GetByExchange, adds test for it. Protects fakepass echange. Renames DisplayQty to DisplayQuantity. Removes verbose. Adds some websocket properties. Updates bitmex asset type in test * Addresses timestamps, type abbreviations, verbosity. Expands binance kline switch cases. Updates some websocket capabilities. * Adds coverage to the stringToOrderType/Status functions introduced in PR * Minor fixes addressing some time, error text and use of StringDataCompareInsensitive * Introduces shiny new system which checks if there is an awaiting ID, if found, processes via wrapper method, else, goes through wsHandleData method. Removes weird locking system from wrapper/websocket data race. Updates bitfinex to properly handle websocket order requests and notifications * Moves fakePassingExchange to test_helper. Fixes some order side implementations for trades. Botches a new error type * Adds new error type to track and handle order classification errors separately * Fully fleshes out ClassificationError for all instances of status conversion. Even in order trades and some wrapper functions * Introduces common.SimpleTimeFormat for "2006-01-02 15:04:05". Fixes binance and bitfinex issues with auth endpoint use, map casting. Expands more order.ClassificationError usage. Fixes some more generic websocket response errors * Future proofs order updating by utilising asset types. Expands testing to accomodate. Adds shiny new time type. Expands wrapper websocket functionality definitions * minty linty * Broken end of day code addressing basic nits on comments, returns and currency conversion * Adds testing to btcmarkets websocket. Also updates websocket orderbook to use update instead * Fixes fun rebase fun fun so fun * Addresses minor nits regarding changed interface and comments * Creates new function `GetRequestFormattedPairAndAssetType` to retrieve a currency pair and asset type based on a string. It will iterate over enabled pairs and compare them to formatted pairs and then return that pair if found. * Fixes test * Adds a single line to the end of the file, because that would be really bad if it wasn't there * Updates fakepassexchange to not use params, updates test params, uses fatal in some tests where its important, updates order manager to have a rwmutex, removes some returns, improves ws key test for binance, updates properties to reflect their actual values, adds some more websocket properties * Addresses binance switch linting * Updates leverage property to int64 * Fixes what was broken
846 lines
23 KiB
Go
846 lines
23 KiB
Go
package poloniex
|
|
|
|
import (
|
|
"bytes"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"net/http"
|
|
"net/url"
|
|
"strconv"
|
|
"time"
|
|
|
|
"github.com/thrasher-corp/gocryptotrader/common"
|
|
"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/order"
|
|
"github.com/thrasher-corp/gocryptotrader/exchanges/request"
|
|
"github.com/thrasher-corp/gocryptotrader/exchanges/websocket/wshandler"
|
|
)
|
|
|
|
const (
|
|
poloniexAPIURL = "https://poloniex.com"
|
|
poloniexAPITradingEndpoint = "tradingApi"
|
|
poloniexAPIVersion = "1"
|
|
poloniexBalances = "returnBalances"
|
|
poloniexBalancesComplete = "returnCompleteBalances"
|
|
poloniexDepositAddresses = "returnDepositAddresses"
|
|
poloniexGenerateNewAddress = "generateNewAddress"
|
|
poloniexDepositsWithdrawals = "returnDepositsWithdrawals"
|
|
poloniexOrders = "returnOpenOrders"
|
|
poloniexTradeHistory = "returnTradeHistory"
|
|
poloniexOrderCancel = "cancelOrder"
|
|
poloniexOrderMove = "moveOrder"
|
|
poloniexWithdraw = "withdraw"
|
|
poloniexFeeInfo = "returnFeeInfo"
|
|
poloniexAvailableBalances = "returnAvailableAccountBalances"
|
|
poloniexTradableBalances = "returnTradableBalances"
|
|
poloniexTransferBalance = "transferBalance"
|
|
poloniexMarginAccountSummary = "returnMarginAccountSummary"
|
|
poloniexMarginBuy = "marginBuy"
|
|
poloniexMarginSell = "marginSell"
|
|
poloniexMarginPosition = "getMarginPosition"
|
|
poloniexMarginPositionClose = "closeMarginPosition"
|
|
poloniexCreateLoanOffer = "createLoanOffer"
|
|
poloniexCancelLoanOffer = "cancelLoanOffer"
|
|
poloniexOpenLoanOffers = "returnOpenLoanOffers"
|
|
poloniexActiveLoans = "returnActiveLoans"
|
|
poloniexLendingHistory = "returnLendingHistory"
|
|
poloniexAutoRenew = "toggleAutoRenew"
|
|
)
|
|
|
|
// Poloniex is the overarching type across the poloniex package
|
|
type Poloniex struct {
|
|
exchange.Base
|
|
WebsocketConn *wshandler.WebsocketConnection
|
|
}
|
|
|
|
// GetHistoricCandles returns rangesize number of candles for the given granularity and pair starting from the latest available
|
|
func (p *Poloniex) GetHistoricCandles(pair currency.Pair, rangesize, granularity int64) ([]exchange.Candle, error) {
|
|
return nil, common.ErrNotYetImplemented
|
|
}
|
|
|
|
// GetTicker returns current ticker information
|
|
func (p *Poloniex) GetTicker() (map[string]Ticker, error) {
|
|
type response struct {
|
|
Data map[string]Ticker
|
|
}
|
|
|
|
resp := response{}
|
|
path := fmt.Sprintf("%s/public?command=returnTicker", p.API.Endpoints.URL)
|
|
|
|
return resp.Data, p.SendHTTPRequest(path, &resp.Data)
|
|
}
|
|
|
|
// GetVolume returns a list of currencies with associated volume
|
|
func (p *Poloniex) GetVolume() (interface{}, error) {
|
|
var resp interface{}
|
|
path := fmt.Sprintf("%s/public?command=return24hVolume", p.API.Endpoints.URL)
|
|
|
|
return resp, p.SendHTTPRequest(path, &resp)
|
|
}
|
|
|
|
// GetOrderbook returns the full orderbook from poloniex
|
|
func (p *Poloniex) GetOrderbook(currencyPair string, depth int) (OrderbookAll, error) {
|
|
vals := url.Values{}
|
|
|
|
if depth != 0 {
|
|
vals.Set("depth", strconv.Itoa(depth))
|
|
}
|
|
|
|
oba := OrderbookAll{Data: make(map[string]Orderbook)}
|
|
if currencyPair != "" {
|
|
vals.Set("currencyPair", currencyPair)
|
|
resp := OrderbookResponse{}
|
|
path := fmt.Sprintf("%s/public?command=returnOrderBook&%s", p.API.Endpoints.URL, vals.Encode())
|
|
err := p.SendHTTPRequest(path, &resp)
|
|
if err != nil {
|
|
return oba, err
|
|
}
|
|
if resp.Error != "" {
|
|
return oba, fmt.Errorf("%s GetOrderbook() error: %s", p.Name, resp.Error)
|
|
}
|
|
ob := Orderbook{}
|
|
for x := range resp.Asks {
|
|
data := resp.Asks[x]
|
|
price, err := strconv.ParseFloat(data[0].(string), 64)
|
|
if err != nil {
|
|
return oba, err
|
|
}
|
|
amount := data[1].(float64)
|
|
ob.Asks = append(ob.Asks, OrderbookItem{Price: price, Amount: amount})
|
|
}
|
|
|
|
for x := range resp.Bids {
|
|
data := resp.Bids[x]
|
|
price, err := strconv.ParseFloat(data[0].(string), 64)
|
|
if err != nil {
|
|
return oba, err
|
|
}
|
|
amount := data[1].(float64)
|
|
ob.Bids = append(ob.Bids, OrderbookItem{Price: price, Amount: amount})
|
|
}
|
|
oba.Data[currencyPair] = Orderbook{Bids: ob.Bids, Asks: ob.Asks}
|
|
} else {
|
|
vals.Set("currencyPair", "all")
|
|
resp := OrderbookResponseAll{}
|
|
path := fmt.Sprintf("%s/public?command=returnOrderBook&%s", p.API.Endpoints.URL, vals.Encode())
|
|
err := p.SendHTTPRequest(path, &resp.Data)
|
|
if err != nil {
|
|
return oba, err
|
|
}
|
|
for currency, orderbook := range resp.Data {
|
|
var ob Orderbook
|
|
for x := range orderbook.Asks {
|
|
price, err := strconv.ParseFloat(orderbook.Asks[x][0].(string), 64)
|
|
if err != nil {
|
|
return oba, err
|
|
}
|
|
ob.Asks = append(ob.Asks, OrderbookItem{
|
|
Price: price,
|
|
Amount: orderbook.Asks[x][1].(float64),
|
|
})
|
|
}
|
|
|
|
for x := range orderbook.Bids {
|
|
price, err := strconv.ParseFloat(orderbook.Bids[x][0].(string), 64)
|
|
if err != nil {
|
|
return oba, err
|
|
}
|
|
ob.Asks = append(ob.Asks, OrderbookItem{
|
|
Price: price,
|
|
Amount: orderbook.Bids[x][1].(float64),
|
|
})
|
|
}
|
|
oba.Data[currency] = Orderbook{Bids: ob.Bids, Asks: ob.Asks}
|
|
}
|
|
}
|
|
return oba, nil
|
|
}
|
|
|
|
// GetTradeHistory returns trades history from poloniex
|
|
func (p *Poloniex) GetTradeHistory(currencyPair, start, end string) ([]TradeHistory, error) {
|
|
vals := url.Values{}
|
|
vals.Set("currencyPair", currencyPair)
|
|
|
|
if start != "" {
|
|
vals.Set("start", start)
|
|
}
|
|
|
|
if end != "" {
|
|
vals.Set("end", end)
|
|
}
|
|
|
|
var resp []TradeHistory
|
|
path := fmt.Sprintf("%s/public?command=returnTradeHistory&%s", p.API.Endpoints.URL, vals.Encode())
|
|
|
|
return resp, p.SendHTTPRequest(path, &resp)
|
|
}
|
|
|
|
// GetChartData returns chart data for a specific currency pair
|
|
func (p *Poloniex) GetChartData(currencyPair, start, end, period string) ([]ChartData, error) {
|
|
vals := url.Values{}
|
|
vals.Set("currencyPair", currencyPair)
|
|
|
|
if start != "" {
|
|
vals.Set("start", start)
|
|
}
|
|
|
|
if end != "" {
|
|
vals.Set("end", end)
|
|
}
|
|
|
|
if period != "" {
|
|
vals.Set("period", period)
|
|
}
|
|
|
|
var resp []ChartData
|
|
path := fmt.Sprintf("%s/public?command=returnChartData&%s", p.API.Endpoints.URL, vals.Encode())
|
|
|
|
err := p.SendHTTPRequest(path, &resp)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return resp, nil
|
|
}
|
|
|
|
// GetCurrencies returns information about currencies
|
|
func (p *Poloniex) GetCurrencies() (map[string]Currencies, error) {
|
|
type Response struct {
|
|
Data map[string]Currencies
|
|
}
|
|
resp := Response{}
|
|
path := fmt.Sprintf("%s/public?command=returnCurrencies", p.API.Endpoints.URL)
|
|
|
|
return resp.Data, p.SendHTTPRequest(path, &resp.Data)
|
|
}
|
|
|
|
// GetLoanOrders returns the list of loan offers and demands for a given
|
|
// currency, specified by the "currency" GET parameter.
|
|
func (p *Poloniex) GetLoanOrders(currency string) (LoanOrders, error) {
|
|
resp := LoanOrders{}
|
|
path := fmt.Sprintf("%s/public?command=returnLoanOrders¤cy=%s", p.API.Endpoints.URL, currency)
|
|
|
|
return resp, p.SendHTTPRequest(path, &resp)
|
|
}
|
|
|
|
// GetBalances returns balances for your account.
|
|
func (p *Poloniex) GetBalances() (Balance, error) {
|
|
var result interface{}
|
|
|
|
err := p.SendAuthenticatedHTTPRequest(http.MethodPost, poloniexBalances, url.Values{}, &result)
|
|
if err != nil {
|
|
return Balance{}, err
|
|
}
|
|
|
|
data := result.(map[string]interface{})
|
|
balance := Balance{}
|
|
balance.Currency = make(map[string]float64)
|
|
|
|
for x, y := range data {
|
|
balance.Currency[x], _ = strconv.ParseFloat(y.(string), 64)
|
|
}
|
|
|
|
return balance, nil
|
|
}
|
|
|
|
// GetCompleteBalances returns complete balances from your account.
|
|
func (p *Poloniex) GetCompleteBalances() (CompleteBalances, error) {
|
|
var result interface{}
|
|
|
|
err := p.SendAuthenticatedHTTPRequest(http.MethodPost, poloniexBalancesComplete, url.Values{}, &result)
|
|
if err != nil {
|
|
return CompleteBalances{}, err
|
|
}
|
|
|
|
data := result.(map[string]interface{})
|
|
balance := CompleteBalances{}
|
|
balance.Currency = make(map[string]CompleteBalance)
|
|
|
|
for x, y := range data {
|
|
dataVals := y.(map[string]interface{})
|
|
balancesData := CompleteBalance{}
|
|
balancesData.Available, _ = strconv.ParseFloat(dataVals["available"].(string), 64)
|
|
balancesData.OnOrders, _ = strconv.ParseFloat(dataVals["onOrders"].(string), 64)
|
|
balancesData.BTCValue, _ = strconv.ParseFloat(dataVals["btcValue"].(string), 64)
|
|
balance.Currency[x] = balancesData
|
|
}
|
|
|
|
return balance, nil
|
|
}
|
|
|
|
// GetDepositAddresses returns deposit addresses for all enabled cryptos.
|
|
func (p *Poloniex) GetDepositAddresses() (DepositAddresses, error) {
|
|
var result interface{}
|
|
addresses := DepositAddresses{}
|
|
|
|
err := p.SendAuthenticatedHTTPRequest(http.MethodPost, poloniexDepositAddresses, url.Values{}, &result)
|
|
if err != nil {
|
|
return addresses, err
|
|
}
|
|
|
|
addresses.Addresses = make(map[string]string)
|
|
data, ok := result.(map[string]interface{})
|
|
if !ok {
|
|
return addresses, errors.New("return val not map[string]interface{}")
|
|
}
|
|
|
|
for x, y := range data {
|
|
addresses.Addresses[x] = y.(string)
|
|
}
|
|
|
|
return addresses, nil
|
|
}
|
|
|
|
// GenerateNewAddress generates a new address for a currency
|
|
func (p *Poloniex) GenerateNewAddress(currency string) (string, error) {
|
|
type Response struct {
|
|
Success int
|
|
Error string
|
|
Response string
|
|
}
|
|
resp := Response{}
|
|
values := url.Values{}
|
|
values.Set("currency", currency)
|
|
|
|
err := p.SendAuthenticatedHTTPRequest(http.MethodPost, poloniexGenerateNewAddress, values, &resp)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
|
|
if resp.Error != "" {
|
|
return "", errors.New(resp.Error)
|
|
}
|
|
|
|
return resp.Response, nil
|
|
}
|
|
|
|
// GetDepositsWithdrawals returns a list of deposits and withdrawals
|
|
func (p *Poloniex) GetDepositsWithdrawals(start, end string) (DepositsWithdrawals, error) {
|
|
resp := DepositsWithdrawals{}
|
|
values := url.Values{}
|
|
|
|
if start != "" {
|
|
values.Set("start", start)
|
|
} else {
|
|
values.Set("start", "0")
|
|
}
|
|
|
|
if end != "" {
|
|
values.Set("end", end)
|
|
} else {
|
|
values.Set("end", strconv.FormatInt(time.Now().Unix(), 10))
|
|
}
|
|
|
|
return resp, p.SendAuthenticatedHTTPRequest(http.MethodPost, poloniexDepositsWithdrawals, values, &resp)
|
|
}
|
|
|
|
// GetOpenOrders returns current unfilled opened orders
|
|
func (p *Poloniex) GetOpenOrders(currency string) (OpenOrdersResponse, error) {
|
|
values := url.Values{}
|
|
values.Set("currencyPair", currency)
|
|
result := OpenOrdersResponse{}
|
|
return result, p.SendAuthenticatedHTTPRequest(http.MethodPost, poloniexOrders, values, &result.Data)
|
|
}
|
|
|
|
// GetOpenOrdersForAllCurrencies returns all open orders
|
|
func (p *Poloniex) GetOpenOrdersForAllCurrencies() (OpenOrdersResponseAll, error) {
|
|
values := url.Values{}
|
|
values.Set("currencyPair", "all")
|
|
result := OpenOrdersResponseAll{}
|
|
return result, p.SendAuthenticatedHTTPRequest(http.MethodPost, poloniexOrders, values, &result.Data)
|
|
}
|
|
|
|
// GetAuthenticatedTradeHistoryForCurrency returns account trade history
|
|
func (p *Poloniex) GetAuthenticatedTradeHistoryForCurrency(currency string, start, end, limit int64) (AuthenticatedTradeHistoryResponse, error) {
|
|
values := url.Values{}
|
|
|
|
if start > 0 {
|
|
values.Set("start", strconv.FormatInt(start, 10))
|
|
}
|
|
|
|
if limit > 0 {
|
|
values.Set("limit", strconv.FormatInt(limit, 10))
|
|
}
|
|
|
|
if end > 0 {
|
|
values.Set("end", strconv.FormatInt(end, 10))
|
|
}
|
|
|
|
values.Set("currencyPair", currency)
|
|
result := AuthenticatedTradeHistoryResponse{}
|
|
return result, p.SendAuthenticatedHTTPRequest(http.MethodPost, poloniexTradeHistory, values, &result.Data)
|
|
}
|
|
|
|
// GetAuthenticatedTradeHistory returns account trade history
|
|
func (p *Poloniex) GetAuthenticatedTradeHistory(start, end, limit int64) (AuthenticatedTradeHistoryAll, error) {
|
|
values := url.Values{}
|
|
|
|
if start > 0 {
|
|
values.Set("start", strconv.FormatInt(start, 10))
|
|
}
|
|
|
|
if limit > 0 {
|
|
values.Set("limit", strconv.FormatInt(limit, 10))
|
|
}
|
|
|
|
if end > 0 {
|
|
values.Set("end", strconv.FormatInt(end, 10))
|
|
}
|
|
|
|
values.Set("currencyPair", "all")
|
|
var result json.RawMessage
|
|
|
|
err := p.SendAuthenticatedHTTPRequest(http.MethodPost, poloniexTradeHistory, values, &result)
|
|
if err != nil {
|
|
return AuthenticatedTradeHistoryAll{}, err
|
|
}
|
|
|
|
var nodata []interface{}
|
|
err = json.Unmarshal(result, &nodata)
|
|
if err == nil {
|
|
return AuthenticatedTradeHistoryAll{}, nil
|
|
}
|
|
|
|
var mainResult AuthenticatedTradeHistoryAll
|
|
return mainResult, json.Unmarshal(result, &mainResult.Data)
|
|
}
|
|
|
|
// PlaceOrder places a new order on the exchange
|
|
func (p *Poloniex) PlaceOrder(currency string, rate, amount float64, immediate, fillOrKill, buy bool) (OrderResponse, error) {
|
|
result := OrderResponse{}
|
|
values := url.Values{}
|
|
|
|
var orderType string
|
|
if buy {
|
|
orderType = order.Buy.Lower()
|
|
} else {
|
|
orderType = order.Sell.Lower()
|
|
}
|
|
|
|
values.Set("currencyPair", currency)
|
|
values.Set("rate", strconv.FormatFloat(rate, 'f', -1, 64))
|
|
values.Set("amount", strconv.FormatFloat(amount, 'f', -1, 64))
|
|
|
|
if immediate {
|
|
values.Set("immediateOrCancel", "1")
|
|
}
|
|
|
|
if fillOrKill {
|
|
values.Set("fillOrKill", "1")
|
|
}
|
|
|
|
return result, p.SendAuthenticatedHTTPRequest(http.MethodPost, orderType, values, &result)
|
|
}
|
|
|
|
// CancelExistingOrder cancels and order by orderID
|
|
func (p *Poloniex) CancelExistingOrder(orderID int64) error {
|
|
result := GenericResponse{}
|
|
values := url.Values{}
|
|
values.Set("orderNumber", strconv.FormatInt(orderID, 10))
|
|
|
|
err := p.SendAuthenticatedHTTPRequest(http.MethodPost, poloniexOrderCancel, values, &result)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
if result.Success != 1 {
|
|
return errors.New(result.Error)
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
// MoveOrder moves an order
|
|
func (p *Poloniex) MoveOrder(orderID int64, rate, amount float64, postOnly, immediateOrCancel bool) (MoveOrderResponse, error) {
|
|
result := MoveOrderResponse{}
|
|
values := url.Values{}
|
|
|
|
if orderID == 0 {
|
|
return result, errors.New("orderID cannot be zero")
|
|
}
|
|
|
|
if rate == 0 {
|
|
return result, errors.New("rate cannot be zero")
|
|
}
|
|
|
|
values.Set("orderNumber", strconv.FormatInt(orderID, 10))
|
|
values.Set("rate", strconv.FormatFloat(rate, 'f', -1, 64))
|
|
|
|
if postOnly {
|
|
values.Set("postOnly", "true")
|
|
}
|
|
|
|
if immediateOrCancel {
|
|
values.Set("immediateOrCancel", "true")
|
|
}
|
|
|
|
if amount != 0 {
|
|
values.Set("amount", strconv.FormatFloat(amount, 'f', -1, 64))
|
|
}
|
|
|
|
err := p.SendAuthenticatedHTTPRequest(http.MethodPost,
|
|
poloniexOrderMove,
|
|
values,
|
|
&result)
|
|
if err != nil {
|
|
return result, err
|
|
}
|
|
|
|
if result.Success != 1 {
|
|
return result, errors.New(result.Error)
|
|
}
|
|
|
|
return result, nil
|
|
}
|
|
|
|
// Withdraw withdraws a currency to a specific delegated address
|
|
func (p *Poloniex) Withdraw(currency, address string, amount float64) (*Withdraw, error) {
|
|
result := &Withdraw{}
|
|
values := url.Values{}
|
|
|
|
values.Set("currency", currency)
|
|
values.Set("amount", strconv.FormatFloat(amount, 'f', -1, 64))
|
|
values.Set("address", address)
|
|
|
|
err := p.SendAuthenticatedHTTPRequest(http.MethodPost, poloniexWithdraw, values, &result)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
if result.Error != "" {
|
|
return nil, errors.New(result.Error)
|
|
}
|
|
|
|
return result, nil
|
|
}
|
|
|
|
// GetFeeInfo returns fee information
|
|
func (p *Poloniex) GetFeeInfo() (Fee, error) {
|
|
result := Fee{}
|
|
|
|
return result, p.SendAuthenticatedHTTPRequest(http.MethodPost, poloniexFeeInfo, url.Values{}, &result)
|
|
}
|
|
|
|
// GetTradableBalances returns tradable balances
|
|
func (p *Poloniex) GetTradableBalances() (map[string]map[string]float64, error) {
|
|
type Response struct {
|
|
Data map[string]map[string]interface{}
|
|
}
|
|
result := Response{}
|
|
|
|
err := p.SendAuthenticatedHTTPRequest(http.MethodPost, poloniexTradableBalances, url.Values{}, &result.Data)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
balances := make(map[string]map[string]float64)
|
|
|
|
for x, y := range result.Data {
|
|
balances[x] = make(map[string]float64)
|
|
for z, w := range y {
|
|
balances[x][z], _ = strconv.ParseFloat(w.(string), 64)
|
|
}
|
|
}
|
|
|
|
return balances, nil
|
|
}
|
|
|
|
// TransferBalance transfers balances between your accounts
|
|
func (p *Poloniex) TransferBalance(currency, from, to string, amount float64) (bool, error) {
|
|
values := url.Values{}
|
|
result := GenericResponse{}
|
|
|
|
values.Set("currency", currency)
|
|
values.Set("amount", strconv.FormatFloat(amount, 'f', -1, 64))
|
|
values.Set("fromAccount", from)
|
|
values.Set("toAccount", to)
|
|
|
|
err := p.SendAuthenticatedHTTPRequest(http.MethodPost, poloniexTransferBalance, values, &result)
|
|
if err != nil {
|
|
return false, err
|
|
}
|
|
|
|
if result.Error != "" && result.Success != 1 {
|
|
return false, errors.New(result.Error)
|
|
}
|
|
|
|
return true, nil
|
|
}
|
|
|
|
// GetMarginAccountSummary returns a summary on your margin accounts
|
|
func (p *Poloniex) GetMarginAccountSummary() (Margin, error) {
|
|
result := Margin{}
|
|
return result, p.SendAuthenticatedHTTPRequest(http.MethodPost, poloniexMarginAccountSummary, url.Values{}, &result)
|
|
}
|
|
|
|
// PlaceMarginOrder places a margin order
|
|
func (p *Poloniex) PlaceMarginOrder(currency string, rate, amount, lendingRate float64, buy bool) (OrderResponse, error) {
|
|
result := OrderResponse{}
|
|
values := url.Values{}
|
|
|
|
var orderType string
|
|
if buy {
|
|
orderType = poloniexMarginBuy
|
|
} else {
|
|
orderType = poloniexMarginSell
|
|
}
|
|
|
|
values.Set("currencyPair", currency)
|
|
values.Set("rate", strconv.FormatFloat(rate, 'f', -1, 64))
|
|
values.Set("amount", strconv.FormatFloat(amount, 'f', -1, 64))
|
|
|
|
if lendingRate != 0 {
|
|
values.Set("lendingRate", strconv.FormatFloat(lendingRate, 'f', -1, 64))
|
|
}
|
|
|
|
return result, p.SendAuthenticatedHTTPRequest(http.MethodPost, orderType, values, &result)
|
|
}
|
|
|
|
// GetMarginPosition returns a position on a margin order
|
|
func (p *Poloniex) GetMarginPosition(currency string) (interface{}, error) {
|
|
values := url.Values{}
|
|
|
|
if currency != "" && currency != "all" {
|
|
values.Set("currencyPair", currency)
|
|
result := MarginPosition{}
|
|
return result, p.SendAuthenticatedHTTPRequest(http.MethodPost, poloniexMarginPosition, values, &result)
|
|
}
|
|
values.Set("currencyPair", "all")
|
|
|
|
type Response struct {
|
|
Data map[string]MarginPosition
|
|
}
|
|
result := Response{}
|
|
return result, p.SendAuthenticatedHTTPRequest(http.MethodPost, poloniexMarginPosition, values, &result.Data)
|
|
}
|
|
|
|
// CloseMarginPosition closes a current margin position
|
|
func (p *Poloniex) CloseMarginPosition(currency string) (bool, error) {
|
|
values := url.Values{}
|
|
values.Set("currencyPair", currency)
|
|
result := GenericResponse{}
|
|
|
|
err := p.SendAuthenticatedHTTPRequest(http.MethodPost, poloniexMarginPositionClose, values, &result)
|
|
if err != nil {
|
|
return false, err
|
|
}
|
|
|
|
if result.Success == 0 {
|
|
return false, errors.New(result.Error)
|
|
}
|
|
|
|
return true, nil
|
|
}
|
|
|
|
// CreateLoanOffer places a loan offer on the exchange
|
|
func (p *Poloniex) CreateLoanOffer(currency string, amount, rate float64, duration int, autoRenew bool) (int64, error) {
|
|
values := url.Values{}
|
|
values.Set("currency", currency)
|
|
values.Set("amount", strconv.FormatFloat(amount, 'f', -1, 64))
|
|
values.Set("duration", strconv.Itoa(duration))
|
|
|
|
if autoRenew {
|
|
values.Set("autoRenew", "1")
|
|
} else {
|
|
values.Set("autoRenew", "0")
|
|
}
|
|
|
|
values.Set("lendingRate", strconv.FormatFloat(rate, 'f', -1, 64))
|
|
|
|
type Response struct {
|
|
Success int `json:"success"`
|
|
Error string `json:"error"`
|
|
OrderID int64 `json:"orderID"`
|
|
}
|
|
|
|
result := Response{}
|
|
|
|
err := p.SendAuthenticatedHTTPRequest(http.MethodPost, poloniexCreateLoanOffer, values, &result)
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
|
|
if result.Success == 0 {
|
|
return 0, errors.New(result.Error)
|
|
}
|
|
|
|
return result.OrderID, nil
|
|
}
|
|
|
|
// CancelLoanOffer cancels a loan offer order
|
|
func (p *Poloniex) CancelLoanOffer(orderNumber int64) (bool, error) {
|
|
result := GenericResponse{}
|
|
values := url.Values{}
|
|
values.Set("orderID", strconv.FormatInt(orderNumber, 10))
|
|
|
|
err := p.SendAuthenticatedHTTPRequest(http.MethodPost, poloniexCancelLoanOffer, values, &result)
|
|
if err != nil {
|
|
return false, err
|
|
}
|
|
|
|
if result.Success == 0 {
|
|
return false, errors.New(result.Error)
|
|
}
|
|
|
|
return true, nil
|
|
}
|
|
|
|
// GetOpenLoanOffers returns all open loan offers
|
|
func (p *Poloniex) GetOpenLoanOffers() (map[string][]LoanOffer, error) {
|
|
type Response struct {
|
|
Data map[string][]LoanOffer
|
|
}
|
|
result := Response{}
|
|
|
|
err := p.SendAuthenticatedHTTPRequest(http.MethodPost, poloniexOpenLoanOffers, url.Values{}, &result.Data)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
if result.Data == nil {
|
|
return nil, errors.New("there are no open loan offers")
|
|
}
|
|
|
|
return result.Data, nil
|
|
}
|
|
|
|
// GetActiveLoans returns active loans
|
|
func (p *Poloniex) GetActiveLoans() (ActiveLoans, error) {
|
|
result := ActiveLoans{}
|
|
return result, p.SendAuthenticatedHTTPRequest(http.MethodPost, poloniexActiveLoans, url.Values{}, &result)
|
|
}
|
|
|
|
// GetLendingHistory returns lending history for the account
|
|
func (p *Poloniex) GetLendingHistory(start, end string) ([]LendingHistory, error) {
|
|
vals := url.Values{}
|
|
|
|
if start != "" {
|
|
vals.Set("start", start)
|
|
}
|
|
|
|
if end != "" {
|
|
vals.Set("end", end)
|
|
}
|
|
|
|
var resp []LendingHistory
|
|
return resp, p.SendAuthenticatedHTTPRequest(http.MethodPost,
|
|
poloniexLendingHistory,
|
|
vals,
|
|
&resp)
|
|
}
|
|
|
|
// ToggleAutoRenew allows for the autorenew of a contract
|
|
func (p *Poloniex) ToggleAutoRenew(orderNumber int64) (bool, error) {
|
|
values := url.Values{}
|
|
values.Set("orderNumber", strconv.FormatInt(orderNumber, 10))
|
|
result := GenericResponse{}
|
|
|
|
err := p.SendAuthenticatedHTTPRequest(http.MethodPost,
|
|
poloniexAutoRenew,
|
|
values,
|
|
&result)
|
|
if err != nil {
|
|
return false, err
|
|
}
|
|
|
|
if result.Success == 0 {
|
|
return false, errors.New(result.Error)
|
|
}
|
|
|
|
return true, nil
|
|
}
|
|
|
|
// SendHTTPRequest sends an unauthenticated HTTP request
|
|
func (p *Poloniex) SendHTTPRequest(path string, result interface{}) error {
|
|
return p.SendPayload(&request.Item{
|
|
Method: http.MethodGet,
|
|
Path: path,
|
|
Result: result,
|
|
Verbose: p.Verbose,
|
|
HTTPDebugging: p.HTTPDebugging,
|
|
HTTPRecording: p.HTTPRecording,
|
|
})
|
|
}
|
|
|
|
// SendAuthenticatedHTTPRequest sends an authenticated HTTP request
|
|
func (p *Poloniex) SendAuthenticatedHTTPRequest(method, endpoint string, values url.Values, result interface{}) error {
|
|
if !p.AllowAuthenticatedRequest() {
|
|
return fmt.Errorf(exchange.WarningAuthenticatedRequestWithoutCredentialsSet,
|
|
p.Name)
|
|
}
|
|
|
|
headers := make(map[string]string)
|
|
headers["Content-Type"] = "application/x-www-form-urlencoded"
|
|
headers["Key"] = p.API.Credentials.Key
|
|
values.Set("nonce", p.Requester.GetNonce(true).String())
|
|
values.Set("command", endpoint)
|
|
|
|
hmac := crypto.GetHMAC(crypto.HashSHA512,
|
|
[]byte(values.Encode()),
|
|
[]byte(p.API.Credentials.Secret))
|
|
|
|
headers["Sign"] = crypto.HexEncodeToString(hmac)
|
|
|
|
path := fmt.Sprintf("%s/%s", p.API.Endpoints.URL, poloniexAPITradingEndpoint)
|
|
|
|
return p.SendPayload(&request.Item{
|
|
Method: method,
|
|
Path: path,
|
|
Headers: headers,
|
|
Body: bytes.NewBufferString(values.Encode()),
|
|
Result: result,
|
|
AuthRequest: true,
|
|
NonceEnabled: true,
|
|
Verbose: p.Verbose,
|
|
HTTPDebugging: p.HTTPDebugging,
|
|
HTTPRecording: p.HTTPRecording,
|
|
})
|
|
}
|
|
|
|
// GetFee returns an estimate of fee based on type of transaction
|
|
func (p *Poloniex) GetFee(feeBuilder *exchange.FeeBuilder) (float64, error) {
|
|
var fee float64
|
|
switch feeBuilder.FeeType {
|
|
case exchange.CryptocurrencyTradeFee:
|
|
feeInfo, err := p.GetFeeInfo()
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
fee = calculateTradingFee(feeInfo,
|
|
feeBuilder.PurchasePrice,
|
|
feeBuilder.Amount,
|
|
feeBuilder.IsMaker)
|
|
|
|
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(feeInfo Fee, purchasePrice, amount float64, isMaker bool) (fee float64) {
|
|
if isMaker {
|
|
fee = feeInfo.MakerFee
|
|
} else {
|
|
fee = feeInfo.TakerFee
|
|
}
|
|
return fee * amount * purchasePrice
|
|
}
|
|
|
|
func getWithdrawalFee(c currency.Code) float64 {
|
|
return WithdrawalFees[c]
|
|
}
|