Recent Posts
Recent Comments
Archives
Today
Total
05-21 03:25
관리 메뉴

이것저것 잡동사니

[예제 코드/Python] 바이낸스 API를 이용한 암호화폐 선물 가격 데이터 얻기 본문

컴퓨터공학/예제 코드

[예제 코드/Python] 바이낸스 API를 이용한 암호화폐 선물 가격 데이터 얻기

Park Siyoung 2022. 6. 11. 08:15
반응형

아래의 파이썬 코드는 특정 기간 동안의 바이낸스 거래소 USDT 선물의 kline(datetime, 시작가, 최고가, 최저가, 종가, 거래량)을 얻기 위해 작성되었다.

Reference : https://binance-docs.github.io/apidocs/futures/en/#sdk-and-code-demonstration

 

binance.py

'''
Author : Park Siyoung (siyoung4528@gmail.com)
Date : 2022.06.11
Description : Python code to get kline of USDT future price of given period by using Binance API.
This is the first version. Lots of things to fix...
'''

from datetime import datetime
import requests
import time

base = 'https://fapi.binance.com'


def datetime_to_timestamp_ms(date_time):
    dt_obj = datetime.strptime(date_time, '%Y-%m-%d %H:%M:%S')
    return int(dt_obj.timestamp() * 1000)


def timestamp_ms_to_datetime(timestamp):
    return datetime.fromtimestamp(timestamp / 1000.0)


def get_server_time():
    res = requests.get(base + '/fapi/v1/time').json()
    return res['serverTime']


def get_order_book(symbol, limit=500):
    params = {'symbol': symbol,
              'limit': limit}
    res = requests.get(base + '/fapi/v1/depth', params=params).json()
    return res['bids'], res['asks']


def get_kline(symbol, from_timestamp, interval='1m', limit=500):
    params = {'symbol': symbol,
              'interval': interval,
              'startTime': from_timestamp,
              'limit': limit}
    res = requests.get(base + '/fapi/v1/klines', params=params).json()

    for item in res:
        for idx in range(6):
            del item[-1]

        for idx in range(1, 6):
            item[idx] = float(item[idx])

    return res

# [datetime, high, open, low, close, volume]
def get_kline_from_to(symbol, from_datetime, to_datetime='3000-01-01 00:00:00', interval='1m', timestamp=False):
    from_timestamp = datetime_to_timestamp_ms(from_datetime)
    from_init_timestamp = from_timestamp
    to_timestamp = datetime_to_timestamp_ms(to_datetime)

    if from_timestamp > to_timestamp:
        return []

    res = []

    while True:
        buf = get_kline(symbol, from_timestamp, interval, 1500)
        if len(buf) == 0:
            break

        res += buf

        if res[-1][0] > to_timestamp:
            break

        from_timestamp = res[-1][0] + 1
        time.sleep(0.3)  # Request Limit : 1200 Weights Per Min

        progress = float(res[-1][0] - from_init_timestamp) / (to_timestamp - from_init_timestamp) * 100
        progress = round(progress * 1000) / 1000
        print('\rDownloading... ', progress, '%      ', sep='', end='')

    while res[-1][0] > to_timestamp:
        del res[-1]

        if len(res) == 0:
            break

    print('\rDownloading... 100%      ', sep='', end='\n')

    if timestamp is False:
        for item in res:
            item[0] = timestamp_ms_to_datetime(item[0])

    return res

 

Usage

import binance

# [datetime, open, high, low, close , volume]
kline = binance.get_kline_from_to('BTCUSDT', '2020-01-01 00:00:01',
					     '2021-01-01 00:00:01', interval='1m')

 

반응형
Comments