Pythonを用いたコインチェックの仮想通貨APIの使い方

コインチェックのAPIを使って仮想通貨botを作りましょう。

この記事ではPythonでコインチェックのAPIに接続し、実際に動作するコードを紹介します。

前準備

Coincheckに口座を開設する

この記事を読みながらAPIを呼ぶコードを書けるように、コインチェックで口座開設をしましょう。

CoincheckのAPI仕様書

コインチェックのAPI仕様書です。

実装中にAPIコールがエラーになり続ける場合は、パーミッション設定を見てみましょう。

requestsモジュールのAPI仕様書

APIコールにrequestsモジュールを使います。
わからないことがあれば、requestsのAPI仕様書を見ましょう。

HTTPレスポンスのステータスコードの概要はここを見てください。

Pythonモジュールのインストール

サンプルコードでimportするモジュールは以下です。インストールしていないものはインストールしてください。

import requests
import json
import time
from datetime import datetime
import hmac
import hashlib

Public API を使う

Public API は口座開設していなくても実行可能なので、お試しでAPIコールしてみましょう。

取引所のステータス取得 exchange_status

取引所がOPENしていないときは、botで取引をしないようにします。
そのときは取引所のステータス取得APIを使用しましょう。

# 取引所のステータス取得
endPoint = 'https://coincheck.com'
path     = '/api/exchange_status'
url = endPoint + path

response = requests.get(url)
res = response.json()
print(json.dumps(res, indent=4))

すべての通貨ペアの取引ステータスが返ってきます。
代表値として、ビットコイン(btc_jpy)の情報を見ればいいと思います。

{
    "exchange_status": [
        {
            "pair": "btc_jpy",
            "status": "available",
            "timestamp": 1724627116,
            "availability": {
                "order": true,
                "market_order": true,
                "cancel": true
            }
        },
        {
            "pair": "etc_jpy",
            "status": "available",
            "timestamp": 1724627116,
            "availability": {
                "order": true,
                "market_order": true,
                "cancel": true
            }
        }
    ]
}

Ticker情報の取得 ticker

Tickerは、シンボルとか通貨ペアとも言われます。

Ticker情報の取得APIで、LTP(Last Traded Price:最終取引価格)、過去24時間での取引量などを取得できます。

# Ticker情報の取得
endPoint = 'https://coincheck.com'
path     = '/api/ticker'
url = endPoint + path

parameters = {
    'pair': 'btc_jpy',
}

response = requests.get(url, params=parameters)
res = response.json()
print(json.dumps(res, indent=4))

以下の情報が返ってきます。

{
    "last": 9271491.0,
    "bid": 9270591.0,
    "ask": 9272000.0,
    "high": 9359998.0,
    "low": 9220000.0,
    "volume": 526.91958023,
    "timestamp": 1724630811
}

板情報の取得 order_books

botで板情報を使いたいときは板情報の取得APIを使用します。

ビットコインの板情報を取得するコードです。

# 板情報の取得
endPoint = 'https://coincheck.com'
path     = '/api/order_books'
url = endPoint + path

parameters = {
    'pair': 'btc_jpy',
}

response = requests.get(url, params=parameters)
res = response.json()
print(json.dumps(res, indent=4))

一部省略していますが、askとbidの価格とサイズを取得できます。
両方とも文字列になっているので、floatへの変換が必要です。

{
    "asks": [
        [
            "9230775.0",
            "0.0432"
        ],
        [
            "9230796.0",
            "0.01"
        ]
    ],
    "bids": [
        [
            "9229828.0",
            "0.001"
        ],
        [
            "9229710.0",
            "0.03"
        ]
    ]
}

基準レートの取得

コインチェックには基準レートなるものがあります。
基準レートの定義が書かれていないので、どのような数字かはわかりません。
買いと売りの価格の中間値かもしれません。

# 基準レート取得
pair ='btc_jpy'
endPoint = 'https://coincheck.com'
path     = '/api/rate/' + pair
url = endPoint + path

response = requests.get(url)
res = response.json()
print(json.dumps(res, indent=4))

基準レートが文字列で返ってきます。

{
    "rate": "9258912.5"
}

レート取得

レート取得APIいうものがあり、これもいまいち用途がわかりません。

「注文での量」か「注文での金額」のどちらかをパラメータに入れる仕様になっています。

試しに、「ビットコイン買いを2万円の金額で注文」という内容でレート取得してみます。

    # レート取得
    endPoint = 'https://coincheck.com'
    path     = '/api/exchange/orders/rate'
    url = endPoint + path

    parameters = {
        'pair': 'btc_jpy',
        'order_type': 'buy',
        'price': 20000, # 2万円
    }

    response = requests.get(url, params=parameters)
    res = response.json()
    print(json.dumps(res, indent=4))

レスポンスを見てみると、「約9,221,306円で0.002ぐらい買える」みたいな内容になっています。

{
    "success": true,
    "rate": "9221306.75138",
    "amount": "0.00216889",
    "price": "20000.0"
}

Private API を使う

Private APIを使うにはAPIキーが必要になります。
Coincheckで口座開設をしてAPIキーを取得しましょう。

実装中にエラーが解消できない場合は、パーミッション設定を確認しましょう。
コインチェックにログインして、左Menuの歯車マーク=>APIキー=>編集 でパーミッション設定を確認できます。

下のサンプルコードでは apiKeysecretKey という変数が出てきますので、ご自身のものに置き換えてください。
・apiKey: ご自身のアクセスキー
・secretKey: ご自身のシークレットアクセスキー

口座残高の取得 balance

残高取得APIで、口座にある通貨の残高をそれぞれ確認できます。

# 残高の取得
endPoint  = 'https://coincheck.com'
path      = '/api/accounts/balance'
url = endPoint + path

timestamp = '{0}000'.format(int(time.mktime(datetime.now().timetuple())))
text = timestamp + endPoint + path
sign = hmac.new(bytes(secretKey.encode('ascii')), bytes(text.encode('ascii')), hashlib.sha256).hexdigest()

headers = {
    "ACCESS-KEY": apiKey,
    "ACCESS-NONCE": timestamp,
    "ACCESS-SIGNATURE": sign,
    "Content-Type": 'application/json',
}

response = requests.get(url, headers=headers)
res = response.json()
print(json.dumps(res, indent=4))

ハイライトしている行の secretKey と apiKey はご自身のものに置き換えてください。

残高があれば、jpybtcのところに数値が入っています。

{
    "success": true,
    "jpy": "0.0",
    "btc": "0.0",
    "jpy_reserved": "0.0",
    "btc_reserved": "0.0",
    "jpy_lend_in_use": "0.0",
    "btc_lend_in_use": "0.0",
    "jpy_lent": "0.0",
    "btc_lent": "0.0",
    "jpy_debt": "0.0",
    "btc_debt": "0.0",
    "jpy_tsumitate": "0.0",
    "btc_tsumitate": "0.0"
}

新規注文

新規注文APIを使ってみます。

例として、ビットコインを900万円の数量0.001で買い注文をしてみます。

# 新規注文
endPoint  = 'https://coincheck.com'
path      = '/api/exchange/orders'
url = endPoint + path

parameters = {
    'order_type': 'buy',
    'pair': 'btc_jpy',
    'rate': 9000000,
    'amount': 0.001,
}

timestamp = '{0}000'.format(int(time.mktime(datetime.now().timetuple())))
text = timestamp + endPoint + path + json.dumps(parameters)
sign = hmac.new(bytes(secretKey.encode('ascii')), bytes(text.encode('ascii')), hashlib.sha256).hexdigest()

headers = {
    "ACCESS-KEY": apiKey,
    "ACCESS-NONCE": timestamp,
    "ACCESS-SIGNATURE": sign,
    "Content-Type": 'application/json',
}

response = requests.post(url, headers=headers, data=json.dumps(parameters))
res = response.json()
print(json.dumps(res, indent=4))

注文に成功すると、以下の形式で返ってきます。
※idのnには数値が入ります。idは10桁の数値です。

{
    "success": true,
    "id": nnnnnnnnnn,
    "amount": "0.001",
    "rate": "9000000.0",
    "order_type": "buy",
    "pair": "btc_jpy",
    "created_at": "yyyy-mm-ddTHH:MM:SS.FFFZ",
    "market_buy_amount": null,
    "time_in_force": "good_til_cancelled",
    "stop_loss_rate": null
}

注文一覧

注文一覧の取得APIを使ってみます。

# 未決済の注文一覧の取得
endPoint  = 'https://coincheck.com'
path      = '/api/exchange/orders/opens'
url = endPoint + path

timestamp = '{0}000'.format(int(time.mktime(datetime.now().timetuple())))
text = timestamp + endPoint + path
sign = hmac.new(bytes(secretKey.encode('ascii')), bytes(text.encode('ascii')), hashlib.sha256).hexdigest()

headers = {
    "ACCESS-KEY": apiKey,
    "ACCESS-NONCE": timestamp,
    "ACCESS-SIGNATURE": sign,
    "Content-Type": 'application/json',
}

response = requests.get(url, headers=headers)
res = response.json()
print(json.dumps(res, indent=4))

レスポンスは以下の形式です。

注文一覧なので、上の新規注文の例で行った注文内容を取得できます。

{
    "success": true,
    "orders": [
        {
            "id": nnnnnnnnnn,
            "order_type": "buy",
            "rate": "9000000.0",
            "pair": "btc_jpy",
            "pending_amount": "0.001",
            "pending_market_buy_amount": null,
            "stop_loss_rate": null,
            "created_at": "yyyy-mm-ddTHH:MM:SS.FFFZ"
        }
    ]
}

注文がゼロの場合は、以下のようなレスポンスになります。

{
    "success": true,
    "orders": []
}

注文キャンセル

注文キャンセルAPIを使って、サンプルとして注文した内容をキャンセルします。

requestsのdeleteを使用します。

※ハイライトしている2行目の注文IDは、実際の注文IDに置き換えてください。

# 注文キャンセル
order_id = nnnnnnnnnn # 注文IDは10桁の数値
endPoint  = 'https://coincheck.com'
path      = '/api/exchange/orders/' + str(order_id)
url = endPoint + path

timestamp = '{0}000'.format(int(time.mktime(datetime.now().timetuple())))
text = timestamp + endPoint + path
sign = hmac.new(bytes(secretKey.encode('ascii')), bytes(text.encode('ascii')), hashlib.sha256).hexdigest()

headers = {
    "ACCESS-KEY": apiKey,
    "ACCESS-NONCE": timestamp,
    "ACCESS-SIGNATURE": sign,
    "Content-Type": 'application/json',
}

response = requests.delete(url, headers=headers)
res = response.json()
print(json.dumps(res, indent=4))

注文キャンセルに成功すると、以下のレスポンスが返ります。

{
    "success": true,
    "id": nnnnnnnnnn
}

間違った注文IDで注文キャンセルを行うと、以下のようなレスポンスが返ってきます。

{
    "success": false,
    "error": "The order doesn't exist."
}

取引履歴 transactions

取引履歴取得APIを使って、取引の約定を確認します。

# 取引履歴の取得
endPoint  = 'https://coincheck.com'
path      = '/api/exchange/orders/transactions'
url = endPoint + path

timestamp = '{0}000'.format(int(time.mktime(datetime.now().timetuple())))
text = timestamp + endPoint + path
sign = hmac.new(bytes(secretKey.encode('ascii')), bytes(text.encode('ascii')), hashlib.sha256).hexdigest()

headers = {
    "ACCESS-KEY": apiKey,
    "ACCESS-NONCE": timestamp,
    "ACCESS-SIGNATURE": sign,
    "Content-Type": 'application/json',
}

response = requests.get(url, headers=headers)
res = response.json()
print(json.dumps(res, indent=4))

レスポンスは下のような形式になっています。
※id, order_idのnには数値が入ります。

{
    "success": true,
    "transactions": [
        {
            "id": nnnnnnnnn,
            "order_id": nnnnnnnnnn,
            "created_at": "yyyy-mm-ddTHH:MM:DD.FFFZ",
            "funds": {
                "btc": "0.001",
                "jpy": "-9000.0"
            },
            "pair": "btc_jpy",
            "rate": "9000000.0",
            "fee_currency": null,
            "fee": "0.0",
            "liquidity": "M",
            "side": "buy"
        }
    ]
}