概要
CryptoCompare というサイトで便利なAPIがありましたので、備忘録記載中。
JPY価格も取得できるので、USDJPYのレートを別途取得する必要もなさそうです。
JSON形式でのレスポンス
単一通貨ペア価格データ取得
Documentation: Single Symbol Price
使用例:
https://min-api.cryptocompare.com/data/price?fsym=WLKN&tsyms=USD,JPY,EUR
複数通貨ペア価格データ取得
Documentation: Multiple Symbols Price
使用例1:
https://min-api.cryptocompare.com/data/pricemulti?fsyms=BTC,WLKN&tsyms=USD,JPY,EUR
使用例2:
https://min-api.cryptocompare.com/data/pricemulti?fsyms=ATOM,BIT,BTC,ETH,GBEX,GST,GMT,QNT,USDC,USDT,WLKN,WTK,XDC,XRP&tsyms=USD,JPY
複数通貨ペア価格フルデータ取得
Documentation: Multiple Symbols Full Data
使用例:
https://min-api.cryptocompare.com/data/pricemultifull?fsyms=ATOM,BIT,BTC,ETH,GBEX,GST,GMT,QNT,USDC,USDT,WLKN,WTK,XDC,XRP&tsyms=USD,JPY
取得できない価格データ
BMAXの価格は取得できない。
https://min-api.cryptocompare.com/data/price?fsym=BMAX&tsyms=USD,JPY
BTR(Bitrue Coin)の価格は取得できず、BIR(BTRIPS)の価格が取得できるものと思われる。
https://min-api.cryptocompare.com/data/price?fsym=BTR&tsyms=USD,JPY
CSV形式のファイルに出力
JSON → CSV整形 プログラム
pythonで作成しています。( python のインストール方法はこちら)
get_cc_price.py
# ======================================================================
# Project Name : Crypto assets tax calculate
# File Name : get_cc_price.py
# Encoding : UTF-8
# Creation Date : 2022-09-04
# Update Date : 2022-09-04
# ======================================================================
import sys
import os
import requests
import pprint
import math
import json
from collections import OrderedDict
import time
from datetime import datetime, timedelta, timezone
import numpy as np
from decimal import Decimal, ROUND_HALF_UP, ROUND_HALF_EVEN
# --------------------------------------------------------------------
# 初期設定
# --------------------------------------------------------------------
# タイムゾーンの設定(JST)
w_tz_JST = timezone(timedelta(hours=+9), 'JST')
dt_tokyo_now = datetime.now(w_tz_JST)
dt_tokyo_now_str1 = dt_tokyo_now.strftime('%Y/%m/%d %H:%M')
dt_tokyo_now_YYYYmm = dt_tokyo_now.strftime('%Y%m')
# タイムゾーンの設定(UTC)
w_tz_XXX = timezone(timedelta(hours=0), 'UTC')
dt_tz_now = datetime.now(w_tz_XXX)
dt_tz_now_str1 = dt_tz_now.strftime('%Y/%m/%d %H:%M')
# --------------------------------------------------------------------
# 出力ディレクトリ
# --------------------------------------------------------------------
out_dir_cc='/Users/Shared/App/Python/cc-price/' + str(dt_tokyo_now.year) + '/' + str(dt_tokyo_now.strftime('%m')) + '/'
if os.name == 'nt':
out_dir_cc='../cc-price/' + str(dt_tokyo_now.year) + '/' + str(dt_tokyo_now.strftime('%m')) + '/'
# 出力ディレクトリ指定時
args = sys.argv
# パラメータチェック
if 2 <= len(args):
# 指定されたパスに上書き
out_dir_cc=args[1] + str(dt_tokyo_now.year) + '/' + str(dt_tokyo_now.strftime('%m')) + '/'
# 出力ディレクトリの存在確認
if not os.path.isdir(out_dir_cc):
os.makedirs(out_dir_cc)
# --------------------------------------------------------------------
# 出力ファイルパス
# --------------------------------------------------------------------
# ログファイルパス
log_file_path=out_dir_cc+'get_cc_price_' + str(dt_tokyo_now.year) + str(dt_tokyo_now.strftime('%m')) + '.log'
# --------------------------------------------------------------------
# 通貨レートファイル保存パス
# --------------------------------------------------------------------
out_file_path=out_dir_cc+'cc_rate_' + dt_tokyo_now_YYYYmm + '.csv'
# --------------------------------------------------------------------
# リクエストURL
# --------------------------------------------------------------------
#url = 'https://min-api.cryptocompare.com/data/pricemultifull?fsyms=ATOM,BIT,BTC,ETH,GBEX,GST,GMT,QNT,USDC,USDT,WLKN,WTK,XDC,XRP&tsyms=USD,JPY'
url = 'https://min-api.cryptocompare.com/data/pricemultifull'
#print("[Execution time(JST)] "+str(dt_tokyo_now_str1) + " [Execution time(" + str(w_tz_XXX) + ")] "+str(dt_tz_now_str1))
# CSVデータヘッダ
w_datalist_header = ['date_JST,date_UTC,Symbol,Id,Trade_JST,Trade_UTC,Market,Price,Median,Quantity,QuantityTotal,Flag,Memo\n']
# リクエストパラメタ設定
params = {'fsyms': 'ATOM,BIT,BTC,ETH,GBEX,GST,GMT,QNT,USDC,USDT,WLKN,WTK,XDC,XRP', 'tsyms': 'USD,JPY' }
count=0
r = requests.get(url, params=params)
#print("[url] "+r.url)
#print("[status_code] "+str(r.status_code))
b_flag=0
# リクエスト送信
rtn_json = r.json()
# レスポンス確認
if r.status_code == 200:
if 4 >= len(str(rtn_json)):
print("[Message] "+'Response string is too short. Response JSON String='+ str(rtn_json))
f = open(log_file_path, 'a', encoding='UTF-8')
datalist = [str(dt_tokyo_now), ',Request uri=' , r.url , ' Response string is too short. Response JSON String=', str(rtn_json), '\n']
f.writelines(datalist)
f.close()
exit(1)
#print("[Response JSON] "+str(rtn_json))
#print("[RAW] "+str(rtn_json['RAW']))
#for index, item in enumerate(rtn_json['RAW']):
w_id=10000
w_Flag="b"
w_Memo="Test"
for key1, val1 in rtn_json.items():
if str(key1)=="RAW":
for key2, val2 in val1.items():
#print("[key2] "+key2)
for key3, val3 in val2.items():
#print("[key3] "+key3)
#print("[val3] "+str(val3))
#print("[MARKET] "+str(val3['MARKET']) + " [FROMSYMBOL] "+str(val3['FROMSYMBOL']) + " [TOSYMBOL] "+str(val3['TOSYMBOL']))
#print("[PRICE] "+str(val3['PRICE']) + " [LASTUPDATE] "+str(val3['LASTUPDATE']) + " [LASTVOLUME] "+str(val3['LASTVOLUME']))
dt_tokyo = datetime.fromtimestamp(math.floor(val3['LASTUPDATE']), timezone(timedelta(hours=+9)))
dt_tokyo_str1 = dt_tokyo.strftime('%Y/%m/%d %H:%M')
dt_world = datetime.fromtimestamp(math.floor(val3['LASTUPDATE']), timezone(timedelta(hours=0)))
#print(dt_world)
dt_tz_str1 = dt_world.strftime('%Y/%m/%d %H:%M')
symbol=str(key2)+"/"+str(key3)
w_id=w_id+1
market=str(val3['MARKET'])
# https://data.cryptocompare.com/indices/cccagg
if 'LASTMARKET' in val3:
#print("[LASTMARKET] "+val3['LASTMARKET'])
market=str(val3['LASTMARKET'])
price=str(val3['PRICE'])
median=price
if 'MEDIAN' in val3:
#print("[MEDIAN] "+str(val3['MEDIAN']))
median=str(val3['MEDIAN'])
w_Quantity=str(val3['LASTVOLUME'])
w_QuantityTtl=w_Quantity
if 'LASTVOLUMETO' in val3:
#print("[LASTVOLUMETO] "+val3['LASTVOLUMETO'])
w_QuantityTtl=str(val3['LASTVOLUMETO'])
if os.path.exists(out_file_path)==True:
f = open(out_file_path, 'a', encoding='UTF-8')
datalist = [dt_tokyo_now_str1, ',' ,dt_tz_now_str1, ',' , symbol , ',' , str(w_id) , ',' , dt_tokyo_str1 , ',' , dt_tz_str1 , ',' , market , ',' , price , ',' , median, ',' , w_Quantity, ',' , w_QuantityTtl, ',' , w_Flag, ',' , w_Memo, '\n']
f.writelines(datalist)
f.close()
else:
f = open(out_file_path, 'w', encoding='UTF-8')
datalist = w_datalist_header
f.writelines(datalist)
datalist = [dt_tokyo_now_str1, ',' ,dt_tz_now_str1, ',' , symbol , ',' , str(w_id) , ',' , dt_tokyo_str1 , ',' , dt_tz_str1 , ',' , market , ',' , price , ',' , median, ',' , w_Quantity, ',' , w_QuantityTtl, ',' , w_Flag, ',' , w_Memo, '\n']
f.writelines(datalist)
f.close()
else:
#print("[key1] "+key1)
break
else:
f = open(log_file_path, 'a', encoding='UTF-8')
datalist = [str(dt_tokyo_now), ',Request uri=' , r.url , ' HTTP Response error. Status=' , str(r.status_code) ,' Response JSON String=', str(rtn_json), '\n']
f.writelines(datalist)
f.close()
exit(1)
exit(0)
プログラム実行
$ get_cc_price.py
出力結果
Windowsの場合
(実行ディレクトリ)..\cc-price\yyyy\mm\cc_rate_yyyymm.csv
macOs/Linuxの場合
/Users/Shared/App/Python/cc-price/yyyy/mm/cc_rate_yyyymm.csv
ログファイル
get_cc_rate_yyyymm.log
※yyyy は西暦4桁 、mmは年月2桁