LoginSignup
6

More than 5 years have passed since last update.

ZaifのストリーミングAPIをphpから使う

Last updated at Posted at 2015-04-03

experimentalらしいですがZaifでwebsocket APIが公開されました(誰か?ってツッコミは無用で)。

textalk/websocketを使って試してみます。

composer.json
"require": {
  "textalk/websocket": "1.0.*"
}

自分で php composer.phar update してね!

で、サンプルスクリプトはこんな感じで・・・

my.php
<?php

require('vendor/autoload.php');

use WebSocket\Client;

$url = "wss://ws.zaif.jp:8888/stream?currency_pair=mona_jpy";

$client = new Client($url);

while(true)
{
    try {
        $json = $client->receive();
        $data = json_decode($json); // var_dump($data)とかするとわかりやすいと思われ

        echo $data->timestamp . " last_price:" . $data->last_price->price . " " . $data->last_price->action . "\n";
    } catch (WebSocket\ConnectionException $e) {
        // ぶちっと切れる感じあるんで再接続
        $client = new Client($url);
    }
}

動かしてみると・・・

ryo@rubuntu:~/$ php my.php 
2015-04-03 19:09:36.039360 last_price:17.4 bid
2015-04-03 19:10:21.706524 last_price:17.4 bid
2015-04-03 19:10:24.845934 last_price:17.3 ask
2015-04-03 19:11:54.615810 last_price:17.3 ask
2015-04-03 19:11:55.325730 last_price:17.3 ask
2015-04-03 19:12:28.431111 last_price:17.3 ask
2015-04-03 19:12:29.152539 last_price:17.3 ask
2015-04-03 19:13:25.663307 last_price:17.3 ask
2015-04-03 19:13:27.630823 last_price:17.3 ask
2015-04-03 19:13:53.579406 last_price:17.3 ask
2015-04-03 19:13:56.745123 last_price:17.3 ask
2015-04-03 19:15:25.771214 last_price:17.3 ask
2015-04-03 19:15:26.482218 last_price:17.3 ask
...

と、流れてきますね

とりあえず10円きったらメールするようにして寝るか・・・(´∀`)

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6