It would be best if you had at least a basic understanding of asynchronous programming to build fast-reacting trading software.
The problem with the synchronous approach used most of the time is that our program must wait for data input from dedicated sources before proceeding to further actions. Connecting to WebSockets and receiving tick data updates or open order updates from exchanges using synchronous software is nearly impossible.
Asynchronous programming allows us to skip waiting for data input and proceed to the control stream or data processing stream. This approach radically improves our software speed and performance.
We will use asyncio python library for building an asynchronous application.
We need to learn a few concepts to start building asynchronous software.
First, our functions are marked as asynchronous with async word, like in JavaScript. Example:
async def my_function()
Second, we use await word to tell the program where it can switch control from one stream to another. Example:
await asyncio.sleep(0)
This line of code does nothing but tell our program not to wait for data input or some long calculations, so our program can switch to another task.
Third, in building asynchronous software, we operate not only functions but tasks. A task can contain one or more functions inside.
Example:
async def input_func():
pass
async def input_task():
await asyncio.sleep(0)
await self.input_func()
And, finally, loops. Our tasks are run inside loops, which can be called ‘control streams’.
Example:
ioloop = asyncio.get_event_loop()
tasks = [ioloop.create_task(input_task()), ioloop.create_task(another_task())]
wait_tasks = asyncio.wait(tasks)
ioloop.run_until_complete(wait_tasks)
This is an example of a simple asynchronous application. You can find it in this GitHub repo.
Top comments (0)