概要
前回 kabuステーションAPIを使用して認証トークンを取得しました
今回はポジションの一覧を取得します
環境
- M2 Pro Mac mini
- macOS 26.4.1
- UTM 4.7.5
- Windows11 Home
- kabuステーション 5.40.0.0
- nginx 1.30.0
- Python 3.12.13
ポジションの一覧を取得する Python スクリプト
- vim list_positions.py
import requests
# =========================
# 設定
# =========================
API_PASSWORD = "xxx" # kabuステーションで設定したAPIパスワード
BASE_URL = "http://192.168.65.9:28081/kabusapi" # 検証環境
# =========================
# トークン取得
# =========================
def get_token():
url = f"{BASE_URL}/token"
body = {"APIPassword": API_PASSWORD}
res = requests.post(url, json=body)
if res.status_code != 200:
print("トークン取得エラー:", res.status_code, res.text)
return None
return res.json().get("Token")
# =========================
# ポジション取得
# =========================
def get_positions(token):
url = f"{BASE_URL}/positions"
headers = {"X-API-KEY": token}
res = requests.get(url, headers=headers)
# トークン期限切れ対応
if res.status_code == 401:
print("トークン期限切れ → 再取得")
token = get_token()
if not token:
return None
headers["X-API-KEY"] = token
res = requests.get(url, headers=headers)
if res.status_code != 200:
print("ポジション取得エラー:", res.status_code, res.text)
return None
return res.json()
# =========================
# メイン処理
# =========================
def main():
token = get_token()
if not token:
print("トークン取得失敗")
return
positions = get_positions(token)
if not positions:
print("ポジションなし or 取得失敗")
return
print("=== 保有ポジション ===")
for p in positions:
print(f"""
銘柄: {p.get('Symbol')}
数量: {p.get('LeavesQty')}
取得単価: {p.get('Price')}
現在値: {p.get('CurrentPrice')}
評価損益: {p.get('ProfitLoss')}
""")
# =========================
if __name__ == "__main__":
main()
- uv run python list_positions.py
最後に
次回は実際に売買する方法を紹介します