Setup Alpaca API implementation

This commit is contained in:
2023-10-20 16:32:41 -04:00
parent 4b0a2a284a
commit 6dc8ecaf26
7 changed files with 138 additions and 101 deletions

View File

@ -1,9 +1,26 @@
import Alpaca from '@alpacahq/alpaca-trade-api'
import { AlpacaPortfolioProvider } from './portfolio'
import { AlpacaQuoteProvider } from './quote'
import { Exchange } from '../interface/exchange'
import { PortfolioProvider } from '../interface/portfolio'
import { QuoteProvider } from '../interface/quote'
export class AlpacaExchange implements Exchange {
readonly alpaca: Alpaca;
/**
* The portfolio provider for the exchange.
*/
readonly portfolioProvider: PortfolioProvider;
/**
* The quote provider for the exchange.
*/
readonly quoteProvider: QuoteProvider;
/**
* The name of the exchange.
*/
readonly name: string;
constructor(keyId: string, secretKey: string, paper: boolean) {
@ -13,6 +30,9 @@ export class AlpacaExchange implements Exchange {
paper: paper
});
this.portfolioProvider = new AlpacaPortfolioProvider(this.alpaca);
this.quoteProvider = new AlpacaQuoteProvider(this.alpaca);
this.name = 'Alpaca';
}
}
}

45
src/alpaca/portfolio.ts Normal file
View File

@ -0,0 +1,45 @@
import Alpaca from '@alpacahq/alpaca-trade-api'
import { PortfolioProvider, Portfolio, Position } from '../interface/portfolio';
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;
}
export class AlpacaPortfolioProvider implements PortfolioProvider {
readonly alpaca: Alpaca;
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)
);
}));
});
}
constructor(alpaca: Alpaca) {
this.alpaca = alpaca;
}
}

25
src/alpaca/quote.ts Normal file
View File

@ -0,0 +1,25 @@
import Alpaca from '@alpacahq/alpaca-trade-api'
import { QuoteProvider, Quote } from '../interface/quote';
export class AlpacaQuoteProvider implements QuoteProvider {
readonly alpaca: Alpaca;
readonly fetchQuote = (symbol: string): Promise<Quote> => {
return this.alpaca.getLatestQuote(symbol).then((quote) => {
return new Quote(
quote.Symbol,
quote.AskPrice,
quote.AskSize,
quote.BidPrice,
quote.BidSize,
new Date(Date.parse(quote.Timestamp))
);
}).catch((err) => {
return err;
})
}
constructor(alpaca: Alpaca) {
this.alpaca = alpaca;
}
}