market update

This commit is contained in:
2025-08-03 20:44:53 +02:00
parent 64e94ef61a
commit 4282f0e48c
2 changed files with 39 additions and 33 deletions

17
app.py
View File

@ -1,11 +1,11 @@
import time import time
from datetime import datetime from datetime import datetime
import threading import threading
from market import market_info_loop, get_latest_price, get_all_latest_prices, get_latest_price_with_timestamp, set_debug from market import market_info_loop, get_latest_price, get_all_latest_prices, get_latest_price_with_timestamp
def start_market_data_thread(debug=False): def start_market_data_thread(debug=False):
"""Start market data collection in a separate thread""" """Start market data collection in a separate thread"""
market_thread = threading.Thread(target=market_info_loop, daemon=True) market_thread = threading.Thread(target=lambda: market_info_loop(debug), daemon=True)
market_thread.start() market_thread.start()
return market_thread return market_thread
@ -14,11 +14,9 @@ def main():
print("-" * 40) print("-" * 40)
# Start market data collection in background thread (debug=False by default) # Start market data collection in background thread (debug=False by default)
start_market_data_thread(debug=True) start_market_data_thread()
# Give some time for initial market data to be collected # Give some time for initial market data to be collected
print("Waiting for initial market data...")
time.sleep(10)
try: try:
while True: while True:
@ -28,14 +26,17 @@ def main():
# Show some sample prices with timestamps # Show some sample prices with timestamps
eth_data = get_latest_price_with_timestamp("ETHUSD") eth_data = get_latest_price_with_timestamp("ETHUSD")
btc_data = get_latest_price_with_timestamp("BTCUSD") btc_data = get_latest_price_with_timestamp("BTCUSD")
shib_data = get_latest_price_with_timestamp("SHIBUSD") sol_data = get_latest_price_with_timestamp("SOLUSD")
# shib_data = get_latest_price_with_timestamp("SHIBUSD")
if eth_data: if eth_data:
print(f"ETH/USD: ${eth_data['price']:.2f} (updated: {eth_data['timestamp_str']})") print(f"ETH/USD: ${eth_data['price']:.2f} (updated: {eth_data['timestamp_str']})")
if btc_data: if btc_data:
print(f"BTC/USD: ${btc_data['price']:.2f} (updated: {btc_data['timestamp_str']})") print(f"BTC/USD: ${btc_data['price']:.2f} (updated: {btc_data['timestamp_str']})")
if shib_data: if sol_data:
print(f"SHIB/USD: ${shib_data['price']:.8f} (updated: {shib_data['timestamp_str']})") print(f"SOL/USD: ${sol_data['price']:.2f} (updated: {sol_data['timestamp_str']})")
# if shib_data:
# print(f"SHIB/USD: ${shib_data['price']:.8f} (updated: {shib_data['timestamp_str']})")
# Show total number of markets with prices # Show total number of markets with prices
all_prices = get_all_latest_prices() all_prices = get_all_latest_prices()

View File

@ -45,29 +45,26 @@ MARKETS = [
# Global variable to store latest prices with timestamps # Global variable to store latest prices with timestamps
latest_prices = {} latest_prices = {}
# Debug flag to control printing def print_market_info(market_info, debug=False):
DEBUG = False if debug:
def print_market_info(market_info):
if DEBUG:
timestamp = datetime.now().strftime("%H:%M:%S") timestamp = datetime.now().strftime("%H:%M:%S")
print('[{0}] {1} : {2:.4f}'.format(timestamp, market_info["market"], market_info["price"])) print('[{0}] {1} : {2:.4f}'.format(timestamp, market_info["market"], market_info["price"]))
def market_info(): def market_info(debug=False):
"""Fetch market information once and update global prices""" """Fetch market information once and update global prices"""
client = Client( client = Client(
eth_private_key=PRIVATE_KEY, eth_private_key=PRIVATE_KEY,
rpc_url=RPC_URL rpc_url=RPC_URL
) )
if DEBUG: if debug:
print("Fetching market data...\n") print("Fetching market data...\n")
for market in MARKETS: for market in MARKETS:
try: try:
market_info_data = client.public.get_market_info(market) market_info_data = client.public.get_market_info(market)
print_market_info(market_info_data) print_market_info(market_info_data, debug)
# Store the latest price and timestamp in global dictionary # Store the latest price and timestamp in global dictionary
market_name = market_info_data["market"] market_name = market_info_data["market"]
@ -78,32 +75,41 @@ def market_info():
'timestamp_str': current_timestamp.strftime("%Y-%m-%d %H:%M:%S") 'timestamp_str': current_timestamp.strftime("%Y-%m-%d %H:%M:%S")
} }
time.sleep(2) # Wait 2 seconds between requests time.sleep(2) # Wait 2 seconds between requests to avoid rate limiting
except Exception as e: except Exception as e:
if DEBUG: if debug:
print(f"Error fetching market {market}: {e}") print(f"Error fetching market {market}: {e}")
print('-' * 50) print('-' * 50)
# Skip this market and continue with the next one
continue
def market_info_loop(): def market_info_loop(debug=False):
"""Continuously fetch market information in a loop""" """Continuously fetch market information in a loop"""
if DEBUG: if debug:
print("Starting market data loop - press Ctrl+C to stop") print("Starting market data loop - press Ctrl+C to stop")
print("-" * 50) print("-" * 50)
try: try:
while True: while True:
market_info() try:
except KeyboardInterrupt: market_info(debug)
if DEBUG: # if debug:
print("\nMarket data loop stopped by user") # print(f"\nSleeping for 30 seconds...\n")
# time.sleep(30) # Wait 30 seconds between full cycles
except Exception as e:
if debug:
print(f"Error in market_info cycle: {e}")
print("Waiting 15 seconds before retry...")
time.sleep(15) # Wait 15 seconds before retrying on error
continue
# except KeyboardInterrupt:
# if debug:
# print("\nMarket data loop stopped by user")
except Exception as e: except Exception as e:
if DEBUG: if debug:
print(f"An error occurred: {e}") print(f"Fatal error occurred: {e}")
print("Market data loop stopped")
def set_debug(enabled):
"""Enable or disable debug printing"""
global DEBUG
DEBUG = enabled
def get_latest_price(market_name): def get_latest_price(market_name):
"""Get the latest price for a specific market""" """Get the latest price for a specific market"""
@ -124,5 +130,4 @@ def get_all_latest_prices_only():
if __name__ == '__main__': if __name__ == '__main__':
# Enable debug when running directly # Enable debug when running directly
set_debug(True) market_info_loop(debug=True)
market_info_loop()