Binance price history to the nearest second

Viewed 3256

I want to get the historical price for Binance for e.g. BTC/USDT at a specific time to the nearest second e.g. 2021-01-12 14:44:32 or 1610462672000.

This is to enable additional calculation for my historical trades that I have downloaded from Binance.

Using the following does not allow me to specify a specific time, it only returns the current price: https://api1.binance.com/api/v3/ticker/price?symbol=BTCUSDT

Result: {"symbol":"BTCUSDT","price":"56647.67000000"}

Second best is to get the candle info for 1 minute interval at a specific time to the nearest minute, but this would be inaccurate since the candle high and low can be separated significantly that would not represent the price at the time of the specific trade well enough. The following does give me the candle info for 1 minute interval at a specific time to the nearest minute. https://api.binance.com/api/v1/klines?symbol=BTCUSDT&interval=1m&limit=1&startTime=1610462672000

Result: [[1610462700000,"33236.78000000","33457.76000000","33226.43000000","33429.99000000","226.79694600",1610462759999,"7557664.59062870",3318,"146.99868600","4897805.74883424","0"]]

The ideal would be the following, to get the price at a specific time to the nearest second, but this does not work. https://api1.binance.com/api/v3/ticker/price?symbol=BTCUSDT&startTime=1610462672000

Any assistance regarding this would be great, thanks.

1 Answers

The lowest granularity that Binance REST API supports (for kline history) is 1 minute candles.

You'll need to use the WSS API, receive message for each trade real-time and aggregate them by each second.

Example in pseudocode:

/*
 * example: [1618829431 => 50000.01, 1618829432 => 50001.05, 1618829433 => 50002.23]
 */
array closeTimeToPrice = [];

function handleNewTradeMessage(message) {
    closeTimeToPrice[message.tradeTimeInSeconds] = message.price;
}

binanceWssApi.subscribe('BTCUSDT@aggTrade', handleNewTradeMessage);
Related