GDAX api, создайте график свечей
Я хотел бы создать график свечей, используя API GDAX. В настоящее время я использую HTTP-запрос для хронологических данных https://docs.gdax.com/ ошибка, это помечено, что я должен использовать websocket API. К сожалению, я не знаю, как обрабатывать исторические данные через API веб-сокета Gdax https://github.com/coinbase/gdax-node. Может ли кто-нибудь помочь мне?
2 ответа
Вот 1м подсвечники, построенные из канала совпадений с использованием веб-розетки GDAX
"use strict";
const
WebSocket = require('ws'),
PRECISION = 8
function _getPair(pair) {
return pair.split('-')
}
let ws = new WebSocket('wss://ws-feed.pro.coinbase.com')
ws.on('open', () => {
ws.send(JSON.stringify({
"type": "subscribe",
"product_ids": [
"ETH-USD",
"BTC-USD"
],
"channels": [
"matches"
]
}))
})
let candles = {}
let lastCandleMap = {}
ws.on('message', msg => {
msg = JSON.parse(msg);
if (!msg.price)
return;
if (!msg.size)
return;
// Price and volume are sent as strings by the API
msg.price = parseFloat(msg.price)
msg.size = parseFloat(msg.size)
let productId = msg.product_id;
let [base, quote] = _getPair(productId);
// Round the time to the nearest minute, Change as per your resolution
let roundedTime = Math.floor(new Date(msg.time) / 60000.0) * 60
// If the candles hashmap doesnt have this product id create an empty object for that id
if (!candles[productId]) {
candles[productId] = {}
}
// If the current product's candle at the latest rounded timestamp doesnt exist, create it
if (!candles[productId][roundedTime]) {
//Before creating a new candle, lets mark the old one as closed
let lastCandle = lastCandleMap[productId]
if (lastCandle) {
lastCandle.closed = true;
delete candles[productId][lastCandle.timestamp]
}
// Set Quote Volume to -1 as GDAX doesnt supply it
candles[productId][roundedTime] = {
timestamp: roundedTime,
open: msg.price,
high: msg.price,
low: msg.price,
close: msg.price,
baseVolume: msg.size,
quoteVolume: -1,
closed: false
}
}
// If this timestamp exists in our map for the product id, we need to update an existing candle
else {
let candle = candles[productId][roundedTime]
candle.high = msg.price > candle.high ? msg.price : candle.high
candle.low = msg.price < candle.low ? msg.price : candle.low
candle.close = msg.price
candle.baseVolume = parseFloat((candle.baseVolume + msg.size).toFixed(PRECISION))
// Set the last candle as the one we just updated
lastCandleMap[productId] = candle
}
})
Они предлагают получить исторические показатели https://docs.gdax.com/ с этой конечной точки, а затем обновлять свечи, используя сообщения канала Websocket - всякий раз, когда происходит "совпадение" / сообщение о тикере получено, вы обновляете последнюю свечу соответственно.
Из документов: "Максимальное количество точек данных для одного запроса составляет 300 свечей. Если при выборе времени начала / окончания и степени детализации будет получено более 300 точек данных, ваш запрос будет отклонен". поэтому, вероятно, почему вы не можете получить данные более чем за 2 дня.
пс. У меня есть живая книга заказов, реализованная здесь, и базовая свечная диаграмма - лоты еще не полностью соединены, но, по крайней мере, доступны для предварительного просмотра до его полной https://github.com/robevansuk/gdax-java/