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

bitFlyer,Zaif,coincheckのビットコインAPIで取得した板方法をpandasに突っ込んでみた

スポンサードリンク

Contents

ビットコインAPIで取得した板方法をpandasに突っ込んでみた

bitFlyer, Zaif, coincheckの
各ビットコイン取引所で
提供されているAPIを呼び出す
Pythonプログラムを作ってきました。

今回は、取得した板情報を使いやすいように
pandasに突っ込む処理を実装してみました。

bitFlyer

bitFlyer ビットコインを始めるなら安心・安全な取引所で

以前作成したプログラムをカスタマイズしています。

# -*- 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')
        asks = util.util.dict_to_pd(result['asks'],'bf')
        return bids,asks
    
    def get_balance(self):
        api = bitflyerApi()
        result = api.get_api_call('/v1/me/getbalance').json()
        print('bitFlyer Balance:')
        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'])
        print(data)
        return data

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

Zaif

これも、以前作成したプログラムを修正しています。

# -*- coding: utf-8 -*-
"""
Created on Fri Mar 10 14:37:22 2017

@author: ichizo
"""

from zaifapi import ZaifPublicApi, ZaifPrivateApi
import util

class zaifApi:
    def __init__(self):
        self.api_key = 'APIキー'
        self.api_secret = 'APIシークレット'

    def get_board(self):
        zaif = ZaifPublicApi()
        result = zaif.depth('btc_jpy')
        bids = util.util.list_to_pd(result['bids'],'zf')
        asks = util.util.list_to_pd(result['asks'],'zf')
        return bids,asks

    def get_balance(self):
        zaif = ZaifPrivateApi(self.api_key, self.api_secret)
        result = zaif.get_info()
        data = {}
        data['jpy_amount'] = float(result['funds']['jpy'])
        data['jpy_available'] = float(result['funds']['jpy'])
        data['btc_amount'] = float(result['funds']['btc'])
        data['btc_available'] = float(result['funds']['btc'])
        return data
    """
        trade(currency_pair="btc_jpy",action="bid",price=5000,amount=0.001)
    """
    def order(self,data):
        zaif = ZaifPrivateApi(self.api_key, self.api_secret)
        return zaif.trade(data)

coincheck

日本で一番簡単にビットコインが買える取引所 coincheck bitcoin

こちらも以前作成したプログラムを修正しています。

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

@author: ichizo
"""

import json
import requests
import time
import hmac
import hashlib
import util

class coincheckApi:
    def __init__(self):
        self.api_key = 'APIキー'
        self.api_secret = 'APIシークレット'
        self.api_endpoint = 'https://coincheck.com'

    def get_api_call(self,path):
        timestamp = str(int(time.time()))
        text = timestamp + self.api_endpoint + 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-NONCE': timestamp,
                'ACCESS-SIGNATURE': sign,
                'Content-Type': 'application/json'
            })
        return request_data

    def post_api_call(self,path,body):
        body = json.dumps(body)
        timestamp = str(int(time.time()))
        text = timestamp + self.api_endpoint + 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-NONCE': timestamp,
                'ACCESS-SIGNATURE': sign,
                'Content-Type': 'application/json'
            })
        return request_data

    def get_board(self):
        api = coincheckApi()
        result = api.get_api_call('/api/order_books').json()
        bids = util.util.list_to_pd(result['bids'],'cc')
        asks = util.util.list_to_pd(result['asks'],'cc')
        return bids,asks

    def get_balance(self):
        api = coincheckApi()
        result = api.get_api_call('/api/accounts/balance').json()
        data = {}
        data['jpy_amount'] = float(result['jpy'])
        data['jpy_available'] = float(result['jpy']) - float(result['jpy_reserved'])
        data['btc_amount'] = float(result['btc'])
        data['btc_available'] = float(result['btc']) - float(result['btc_reserved'])
        return data
    
    def order(self,data):
        api = coincheckApi()
        result = api.post_api_call('/api/exchange/orders',data).json()
        return result

共通部品

bitflyerApi.py, zaifApi.py, coincheckApi.py の
それぞれのプログラム内で使用している共通部品です。

APIで返ってきた板情報をpandasのDataFrameに
セットして返す処理を行っています。

# -*- coding: utf-8 -*-
"""
Created on Sun Mar 12 20:56:18 2017

@author: ichizo
"""

import pandas as pd

class util:

    def dict_to_pd(datas,code):
        price = []
        size = []
        code = []
        for data in datas:
            price.append(float(data['price']))
            size.append(float(data['size']))
            code.append(code)
        vals = pd.DataFrame([price,size,code]).T
        vals.columns = ["price","size","code"]
        return vals

    def list_to_pd(datas,code):
        price = []
        size = []
        code = []
        for data in datas:
            price.append(float(data[0]))
            size.append(float(data[1]))
            code.append(code)
        vals = pd.DataFrame([price,size,code]).T
        vals.columns = ["price","size","code"]
        return vals

その他

あとは、QUOINEのAPIを使う処理を実装したいのですが、
Private APIの呼び出しでつまづいています。

多分、Token IDの指定が良くないんだろうなと思いつつ、
何をセットすればいいのか分かんないのです。

APIトークンを生成したときに表示されている
ID(5桁の数字)でいいのかな~?

ご存知の方いらっしゃったら教えてください!

QUOINEのサポートにメッセージを送ったのですが、
ちょうど土日を挟んでしまって返信待ちの状態です・・・。

ココを見ると「USERID」と書いているので
やっぱり5桁の数字なんでしょうか・・・。
いずれにしても、もうちょっと弄ってみます。

2017/3/13 追記

QUOINEのAPIで接続を行うことができました。

ソースコードは変えずに次の日に接続してみたところ
何事もなく接続できたので
QUOINE側で何らかの処理があったのかもしれません。

登録(もしくは本人確認書類の提出)から
日が浅かったために、それらの承認後に
APIが有効になったということでしょうか。

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

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