{$mode delphi}
{$ifdef windows}{$apptype console}{$endif}
uses
Classes,
SysUtils,
fphttpclient,
fpjson,
jsonparser,
openssl,
opensslsockets;
const
YAHOO_API_KEY = 'your_api_key_here'; // Replace with actual key
YAHOO_FINANCE_API = 'https://query1.finance.yahoo.com/v7/finance/quote?symbols=EURUSD=X';
FALLBACK_API = 'https://api.exchangerate-api.com/v4/latest/EUR';
function GetYahooExchangeRate: Double;
var
Client: TFPHttpClient;
Response: String;
JSONData: TJSONData;
QuotesArray: TJSONArray;
begin
Result := 0;
Client := TFPHttpClient.Create(nil);
try
// Configure Yahoo Finance API request
Client.RequestHeaders.Clear;
Client.AddHeader('Accept', 'application/json');
Client.AddHeader('x-api-key', YAHOO_API_KEY); // API key header
try
// Make authenticated request
Response := Client.Get(YAHOO_FINANCE_API);
JSONData := GetJSON(Response);
try
// Parse the updated Yahoo Finance API response format
QuotesArray := (JSONData as TJSONObject).Get('quoteResponse',
TJSONObject(nil)).Get('result', TJSONArray(nil));
if (QuotesArray <> nil) and (QuotesArray.Count > 0) then
Result := (QuotesArray.Items[0] as TJSONObject).Get('regularMarketPrice', 0.0);
finally
JSONData.Free;
end;
except
on E: Exception do
Writeln('Yahoo API Error: ', E.Message);
end;
finally
Client.Free;
end;
end;
function GetFallbackExchangeRate: Double;
var
Client: TFPHttpClient;
Response: String;
JSONData: TJSONData;
begin
Result := 0;
Client := TFPHttpClient.Create(nil);
try
Client.RequestHeaders.Clear;
Client.AddHeader('User-Agent', 'CDDatabase/1.0');
try
Response := Client.Get(FALLBACK_API);
JSONData := GetJSON(Response);
try
Result := (JSONData as TJSONObject).Get('rates',
TJSONObject(nil)).Get('USD', 0.0);
finally
JSONData.Free;
end;
except
on E: Exception do
Writeln('Fallback API Error: ', E.Message);
end;
finally
Client.Free;
end;
end;
var
ExchangeRate: Double;
begin
Writeln('Attempting to fetch EUR/USD rate...');
// Try Yahoo with API key first
ExchangeRate := GetYahooExchangeRate;
// If Yahoo fails, use fallback
if ExchangeRate = 0 then
begin
Writeln('Yahoo API failed, using fallback...');
ExchangeRate := GetFallbackExchangeRate;
end;
if ExchangeRate > 0 then
Writeln(Format('Current EUR/USD: %.4f', [ExchangeRate]))
else
Writeln('All API attempts failed');
end.