okex

package
v0.0.0-...-a2c5123 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 26, 2018 License: MIT Imports: 19 Imported by: 0

README

GoCryptoTrader package Okex

Build Status Software License GoDoc Coverage Status Go Report Card

This okex package is part of the GoCryptoTrader codebase.

This is still in active development

You can track ideas, planned features and what's in progresss on this Trello board: https://trello.com/b/ZAhMhpOy/gocryptotrader.

Join our slack to discuss all things related to GoCryptoTrader! GoCryptoTrader Slack

OKex Exchange

Current Features
  • REST Support
How to enable
  // Exchanges will be abstracted out in further updates and examples will be
  // supplied then
How to do REST public/private calls
  • If enabled via "configuration".json file the exchange will be added to the IBotExchange array in the go var bot Bot and you will only be able to use the wrapper interface functions for accessing exchange data. View routines.go for an example of integration usage with GoCryptoTrader. Rudimentary example below:

main.go

var o exchange.IBotExchange

for i := range bot.exchanges {
  if bot.exchanges[i].GetName() == "OKex" {
    y = bot.exchanges[i]
  }
}

// Public calls - wrapper functions

// Fetches current ticker information
tick, err := o.GetTickerPrice()
if err != nil {
  // Handle error
}

// Fetches current orderbook information
ob, err := o.GetOrderbookEx()
if err != nil {
  // Handle error
}

// Private calls - wrapper functions - make sure your APIKEY and APISECRET are
// set and AuthenticatedAPISupport is set to true

// Fetches current account information
accountInfo, err := o.GetExchangeAccountInfo()
if err != nil {
  // Handle error
}
  • If enabled via individually importing package, rudimentary example below:
// Public calls

// Fetches current ticker information
ticker, err := o.GetSpotTicker()
if err != nil {
  // Handle error
}

// Fetches current orderbook information
ob, err := o.GetSpotMarketDepth()
if err != nil {
  // Handle error
}

// Private calls - make sure your APIKEY and APISECRET are set and
// AuthenticatedAPISupport is set to true

// GetContractPosition returns contract positioning
accountInfo, err := o.GetContractPosition(...)
if err != nil {
  // Handle error
}

// Submits an order and the exchange and returns its tradeID
tradeID, err := o.PlaceContractOrders(...)
if err != nil {
  // Handle error
}
Please click GoDocs chevron above to view current GoDoc information for this package

Contribution

Please feel free to submit any pull requests or suggest any desired features to be added.

When submitting a PR, please abide by our coding guidelines:

  • Code must adhere to the official Go formatting guidelines (i.e. uses gofmt).
  • Code must be documented adhering to the official Go commentary guidelines.
  • Code must adhere to our coding style.
  • Pull requests need to be based on and opened against the master branch.

Donations

If this framework helped you in any way, or you would like to support the developers working on it, please donate Bitcoin to:

1F5zVDgNjorJ51oGebSvNCrSAHpwGkUdDB

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// SpotNewOrderRequestTypeBuy buy order
	SpotNewOrderRequestTypeBuy = SpotNewOrderRequestType("buy")

	// SpotNewOrderRequestTypeSell sell order
	SpotNewOrderRequestTypeSell = SpotNewOrderRequestType("sell")

	// SpotNewOrderRequestTypeBuyMarket buy market order
	SpotNewOrderRequestTypeBuyMarket = SpotNewOrderRequestType("buy_market")

	// SpotNewOrderRequestTypeSellMarket sell market order
	SpotNewOrderRequestTypeSellMarket = SpotNewOrderRequestType("sell_market")
)
View Source
var (
	TimeIntervalMinute         = TimeInterval("1min")
	TimeIntervalThreeMinutes   = TimeInterval("3min")
	TimeIntervalFiveMinutes    = TimeInterval("5min")
	TimeIntervalFifteenMinutes = TimeInterval("15min")
	TimeIntervalThirtyMinutes  = TimeInterval("30min")
	TimeIntervalHour           = TimeInterval("1hour")
	TimeIntervalFourHours      = TimeInterval("4hour")
	TimeIntervalSixHours       = TimeInterval("6hour")
	TimeIntervalTwelveHours    = TimeInterval("12hour")
	TimeIntervalDay            = TimeInterval("1day")
	TimeIntervalThreeDays      = TimeInterval("3day")
	TimeIntervalWeek           = TimeInterval("1week")
)

vars for time intervals

Functions

This section is empty.

Types

type ActualContractDepth

type ActualContractDepth struct {
	Asks []struct {
		Price  float64
		Volume float64
	}
	Bids []struct {
		Price  float64
		Volume float64
	}
}

ActualContractDepth better manipulated structure to return

type ActualContractTradeHistory

type ActualContractTradeHistory struct {
	Amount   float64 `json:"amount"`
	DateInMS float64 `json:"date_ms"`
	Date     float64 `json:"date"`
	Price    float64 `json:"price"`
	TID      float64 `json:"tid"`
	Type     string  `json:"buy"`
}

ActualContractTradeHistory holds contract trade history

type ActualSpotDepth

type ActualSpotDepth struct {
	Asks []struct {
		Price  float64
		Volume float64
	}
	Bids []struct {
		Price  float64
		Volume float64
	}
}

ActualSpotDepth better manipulated structure to return

type ActualSpotDepthRequestParams

type ActualSpotDepthRequestParams struct {
	Symbol string `json:"symbol"` // Symbol; example ltc_btc
	Size   int    `json:"size"`   // value: 1-200
}

ActualSpotDepthRequestParams represents Klines request data.

type ActualSpotTradeHistory

type ActualSpotTradeHistory struct {
	Amount   float64 `json:"amount"`
	DateInMS float64 `json:"date_ms"`
	Date     float64 `json:"date"`
	Price    float64 `json:"price"`
	TID      float64 `json:"tid"`
	Type     string  `json:"buy"`
}

ActualSpotTradeHistory holds contract trade history

type ActualSpotTradeHistoryRequestParams

type ActualSpotTradeHistoryRequestParams struct {
	Symbol string `json:"symbol"` // Symbol; example ltc_btc
	Since  int    `json:"since"`  // TID; transaction record ID (return data does not include the current TID value, returning up to 600 items)
}

ActualSpotTradeHistoryRequestParams represents Klines request data.

type CandleStickData

type CandleStickData struct {
	Timestamp float64 `json:"timestamp"`
	Open      float64 `json:"open"`
	High      float64 `json:"high"`
	Low       float64 `json:"low"`
	Close     float64 `json:"close"`
	Volume    float64 `json:"volume"`
	Amount    float64 `json:"amount"`
}

CandleStickData holds candlestick data

type ContractDepth

type ContractDepth struct {
	Asks   []interface{} `json:"asks"`
	Bids   []interface{} `json:"bids"`
	Result bool          `json:"result"`
	Error  interface{}   `json:"error_code"`
}

ContractDepth response depth

type ContractPrice

type ContractPrice struct {
	Date   string `json:"date"`
	Ticker struct {
		Buy        float64 `json:"buy"`
		ContractID float64 `json:"contract_id"`
		High       float64 `json:"high"`
		Low        float64 `json:"low"`
		Last       float64 `json:"last"`
		Sell       float64 `json:"sell"`
		UnitAmount float64 `json:"unit_amount"`
		Vol        float64 `json:"vol"`
	} `json:"ticker"`
	Result bool        `json:"result"`
	Error  interface{} `json:"error_code"`
}

ContractPrice holds date and ticker price price for contracts.

type DealsStreamData

type DealsStreamData = [][]string

type DepthStreamData

type DepthStreamData struct {
	Asks      [][]string `json:"asks"`
	Bids      [][]string `json:"bids"`
	Timestamp float64    `json:"timestamp"`
}

type FuturePosition

type FuturePosition struct {
	ForceLiquidationPrice float64    `json:"force_liqu_price"`
	Holding               []HoldData `json:"holding"`
}

FuturePosition contains an array of holding types

type FutureTradeHistory

type FutureTradeHistory struct {
	Amount float64 `json:"amount"`
	Date   int     `json:"date"`
	Price  float64 `json:"price"`
	TID    float64 `json:"tid"`
	Type   string  `json:"type"`
}

FutureTradeHistory will contain futures trade data

type HoldData

type HoldData struct {
	BuyAmount      float64 `json:"buy_amount"`
	BuyAvailable   float64 `json:"buy_available"`
	BuyPriceAvg    float64 `json:"buy_price_avg"`
	BuyPriceCost   float64 `json:"buy_price_cost"`
	BuyProfitReal  float64 `json:"buy_profit_real"`
	ContractID     float64 `json:"contract_id"`
	ContractType   string  `json:"contract_type"`
	CreateDate     int     `json:"create_date"`
	LeverRate      float64 `json:"lever_rate"`
	SellAmount     float64 `json:"sell_amount"`
	SellAvailable  float64 `json:"sell_available"`
	SellPriceAvg   float64 `json:"sell_price_avg"`
	SellPriceCost  float64 `json:"sell_price_cost"`
	SellProfitReal float64 `json:"sell_profit_real"`
	Symbol         string  `json:"symbol"`
}

HoldData is a sub type for FuturePosition

type Info

type Info struct {
	AccountRights float64 `json:"account_rights"`
	KeepDeposit   float64 `json:"keep_deposit"`
	ProfitReal    float64 `json:"profit_real"`
	ProfitUnreal  float64 `json:"profit_unreal"`
	RiskRate      float64 `json:"risk_rate"`
}

Info holds individual information

type KlineStreamData

type KlineStreamData = [][]string

type KlinesRequestParams

type KlinesRequestParams struct {
	Symbol string       // Symbol; example btcusdt, bccbtc......
	Type   TimeInterval // Kline data time interval; 1min, 5min, 15min......
	Size   int          // Size; [1-2000]
	Since  int64        // Since timestamp, return data after the specified timestamp (for example, 1417536000000)
}

KlinesRequestParams represents Klines request data.

type MultiStreamData

type MultiStreamData struct {
	Channel string          `json:"channel"`
	Data    json.RawMessage `json:"data"`
}

type OKEX

type OKEX struct {
	exchange.Base
	WebsocketConn *websocket.Conn

	// Spot and contract market error codes as per https://www.okex.com/rest_request.html
	ErrorCodes map[string]error

	// Stores for corresponding variable checks
	ContractTypes    []string
	CurrencyPairs    []string
	ContractPosition []string
	Types            []string
	// contains filtered or unexported fields
}

OKEX is the overaching type across the OKEX methods

func (*OKEX) CancelAllExchangeOrders

func (o *OKEX) CancelAllExchangeOrders() error

CancelAllExchangeOrders cancels all orders associated with a currency pair

func (*OKEX) CancelExchangeOrder

func (o *OKEX) CancelExchangeOrder(orderID int64) error

CancelExchangeOrder cancels an order by its corresponding ID number

func (*OKEX) CheckContractPosition

func (o *OKEX) CheckContractPosition(position string) error

CheckContractPosition checks to see if the string is a valid position for okex

func (*OKEX) CheckContractType

func (o *OKEX) CheckContractType(contractType string) error

CheckContractType checks to see if the string is a correct asset

func (*OKEX) CheckSymbol

func (o *OKEX) CheckSymbol(symbol string) error

CheckSymbol checks to see if the string is a valid symbol for okex

func (*OKEX) CheckType

func (o *OKEX) CheckType(typeInput string) error

CheckType checks to see if the string is a correct type

func (*OKEX) GetContractCandlestickData

func (o *OKEX) GetContractCandlestickData(symbol, typeInput, contractType string, size, since int) ([]CandleStickData, error)

GetContractCandlestickData returns CandleStickData

symbol e.g. btc_usd type e.g. 1min or 1 minute candlestick data contract_type e.g. this_week size: specify data size to be acquired since: timestamp(eg:1417536000000). data after the timestamp will be returned

func (*OKEX) GetContractExchangeRate

func (o *OKEX) GetContractExchangeRate() (float64, error)

GetContractExchangeRate returns the current exchange rate for the currency pair USD-CNY exchange rate used by OKEX, updated weekly

func (*OKEX) GetContractFutureEstimatedPrice

func (o *OKEX) GetContractFutureEstimatedPrice(symbol string) (float64, error)

GetContractFutureEstimatedPrice returns futures estimated price

symbol e.g btc_usd

func (*OKEX) GetContractFuturesTradeHistory

func (o *OKEX) GetContractFuturesTradeHistory(symbol, date string, since int) error

GetContractFuturesTradeHistory returns OKEX Contract Trade History (Not for Personal)

func (*OKEX) GetContractHoldingsNumber

func (o *OKEX) GetContractHoldingsNumber(symbol, contractType string) (number float64, contract string, err error)

GetContractHoldingsNumber returns current number of holdings

func (*OKEX) GetContractIndexPrice

func (o *OKEX) GetContractIndexPrice(symbol string) (float64, error)

GetContractIndexPrice returns the current index price

symbol e.g. btc_usd

func (*OKEX) GetContractMarketDepth

func (o *OKEX) GetContractMarketDepth(symbol, contractType string) (ActualContractDepth, error)

GetContractMarketDepth returns contract market depth

symbol e.g. "btc_usd" contractType e.g. "this_week" "next_week" "quarter"

func (*OKEX) GetContractPosition

func (o *OKEX) GetContractPosition(symbol, contractType string) error

GetContractPosition returns User Contract Positions (Cross-Margin Mode)

func (*OKEX) GetContractPrice

func (o *OKEX) GetContractPrice(symbol, contractType string) (ContractPrice, error)

GetContractPrice returns current contract prices

symbol e.g. "btc_usd" contractType e.g. "this_week" "next_week" "quarter"

func (*OKEX) GetContractTradeHistory

func (o *OKEX) GetContractTradeHistory(symbol, contractType string) ([]ActualContractTradeHistory, error)

GetContractTradeHistory returns trade history for the contract market

func (*OKEX) GetContractUserInfo

func (o *OKEX) GetContractUserInfo() error

GetContractUserInfo returns OKEX Contract Account Info(Cross-Margin Mode)

func (*OKEX) GetContractlimit

func (o *OKEX) GetContractlimit(symbol, contractType string) (map[string]float64, error)

GetContractlimit returns upper and lower price limit

func (*OKEX) GetErrorCode

func (o *OKEX) GetErrorCode(code interface{}) error

GetErrorCode finds the associated error code and returns its corresponding string

func (*OKEX) GetExchangeAccountInfo

func (o *OKEX) GetExchangeAccountInfo() (exchange.AccountInfo, error)

GetExchangeAccountInfo retrieves balances for all enabled currencies for the OKEX exchange

func (*OKEX) GetExchangeDepositAddress

func (o *OKEX) GetExchangeDepositAddress(cryptocurrency pair.CurrencyItem) (string, error)

GetExchangeDepositAddress returns a deposit address for a specified currency

func (*OKEX) GetExchangeFundTransferHistory

func (o *OKEX) GetExchangeFundTransferHistory() ([]exchange.FundHistory, error)

GetExchangeFundTransferHistory returns funding history, deposits and withdrawals

func (*OKEX) GetExchangeHistory

func (o *OKEX) GetExchangeHistory(p pair.CurrencyPair, assetType string) ([]exchange.TradeHistory, error)

GetExchangeHistory returns historic trade data since exchange opening.

func (*OKEX) GetExchangeOrderInfo

func (o *OKEX) GetExchangeOrderInfo(orderID int64) (exchange.OrderDetail, error)

GetExchangeOrderInfo returns information on a current open order

func (*OKEX) GetLatestSpotPrice

func (o *OKEX) GetLatestSpotPrice(symbol string) (float64, error)

GetLatestSpotPrice returns latest spot price of symbol

symbol: string of currency pair

func (*OKEX) GetOrderbookEx

func (o *OKEX) GetOrderbookEx(currency pair.CurrencyPair, assetType string) (orderbook.Base, error)

GetOrderbookEx returns orderbook base on the currency pair

func (*OKEX) GetSpotKline

func (o *OKEX) GetSpotKline(arg KlinesRequestParams) ([]CandleStickData, error)

GetSpotKline returns candlestick data

func (*OKEX) GetSpotMarketDepth

func (o *OKEX) GetSpotMarketDepth(asd ActualSpotDepthRequestParams) (ActualSpotDepth, error)

GetSpotMarketDepth returns Market Depth

func (*OKEX) GetSpotRecentTrades

func (o *OKEX) GetSpotRecentTrades(ast ActualSpotTradeHistoryRequestParams) ([]ActualSpotTradeHistory, error)

GetSpotRecentTrades returns recent trades

func (*OKEX) GetSpotTicker

func (o *OKEX) GetSpotTicker(symbol string) (SpotPrice, error)

GetSpotTicker returns Price Ticker

func (*OKEX) GetTickerPrice

func (o *OKEX) GetTickerPrice(p pair.CurrencyPair, assetType string) (ticker.Price, error)

GetTickerPrice returns the ticker for a currency pair

func (*OKEX) GetUserInfo

func (o *OKEX) GetUserInfo() (SpotUserInfo, error)

GetUserInfo returns the user info

func (*OKEX) ModifyExchangeOrder

func (o *OKEX) ModifyExchangeOrder(orderID int64, action exchange.ModifyOrder) (int64, error)

ModifyExchangeOrder will allow of changing orderbook placement and limit to market conversion

func (*OKEX) PlaceContractOrders

func (o *OKEX) PlaceContractOrders(symbol, contractType, position string, leverageRate int, price, amount float64, matchPrice bool) (float64, error)

PlaceContractOrders places orders

func (*OKEX) Run

func (o *OKEX) Run()

Run implements the OKEX wrapper

func (*OKEX) SendAuthenticatedHTTPRequest

func (o *OKEX) SendAuthenticatedHTTPRequest(method string, values url.Values, result interface{}) (err error)

SendAuthenticatedHTTPRequest sends an authenticated http request to a desired path

func (*OKEX) SendHTTPRequest

func (o *OKEX) SendHTTPRequest(path string, result interface{}) error

SendHTTPRequest sends an unauthenticated HTTP request

func (*OKEX) SetCheckVarDefaults

func (o *OKEX) SetCheckVarDefaults()

SetCheckVarDefaults sets main variables that will be used in requests because api does not return an error if there are misspellings in strings. So better to check on this, this end.

func (*OKEX) SetDefaults

func (o *OKEX) SetDefaults()

SetDefaults method assignes the default values for Bittrex

func (*OKEX) SetErrorDefaults

func (o *OKEX) SetErrorDefaults()

SetErrorDefaults sets the full error default list

func (*OKEX) Setup

func (o *OKEX) Setup(exch config.ExchangeConfig)

Setup method sets current configuration details if enabled

func (*OKEX) SpotCancelOrder

func (o *OKEX) SpotCancelOrder(symbol string, argOrderID int64) (int64, error)

SpotCancelOrder cancels a spot order symbol such as ltc_btc orderID orderID returns orderID or an error

func (*OKEX) SpotNewOrder

func (o *OKEX) SpotNewOrder(arg SpotNewOrderRequestParams) (int64, error)

SpotNewOrder creates a new spot order

func (*OKEX) Start

func (o *OKEX) Start(wg *sync.WaitGroup)

Start starts the OKEX go routine

func (*OKEX) SubmitExchangeOrder

func (o *OKEX) SubmitExchangeOrder(p pair.CurrencyPair, side exchange.OrderSide, orderType exchange.OrderType, amount, price float64, clientID string) (int64, error)

SubmitExchangeOrder submits a new order

func (*OKEX) UpdateOrderbook

func (o *OKEX) UpdateOrderbook(p pair.CurrencyPair, assetType string) (orderbook.Base, error)

UpdateOrderbook updates and returns the orderbook for a currency pair

func (*OKEX) UpdateTicker

func (o *OKEX) UpdateTicker(p pair.CurrencyPair, assetType string) (ticker.Price, error)

UpdateTicker updates and returns the ticker for a currency pair

func (*OKEX) WebsocketClient

func (o *OKEX) WebsocketClient()

WebsocketClient the main function handling the OKEX websocket Documentation URL: https://github.com/okcoin-okex/API-docs-OKEx.com/blob/master/API-For-Spot-EN/WEBSOCKET%20API%20for%20SPOT.md

func (*OKEX) WithdrawCryptoExchangeFunds

func (o *OKEX) WithdrawCryptoExchangeFunds(address string, cryptocurrency pair.CurrencyItem, amount float64) (string, error)

WithdrawCryptoExchangeFunds returns a withdrawal ID when a withdrawal is submitted

func (*OKEX) WithdrawFiatExchangeFunds

func (o *OKEX) WithdrawFiatExchangeFunds(currency pair.CurrencyItem, amount float64) (string, error)

WithdrawFiatExchangeFunds returns a withdrawal ID when a withdrawal is submitted

func (*OKEX) WithdrawFiatExchangeFundsToInternationalBank

func (o *OKEX) WithdrawFiatExchangeFundsToInternationalBank(currency pair.CurrencyItem, amount float64) (string, error)

WithdrawFiatExchangeFundsToInternationalBank returns a withdrawal ID when a withdrawal is submitted

type SpotDepth

type SpotDepth struct {
	Asks   []interface{} `json:"asks"`
	Bids   []interface{} `json:"bids"`
	Result bool          `json:"result"`
	Error  interface{}   `json:"error_code"`
}

SpotDepth response depth

type SpotNewOrderRequestParams

type SpotNewOrderRequestParams struct {
	Amount float64                 `json:"amount"` // Order quantity
	Price  float64                 `json:"price"`  // Order price
	Symbol string                  `json:"symbol"` // Symbol; example btc_usdt, eth_btc......
	Type   SpotNewOrderRequestType `json:"type"`   // Order type (see below)
}

SpotNewOrderRequestParams holds the params for making a new spot order

type SpotNewOrderRequestType

type SpotNewOrderRequestType string

SpotNewOrderRequestType order type

type SpotPrice

type SpotPrice struct {
	Date   string `json:"date"`
	Ticker struct {
		Buy        float64 `json:"buy,string"`
		ContractID float64 `json:"contract_id"`
		High       float64 `json:"high,string"`
		Low        float64 `json:"low,string"`
		Last       float64 `json:"last,string"`
		Sell       float64 `json:"sell,string"`
		UnitAmount float64 `json:"unit_amount,string"`
		Vol        float64 `json:"vol,string"`
	} `json:"ticker"`
	Result bool        `json:"result"`
	Error  interface{} `json:"error_code"`
}

SpotPrice holds date and ticker price price for contracts.

type SpotUserInfo

type SpotUserInfo struct {
	Result bool                                    `json:"result"`
	Info   map[string]map[string]map[string]string `json:"info"`
}

SpotUserInfo holds the spot user info

type TickerStreamData

type TickerStreamData struct {
	Buy       string  `json:"buy"`
	Change    string  `json:"change"`
	High      string  `json:"high"`
	Low       string  `json:"low"`
	Last      string  `json:"last"`
	Sell      string  `json:"sell"`
	DayLow    string  `json:"dayLow"`
	DayHigh   string  `json:"dayHigh"`
	Timestamp float64 `json:"timestamp"`
	Vol       string  `json:"vol"`
}

type TimeInterval

type TimeInterval string

TimeInterval represents interval enum.

type UserInfo

type UserInfo struct {
	Info struct {
		BTC Info `json:"btc"`
		LTC Info `json:"ltc"`
	} `json:"info"`
	Result bool `json:"result"`
}

UserInfo holds a collection of user data

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL