Python システムトレード ビットコイン

bitFlyerのAPIを使ってビットコイン先物の価格情報を取得してみる

スポンサードリンク

Contents

bitFlyerでビットコイン先物の価格情報を取得してみる

bitFlyerでは、ビットコインの先物を取引できます。

現在(2017/05/09)だと、「BTCJPY12MAY2017」と「BTCJPY19MAY2017」の2種類になります。

1週間先(今週)と2週間先(来週)の金曜日が満期日の先物になります。

APIで使用するには、product_codeに「BTCJPY12MAY2017」もしくは「BTCJPY19MAY2017」を使用すればOKです。

今回は、これを使って、ビットコイン現物と2種類の先物の価格情報(Ticker)を取得します。

後々グラフで表示したいので、とりあえずMySQLのデータベースにINSERTするところまでを目指します。

では、早速ソースです。

ビットコイン現物と先物価格情報を取得(bitFlyer APIを使用)

# -*- coding: utf-8 -*-
"""
Created on Thu Mar  9 12:14:31 2017

@author: ichizo
"""

import bitflyerApi
from datetime import datetime
import pymysql

markets_path = '/v1/markets'

"""
dbh = pymysql.connect(
         host='localhost',
         user='root',
         password='',
         db='bitcoin',
         charset='utf8',
         cursorclass=pymysql.cursors.DictCursor
    )
"""

def get_product_code_list():
    api = bitflyerApi.bitflyerApi()
    market_list = api.get_api_call(markets_path).json()
    print(market_list)
    
    pc_list = []
    for market in market_list:
        if market['product_code'] != 'FX_BTC_JPY' and market['product_code'] != 'ETH_BTC':
            
            if 'alias' in market:
                pc = {'product_code':market['product_code'], 'alias':market['alias']}
            else:
                pc = {'product_code':market['product_code'], 'alias':market['product_code']}
    
            pc_list.append(pc)

    return pc_list

def insert_data(data):
    sql = "INSERT INTO bitflyers (product_code, alias, timestamp, \
            best_bid, best_ask, best_bid_size, best_ask_size, \
            total_bid_depth, total_ask_depth, ltp, \
            volume, volume_by_product, created) \
            VALUES ( \
            '%s', '%s' ,'%s', '%s', '%s', '%s', '%s', \
            '%s', '%s', '%s', '%s', '%s', '%s')" \
             % (data['product_code'], data['alias'], data['timestamp'], 
            data['best_bid'], data['best_ask'], data['best_bid_size'], data['best_ask_size'], \
            data['total_bid_depth'], data['total_ask_depth'], data['ltp'], \
            data['volume'], data['volume_by_product'], data['created'])
    print(sql)
"""
    stmt = dbh.cursor()

    stmt.execute(sql)
    dbh.commit()
    
    stmt.close()
    dbh.close()
"""

if __name__ == '__main__':
    
    pc_list = get_product_code_list();
    print(pc_list)
    
    api = bitflyerApi.bitflyerApi()
    now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    
    for pc in pc_list:
        channel = 'lightning_ticker_' + pc['product_code']
        result = api.pubnub_call(channel)
        print(result)
        result['timestamp'] = result['timestamp'][:26].replace('T',' ')
        result['alias'] = pc['alias']
        result['created'] = now
        
        insert_data(result)

とりあえず、SQL(INSERT文)を発行するところまでは実装しました。

PyMySQLの部分をコメントアウトしていますが、Python上でMySQLが扱えれば動くはずです(多分)。

今、手元に環境がないため、MySQLにデータが入るところまでは確認できていません。

近いうちにVPSでも契約しようかと思います。

今回実装したPythonプログラムでは、以前開発したAPIを扱うプログラムを使用していますので、そのソースも載せておきます。

必要なライブラリ等は以前の記事をご覧ください。

bitFlyer API

# -*- coding: utf-8 -*-
"""
Created on Thu Mar  9 12:00:27 2017

@author: ichizo
"""
from pubnub.pnconfiguration import PNConfiguration
from pubnub.pubnub import PubNub, SubscribeListener
import json
import requests
import time
import hmac
import hashlib
import util

class bitflyerApi:
    def __init__(self):
        self.api_key = 'APIキー'
        self.api_secret = 'APIシークレットキー'
        self.api_endpoint = 'https://api.bitflyer.jp'

    def get_api_call(self,path):
        method = 'GET'
        timestamp = str(time.time())
        text = timestamp + method + path
        sign = hmac.new(bytes(self.api_secret.encode('ascii')), bytes(text.encode('ascii')), hashlib.sha256).hexdigest()
        request_data=requests.get(
            self.api_endpoint+path
            ,headers = {
                'ACCESS-KEY': self.api_key,
                'ACCESS-TIMESTAMP': timestamp,
                'ACCESS-SIGN': sign,
                'Content-Type': 'application/json'
            })
        return request_data

    def post_api_call(self,path,body):
        body = json.dumps(body)
        method = 'POST'
        timestamp = str(time.time())
        text = timestamp + method + path + body
        sign = hmac.new(bytes(self.api_secret.encode('ascii')), bytes(text.encode('ascii')), hashlib.sha256).hexdigest()
        request_data=requests.post(
            self.api_endpoint+path
            ,data= body
            ,headers = {
                'ACCESS-KEY': self.api_key,
                'ACCESS-TIMESTAMP': timestamp,
                'ACCESS-SIGN': sign,
                'Content-Type': 'application/json'
            })
        return request_data

    """
        channel: 'lightning_ticker_BTC_JPY'
    """
    def pubnub_call(self,channel):
        pnconfig = PNConfiguration()
        pnconfig.subscribe_key = "sub-c-52a9ab50-291b-11e5-baaa-0619f8945a4f"
        pnconfig.ssl = False
     
        pubnub = PubNub(pnconfig)
        
        my_listener = SubscribeListener()
        pubnub.add_listener(my_listener)
         
        pubnub.subscribe().channels(channel).execute()
        my_listener.wait_for_connect()
    
        bf_result = my_listener.wait_for_message_on(channel)
        bf_data = bf_result.message
 
        pubnub.unsubscribe().channels(channel).execute()
        my_listener.wait_for_disconnect()
        
        return bf_data

    def get_board(self):
        api = bitflyerApi()
        result = api.pubnub_call('lightning_board_snapshot_BTC_JPY')
        bids = util.util.dict_to_pd(result['bids'],'bf',False)
        asks = util.util.dict_to_pd(result['asks'],'bf',True)
        return bids,asks
    
    def get_balance(self):
        api = bitflyerApi()
        result = api.get_api_call('/v1/me/getbalance').json()
        data = {}
        for row in result:
            if (row['currency_code'] == 'JPY'):
                data['jpy_amount'] = float(row['amount'])
                data['jpy_available'] = float(row['available'])
            elif (row['currency_code'] == 'BTC'):
                data['btc_amount'] = float(row['amount'])
                data['btc_available'] = float(row['available'])
        return data

    def order(self,data):
        api = bitflyerApi()
        result = api.post_api_call('/v1/me/sendchildorder',data).json()
        return result

データがたまったら、グラフで表示させる部分も実装してみようかと思います。

これらのデータで色々とできそうで、これから楽しみです!

-Python, システムトレード, ビットコイン
-, , , ,

© 2024 FX・ビットコイン・オプションのシステムトレード開発と取引録 Powered by AFFINGER5