LoginSignup
12
21

More than 3 years have passed since last update.

kabuステーション®APIをPythonから使う

Last updated at Posted at 2020-09-03

概要

auカブコム証券が個人に提供するkabuステーションAPIをPythonから利用する。
なお、kabuステーションはインストール済みのものとする。

環境

  • Windows 10
  • Python 3.8.5 ( Microsoft Store からインストール )

追加パッケージ

  • requests
  • pyyaml

コード

以下では、取引余力の取得、残高の表示、注文の表示を行っている。

import json
import requests
import yaml

# ---

def get_token():  # トークンを取得する。取得する度・またはkabuステーション再起動の度に変わる。
    with open('auth.yaml', 'r') as yml:
        auth = yaml.safe_load(yml)

    url = 'http://localhost:18080/kabusapi/token'
    headers = {'content-type': 'application/json'}
    payload = json.dumps(
        {'APIPassword': auth['PASS'],}
        ).encode('utf8')

    response = requests.post(url, data=payload, headers=headers)

    return json.loads(response.text)['Token']

# ---

token = get_token()

url = 'http://localhost:18080/kabusapi/wallet/cash'
response = requests.get(url, headers={'X-API-KEY': token,})
cash = json.loads(response.text)

print("取引余力\t{}".format(cash['StockAccountWallet']))

url = 'http://localhost:18080/kabusapi/positions'
response = requests.get(url, headers={'X-API-KEY': token,})
positions = json.loads(response.text)

print('コード 銘柄 平均取得価格 保有数 現在値 損益')
for position in positions:
    print("{}\t{}\t{}\t{}\t{}\t{}".format(
        position['Symbol'],
        position['SymbolName'],
        position['Price'],
        position['LeavesQty'],
        position['CurrentPrice'],
        position['ProfitLoss']))

url = 'http://localhost:18080/kabusapi/orders'
response = requests.get(url, headers={'X-API-KEY': token,})
orders = json.loads(response.text)

print('コード 銘柄 注文価格 注文数 期限')
for order in orders:
    if order['State'] == 1:
        print("{}\t{}\t{}\t{}\t{}".format(
            order['Symbol'],
            order['SymbolName'],
            order['Price'],
            order['OrderQty'],
            order['ExpireDay'],))

その他

本番環境ポートが 18080 、検証環境ポートが 18081 である。
また localhost 以外の接続は不可。

【要望】localhost以外からのAPIアクセスについて
  Issue#34 https://github.com/kabucom/kabusapi/issues/34

試しに PowerShell で

netsh http add urlacl url=http://[ IP ADDRESS ]:18080/ user=Everyone

でバインドしたところ、503 エラーで Reject された。

関連記事

12
21
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
21