import threading, select
import shinybroker as sb
ib_socket, API_VERSION, CONNECTION_TIME = sb.create_ibkr_socket_conn()
ib_msg_reader_thread = threading.Thread(
target=sb.ib_msg_reader_run_loop,
kwargs={'ib_sock': ib_socket, 'verbose': True}
)
ib_msg_reader_thread.start()
(rd, wt, er) = select.select([], [ib_socket], [])
wt[0].send(
sb.req_historical_data(
reqId=1,
contract=sb.Contract({
'symbol': "AAPL",
'secType': "STK",
'exchange': "SMART",
'currency': "USD"
}),
durationStr="1 W",
keepUpToDate=0
)
)
(rd, wt, er) = select.select([], [ib_socket], [])
wt[0].send(
sb.req_sec_def_opt_params(
reqId=1,
underlyingSymbol="AAPL",
underlyingSecType="STK",
underlyingConId=265598
)
)"Headless Mode" for In-App Scripting and Development
“Somewhat Interactive” Development Mode
As you’re developing apps, it’s sometimes useful to just create a scratch file containing a bit of code that grabs some input. You can watch the information get printed by the async reader loop as it becomes available off the socket, and maybe copy-paste it from the terminal printout do perform some of your exploratory development work.
Simple exploratory example:
In-App Scripting
In your apps, you might want to make a short query, immediately gather the results, and use it. One example use case might be – you’d like to loop through the options chains for a particular stock, but to do that you need an idea of the stock’s current price (to determine moneyness). In addition, you need to know what expiries and strikes are available for options on that stock.
You can accomplish this in ShinyBroker by using a sync mode design pattern that creates a clean socket, makes the query, waits for the data to be returned in a blocking call (explaination of blocking & non-blocking), formats the results, and returns it to you for use.
Getting Synchronous Results with a Blocking Call
import select
import shinybroker as sb
ib_socket, API_VERSION, CONNECTION_TIME = sb.create_ibkr_socket_conn(
client_id=9999
)
(rd, wt, er) = select.select([], [ib_socket], [])
wt[0].send(
sb.req_sec_def_opt_params(
reqId=1,
underlyingSymbol="AAPL",
futFopExchange="",
underlyingSecType="STK",
underlyingConId=265598
)
)
while True:
incoming_msg = sb.ib_msg_reader_sync(sock=ib_socket)
print(incoming_msg)
if incoming_msg[0] == sb.functionary['incoming_msg_codes'][
'SECURITY_DEFINITION_OPTION_PARAMETER'
]:
sdop = sb.format_sec_def_opt_params_input(sdop=incoming_msg[1:])
break