LoginSignup
11
9

More than 3 years have passed since last update.

python-kabusapiの使い方

Last updated at Posted at 2020-10-07

概要

前回、kabuステーション®API - REST API用のPythonラッパーを作成したが、簡易的な使用方法を述べる。
また、実際に自分が保有中銘柄や注文中銘柄の確認で使用しているコードを記載する。

Github 参照: https://github.com/shirasublue/python-kabusapi

環境

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

大まかなフロー

通常の場合

  1. kabusapi をインポートする。
  2. Context で初期設定を行う。
  3. 煮るなり焼くなりする。

複数のプログラムを同時実行する場合

  1. 同様
  2. Context の初期設定で、最初に立ち上げた他のプログラムから取得したtokenを指定する。
  3. 煮るなり焼くなりする。

サンプルコード

インポート・トークン取得

import kabusapi
api = kabusapi.Context('localhost', '18080', 'hogehoge')

ちなみに、Context の引数のデフォルト値は

hostname='localhost',
port=18080,
password=None,
token=None,

となっているため、通常の使い方では以下のようにパスワードのみ指定すれば本番環境に接続できる。

api = kabusapi.Context(password='hogehoge')

また、kabuステーションAPIでは、トークンを取得する度・または起動する度にトークンが変更される。
他プログラムでtokenが取得されている場合は、以下のようにして設定可能である。

api = kabusapi.Context(token='fugafuga')

トークンを確認するには、api.token を参照すればよい。


print(api.token)

保有中の銘柄表示


positions = api.positions()

positions = sorted(positions, key=lambda x: x['Symbol'])  # 銘柄コード順にソート

print('コード 銘柄         平均取得価格     保有数     現在値       損益')
for position in positions:
    profit_loss = position['ProfitLoss']
    if profit_loss == None:
        profit_loss = '---'

    print("{}\t{:11.7}\t{:>10}\t{:>10}\t{:>10}\t{:>10}".format(
        position['Symbol'],
        position['SymbolName'],
        position['Price'],
        position['LeavesQty'],
        position['CurrentPrice'],
        profit_loss))

注文中の銘柄表示

orders = api.orders()

print('コード 銘柄           注文価格     注文数      現在値      期限')
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 = api.board(symbol=order['Symbol'], exchange=1)
    current_price = board["CurrentPrice"]
    if current_price == None:
        current_price = "---"

    print("{}\t{:11.7}\t{:>10}/{:<}\t{:>10}\t{:>10}\t{:>10}".format(
        order['Symbol'],
        order['SymbolName'],
        price,
        side,
        order['OrderQty'],
        current_price,
        order['ExpireDay'],
        ))

関連記事

11
9
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
11
9