cc22174b78
- Implemented tests for fetching historical bars for AAPL with different timeframes (1D, 5Min, 1H). - Verified response structure and data integrity for each timeframe. - Ensured that the API returns valid data and appropriate status for the requests.
44 lines
1.4 KiB
TypeScript
44 lines
1.4 KiB
TypeScript
import type { AlpacaAccount } from "../../../types";
|
|
import Alpaca from "@alpacahq/alpaca-trade-api";
|
|
|
|
const alpaca = new Alpaca({
|
|
keyId: process.env.ALPACA_API_KEY!,
|
|
secretKey: process.env.ALPACA_SECRET_KEY!,
|
|
baseUrl: process.env.ALPACA_BASE_URL || "https://paper-api.alpaca.markets",
|
|
dataBaseUrl: process.env.ALPACA_DATA_URL || "https://data.alpaca.markets",
|
|
retryOnError: false,
|
|
});
|
|
|
|
async function fetchAlpacaAccount(): Promise<AlpacaAccount> {
|
|
try {
|
|
console.log("Fetching Alpaca account with key:", process.env.ALPACA_API_KEY?.substring(0, 8) + "...");
|
|
const account = await alpaca.getAccount();
|
|
console.log("Alpaca account fetched successfully");
|
|
return {
|
|
cash: parseFloat(account.cash),
|
|
buying_power: parseFloat(account.buying_power),
|
|
portfolio_value: parseFloat(account.portfolio_value),
|
|
};
|
|
} catch (error) {
|
|
console.error("Alpaca API fetch error:", error);
|
|
return {
|
|
cash: 0,
|
|
buying_power: 0,
|
|
portfolio_value: 0,
|
|
};
|
|
}
|
|
}
|
|
|
|
export async function loader() {
|
|
try {
|
|
const account = await fetchAlpacaAccount();
|
|
return Response.json(account);
|
|
} catch (error) {
|
|
console.error("Alpaca API error:", error);
|
|
const message = error instanceof Error ? error.message : "Unknown error";
|
|
return Response.json(
|
|
{ error: `Failed to fetch account info: ${message}` },
|
|
{ status: 500 }
|
|
);
|
|
}
|
|
} |