Hands-On Guide: Building a Multi-Symbol Price Tracker with Python
Monitoring a single asset is fine for basic tests, but real-world trading and market analysis often require tracking multiple instruments simultaneously. Writing a multi-symbol polling script allows you to scan a watchlist of indices or currency pairs in a single execution loop.
In this hands-on tutorial, we will build a lightweight Python script that iterates through a watchlist of symbols and evaluates price variations using a dictionary structure.
---------------------------------------------------
1. Structuring Your Watchlist with Python Dictionaries
Instead of writing separate variables for every asset, we can store our symbols and target thresholds in a clean dictionary structure. This makes it easy to scale your script from two symbols to twenty without cluttering your code.
---------------------------------------------------
2. Complete Multi-Symbol Python Script
Open Termux or your preferred development environment, create a new file named multi_tracker.py, and paste the following code:
import time
import requests
import logging
# Configure basic logging
logging.basicConfig(
filename='multi_tracker.log',
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s'
)
# Define your asset watchlist with target alert prices
WATCHLIST = {
"VOLATILITY_10": {"target": 1500.0, "last_price": None},
"VOLATILITY_50": {"target": 4200.0, "last_price": None},
"BOOM_1000": {"target": 11500.0, "last_price": None}
}
SCAN_INTERVAL = 30 # Seconds between check cycles
def fetch_asset_price(symbol):
"""
Simulated API price fetcher for individual symbols.
Replace with your actual broker REST endpoint or websocket feed.
"""
url = f"https://api.example.com/v1/ticker?symbol={symbol}"
try:
response = requests.get(url, timeout=5)
if response.status_code == 200:
data = response.json()
return float(data.get("price", 0.0))
except Exception as e:
logging.error(f"Error fetching {symbol}: {e}")
return None
def main():
logging.info("Starting Multi-Symbol Tracker...")
print("--- Multi-Symbol Tracker Active ---")
while True:
for symbol, data in WATCHLIST.items():
current_price = fetch_asset_price(symbol)
if current_price:
print(f"[{time.strftime('%H:%M:%S')}] {symbol}: {current_price}")
# Check against target threshold
if data["last_price"] is not None:
price_diff = current_price - data["last_price"]
if abs(price_diff) >= 5.0: # Significant shift threshold
logging.info(f"Movement alert for {symbol}: Shift of {price_diff}")
# Update stored reference price
WATCHLIST[symbol]["last_price"] = current_price
time.sleep(2) # Brief pause between individual requests to avoid rate limits
print(f"--- Completed scan cycle. Waiting {SCAN_INTERVAL}s... ---\n")
time.sleep(SCAN_INTERVAL)
if __name__ == "__main__":
main()
---------------------------------------------------
3. Running and Testing on Mobile (Termux)
1. Save your file in nano (Ctrl + O, Enter, Ctrl + X).
2. Execute the script in your terminal:
python multi_tracker.py
3. Keep your session active in the background by running termux-wake-lock if you are running it overnight on your phone.
---------------------------------------------------
Final Thoughts
Scaling your Python scripts from single assets to multi-symbol watchlists opens up powerful possibilities for automated tracking. You can easily plug this framework into Telegram bot APIs to receive instant multi-asset push alerts.
Stay tuned for our next guide as we continue building out our technical library!
Comments
Post a Comment