株の自動売買をしてみる:本番環境で買い注文を出す
auカブコム証券のkabuステーション®APIを利用して、株の自動売買にチャレンジしています。 買い注文が出来るかどうか、本番環境で試してみます。
# buy_executor.py import os import urllib.request import json import pprint from src.order_constants import OrderConstants from dotenv import load_dotenv load_dotenv() class BuyExecutor: def __init__(self, config, token): self.config = config self.token = token @property def order_details(self): return { 'Password': os.getenv('ORDER_PASSWORD'), 'Symbol': os.getenv('HJ'), 'Exchange': 1, 'SecurityType': OrderConstants.STOCK, 'Side': OrderConstants.BUY, 'CashMargin': OrderConstants.CASH, 'DelivType': OrderConstants.DEPOSIT, 'FundType': OrderConstants.PROTECTION, 'AccountType': OrderConstants.SPECIFIC, 'Qty': 100, 'FrontOrderType': 20, 'Price': ******, 'ExpireDay': 20230908 } def send_order(self): json_data = json.dumps(self.order_details).encode('utf-8') url = f"{self.config['URL']}sendorder" req = urllib.request.Request(url, json_data, method='POST') self.set_request_headers(req) try: with urllib.request.urlopen(req) as res: print(f"{self.order_details['Symbol']}の買い注文を出しました") except urllib.error.HTTPError as e: print(f"HTTPError: {e}") content = json.loads(e.read()) pprint.pprint(content) except Exception as e: print(f"ExceptionError: {e}") def set_request_headers(self, req): req.add_header('Content-Type', 'application/json') req.add_header('X-API-KEY', self.token)
銘柄、数量、金額等がハードコーディングになっていますが、とりあえず今回は、注文できることが確認できればいいので、このまま指値で注文してみます。
# main.py from src.buy_executor import BuyExecutor if __name__ == '__main__': env, config = return_environment_from_args() token = read_token(env) buy_executor = BuyExecutor(config, token) buy_executor.send_order()
実行してみます。python main.py --env prod
注文が出来ていることが確認できました。