-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path10_async_api.py
More file actions
58 lines (47 loc) · 1.78 KB
/
Copy path10_async_api.py
File metadata and controls
58 lines (47 loc) · 1.78 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
"""
10_async_api.py
---------------
Concept: Asynchronous Programming (async use in API calls)
Context: Efficiently fetching data from multiple exchanges simultaneously.
Note: This concept is crucial for High-Frequency Trading (HFT) or when monitoring many pairs.
"""
import asyncio
import time
import random
# 1. Synchronous (Normal) Approach - Blocking
def get_price_sync(exchange, symbol):
print(f"[Sync] Requesting {symbol} from {exchange}...")
time.sleep(1) # Simulating network delay
print(f"[Sync] Received {symbol} from {exchange}")
return 100
def run_sync():
print("--- Starting Synchronous Fetch ---")
start = time.time()
get_price_sync("Binance", "BTC/USDT")
get_price_sync("Coinbase", "BTC/USDT")
get_price_sync("Kraken", "BTC/USDT")
end = time.time()
print(f"Sync Total Time: {end - start:.2f} seconds\n")
# 2. Asynchronous Approach - Non-blocking
async def get_price_async(exchange, symbol):
print(f"[Async] Requesting {symbol} from {exchange}...")
await asyncio.sleep(1) # Simulating network delay (non-blocking)
print(f"[Async] Received {symbol} from {exchange}")
return random.uniform(20000, 60000)
async def run_async():
print("--- Starting Asynchronous Fetch ---")
start = time.time()
# Schedule all 3 calls to run concurrently
task1 = get_price_async("Binance", "BTC/USDT")
task2 = get_price_async("Coinbase", "BTC/USDT")
task3 = get_price_async("Kraken", "BTC/USDT")
# Wait for all of them to complete
await asyncio.gather(task1, task2, task3)
end = time.time()
print(f"Async Total Time: {end - start:.2f} seconds")
print("(Notice it took ~1 second total, not 3!)")
if __name__ == "__main__":
# Run Sync
run_sync()
# Run Async
asyncio.run(run_async())