import { PositionsResponse, PnLResponse, ApiErrorResponse } from './types.js';
export class PortfolioApiClient {
private baseUrl: string;
constructor(baseUrl: string = 'http://localhost:3000') {
this.baseUrl = baseUrl.replace(/\/$/, ''); // Remove trailing slash
}
async getPositions(): Promise<PositionsResponse> {
try {
const response = await fetch(`${this.baseUrl}/api/positions`);
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
const data = await response.json();
if (!data.success) {
throw new Error(data.error || 'API returned unsuccessful response');
}
return data;
} catch (error) {
console.error('Error fetching positions:', error);
throw new Error(`Failed to fetch positions: ${error instanceof Error ? error.message : 'Unknown error'}`);
}
}
async getPnL(refresh: boolean = false): Promise<PnLResponse> {
try {
const url = `${this.baseUrl}/api/pnl${refresh ? '?refresh=true' : ''}`;
const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
const data = await response.json();
if (!data.success) {
throw new Error(data.error || 'API returned unsuccessful response');
}
return data;
} catch (error) {
console.error('Error fetching P&L:', error);
throw new Error(`Failed to fetch P&L: ${error instanceof Error ? error.message : 'Unknown error'}`);
}
}
async refreshHistoricalData(): Promise<{ success: boolean; message?: string }> {
try {
const response = await fetch(`${this.baseUrl}/api/historical-prices`, {
method: 'POST'
});
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
const data = await response.json();
if (!data.success) {
throw new Error(data.error || 'API returned unsuccessful response');
}
return { success: true, message: 'Historical data refreshed successfully' };
} catch (error) {
console.error('Error refreshing historical data:', error);
throw new Error(`Failed to refresh historical data: ${error instanceof Error ? error.message : 'Unknown error'}`);
}
}
async checkConnection(): Promise<boolean> {
try {
const response = await fetch(`${this.baseUrl}/api/positions`);
return response.ok;
} catch (error) {
console.error('Portfolio API connection check failed:', error);
return false;
}
}
}