Spaces:
Paused
Paused
import requests | |
def get_live_rates_for_pair(pair="XAUUSD"): | |
""" | |
Get live Bid and Ask prices for a specified forex pair. | |
Returns dict with { "pair": ..., "bid": ..., "ask": ..., "difference": ... } | |
""" | |
url = "https://research.titanfx.com/api/live-rate?group=forex" | |
headers = { | |
"referer": "https://research.titanfx.com/instruments/gbpusd", | |
"sec-ch-ua": "\"Not)A;Brand\";v=\"8\", \"Chromium\";v=\"138\", \"Google Chrome\";v=\"138\"", | |
"sec-ch-ua-mobile": "?0", | |
"sec-ch-ua-platform": "\"Windows\"", | |
"sec-fetch-dest": "empty", | |
"sec-fetch-mode": "cors", | |
"sec-fetch-site": "same-origin", | |
"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36" | |
} | |
try: | |
response = requests.get(url, headers=headers) | |
response.raise_for_status() | |
data = response.json() | |
if pair not in data: | |
return None | |
pair_data = data[pair] | |
# Format bid price | |
bid_price = float(f"{pair_data[0]}.{pair_data[1]}") | |
# Format ask price | |
ask_price = float(f"{pair_data[2]}.{pair_data[3]}") | |
# Calculate difference | |
difference = ask_price - bid_price | |
return { | |
"pair": pair, | |
"bid": bid_price, | |
"ask": ask_price, | |
"difference": difference | |
} | |
except Exception as e: | |
print(f"Error while fetching price: {e}") | |
return None | |