Неверные значения из API веб-сокетов Mt. Gox

Я пытаюсь использовать веб-сокеты Mt.Gox API, чтобы получить последние котировки для валюты доллара США. Итак, я пишу следующий код, который подключается к «ws://websocket.mtgox.com:80/mtgox» и прослушивает сообщения.

#include <websocketpp/config/asio_no_tls_client.hpp>
#include <websocketpp/client.hpp>

#include <boost/property_tree/json_parser.hpp>

#include <cstdlib>
#include <iostream>
#include <map>
#include <string>

typedef websocketpp::client<websocketpp::config::asio_client> websocket_client_t;
typedef websocketpp::config::asio_client::message_type::ptr websocket_message_ptr_t;

const std::string WEBSOCKET_MTGOX_API_BASE_URL = "ws://websocket.mtgox.com:80/mtgox";
const std::string ORIGIN_HEADER_VALUE = "http://www.example.com";
const std::string TICKER_CHANNEL_ID = "d5f06780-30a8-4a48-a2f8-7ed181b4a13f";

boost::property_tree::ptree construct_pt_from_string(const std::string& json_string)
{
    boost::property_tree::ptree pt;
    std::stringstream json_isstr;
    json_isstr << json_string;

    boost::property_tree::read_json(json_isstr, pt);

    return pt;
}

bool is_ticker_channel(const boost::property_tree::ptree& pt)
{
    try
    {
        const std::string& channel_id = pt.get<std::string>("channel");
        if (channel_id != TICKER_CHANNEL_ID)
        {
            return false;
        }
    }
    catch (const boost::property_tree::ptree_error& ex)
    {
        return false;
    }

    return true;
}

void parse_message(const std::string& message)
{
    boost::property_tree::ptree message_pt;
    try
    {
        message_pt = construct_pt_from_string(message);
    }
    catch (const boost::property_tree::json_parser_error& ex)
    {
        std::cerr << "An error occurred while parsing message: " << ex.what() << '\n';
        return;
    }

    if (!is_ticker_channel(message_pt))
    {
        return;
    }

    try
    {
        const std::string& currency = message_pt.get<std::string>("ticker.buy.currency");
        double buy = message_pt.get<double>("ticker.buy.value");
        double sell = message_pt.get<double>("ticker.sell.value");

        std::cout << "Currency: " << currency << " | Buy: " << buy << " | Sell: " << sell << '\n';
    }
    catch (const boost::property_tree::ptree_error& ex)
    {
        std::cerr << "An error occurred while parsing message: " << ex.what() << '\n';
        return;
    }
}

void on_websocket_open(websocketpp::connection_hdl hdl)
{
    std::cout << "WebSocket successfully opened \n";
}

void on_websocket_close(websocketpp::connection_hdl hdl)
{
    std::cout << "WebSocket closed \n";
}

void on_websocket_message(websocket_client_t* c, websocketpp::connection_hdl hdl, websocket_message_ptr_t msg)
{
    const std::string& message = msg->get_payload();
    parse_message(message);
}

int main()
{
    try
    {
        websocket_client_t c;

        c.init_asio();

        c.set_open_handler(on_websocket_open);
        c.set_close_handler(on_websocket_close);
        c.set_message_handler(
            websocketpp::lib::bind(
                &on_websocket_message
                , &c
                , websocketpp::lib::placeholders::_1
                , websocketpp::lib::placeholders::_2
            )
        );

        websocketpp::lib::error_code error_code;
        websocket_client_t::connection_ptr con = c.get_connection(WEBSOCKET_MTGOX_API_BASE_URL + "?Currency=USD", error_code);
        if (error_code)
        {
            std::cerr << "An error occurred while using function get_connection: " << error_code.message() << '\n';
            return EXIT_FAILURE;
        }
        con->replace_header("Origin", ORIGIN_HEADER_VALUE);

        c.connect(con);

        c.run();
    }
    catch (const std::exception& e)
    {
        std::cout << e.what() << std::endl;
    }
    catch (const websocketpp::lib::error_code& e)
    {
        std::cout << e.message() << std::endl;
    }
}

Когда получено сообщение с каналом == "d5f06780-30a8-4a48-a2f8-7ed181b4a13f" (канал тикера), я пытаюсь разобрать его и получить значения ticker.buy.value и ticker.sell.value. Но значения далеки от аналогов из этой статистики - http://bitcoincharts.com/markets/currency/USD.html (только совпадения с низким и высоким уровнем). Что я делаю не так? Может быть, другой канал, сервер, поле json из сообщения или что-то еще?


person FrozenHeart    schedule 19.11.2013    source источник
comment
Я пошел по вашим стопам ( stackoverflow.com /questions/20055987/ ) Насколько я вижу, цены URL-адресов биткойн-чартов представляют собой статистику, собранную из значений реального времени, поступающих от вашего подключения к веб-сокету. Текущие цены спроса и предложения можно получить из канала depth.BTCUSD. Сделки показывают вам фактические сделки покупки и продажи. Тикер — это среднее значение, рассчитанное самим mtgox. Им легко манипулировать, поэтому, на мой взгляд, лучше придерживаться создания собственных данных свечей, используя торговый канал. И спасибо за код.   -  person nurettin    schedule 04.02.2014