時期的に必要になったので作った
コード
get_zaif_api.py
import json
import hmac
import hashlib
import requests
from future.moves.urllib.parse import urlencode
from datetime import datetime
import time
secret = 'your secret key'
key = 'your key'
get_from = 0
fw = open('zaif_trade_btc-jpy.csv','w')
fw.write('date,currency_pair,action,price,amount,total,fee\n')
while True:
nonce = int(datetime.now().strftime('%s'))
params = {
'method': 'trade_history',
'nonce':nonce,
'from': get_from,
'currency_pair': 'btc_jpy', #bch-jpy, bch-btc
'count':1000
}
encoded_params = urlencode(params)
signature = hmac.new(bytearray(secret.encode('utf-8')), digestmod=hashlib.sha512)
signature.update(encoded_params.encode('utf-8'))
headers = {
'key': key,
'sign': signature.hexdigest()
}
response = requests.post('https://api.zaif.jp/tapi', data=encoded_params, headers=headers)
if response.status_code != 200:
raise Exception('return status code is {}'.format(response.status_code))
data = json.loads(response.text)
if not len(data['return']):
break
for order_id, history in sorted(data['return'].items(),key=lambda x:x[1]['timestamp'],reverse=True):
date = datetime.fromtimestamp(float(history['timestamp'])).strftime('%Y-%m-%d %H:%M:%S')
pair = history['currency_pair']
action = 'buy' if history['action'] == 'bid' else 'sell'
total = history['price'] * history['amount']
try:
fee = history['fee'] - history['bonus'] # btc-jpy
except:
fee = history['fee_amount'] # bch-jpy, bch-btcで動作確認
print date, pair, action, history['price'], history['amount'], total, fee
fw.write('{},{},{},{},{},{},{}\n'.format(date, pair, action, history['price'], history['amount'], total, fee))
get_from += len(data['return'])
print get_from # 1 loopでの取得数を出力
time.sleep(3)
fw.close()
実行結果
下記のフォーマットで全期間の取引履歴を出力する
zaif_trade_btc-jpy.csv
date,currency_pair,action,price,amount,total,fee
2017-12-18 23:10:50,btc_jpy,sell,2150005.0,0.206,442901.03,-200.0
2017-12-17 07:08:57,btc_jpy,buy,2224000.0,0.2,444800.0,-44.4
2017-12-17 07:08:55,btc_jpy,sell,2224400.0,0.25,556100.0,-200.0
2017-12-17 07:06:03,btc_jpy,sell,2222505.0,0.2,444501.0,-200.0
2017-12-17 07:03:20,btc_jpy,sell,2228000.0,0.009,20052.0,-10.0
...