64 lines
1.8 KiB
TypeScript
64 lines
1.8 KiB
TypeScript
import Alpaca from '@alpacahq/alpaca-trade-api';
|
|
import { PortfolioProvider, Portfolio, Position } from '../interface/portfolio';
|
|
|
|
/**
|
|
* The position object returned by Alpaca.
|
|
* @see https://alpaca.markets/docs/api-references/trading-api/positions/#properties
|
|
*/
|
|
class AlpacaPosition {
|
|
asset_id!: string;
|
|
symbol!: string;
|
|
exchange!: string;
|
|
asset_class!: string;
|
|
avg_entry_price!: string;
|
|
qty!: string;
|
|
qty_available!: string;
|
|
side!: string;
|
|
market_value!: string;
|
|
cost_basis!: string;
|
|
unrealized_pl!: string;
|
|
unrealized_plpc!: string;
|
|
unrealized_intraday_pl!: string;
|
|
unrealized_intraday_plpc!: string;
|
|
current_price!: string;
|
|
lastday_price!: string;
|
|
change_today!: string;
|
|
asset_marginable!: string;
|
|
}
|
|
|
|
/**
|
|
* Provides a portfolio using the Alpaca API client.
|
|
*/
|
|
export class AlpacaPortfolioProvider implements PortfolioProvider {
|
|
/**
|
|
* The Alpaca API client.
|
|
*/
|
|
readonly alpaca: Alpaca;
|
|
|
|
/**
|
|
* Fetches the portfolio.
|
|
*/
|
|
readonly fetchPortfolio = (): Promise<Portfolio> => {
|
|
return (this.alpaca.getPositions() as Promise<AlpacaPosition[]>).then((positions) => {
|
|
return new Portfolio(positions.map((position) => {
|
|
return new Position(
|
|
position.symbol,
|
|
parseInt(position.qty, 10),
|
|
parseFloat(position.market_value),
|
|
parseFloat(position.cost_basis),
|
|
parseFloat(position.market_value)
|
|
);
|
|
}));
|
|
});
|
|
};
|
|
|
|
/**
|
|
* Creates a new AlpacaPortfolioProvider instance.
|
|
* @constructor
|
|
* @param {Alpaca} alpaca - The Alpaca API client.
|
|
*/
|
|
constructor(alpaca: Alpaca) {
|
|
this.alpaca = alpaca;
|
|
}
|
|
}
|