Данные в реальном времени можно получить с помощью TWS API интерактивных брокеров, как показано в (*1), и отобразить на консоли, как показано в (*2).
Здесь я хотел бы отобразить значения reqId1, reqId2 и reqId3 в реальном времени по вертикали, а BID и ASK по горизонтали, как показано в tkinter(*3).
Например, если { 'reqId': 1, 'tickType': 'BID', 'price': 0,658}, BID reqId1 отображается как 0,658 от цены, а если новый {'reqId': 1, 'tickType': 'BID ', 'price': 0,6581}, цена будет отображаться как 0,6581.
Чтобы сделать вышеизложенное, как мне ввести код tkinter (*3) в TWS API ( *1) код?
В частности, как мне изменить функцию [def TicketPrice]?
(*1) import time
from ibapi.client import *
from ibapi.wrapper import *
global clientId
clientId = 1001
nextOrderId = None
class TestApp(EClient, EWrapper):
def __init__(self):
EClient.__init__(self, self)
def nextValidId(self, orderId: int):
self.nextOrderId = orderId
global nextOrderId
nextOrderId = self.nextOrderId
print("NextValidId:", orderId)
def market_data(self, reqId, contract):
self.reqMarketDataType(1) # Live
self.reqMktData(
reqId=reqId,
contract=contract,
genericTickList="",
snapshot=False,
regulatorySnapshot=False,
mktDataOptions=[])
def tickPrice(self, reqId, tickType, price, attrib):
result_dict = {
'reqId':reqId,
'tickType':TickTypeEnum.to_str(tickType),
'price':price
}
print(result_dict)
def stop(self):
self.disconnect()
def req_streaming_data(port, contract_dict):
app = TestApp()
app.connect("127.0.0.1", port, clientId)
time.sleep(3)
for key in contract_dict:
app.market_data(reqId=key, contract=contract_dict[key])
app.run()
class CurrencyContract():
def create_currency_contract(self, currency_code:str):
symbol, currency = currency_code[:3], currency_code[3:]
contract = Contract()
contract.symbol = symbol
contract.secType = 'CASH'
contract.currency = currency
contract.exchange = 'IDEALPRO'
return contract
def main(port:int):
C = CurrencyContract()
contract_list = [
C.create_currency_contract(currency_code='AUDUSD'),
C.create_currency_contract(currency_code='GBPUSD'),
C.create_currency_contract(currency_code='EURUSD')
]
contract_dict = {i+1: value for i, value in enumerate(contract_list)}
req_streaming_data(port, contract_dict)
if __name__ == "__main__":
PAPER_PORT = 7497
main(PAPER_PORT)
(*2)
{'reqId': 1, 'tickType': 'BID', 'price': 0.658}
{'reqId': 1, 'tickType': 'ASK', 'price': 0.6581}
...
{'reqId': 1, 'tickType': 'BID', 'price': 0.6581}
{'reqId': 1, 'tickType': 'ASK', 'price': 0.65815}
{'reqId': 2, 'tickType': 'BID', 'price': 1.2889}
{'reqId': 2, 'tickType': 'ASK', 'price': 1.289}
{'reqId': 3, 'tickType': 'BID', 'price': 1.072}
...
(*3)
import tkinter as tk
data = [
{'reqId': 1, 'tickType': 'BID', 'price': 0.658}
{'reqId': 1, 'tickType': 'ASK', 'price': 0.6581}
...
{'reqId': 1, 'tickType': 'BID', 'price': 0.6581}
{'reqId': 1, 'tickType': 'ASK', 'price': 0.65815}
{'reqId': 2, 'tickType': 'BID', 'price': 1.2889}
{'reqId': 2, 'tickType': 'ASK', 'price': 1.289}
{'reqId': 3, 'tickType': 'BID', 'price': 1.072}
...
]
# Create GUI
root = tk.Tk()
root.title("realtime price display")
# Create Label (3x2 Grid)
labels = {}
for req_id in range(1, 4):
for tick_type in ['BID', 'ASK']:
label = tk.Label(root, text="0.000", width=10)
label.grid(row=req_id-1, column=tick_type == 'BID')
labels[(req_id, tick_type)] = label
# Data update function
def update_labels(index=0):
item = data[index]
req_id = item['reqId']
tick_type = item['tickType']
price = item['price']
if (req_id, tick_type) in labels:
labels[(req_id, tick_type)].config(text=f"{price:.5f}")
if index < len(data)-1:
root.after(500, update_labels, index+1) # recall after 500[mili sec]
# initial display and start update
update_labels()
root.mainloop()
Подробнее здесь: https://stackoverflow.com/questions/791 ... th-tkinter
Отображение цены тика TWS API с помощью tkinter ⇐ Python
-
- Похожие темы
- Ответы
- Просмотры
- Последнее сообщение
-
-
TWS API ib_insync Задержка заказа в скобках на 35+ секунд после отправки
Anonymous » » в форуме Python - 0 Ответы
- 12 Просмотры
-
Последнее сообщение Anonymous
-