bitflyergo

package module
v1.3.14 Latest Latest
Warning

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

Go to latest
Published: Aug 21, 2021 License: MIT Imports: 18 Imported by: 2

README

bitflyergo

.github/workflows/test.yml CircleCI Go Report Card

bitflyergo is golang library to trade cryptocurrency on bitFlyer.

Support following functions.

  • REST-API Client
  • Realtime API (WebSocket JSON-RPC)
  • Utility functions

How to use

Here are some ways to use the library. If you want to know API specification, See tha public documents.

Initialize

You need to call bitflyergo.NewBitflyer with arguments. First argument is your api key, second that is your api secret. If you don't use private api, you may specify blank.

apiKey := "<Your API Key>"
apiSecret := "<Your API Secret>"
bf := bitflyergo.NewBitflyer(apiKey, apiSecret)
Call Public API
/v1/getexecutions

Get the last five execution histories of FX_BTC_JPY.

  • product_code: FX_BTC_JPY
  • count: 5
params := map[string]string{
    "product_code": "FX_BTC_JPY",
    "count":        "5",
}
executions, err := bf.GetExecutions(params)

Return value is []bitflyergo.Execution.

for _, e := range *executions {
    fmt.Println(e)
}
{800001572 2019-02-09T10:49:55.58 398759 0.01 BUY JRF20190209-XXXXX-XXXXX1 JRF20190209-YYYYYY-YYYYY1}
{800001572 2019-02-09T10:49:55.57 398758 0.01 BUY JRF20190209-XXXXX-XXXXX2 JRF20190209-YYYYYY-YYYYY2}
...
/v1/getboard
board, err := bf.GetBoard()
Call Private API
/v1/me/getexecutions
/v1/me/getchildorders
params := map[string]string{
    "": "",
}
childOrders, err := api.GetChildOrders(params)
/v1/me/getpositions
productCode := "FX_BTC_JPY"
positions, err := api.GetPositions(productCode)
/v1/me/getcollateral
collateral, err := api.GetCollateral()
/v1/me/getbalance
balance, err := api.GetBalance()
/v1/me/sendchildorder

Place the limit order. SendChildOrder returns childOrderAcceptanceId string. childOrderAcceptanceId is when order is accepted ID.

params := map[string]string{
    "price": "400000",
}
childOrderAcceptanceId, err := api.SendChildOrder("FX_BTC_JPY", "LIMIT", "BUY", 0.01, params)

Place the market order. market order does't need to specify price of argument.

childOrderAcceptanceId, err := api.SendChildOrder("FX_BTC_JPY", "MARKET", "BUY", 0.01, nil)
Receive streaming data from websocket

bitflyergo provides the APIs to use bitFlyer Lightning Realtime API.

First, you need to implement Callback interface's methods.

// OnReceiveBoard is the callbck when board is received from websocket.
OnReceiveBoard(channelName string, board *Board)

// OnReceiveBoardSnapshot is the callbck when board snapshot is received from websocket.
OnReceiveBoardSnapshot(channelName string, board *Board)

// OnReceiveExecutions is the callbck when executions is received from websocket.
OnReceiveExecutions(channelName string, executions []Execution)

// OnReceiveTicker is the callbck when ticker is received from websocket.
OnReceiveTicker(channelName string, ticker *Ticker)

// OnReceiveChildOrderEvents is the callbck when child order event is received from websocket.
OnReceiveChildOrderEvents(channelName string, event []ChildOrderEvent)

// OnReceiveParentOrderEvents is the callbck when board is received from websocket.
OnReceiveParentOrderEvents(channelName string, event []ParentOrderEvent)

// OnErrorOccur is the callbck when error is occurred during receiving stream data.
OnErrorOccur(channelName string, err error)

Then, Write code for receiving Realtime API data from websocket.

// Create WebSocketClient with Callback interface implement.
ws := WebSocketClient{
    Debug: false,
	Cb:    &YourCallbackImplement{},
}

// connect Realtime API.
err := ws.Connect()
if err != nil {
	log.Fatal(err)
}

// start receiving data. must to use goroutine.
go ws.Receive()

// subscribe channel
ws.SubscribeExecutions("FX_BTC_JPY")

interrupt := make(chan os.Signal, 1)
signal.Notify(interrupt, syscall.SIGINT, syscall.SIGTERM, syscall.SIGKILL)
LOOP:
	for {
		select {
		case _ = <-interrupt:
			break LOOP
		}
	}

How to test

Tests using private api require following environment variables.

export APIKEY=<value>
export APISECRET=<value>

Documentation

Index

Constants

View Source
const (

	// PathGetMyExecutions is path of api to get own executions
	PathGetMyExecutions = "/me/getexecutions"

	// PathGetChildOrders is path of api to get own child orders
	PathGetChildOrders = "/me/getchildorders"

	// PathGetPositions is path of api to get positions
	PathGetPositions = "/me/getpositions"

	// PathGetCollateral is path of api to get collateral
	PathGetCollateral = "/me/getcollateral"

	// PathGetBalance is path of api to get balance
	PathGetBalance = "/me/getbalance"

	// PathSendChildOrder is path of api to send child order
	PathSendChildOrder = "/me/sendchildorder"

	// PathCancelChildOrder is path of api to cancel child order
	PathCancelChildOrder = "/me/cancelchildorder"

	// PathCancelAllChildOrders is path of api to cancel all child orders
	PathCancelAllChildOrders = "/me/cancelallchildorders"
)
View Source
const (
	// PathGetMarkets is path of '/getmarkets'
	PathGetMarkets = "/getmarkets"

	// PathGetBoard is path of '/getboard'
	PathGetBoard = "/getboard"

	// PathGetTicker is path of '/getticker'
	PathGetTicker = "/getticker"

	// PathGetExecutions is path of '/getexecutions'
	PathGetExecutions = "/getexecutions"

	// PathGetBoardState is path of '/getboardstate'
	PathGetBoardState = "/getboardstate"

	// PathGetHealth is path of '/gethealth'
	PathGetHealth = "/gethealth"
)
View Source
const (
	HealthNormal         = "NORMAL"        // health: NORMAL
	HealthBusy           = "BUSY"          // health: BUSY
	HealthVeryBusy       = "VERY_BUSY"     // health: VERY_BUSY
	HealthSuperBusy      = "SUPER_BUSY"    // health: SUPER_BUSY
	HealthNoOrder        = "NO_ORDER"      // health: NO_ORDER
	HealthStop           = "STOP"          // health: STOP
	StateRunning         = "RUNNING"       // state: RUNNING
	StateClosed          = "CLOSED"        // state: CLOSED
	StateStarting        = "STARTING"      // state: STARTING
	StatePreopen         = "PREOPEN"       // state: PREOPEN
	StateCircuitBreak    = "CIRCUIT_BREAK" // state: CIRCUIT_BREAK
	StateAwatingSq       = "AWAITING_SQ"   // state: AWAITING_SQ
	StateMatured         = "MATURED"       // state: MATURED
	ChildOrderTypeLimit  = "LIMIT"         // order type: LIMIT
	ChildOrderTypeMarket = "MARKET"        // order type: MARKET
	SideBuy              = "BUY"           // side: BUY
	SideSell             = "SELL"          // side: SELL
	MinimumOrderbleSize  = 0.01            // minimum orderable size
)

Export const

View Source
const (

	// ProductCodeBtcJpy is product code of BTC_JPY
	ProductCodeBtcJpy = "BTC_JPY"

	// ProductCodeFxBtcJpy is product code of FX_BTC_JPY
	ProductCodeFxBtcJpy = "FX_BTC_JPY"

	// ProductCodeEthBtc is product code of ETH_BTC
	ProductCodeEthBtc = "ETH_BTC"
)

Variables

View Source
var Logger *log.Logger

Logger is logger.

Functions

This section is empty.

Types

type ApiError

type ApiError struct {
	Status       int    `json:"status"`        // status
	ErrorMessage string `json:"error_message"` // error_message
	Data         string `json:"data"`          // data
}

ApiError is lightning api error.

func (*ApiError) Error

func (err *ApiError) Error() string

Error returns error string

type Balance

type Balance struct {
	CurrencyCode string  `json:"currency_code"` // currency_code
	Amount       float64 `json:"amount"`        // amount
	Available    float64 `json:"available"`     // available
}

Balance is the balance of account.

type Bitflyer

type Bitflyer struct {
	BaseUrl    string // base url
	ApiVersion string // api version

	Debug         bool          // if true, debug mode
	RetryLimit    int           // retry limit
	RetryStatus   []int         // status to retry
	RetryInterval time.Duration // retry interval
	// contains filtered or unexported fields
}

Bitflyer is bitFlyer api client.

func NewBitflyer

func NewBitflyer(
	apiKey string,
	apiSecret string,
	retryStatus []int,
	retryLimit int,
	retryInterval time.Duration) *Bitflyer

NewBitflyer creates Bitflyer instance.

func (*Bitflyer) CancelAllChildOrders

func (bf *Bitflyer) CancelAllChildOrders(productCode string) error

CancelAllChildOrders cancels all child orders.

func (*Bitflyer) CancelChildOrder

func (bf *Bitflyer) CancelChildOrder(productCode string, childOrderAcceptanceId string) error

CancelChildOrder cancels child orders.

func (*Bitflyer) GetBalance

func (bf *Bitflyer) GetBalance() (*[]Balance, error)

GetBalance gets balance.

func (*Bitflyer) GetBoard

func (bf *Bitflyer) GetBoard(productCode string) (*Board, error)

GetBoard gets board of specified product_code.

func (*Bitflyer) GetBoardState

func (bf *Bitflyer) GetBoardState(productCode string) (*BoardState, error)

GetBoardState gets board state of spefied product_code.

func (*Bitflyer) GetChildOrders

func (bf *Bitflyer) GetChildOrders(params map[string]string) ([]ChildOrder, error)

GetChildOrders gets own child orders.

Required parameters - product_code

func (*Bitflyer) GetChildOrdersByDate

func (bf *Bitflyer) GetChildOrdersByDate(productCode string, from time.Time, to time.Time) ([]ChildOrder, error)

func (*Bitflyer) GetCollateral

func (bf *Bitflyer) GetCollateral() (*Collateral, error)

GetCollateral gets collateral.

func (*Bitflyer) GetExecutions

func (bf *Bitflyer) GetExecutions(params map[string]string) ([]Execution, error)

GetExecutions gets executions.

func (*Bitflyer) GetHealth

func (bf *Bitflyer) GetHealth(productCode string) (*Health, error)

GetHealth gets heath of market.

func (*Bitflyer) GetMarkets

func (bf *Bitflyer) GetMarkets() ([]Market, error)

GetMarkets gets market information.

func (*Bitflyer) GetMyExecutions

func (bf *Bitflyer) GetMyExecutions(params map[string]string) ([]MyExecution, error)

GetMyExecutions gets own executions.

func (*Bitflyer) GetMyExecutionsByDate

func (bf *Bitflyer) GetMyExecutionsByDate(productCode string, from time.Time, to time.Time) ([]MyExecution, error)

func (*Bitflyer) GetPositions

func (bf *Bitflyer) GetPositions(productCode string) ([]Position, error)

GetPositions gets positions.

func (*Bitflyer) GetRelatedExecutionByOrder

func (bf *Bitflyer) GetRelatedExecutionByOrder(order ChildOrder) ([]MyExecution, error)

func (*Bitflyer) GetTicker

func (bf *Bitflyer) GetTicker(productCode string) (*Ticker, error)

GetTicker gets ticker of specified product_code.

func (*Bitflyer) SendChildOrder

func (bf *Bitflyer) SendChildOrder(productCode string, childOrderType string,
	side string, size float64, params map[string]string) (map[string]string, error)

SendChildOrder send child order.

type Board

type Board struct {
	Time     time.Time           `json:"time"`      // time
	MidPrice float64             `json:"mid_price"` // mid_price
	Bids     map[float64]float64 `json:"bids"`      // bids
	Asks     map[float64]float64 `json:"asks"`      // asks
}

Board is board.

type BoardState

type BoardState struct {
	Health string             `json:"health"` // health
	State  string             `json:"state"`  // state
	Data   map[string]float64 `json:"data"`   // data
}

BoardState is board's state.

type Callback added in v1.3.0

type Callback interface {

	// OnReceiveBoard is the callbck when board is received from websocket.
	OnReceiveBoard(channelName string, board *Board)

	// OnReceiveBoardSnapshot is the callbck when board snapshot is received from websocket.
	OnReceiveBoardSnapshot(channelName string, board *Board)

	// OnReceiveExecutions is the callbck when executions is received from websocket.
	OnReceiveExecutions(channelName string, executions []Execution)

	// OnReceiveTicker is the callbck when ticker is received from websocket.
	OnReceiveTicker(channelName string, ticker *Ticker)

	// OnReceiveChildOrderEvents is the callbck when child order event is received from websocket.
	OnReceiveChildOrderEvents(channelName string, event []ChildOrderEvent)

	// OnReceiveParentOrderEvents is the callbck when board is received from websocket.
	OnReceiveParentOrderEvents(channelName string, event []ParentOrderEvent)

	// OnErrorOccur is the callbck when error is occurred during receiving stream data.
	OnErrorOccur(channelName string, err error)
}

Callback is the callback functions when receiving data from websocket.

type ChildOrder

type ChildOrder struct {
	Id                     int64          `json:"id"`                        // id
	ChildOrderId           string         `json:"child_order_id"`            // child_order_id
	ProductCode            string         `json:"product_code"`              // product_code
	Side                   string         `json:"side"`                      // side
	ChildOrderType         string         `json:"child_order_type"`          // child_order_type
	Price                  float64        `json:"price"`                     // price
	AveragePrice           float64        `json:"average_price"`             // average_price
	Size                   float64        `json:"size"`                      // size
	ChildOrderState        string         `json:"child_order_state"`         // child_order_state
	ExpireDate             TimeWithSecond `json:"expire_date"`               // expire_date
	ChildOrderDate         TimeWithSecond `json:"child_order_date"`          // child_order_date
	ChildOrderAcceptanceId string         `json:"child_order_acceptance_id"` // child_order_acceptance_id
	OutstandingSize        float64        `json:"outstanding_size"`          // outstanding_size
	CancelSize             float64        `json:"cancel_size"`               // cancel_size
	ExecutedSize           float64        `json:"executed_size"`             // executed_size
	TotalCommission        float64        `json:"total_commission"`          // total_commission
	Executions             []MyExecution
}

ChildOrder is own child orders.

type ChildOrderEvent

type ChildOrderEvent struct {
	ProductCode            string         `json:"product_code"`              // product_code
	ChildOrderId           string         `json:"child_order_id"`            // child_order_id
	ChildOrderAcceptanceId string         `json:"child_order_acceptance_id"` // child_order_acceptance_id
	EventDate              EventTime      `json:"event_date"`                // event_date
	EventType              string         `json:"event_type"`                // event_type
	ChildOrderType         string         `json:"child_order_type"`          // child_order_type
	ExpireDate             TimeWithSecond `json:"expire_date"`               // expire_date
	Reason                 string         `json:"reason"`                    // reason
	ExecId                 int            `json:"exec_id"`                   // exec_id
	Side                   string         `json:"side"`                      // side
	Price                  int            `json:"price"`                     // price
	Size                   float64        `json:"size"`                      // size
	Commission             float64        `json:"commission"`                // commission
	Sfd                    float64        `json:"sfd"`                       // sfd
}

ChildOrderEvent is type of child order event receiving from websocket.

func (*ChildOrderEvent) String

func (t *ChildOrderEvent) String() string

String converts all fields value to one string.

type Collateral

type Collateral struct {
	Collateral        float64 `json:"collateral"`         // collateral
	OpenPositionPnl   float64 `json:"open_position_pnl"`  // open_position_pnl
	RequireCollateral float64 `json:"require_collateral"` // require_collateral
	KeepRate          float64 `json:"keep_rate"`          // keep_rate
}

Collateral is the collateral of account.

type EventTime

type EventTime struct {
	*time.Time
}

func (*EventTime) UnmarshalJSON

func (tt *EventTime) UnmarshalJSON(data []byte) error

UnmarshalJSON converts json data to EventTime.

type Execution

type Execution struct {
	Id                         int64     `json:"id"`                             // id
	ExecDate                   time.Time `json:"exec_date"`                      // exec_date
	Price                      float64   `json:"price"`                          // price
	Size                       float64   `json:"size"`                           // size
	Side                       string    `json:"side"`                           // side
	BuyChildOrderAcceptanceId  string    `json:"buy_child_order_acceptance_id"`  // buy_child_order_acceptance_id
	SellChildOrderAcceptanceId string    `json:"sell_child_order_acceptance_id"` // sell_child_order_acceptance_id
	ReceivedTime               time.Time `json:receivedTime`                     // receivedTime
}

Execution is one of the execution history

func (*Execution) Delay

func (e *Execution) Delay() time.Duration

Delay returns delayed time of execution.

type Health

type Health struct {
	Status string `json:"status"` // status
}

Health is market health state.

type Market

type Market struct {
	ProductCode string `json:"product_code"` // product_code
	MarketType  string `json:"market_type"`  // market_type
	Alias       string `json:"alias"`        // alias
}

Market is the return value of '/getmarkets' API.

type MyExecution

type MyExecution struct {
	Id                     int64      `json:"id"`                        // id
	ChildOrderId           string     `json:"child_order_id"`            // child_order_id
	Side                   string     `json:"side"`                      // side
	Price                  float64    `json:"price"`                     // price
	Size                   float64    `json:"size"`                      // size
	Commission             float64    `json:"commission"`                // commission
	ExecDate               TickerTime `json:"exec_date"`                 // exec_date
	ChildOrderAcceptanceId string     `json:"child_order_acceptance_id"` // child_order_acceptance_id
}

MyExecution is executed own history.

type OHLC

type OHLC struct {
	Time   time.Time
	Open   float64
	High   float64
	Low    float64
	Close  float64
	Volume float64
	Delay  time.Duration
}

OHLC is four value candle(open, high, low, close).

func CreateOHLC

func CreateOHLC(executions []Execution, timeFrameSec int) ([]OHLC, error)

CreateOHLC converts executions to OHLC.

e.g.

timeFrameSec: 3 -> range is between xx:xx:00.000000 and xx:xx:02.999999
timeFrameSec: 5 -> range is between xx:xx:00.000000 and xx:xx:04.999999

type OpenDate added in v1.3.10

type OpenDate struct {
	*time.Time
}

OpenDate is the date created position

func (*OpenDate) UnmarshalJSON added in v1.3.10

func (tt *OpenDate) UnmarshalJSON(data []byte) error

UnmarshalJSON unmarchals json data.

type ParentOrderEvent

type ParentOrderEvent struct {
	ProductCode             string         `json:"product_code"`               // product_code
	ParentOrderId           string         `json:"parent_order_id"`            // parent_order_id
	ParentOrderAcceptanceId string         `json:"parent_order_acceptance_id"` // parent_order_acceptance_id
	EventDate               EventTime      `json:"event_date"`                 // event_date
	EventType               string         `json:"event_type"`                 // event_type
	ParentOrderType         string         `json:"parent_order_type"`          // parent_order_type
	Reason                  string         `json:"reason"`                     // reason
	ChildOrderType          string         `json:"child_order_type"`           // child_order_type
	ParameterIndex          int            `json:"parameter_index"`            // parameter_index
	ChildOrderAcceptanceId  string         `json:"child_order_acceptance_id"`  // child_order_acceptance_id
	Side                    string         `json:"side"`                       // side
	Price                   int            `json:"price"`                      // price
	Size                    float64        `json:"size"`                       // size
	ExpireDate              TimeWithSecond `json:"expire_date"`                // expire_date
}

Event of parent order happened.

type Position

type Position struct {
	ProductCode         string   `json:"product_code"`          // product_code
	Side                string   `json:"side"`                  // side
	Price               float64  `json:"price"`                 // price
	Size                float64  `json:"size"`                  // size
	Commission          float64  `json:"commission"`            // commission
	SwapPointAccumulate float64  `json:"swap_point_accumulate"` // swap_point_accumulate
	RequireCollateral   float64  `json:"require_collateral"`    // require_collateral
	OpenDate            OpenDate `json:"open_date"`             // open_date
	Leverage            float64  `json:"leverage"`              // leverage
	Pnl                 float64  `json:"pnl"`                   // pnl
	Std                 float64  `json:"sfd"`                   // sfd
}

Position is own positions.

type Ticker

type Ticker struct {
	ProductCode     string     `json:"product_code"`      // product_code
	Timestamp       TickerTime `json:"timestamp"`         // timestamp
	TickId          int64      `json:"tick_id"`           // tick_id
	BestBid         float64    `json:"best_bid"`          // best_bid
	BestAsk         float64    `json:"best_ask"`          // best_ask
	BestBidSize     float64    `json:"best_bid_size"`     // best_bid_size
	BestAskSize     float64    `json:"best_ask_size"`     // best_ask_size
	TotalBidDepth   float64    `json:"total_bid_depth"`   // total_bid_depth
	TotalAskDepth   float64    `json:"total_ask_depth"`   // total_ask_depth
	Ltp             float64    `json:"ltp"`               // ltp
	Volume          float64    `json:"volume"`            // volume
	VolumeByProduct float64    `json:"volume_by_product"` // volume_by_product
}

Ticker is the return value of '/getticker' API.

type TickerTime

type TickerTime struct {
	*time.Time
}

TickerTime is time of ticker.

func (*TickerTime) UnmarshalJSON

func (tt *TickerTime) UnmarshalJSON(data []byte) error

UnmarshalJSON unmarchals json data.

type TimeWithSecond

type TimeWithSecond struct {
	*time.Time
}

TimeWithSecond is time with second as time.Time

func (*TimeWithSecond) UnmarshalJSON

func (tt *TimeWithSecond) UnmarshalJSON(data []byte) error

UnmarshalJSON unmarchals json data.

type WebSocketClient

type WebSocketClient struct {
	Con   *websocket.Conn
	Debug bool
	Cb    Callback
}

func (*WebSocketClient) Auth

func (bf *WebSocketClient) Auth(apiKey string, apiSecret string) error

Auth authenticates client to subscribe private channels.

func (*WebSocketClient) Connect

func (bf *WebSocketClient) Connect() error

Connect connects to bitflyer's realtime api server.

func (*WebSocketClient) Receive

func (bf *WebSocketClient) Receive()

Receive start receiving stream data from websocket.

func (*WebSocketClient) SubscribeBoard

func (bf *WebSocketClient) SubscribeBoard(symbol string)

SubscribeBoard subscribes board.

func (*WebSocketClient) SubscribeBoardSnapshot

func (bf *WebSocketClient) SubscribeBoardSnapshot(symbol string)

SubscribeBoardSnapshot subscribes board snapshot.

func (*WebSocketClient) SubscribeChildOrder

func (bf *WebSocketClient) SubscribeChildOrder()

SubscribeChildOrder subscribes child orders.

func (*WebSocketClient) SubscribeExecutions

func (bf *WebSocketClient) SubscribeExecutions(symbol string)

SubscribeExecutions subscribes executions.

func (*WebSocketClient) SubscribeParentOrder

func (bf *WebSocketClient) SubscribeParentOrder()

SubscribeParentOrder subscribes parent orders.

func (*WebSocketClient) SubscribeTicker

func (bf *WebSocketClient) SubscribeTicker(symbol string)

SubscribeTicker subscribes ticker.

func (*WebSocketClient) UnsubscribeBoard

func (bf *WebSocketClient) UnsubscribeBoard(symbol string)

func (*WebSocketClient) UnsubscribeBoardSnapshot

func (bf *WebSocketClient) UnsubscribeBoardSnapshot(symbol string)

func (*WebSocketClient) UnsubscribeChildOrder

func (bf *WebSocketClient) UnsubscribeChildOrder()

func (*WebSocketClient) UnsubscribeExecutions

func (bf *WebSocketClient) UnsubscribeExecutions(symbol string)

UnsubscribeExecutions unsubscribes 'lightning_executions_${symbol}'.

func (*WebSocketClient) UnsubscribeParentOrder

func (bf *WebSocketClient) UnsubscribeParentOrder()

func (*WebSocketClient) UnsubscribeTicker

func (bf *WebSocketClient) UnsubscribeTicker(symbol string)

UnsubscribeTicker unsubscribes 'lightning_ticker_${symbol}'.

Jump to

Keyboard shortcuts

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