Skip to content

Instantly share code, notes, and snippets.

@KobayashiTakaki
Created October 5, 2024 15:16
Show Gist options
  • Save KobayashiTakaki/e05982156bf5b7fd1d0a7641395b3918 to your computer and use it in GitHub Desktop.
Save KobayashiTakaki/e05982156bf5b7fd1d0a7641395b3918 to your computer and use it in GitHub Desktop.
bitFlyer lightning Realtime API から約定を取得するGoのサンプルコード
package main
import (
"encoding/json"
"fmt"
"net/url"
"time"
"github.com/gorilla/websocket"
)
const TIME_LAYOUT = "2006-01-02T15:04:05.999999999Z"
func main() {
// https://bf-lightning-api.readme.io/docs/realtime-executions
u := url.URL{
Scheme: "wss",
Host: "ws.lightstream.bitflyer.com",
Path: "/json-rpc",
}
c, _, err := websocket.DefaultDialer.Dial(u.String(), nil)
if err != nil {
fmt.Println(err)
return
}
err = c.SetWriteDeadline(time.Now().Add(10 * time.Second))
if err != nil {
fmt.Println(err)
return
}
req := SubscribeRequestObject{
JSONRPC: "2.0",
Method: "subscribe",
Params: SubscribeParams{Channel: "lightning_executions_FX_BTC_JPY"},
}
err = c.WriteJSON(req)
if err != nil {
fmt.Println(err)
return
}
res := new(ResponseObject)
err = c.ReadJSON(&res)
if err != nil {
fmt.Println(err)
return
}
if res.Error != nil {
fmt.Printf("error while subscribe. error: %v", res.Error)
return
}
for {
msg := new(ExecutionsChannelMessageRequestObject)
err := c.ReadJSON(msg)
if err != nil {
fmt.Println(err)
return
}
if msg.Method == "channelMessage" {
executions := msg.Params.Message
for _, e := range executions {
t, err := time.Parse(TIME_LAYOUT, e.ExecDate)
if err != nil {
fmt.Println(err)
continue
}
id, err := e.ID.Int64()
if err != nil {
fmt.Println(err)
continue
}
fmt.Printf("id: %d, side: %s, price: %f, size: %f, exec_date: %s\n", id, e.Side, e.Price, e.Size, t)
}
}
}
}
type SubscribeRequestObject struct {
JSONRPC string `json:"jsonrpc"`
Method string `json:"method"`
Params SubscribeParams `json:"params"`
ID *int64 `json:"id"`
}
type SubscribeParams struct {
Channel string `json:"channel"`
}
type ExecutionsChannelMessageRequestObject struct {
JSONRPC string `json:"jsonrpc"`
Method string `json:"method"`
Params ExecutionsChannelMessageParams `json:"params"`
ID *int64 `json:"id"`
}
type ResponseObject struct {
JSONRPC string `json:"jsonrpc"`
Result any `json:"result"`
Error any `json:"error"`
ID *int64 `json:"id"`
}
type ExecutionsChannelMessageParams struct {
Channel string `json:"channel"`
Message []struct {
ID json.Number `json:"id"`
Side string `json:"side"`
Price float64 `json:"price"`
Size float64 `json:"size"`
ExecDate string `json:"exec_date"`
BuyChildOrderAcceptanceID string `json:"buy_child_order_acceptance_id"`
SellChildOrderAcceptanceID string `json:"sell_child_order_acceptance_id"`
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment