少し前にJuliaのHTTP.jlを使ってbitflyerからリアルタイムに価格データを取得するコードを書いたので、備忘録として書き残します。 ※Javascriptなどのサンプルコードは公式ページ(https://bf-lightning-api.readme.io/docs/endpoint-json-rpc)にて提供されています。
HTTP.jlがWebSocketsモジュールを提供しているので、これを使います。
using HTTP using HTTP.WebSockets using URIs using JSON3 # wss://ws.lightstream.bitflyer.com/json-rpc url = URI(scheme="wss", host="ws.lightstream.bitflyer.com", path="/json-rpc") |> string # 取得する仮想通貨のコード product_code = "BTC_JPY" WebSockets.open(url) do ws try # JSONRPCのプロトコルに従って、 # コネクション時にsubscribeをリクエストする msg = Dict( "version" => "2.0", "method" => "subscribe", "params" => Dict( "channel" => "lightning_ticker_$(product_code)", ), ) @debug msg send(ws, JSON3.write(msg)) # リクエスト @info "open" for msg in ws # レスポンスデータ @show msg end catch e error(e) finally close(ws) @info "closed" end end
接続に成功すると、次のようなJSONが逐次送られてきます。
"{\"jsonrpc\":\"2.0\",\"method\":\"channelMessage\",\"params\":{\"channel\":\"lightning_ticker_BTC_JPY\",\"message\":{\"product_code\":\"BTC_JPY\",\"state\":\"RUNNING\",\"timestamp\":\"2023-08-17T07:25:01.3680432Z\",\"tick_id\":59827584,\"best_bid\":4197736.0,\"best_ask\":4198155.0,\"best_bid_size\":0.01,\"best_ask_size\":0.10,\"total_bid_depth\":390.953720690000,\"total_ask_depth\":338.76347988,\"market_bid_size\":0.0,\"market_ask_size\":0.0,\"ltp\":4198155.0,\"volume\":1211.068567520000,\"volume_by_product\":1211.068567520000,\"preopen_end\":null,\"circuit_break_end\":null}}}"
あとは必要に応じ型を用意して、JSON3.read
でjson文字列ををparseすればOK