🎉

bitFlyerの価格をブラウザで表示する

2023/10/22に公開
<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>BTCJPY 最新価格取得 via WebSocket</title>
    <script>
        let socket;

        function startWebSocket() {
            socket = new WebSocket("wss://ws.lightstream.bitflyer.com/json-rpc");

            socket.onopen = () => {
                console.log("WebSocket接続成功");
                const message = JSON.stringify({
                    method: "subscribe",
                    params: {
                        channel: "lightning_ticker_BTC_JPY"
                    }
                });
                socket.send(message);
            };

            socket.onmessage = (event) => {
                const response = JSON.parse(event.data);
                if (response.method && response.method === "channelMessage") {
                    const ticker = response.params.message;

                    const dateTime = new Date(ticker.timestamp);
                    dateTime.setHours(dateTime.getHours());
                    const formattedDateTime = `${dateTime.getFullYear()}-${String(dateTime.getMonth()+1).padStart(2, '0')}-${String(dateTime.getDate()).padStart(2, '0')} ${String(dateTime.getHours()).padStart(2, '0')}:${String(dateTime.getMinutes()).padStart(2, '0')}:${String(dateTime.getSeconds()).padStart(2, '0')}.${String(dateTime.getMilliseconds()).padStart(3, '0')}`;

                    document.getElementById('display').innerText = ` ${ticker.product_code}  ${formattedDateTime}   ${ticker.ltp} JPY`;
                }
            };

            socket.onerror = (error) => {
                console.error("WebSocketエラー:", error);
            };

            socket.onclose = (event) => {
                if (event.wasClean) {
                    console.log(`接続終了: code=${event.code}, reason=${event.reason}`);
                } else {
                    console.error('接続が突然終了');
                }
            };
        }
    </script>
</head>
<body onload="startWebSocket()">
    <h1>bitFlyer 最新価格 (WebSocket)</h1>
    <p id="display">通貨ペア: 取得中... 時刻: 取得中... 価格: 取得中...</p>
</body>
</html>


Discussion