Good morning,
I´m learning the introduction of algorithmic trading in Binance with the python-binance package and it is the first time I start with asynchronous programming.
I have created a simple_bot() function that makes a buy when having the pair BTCUSDT divsible by 10 at market price.
I have tried to understand the following main() code but I cannot comprehend why:
- We need to use await for the client object rather than the other first three lines.
- Why do we need to use async in the definition of main().
- Why do we need to use async in the section with ts as tscm: I have a bit of idea here and I think that it is to have the while loop executing and using simple_bot() at the same time.
Here I provide the code that I have been using:
from binance import BinanceSocketManager, AsyncClient
import asyncio
stop_streaming = False #Seting a stop streaming variable (initially:False)
def simple_bot(msg):
'''Define how to process incoming WebSocket messages'''
time = pd.to_datetime(msg["E"], unit = "ms")
price = float(msg["c"])
print("Time: {} | Price: {}".format(time, price))
if int(price) % 10 == 0:
order = client.create_order(symbol = "BTCUSDT", side = "BUY", type = "MARKET", quantity = 0.1)
print("n" + 50 * "-")
print("Buy {} BTC for {} USDT".format(order["executedQty"], order["cummulativeQuoteQty"]))
print(50 * "-" + "n")
global stop_streaming
stop_streaming=True
# PROBLEM HERE
async def main():
client = await AsyncClient.create()
bm = BinanceSocketManager(client)
ts = bm.symbol_miniticker_socket(symbol = "BTCUSDT")
async with ts as tscm:
while True:
res = await tscm.recv()
simple_bot(res)
if stop_streaming:
break
await client.close_connection()
await main()
I understand that the while loop is to remain doing calls to simple_bot() until the condition is met, and the client part is to connect to binance. Is just the asynchronic part of the code that is giving me problems.