今回はクラウドワークスの案件でAUカブコム証券が提供しているトレードツールである「KABU STATION」のAPIを使った自動取引プログラムをPythonベースで作成したので、その際に得た知見をメモしておきます。
Contents [hide]
前準備
余談ですが、以前以下のビットコインでのシステムトレードをやってみる記事で日本で株式の自動取引を提供しているAPIはないと書いたのですが、AUカブコム証券がついに提供を開始しており、ようやく株式も自分で綿密にロジックを組んだ自動取引が実行できる環境が整ってきましたという感じですね!
関連記事:Pythonで自動売買Botを作る①~システムトレードの流れを把握する
まずkabustatitionのAPIを使用して株式を自動売買するためには、AUカブコム証券で口座開設を行う必要があります。
口座開設ページ:https://s10.kabu.co.jp/_mem_bin/ApplyKojin/ApplyInfo.asp
自分の場合口座開設までに2週間ほどかかりました。
そして口座開設ができたらWEBサイトにログインしてKabustationAPIを有効化します。ちなみにこのカブstationは初月無料ですが、そこからは月額980円掛かるので注意してください。
KabustationAPIの利用設定:https://kabucom.github.io/kabusapi/ptal/howto.html
ここまでを行い、かつPythonの環境構築ができている前提で話を勧めます。Pythonとは何ぞやという人は以下の記事で参照してください。(環境構築についてはMENTAでご相談いただければ対応します)
関連記事:【Python】Anacondaのインストールと初期設定から便利な使い方までを徹底解説!
そして、各APIを叩く前にまず認証トークンを発行する関数を定義しておきます。
これはどのAPIを叩く際にも必要です。
ここから先の各種コードは以下のKABUSTATIONが提供しているAPIレファレンスを参考にしています。
APIリファレンス:https://kabucom.github.io/kabusapi/reference/index.html
注意点
KabustationのAPIを使用する場合には仮想通貨取引所のようにインターネット上にあるAPIサーバーにアクセスするのではなく、ローカルにインストールしたKABUSTATIONを経由する形になります。
つまり、APIを叩くためには常にKABUSTATIONを起動しておく必要があります。後述するAPIは全てローカルサーバーのURLを叩いていますが、これはKABUSTATIONが起動した際に自動的にバックグラウンドで起動しているみたいです。
認証トークンの発行
KabustationのAPIを使用する場合にはまず認証トークンを発行する必要があります。
発行について関数にまとめたものを使用例と同じく載せておきます。
<認証トークンを発行するサンプルコード>
import urllib.request
import json
host_ = '18080' # 本番環境
pass_ = 'KABUSTATIONで設定時に決めたパスワード'
# 認証用のトークンを作成する関数
def generate_token():
obj = {'APIPassword': pass_}
json_data = json.dumps(obj).encode('utf8')
url = f'http://localhost:{host_}/kabusapi/token'
req = urllib.request.Request(url, json_data, method='POST')
req.add_header('Content-Type', 'application/json')
try:
with urllib.request.urlopen(req) as res:
content = json.loads(res.read())
token_value = content.get('Token')
return token_value
except urllib.error.HTTPError as e:
print(e)
return e
# 関数を実行してトークンを発行
token = generate_token()
print(token)
これで準備は整いました。
KabuステーションAPIのサンプルコード(口座残高・注文情報)
口座残高の取得(現物)
<サンプルコード>
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']))
<関数化したもの>
# 現物余力を取得する関数
def get_cashbalance(token,symbol=None):
#symbol: 現物の各銘柄の保有枚数
if symbol == None:
url = f'http://localhost:18080/kabusapi/wallet/cash'
response = requests.get(url, headers={'X-API-KEY': token,})
cash = json.loads(response.text)
return cash['StockAccountWallet']
else:
url = f'http://localhost:18080/kabusapi/wallet/cash/{symbol}'
print(url)
response = requests.get(url, headers={'X-API-KEY': token,})
cash = json.loads(response.text)
return cash
# 使用例
cash = get_cashbalance(token,symbol=None)
print(f'残高は{cash}円です')
口座残高の取得(信用)
# 信用余力を取得する関数
def get_marginbalance(token,symbol=None):
#symbol: 現物の各銘柄の保有枚数
if symbol == None:
url = f'http://localhost:18080/kabusapi/wallet/margin'
else:
url = f'http://localhost:18080/kabusapi/wallet/margin/{symbol}'
response = requests.get(url, headers={'X-API-KEY': token,})
cash = json.loads(response.text)
return cash
# 使用例
cash = get_marginbalance(token,symbol=None)
print(f'信用残高は{cash}円です')
ポジションの取得
<サンプルコード>
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'])
)
<関数化したもの>
# ポジションを確認する関数
def get_position(token, product=0):
url = f'http://localhost:18080/kabusapi/positions?product={product}'
response = requests.get(url, headers={'X-API-KEY': token,})
positions = json.loads(response.text)
data = []
for position in positions:
#print(position)
if position['Side'] == '2':
side = '買'
elif position['Side'] == '1':
side = '売'
try:
typeid = position['MarginTradeType']
ordertype = '信用'
except:
typeid = -1
ordertype = '現物'
data.append(
[ordertype,typeid,
position['ExecutionID'],
position['Symbol'],
position['SymbolName'],
side,
position['Price'],
position['LeavesQty'],
position['CurrentPrice'],
position['ProfitLoss']]
)
return pd.DataFrame(data, columns=['注文種別','信用注文タイプ','ポジションID','コード','銘柄', '売買','注文価格','注文数','現在価格', '損益'])
<使用例>
# 全てのポジションを取得
position_data = get_position(token)
print(position_data.head())
print('-----------')
# 現物ポジションを取得
position_data = get_position(token,1)
print(position_data.head())
print('-----------')
# 信用ポジションを取得
position_data = get_position(token,2)
print(position_data.head())
注文一覧の取得
<サンプルコード>
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'],)
)
<関数化したもの>
#注文一覧を取得
def get_order(token,order_type=0):
url = f'http://localhost:18080/kabusapi/orders?product={order_type}'
response = requests.get(url, headers={'X-API-KEY': token,})
orders = json.loads(response.text)
data = []
for order in orders:
state = order['State']
if state >= 4: # 1,2,3: 待機,処理中,処理済
continue
price = order['Price']
if price == 0.0:
price = '成行 '
side = order['Side']
if side == '2':
side = '買'
elif side == '1':
side = '売'
board = get_priceinfo(1, order['Symbol'], token)
current_price = board["CurrentPrice"]
if current_price == None:
current_price = "---"
data.append(
[order['ID'],
order['Symbol'],
order['SymbolName'],
price,
side,
order['OrderQty'],
current_price,
order['ExpireDay'],])
return pd.DataFrame(data, columns=['注文ID','コード','銘柄', '注文価格','売/買','注文数','現在価格','期限'])
<使用例>
# 全ての注文を取得
order_data = get_order(token)
print(order_data.head())
# 現物注文を取得
order_data = get_order(token, 1)
print(order_data.head())
# 信用注文を取得
order_data = get_order(token, 2)
print(order_data.head())
インデントがずれている場合は以下のgitに記載したコードを参照していただけると幸いです。
https://github.com/beginerSE/kabustationAPI_samplecode
次は各銘柄の板情報・価格情報をAPI経由で取得する方法について紹介していきたいと思います
続編:【Python】KabuステーションAPIのサンプルコードと使い方②(板情報・価格情報の取得)
参照:https://qiita.com/shirasublue/items/914e1d62d8308623b56b
コメント
[…] 前回の記事:【Python】AUカブコム証券のKabuステーションAPIのサンプルコードと使い方①(口座残高・注文一覧) […]