Open ko38464646 opened 4 months ago
import urllib.request import json import requests import config import websocket import _thread import time import pprint import sys
trade_flag = 1 trigger_stock_code = '' stock_code = '' Order_quantity = 0 Order_price1 = None Order_price2 = None Order_price3 = None last_triggered_price1 = None last_triggered_price2 = None last_triggered_price3 = None order_method = 'first' high_price = 0.0
def generate_token(): obj = {'APIPassword': config.API_PASSWORD} json_data = json.dumps(obj).encode('utf8') url = 'http://localhost:18080/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') config.API_KEY = token_value return token_value except urllib.error.HTTPError as e: print(e) return None
def ats_register(token, symbols): obj = { 'Symbols': symbols, } json_data = json.dumps(obj).encode('utf8') url = 'http://localhost:18080/kabusapi/register' req = urllib.request.Request(url, json_data, method='PUT') req.add_header('Content-Type', 'application/json') req.add_header('X-API-KEY', config.API_KEY) try: with urllib.request.urlopen(req) as res: content = json.loads(res.read()) pprint.pprint(content) except urllib.error.HTTPError as e: print(e) content = json.loads(e.read()) pprint.pprint(content) except Exception as e: print(e)
def market_buy_order(symbol, quantity): url = "http://localhost:18080/kabusapi/sendorder" headers = { "Content-Type": "application/json", "X-API-KEY": config.API_KEY } data = { "Password": config.PASSWORD, "Symbol": symbol, "Exchange": 1, "SecurityType": 1, "Side": "2", "CashMargin": 2, 'MarginTradeType': 3, "DelivType": 0, "AccountType": 4, "Qty": quantity, 'FrontOrderType': 10, "Price": 0, "ExpireDay": 0 } response = requests.post(url, headers=headers, data=json.dumps(data)) if response.status_code == 200: response_data = response.json() if 'OrderId' in response_data: print(f"Order placed successfully. Order ID: {response_data['OrderId']}") else: print(f"Order failed: {response_data}") else: print(f"Error: {response.status_code}, {response.json()}") if response.status_code == 400 and response.json().get('Code') == 4001001: print("口座残高が不足しています。")
def market_sell_order(symbol): url = f'http://localhost:18080/kabusapi/positions' headers = { "Content-Type": "application/json", "X-API-KEY": config.API_KEY } response = requests.get(url, headers=headers) if response.status_code == 200: positions = response.json() for position in positions: if position['Side'] == '2': qty = position['LeavesQty'] order_id = position['ExecutionID'] sell_data = { "Password": config.PASSWORD, "Symbol": symbol, "Exchange": 1, "SecurityType": 1, "Side": "1", "CashMargin": 3, 'MarginTradeType': 3, "DelivType": 0, "AccountType": 4, "Qty": qty, 'FrontOrderType': 10, "Price": 0, "ExpireDay": 0, "PositionId": order_id } sell_response = requests.post(url, headers=headers, data=json.dumps(sell_data)) if sell_response.status_code == 200: print(f"Sell order placed successfully for {qty} shares of {symbol}.") else: print(f"Error placing sell order: {sell_response.status_code}, {sell_response.json()}") else: print(f"Error fetching positions: {response.status_code}, {response.json()}")
def ats_sendorder_margin_new(trade_flag, stock_code, Order_quantity, Order_price): url = "http://localhost:18080/kabusapi/sendorder" headers = { "Content-Type": "application/json", "X-API-KEY": config.API_KEY } data = { "Password": config.PASSWORD, "Symbol": stock_code, "Exchange": 1, "SecurityType": 1, "FrontOrderType": 20, "Side": "2", "CashMargin": 2, 'MarginTradeType': 3, "DelivType": 0, "AccountType": 4, "Qty": Order_quantity, "Price": Order_price, "ExpireDay": 0 } response = requests.post(url, headers=headers, data=json.dumps(data)) if response.status_code == 200: response_data = response.json() if 'OrderId' in response_data: print(f"Order placed successfully. Order ID: {response_data['OrderId']}") else: print(f"Order failed: {response_data}") else: response_data = response.json() print(f"Error: {response.status_code}, {response_data}") if response.status_code == 500 and response_data.get('Code') == 21: print("可能額が不足しています。ご注文内容をご確認ください。") elif response.status_code == 400 and response_data.get('Code') == 4001005: print("パラメータ変換エラーが発生しました。ご注文内容をご確認ください。")
def receive_websocket(content, trade_flag, trigger_stock_code, Order_price1, Order_price2, Order_price3, stock_code, Order_quantity, last_triggered_price1, last_triggered_price2, last_triggered_price3, order_method, high_price): content_Symbol = content['Symbol'] content_SymbolName = content['SymbolName'] content_CurrentPrice = content['CurrentPrice'] opening_price = content.get('OpeningPrice')
print(f'content_Symbol: {content_Symbol}') print(f'content_SymbolName: {content_SymbolName}') print(f'content_CurrentPrice: {content_CurrentPrice}') print(f'opening_price: {opening_price}') if content_Symbol == trigger_stock_code: if order_method == 'first': ref_price = None if opening_price: if Order_price1 and opening_price > Order_price1: ref_price = Order_price1 if Order_price2 and opening_price > Order_price2: ref_price = Order_price2 if Order_price3 and opening_price > Order_price3: ref_price = Order_price3 if ref_price and opening_price >= ref_price: Order_price1 = opening_price last_triggered_price1 = None order_method = 'first_from_opening' if Order_price1 and content_CurrentPrice >= Order_price1 and last_triggered_price1 != content_CurrentPrice: print(f'発注条件に到達しました (Order_price1)') market_buy_order(stock_code, Order_quantity) last_triggered_price1 = content_CurrentPrice if Order_price1 and content_CurrentPrice == Order_price1 - 1: print(f'決済条件に到達しました (Order_price1 - 1)') market_sell_order(stock_code) last_triggered_price1 = content_CurrentPrice if Order_price2 and content_CurrentPrice >= Order_price2 and last_triggered_price2 != content_CurrentPrice: print(f'発注条件に到達しました (Order_price2)') market_buy_order(stock_code, Order_quantity) last_triggered_price2 = content_CurrentPrice if Order_price2 and content_CurrentPrice == Order_price2 - 1: print(f'決済条件に到達しました (Order_price2 - 1)') market_sell_order(stock_code) last_triggered_price2 = content_CurrentPrice if Order_price3 and content_CurrentPrice >= Order_price3 and last_triggered_price3 != content_CurrentPrice: print(f'発注条件に到達しました (Order_price3)') market_buy_order(stock_code, Order_quantity) last_triggered_price3 = content_CurrentPrice if Order_price3 and content_CurrentPrice == Order_price3 - 1: print(f'決済条件に到達しました (Order_price3 - 1)') market_sell_order(stock_code) last_triggered_price3 = content_CurrentPrice elif order_method == 'second': if Order_price1 and content_CurrentPrice == Order_price1 - 1 and last_triggered_price1 != content_CurrentPrice: print(f'決済条件に到達しました (Order_price1 - 1)') market_sell_order(stock_code) high_price = Order_price1 last_triggered_price1 = content_CurrentPrice if Order_price2 and content_CurrentPrice == Order_price2 - 1 and last_triggered_price2 != content_CurrentPrice: print(f'決済条件に到達しました (Order_price2 - 1)') market_sell_order(stock_code) high_price = Order_price2 last_triggered_price2 = content_CurrentPrice if Order_price3 and content_CurrentPrice == Order_price3 - 1 and last_triggered_price3 != content_CurrentPrice: print(f'決済条件に到達しました (Order_price3 - 1)') market_sell_order(stock_code) high_price = Order_price3 last_triggered_price3 = content_CurrentPrice if content_CurrentPrice > high_price: high_price = content_CurrentPrice if content_CurrentPrice == high_price + 1 and high_price != last_triggered_price1: print(f'発注条件に到達しました (high_price + 1)') market_buy_order(stock_code, Order_quantity) last_triggered_price1 = high_price + 1 return trade_flag, last_triggered_price1, last_triggered_price2, last_triggered_price3, high_price
def on_message(ws, message): global trade_flag, trigger_stock_code, Order_price1, Order_price2, Order_price3, stock_code, Order_quantity, last_triggered_price1, last_triggered_price2, last_triggered_price3, order_method, high_price print('--- RECV MSG. ---') content = json.loads(message) print('Received content:', content) trade_flag, last_triggered_price1, last_triggered_price2, last_triggered_price3, high_price = receive_websocket( content, trade_flag, trigger_stock_code, Order_price1, Order_price2, Order_price3, stock_code, Order_quantity, last_triggered_price1, last_triggered_price2, last_triggered_price3, order_method, high_price )
def on_error(ws, error): print('--- ERROR ---') print(error)
def on_close(ws): print('--- DISCONNECTED ---')
def on_open(ws): print('--- CONNECTED ---') def run(*args): while True: line = sys.stdin.readline() if line != '': print('closing...') ws.close() _thread.start_new_thread(run, ())
def ats_websocket(): websocket.enableTrace(True) url = 'ws://localhost:18080/kabusapi/websocket' ws = websocket.WebSocketApp(url, on_message=on_message, on_error=on_error, on_close=on_close) ws.on_open = on_open ws.run_forever()
def start_websocket(stock_code_input, order_price1_input, order_price2_input, order_price3_input, order_quantity_input, order_method_input): global trade_flag, trigger_stock_code, Order_price1, Order_price2, Order_price3, stock_code, Order_quantity, last_triggered_price1, last_triggered_price2, last_triggered_price3, order_method, high_price trade_flag = 1 trigger_stock_code = stock_code_input Order_price1 = float(order_price1_input) if order_price1_input else None Order_price2 = float(order_price2_input) if order_price2_input else None Order_price3 = float(order_price3_input) if order_price3_input else None stock_code = stock_code_input Order_quantity = int(order_quantity_input) order_method = order_method_input last_triggered_price1 = None last_triggered_price2 = None last_triggered_price3 = None high_price = 0.0
token = generate_token() if token: symbols = [{'Symbol': stock_code_input, 'Exchange': 1}] ats_register(token, symbols) ats_websocket() else: print("トークンの生成に失敗しました。")
def stop_websocket(stock_code): print(f'WebSocket connection stopped for stock code: {stock_code}')
このコードの場合、設定価格が2000の場合、1999になれば返済、それ以外は記載していないのに、2001、2002などで買い増しされてしまいます。どうすればいいでしょうか?
申し訳ございませんが、お客さまの個別の実装内容についてのご質問にはお答えできかねますこと、ご了承ください。
返済となるmarket_sell_order以外にも、数か所にmarket_buy_orderの記載があるようにお見受けいたします。 新規発注、返済の条件にお間違えがないか、ご確認をお願いいたします。
import urllib.request import json import requests import config import websocket import _thread import time import pprint import sys
グローバル変数
trade_flag = 1 trigger_stock_code = '' stock_code = '' Order_quantity = 0 Order_price1 = None Order_price2 = None Order_price3 = None last_triggered_price1 = None last_triggered_price2 = None last_triggered_price3 = None order_method = 'first' high_price = 0.0
def generate_token(): obj = {'APIPassword': config.API_PASSWORD} json_data = json.dumps(obj).encode('utf8') url = 'http://localhost:18080/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') config.API_KEY = token_value return token_value except urllib.error.HTTPError as e: print(e) return None
def ats_register(token, symbols): obj = { 'Symbols': symbols, } json_data = json.dumps(obj).encode('utf8') url = 'http://localhost:18080/kabusapi/register' req = urllib.request.Request(url, json_data, method='PUT') req.add_header('Content-Type', 'application/json') req.add_header('X-API-KEY', config.API_KEY) try: with urllib.request.urlopen(req) as res: content = json.loads(res.read()) pprint.pprint(content) except urllib.error.HTTPError as e: print(e) content = json.loads(e.read()) pprint.pprint(content) except Exception as e: print(e)
def market_buy_order(symbol, quantity): url = "http://localhost:18080/kabusapi/sendorder" headers = { "Content-Type": "application/json", "X-API-KEY": config.API_KEY } data = { "Password": config.PASSWORD, "Symbol": symbol, "Exchange": 1, "SecurityType": 1, "Side": "2", "CashMargin": 2, 'MarginTradeType': 3, "DelivType": 0, "AccountType": 4, "Qty": quantity, 'FrontOrderType': 10, "Price": 0, "ExpireDay": 0 } response = requests.post(url, headers=headers, data=json.dumps(data)) if response.status_code == 200: response_data = response.json() if 'OrderId' in response_data: print(f"Order placed successfully. Order ID: {response_data['OrderId']}") else: print(f"Order failed: {response_data}") else: print(f"Error: {response.status_code}, {response.json()}") if response.status_code == 400 and response.json().get('Code') == 4001001: print("口座残高が不足しています。")
def market_sell_order(symbol): url = f'http://localhost:18080/kabusapi/positions' headers = { "Content-Type": "application/json", "X-API-KEY": config.API_KEY } response = requests.get(url, headers=headers) if response.status_code == 200: positions = response.json() for position in positions: if position['Side'] == '2': qty = position['LeavesQty'] order_id = position['ExecutionID'] sell_data = { "Password": config.PASSWORD, "Symbol": symbol, "Exchange": 1, "SecurityType": 1, "Side": "1", "CashMargin": 3, 'MarginTradeType': 3, "DelivType": 0, "AccountType": 4, "Qty": qty, 'FrontOrderType': 10, "Price": 0, "ExpireDay": 0, "PositionId": order_id } sell_response = requests.post(url, headers=headers, data=json.dumps(sell_data)) if sell_response.status_code == 200: print(f"Sell order placed successfully for {qty} shares of {symbol}.") else: print(f"Error placing sell order: {sell_response.status_code}, {sell_response.json()}") else: print(f"Error fetching positions: {response.status_code}, {response.json()}")
def ats_sendorder_margin_new(trade_flag, stock_code, Order_quantity, Order_price): url = "http://localhost:18080/kabusapi/sendorder" headers = { "Content-Type": "application/json", "X-API-KEY": config.API_KEY } data = { "Password": config.PASSWORD, "Symbol": stock_code, "Exchange": 1, "SecurityType": 1, "FrontOrderType": 20, "Side": "2", "CashMargin": 2, 'MarginTradeType': 3, "DelivType": 0, "AccountType": 4, "Qty": Order_quantity, "Price": Order_price, "ExpireDay": 0 } response = requests.post(url, headers=headers, data=json.dumps(data)) if response.status_code == 200: response_data = response.json() if 'OrderId' in response_data: print(f"Order placed successfully. Order ID: {response_data['OrderId']}") else: print(f"Order failed: {response_data}") else: response_data = response.json() print(f"Error: {response.status_code}, {response_data}") if response.status_code == 500 and response_data.get('Code') == 21: print("可能額が不足しています。ご注文内容をご確認ください。") elif response.status_code == 400 and response_data.get('Code') == 4001005: print("パラメータ変換エラーが発生しました。ご注文内容をご確認ください。")
def receive_websocket(content, trade_flag, trigger_stock_code, Order_price1, Order_price2, Order_price3, stock_code, Order_quantity, last_triggered_price1, last_triggered_price2, last_triggered_price3, order_method, high_price): content_Symbol = content['Symbol'] content_SymbolName = content['SymbolName'] content_CurrentPrice = content['CurrentPrice'] opening_price = content.get('OpeningPrice')
def on_message(ws, message): global trade_flag, trigger_stock_code, Order_price1, Order_price2, Order_price3, stock_code, Order_quantity, last_triggered_price1, last_triggered_price2, last_triggered_price3, order_method, high_price print('--- RECV MSG. ---') content = json.loads(message) print('Received content:', content) trade_flag, last_triggered_price1, last_triggered_price2, last_triggered_price3, high_price = receive_websocket( content, trade_flag, trigger_stock_code, Order_price1, Order_price2, Order_price3, stock_code, Order_quantity, last_triggered_price1, last_triggered_price2, last_triggered_price3, order_method, high_price )
def on_error(ws, error): print('--- ERROR ---') print(error)
def on_close(ws): print('--- DISCONNECTED ---')
def on_open(ws): print('--- CONNECTED ---') def run(*args): while True: line = sys.stdin.readline() if line != '': print('closing...') ws.close() _thread.start_new_thread(run, ())
def ats_websocket(): websocket.enableTrace(True) url = 'ws://localhost:18080/kabusapi/websocket' ws = websocket.WebSocketApp(url, on_message=on_message, on_error=on_error, on_close=on_close) ws.on_open = on_open ws.run_forever()
def start_websocket(stock_code_input, order_price1_input, order_price2_input, order_price3_input, order_quantity_input, order_method_input): global trade_flag, trigger_stock_code, Order_price1, Order_price2, Order_price3, stock_code, Order_quantity, last_triggered_price1, last_triggered_price2, last_triggered_price3, order_method, high_price trade_flag = 1 trigger_stock_code = stock_code_input Order_price1 = float(order_price1_input) if order_price1_input else None Order_price2 = float(order_price2_input) if order_price2_input else None Order_price3 = float(order_price3_input) if order_price3_input else None stock_code = stock_code_input Order_quantity = int(order_quantity_input) order_method = order_method_input last_triggered_price1 = None last_triggered_price2 = None last_triggered_price3 = None high_price = 0.0
def stop_websocket(stock_code): print(f'WebSocket connection stopped for stock code: {stock_code}')
このコードの場合、設定価格が2000の場合、1999になれば返済、それ以外は記載していないのに、2001、2002などで買い増しされてしまいます。どうすればいいでしょうか?