前回に引き続き、KabuステーションAPIについて、現物取引・信用取引の注文発注・注文取消のやり方をサンプルコードを紹介していきたい思います
留意事項
サンプルコードに使用しているtokenっや注文一覧の確認方法はAPIを叩く際に必要な認証トークンで作り方は過去記事で作った関数を元にしています。
新規注文の発注
現物取引の注文発注
<現物注文のサンプルコード>
# 現物注文を出す関数
def send_cashorder(token, pass_, symbol, exchange, side, ordertype, qty, price, expire):
if side == 'buy':
side = '2'
dtype = 2
ftype = 'AA'
elif side == 'sell':
side = '1'
dtype = 0
ftype = ' '
# 成行注文のときのオプション
if str(ordertype) == '10':
price = 0
obj = { 'Password': pass_,
'Symbol': str(symbol), # 銘柄コード
'Exchange': int(exchange), #1が「東証」
'SecurityType': 1, # 1が「株式」
'Side': side, # 1が「売り」、2が「買い」
'CashMargin': 1, #1が「現物」 2が「信用新規」 3が「信用返済」
'DelivType': dtype,
'AccountType': 2, # 口座の種類 2が「一般」
'Qty': int(qty),
'FrontOrderType': int(ordertype),
'FundType':ftype,
'Price': price,
'ExpireDay': expire
}
#print(obj)
json_data = json.dumps(obj).encode('utf-8')
url = 'http://localhost:18080/kabusapi/sendorder'
req = urllib.request.Request(url, json_data, method='POST')
req.add_header('Content-Type', 'application/json')
req.add_header('X-API-KEY', token)
try:
with urllib.request.urlopen(req) as res:
#print(res.status, res.reason)
for header in res.getheaders():
#print(header)
content = json.loads(res.read())
return content
except urllib.error.HTTPError as e:
print(e)
content = json.loads(e.read())
return content
except Exception as e:
print(e)
return e
- token:認証トークン
- pass_:取引パスワード
- symbol:銘柄コード
- exchange:取引所(東証は1)
- side:’buy’ ‘sell’
- ordertype:成行が「10」指値が「20」
- qty:注文数
- price:注文価格
- expire:期限
## 使用例 ## #指値注文(買) send_cashorder(token, '取引パスワード', 5104, 1, 'buy',20, 100, 400, 0) #指値注文(売) send_cashorder(token, '取引パスワード', 5104, 1, 'sell',20, 100, 400, 0) #成行注文(買) send_cashorder(token, '取引パスワード', 5104, 1, 'buy',10, 100, 400, 0) #成行注文(売) send_cashorder(token, '取引パスワード', 5104, 1, 'sell',10, 100, 400, 0)
信用取引の注文の発注
# 信用取引の注文を出す関数
def send_marginorder(token, pass_, symbol, exchange, side, margintype, ordertype,qty, price, expire):
if side == 'buy':
side = '2'
elif side == 'sell':
side = '1'
if int(ordertype) == 10: #成行注文の場合は価格が0でないとエラーになるため
price = 0
obj = { 'Password': pass_,
'Symbol': str(symbol), # 銘柄コード
'Exchange': int(exchange), #1が「東証」
'SecurityType': 1, # 1が「株式」
'Side': side, # 1が「売り」、2が「買い」
'CashMargin': 2, #1が「現物」 2が「信用」
'MarginTradeType': margintype, #1が「制度信用」2が「長期」3が「デイトレ」
'DelivType': 0,
'AccountType': 2, # 口座の種類 2が「一般」
'Qty': int(qty),
'FrontOrderType': ordertype,
'Price': price,
'ExpireDay': expire
}
#print(obj)
json_data = json.dumps(obj).encode('utf-8')
url = 'http://localhost:18080/kabusapi/sendorder'
req = urllib.request.Request(url, json_data, method='POST')
req.add_header('Content-Type', 'application/json')
req.add_header('X-API-KEY', token)
try:
with urllib.request.urlopen(req) as res:
#print(res.status, res.reason)
#for header in res.getheaders():
#print(header)
content = json.loads(res.read())
return content
except urllib.error.HTTPError as e:
print(e)
content = json.loads(e.read())
#pprint.pprint(content)
return content
except Exception as e:
#print(e)
return e
<使用例>
send_marginorder(token=token, pass_='取引パスワード', symbol=5104, exchange=1, side='sell', margintype=3, ordertype=20, qty=100, price=360, expire=0)
信用ポジの決済
# ポジションを決済する関数
def send_margin_closeorder(token, pass_, exchange, order_id, order_type, price, expire):
position_data = get_position(token,2)
posi_data = position_data[position_data['ポジションID']==order_id]
qty = posi_data['注文数'][0]
if order_type == 10:
price = 0
if posi_data['売買'][0]=='買':
side = '1'
elif posi_data['売買'][0]=='売':
side = '2'
margintype = posi_data['信用注文タイプ'][0]
symbol = posi_data['コード'][0]
obj = { 'Password': pass_,
'Symbol': str(symbol), # 銘柄コード
'Exchange': int(exchange), #1が「東証」
'SecurityType': 1, # 1が「株式」
'FrontOrderType': order_type,
'TimeInForce': 0,
'Side': side,
'CashMargin': 3,
'MarginTradeType': int(margintype),
'DelivType': 2,
'FundType': 11,
'AccountType': 2, # 口座の種類 2が「一般」
'Qty': int(qty),
'Price': int(price),
'ExpireDay': expire,
'ClosePositions': [{'HoldID':order_id ,'Qty':int(qty)}]
}
print(obj)
json_data = json.dumps(obj).encode('utf-8')
url = 'http://localhost:18080/kabusapi/sendorder'
req = urllib.request.Request(url, json_data, method='POST')
req.add_header('Content-Type', 'application/json')
req.add_header('X-API-KEY', token)
try:
with urllib.request.urlopen(req) as res:
print(res.status, res.reason)
for header in res.getheaders():
print(header)
content = json.loads(res.read())
return content
except urllib.error.HTTPError as e:
print(e)
content = json.loads(e.read())
#pprint.pprint(content)
return content
except Exception as e:
#print(e)
return e
<使用例>
# 成行で決済注文を出す send_margin_closeorder(token, '取引パスワード', 1, 'E~で始まるポジションID', 10, 0, 0) #指値注文で決済注文を出す send_margin_closeorder(token, '取引パスワード', 1, 'E~で始まるポジションID', 20, 2000, 0)
よくあるエラーメッセージ
{'Code': 5, 'Message': '正しい有効期限を設定してください'}
デフォルトではexpire=0だが、引け後に注文だすと当日は既に締め切っているのでエラーになる。
解決策は翌営業日以降の日付を数値型で入力する。
例;send_cashorder(token, ‘取引パスワード’, 5104, 1, ‘sell’,10, 100, 400, 20220414)
注文の取消
<関数化したサンプルコード>
# 注文を取り消す関数
def cancel_order(token, pass_, id_):
url = 'http://localhost:18080/kabusapi/cancelorder'
obj = {
'Password': pass_,
'OrderId': id_
}
json_data = json.dumps(obj).encode('utf-8')
req = urllib.request.Request(url, json_data, method='PUT')
req.add_header('Content-Type', 'application/json')
req.add_header('X-API-KEY', token)
try:
with urllib.request.urlopen(req) as res:
#print(res.status, res.reason)
for header in res.getheaders():
print(header)
content = json.loads(res.read())
return content
except urllib.error.HTTPError as e:
print(e)
content = json.loads(e.read())
return content
except Exception as e:
print(e)
return e
注文の取消は「注文ID」を使います。
<使用例>
cancel_order(token, '取引パスワード', '注文ID')
インデントがずれている場合はGITのコードを参照していただけると幸いです。
https://github.com/beginerSE/kabustationAPI_samplecode
注文IDは以前定義したget_order(token)で取得できます。
参照:【Python】AUカブコム証券のKabuステーションAPIのサンプルコードと使い方①(口座残高・注文一覧の確認)
オススメ参考書

コメント