adaptic-utils-dev v0.0.151
Adaptic Utilities
Last updated: 20 Jan 2025
A comprehensive utility library for financial data processing, time manipulation, and formatting.
NPM repo: https://www.npmjs.com/package/adaptic-utils
Installation
npm install adaptic-utils
Usage
Import the functions from the library:
import { adaptic } from 'adaptic-utils';
Environment Variables
POLYGON_API_KEY
ALPHA_VANTAGE_API_KEY
ALPACA_API_KEY
- Required for crypto data and newsALPACA_API_SECRET
- Required for crypto data and newsGOOGLE_SHEETS_CLIENT_EMAIL
- Required for Google Sheets operationsGOOGLE_SHEETS_PRIVATE_KEY
- Required for Google Sheets operations (with newlines preserved)BACKEND_HTTPS_URL
= for the backend functionsNODE_ENV
='production' for backend functions to work with a remote server
Alpaca Functions
fetchAccountDetails(accountId: string): Promise<AccountConfiguration>
Asynchronously retrieves detailed information about a specific Alpaca trading account.
Parameters:
accountId: string
- The Alpaca account ID
Returns:
Promise<AccountConfiguration>
- Account configuration details including:{ marketOpen: boolean; realTime: boolean; minOrderSize: number; maxOrderSize: number; dtbp_check: 'both' | 'entry' | 'exit'; trade_confirm_email: 'all' | 'none'; suspend_trade: boolean; no_shorting: boolean; fractional_trading: boolean; max_margin_multiplier: '1' | '2' | '4'; max_options_trading_level: 0 | 1 | 2; pdt_check: 'both' | 'entry' | 'exit'; ptp_no_exception_entry: boolean; }
Example:
const accountDetails = await adaptic.alpaca.fetchAccountDetails('your-account-id');
fetchPositions(accountId: string): Promise<Position[]>
Asynchronously fetches current open positions for a specific Alpaca trading account.
Parameters:
accountId: string
- The Alpaca account ID
Returns:
Promise<Position[]>
- Array of positions with the following type:{ asset_id: string; symbol: string; exchange: string; asset_class: string; asset_marginable: boolean; qty: string; qty_available: string; avg_entry_price: string; side: 'long' | 'short'; 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; }
Example:
const positions = await adaptic.alpaca.fetchPositions('your-account-id');
fetchPortfolioHistory(accountId: string, params: { period?: string, timeframe?: string, start?: string, end?: string }): Promise<PortfolioHistory>
Asynchronously retrieves historical portfolio performance data with flexible time range options.
Parameters:
accountId: string
- The Alpaca account IDparams: object
period?: string
- Optional time period ('1D', '1W', '1M', '3M', '1Y')timeframe?: string
- Optional data granularitystart?: string
- Optional start dateend?: string
- Optional end date
Returns:
Promise<PortfolioHistory>
- Portfolio history data:{ equity: number[]; timestamp: number[]; }
Example:
const portfolioHistory = await adaptic.alpaca.fetchPortfolioHistory('your-account-id', {
period: '1M',
timeframe: '1D'
});
createOrder(params: CreateOrderParams): Promise<Order>
Creates a new order for trading.
Parameters:
params: CreateOrderParams
:{ symbol: string; qty?: string; notional?: string; side: 'buy' | 'sell'; type: 'market' | 'limit' | 'stop' | 'stop_limit' | 'trailing_stop'; time_in_force: 'day' | 'gtc' | 'opg' | 'cls' | 'ioc' | 'fok'; limit_price?: string; stop_price?: string; trail_price?: string; trail_percent?: string; extended_hours?: boolean; client_order_id?: string; order_class?: 'simple' | 'oco' | 'oto' | 'bracket'; take_profit?: { limit_price: string; stop_price?: string; order_class?: OrderClass; }; stop_loss?: { stop_price: string; limit_price?: string; order_class?: OrderClass; }; position_intent?: 'buy_to_open' | 'buy_to_close' | 'sell_to_open' | 'sell_to_close'; }
Returns:
Promise<Order>
- Created order details with full order type information
Crypto Functions
fetchBars(params: CryptoBarsParams): Promise<CryptoBarsResponse>
Fetches historical bar data for crypto trading pairs.
Parameters:
params: CryptoBarsParams
:{ symbols: CryptoPair[]; timeframe: CryptoTimeframe; // '1Min' | '5Min' | '15Min' | '1Hour' | '1Day' | '1Week' | '1Month' start?: Date; end?: Date; limit?: number; page_token?: string; sort?: 'asc' | 'desc'; }
Returns:
Promise<CryptoBarsResponse>
:
where{ bars: { [symbol: string]: CryptoBar[]; }; next_page_token?: string; }
CryptoBar
is:{ t: number; // timestamp o: number; // open h: number; // high l: number; // low c: number; // close v: number; // volume }
Market Data Functions
fetchPolygonPrices(symbol: string, params: object): Promise<PolygonPriceData[]>
Fetches historical price data from Polygon.io.
Parameters:
symbol: string
- The trading symbolparams: object
- Query parameters for the data fetch
Returns:
Promise<PolygonPriceData[]>
:{ date: string; timeStamp: number; open: number; high: number; low: number; close: number; vol: number; vwap: number; }[]
Performance Metrics
calculateBeta(returns: number[], benchmarkReturns: number[]): CalculateBetaResult
Calculates beta and related statistics for a portfolio against a benchmark.
Parameters:
returns: number[]
- Array of portfolio returnsbenchmarkReturns: number[]
- Array of benchmark returns
Returns:
CalculateBetaResult
:{ beta: number; covariance: number; variance: number; averagePortfolioReturn: number; averageBenchmarkReturn: number; }
calculateMaxDrawdown(portfolioValues: number[]): number
Calculates the maximum drawdown from peak for a series of portfolio values.
Parameters:
portfolioValues: number[]
- Array of portfolio values over time
Returns:
number
- Maximum drawdown as a decimal (e.g., 0.25 for 25% drawdown)
calculateDailyReturns(portfolioValues: number[]): number[]
Computes daily returns from a series of portfolio values.
Parameters:
portfolioValues: number[]
- Array of portfolio values
Returns:
number[]
- Array of daily returns as decimals
News Functions
fetchNews(params: NewsParams): Promise<NewsResponse>
Fetches financial news articles.
Parameters:
params: NewsParams
:{ start?: Date | string; end?: Date | string; symbols?: string | string[]; limit?: number; sort?: 'asc' | 'desc'; page_token?: string; }
Returns:
Promise<NewsResponse>
:{ news: { id: number; author: string; content: string; created_at: string; updated_at: string; headline: string; source: string; summary: string; url: string; symbols: string[]; images: { size: 'large' | 'small' | 'thumb'; url: string; }[]; }[]; next_page_token?: string; }
Time Utilities
Market Time Types
The following types are used throughout the market time utilities:
type Period = "1D" | "3D" | "1W" | "1M" | "3M" | "6M" | "1Y" | "YTD";
type Timeframe = "1Min" | "5Min" | "15Min" | "1H" | "1D";
type IntradayReporting = 'market_hours' | 'extended_hours' | 'continuous';
type OutputFormat = 'iso' | 'unix-seconds' | 'unix-ms';
interface MarketTimeParams {
period?: Period;
start?: Date;
end?: Date;
timezone?: string;
intraday_reporting?: IntradayReporting;
outputFormat?: OutputFormat;
}
interface PeriodDates {
start: string | number;
end: string | number;
}
createMarketTimeUtil(timezone?: string, intraday_reporting?: IntradayReporting): MarketTimeUtil
Creates a utility for market time-related operations.
Parameters:
timezone?: string
- Optional timezone (default: 'America/New_York')intraday_reporting?: IntradayReporting
- Optional intraday reporting mode:'market_hours'
- Regular market hours (9:30 AM - 4:00 PM ET)'extended_hours'
- Extended market hours (4:00 AM - 8:00 PM ET)'continuous'
- All day, 24/7
Returns:
MarketTimeUtil
- Market time utility object
toUnixTimestamp(date: Date): number
Converts a date to Unix timestamp.
Parameters:
date: Date
- The date to convert
Returns:
number
- Unix timestamp
getTimeAgo(date: Date): string
Returns a human-readable time difference from now.
Parameters:
date: Date
- The date to calculate from
Returns:
string
- Human-readable time difference (e.g., '1 minute ago')
normalizeDate(date: Date): string
Standardizes a date to a consistent format.
Parameters:
date: Date
- The date to standardize
Returns:
string
- Standardized date string (e.g., '2024-11-09')
getDateInNY(time: number | string | { year: number; month: number; day: number }): Date
Returns the current date in New York timezone.
Parameters:
time: number | string | { year: number; month: number; day: number }
- The time or date to convert
Returns:
Date
- Date in New York timezone
getStartAndEndTimestamps(params: MarketTimeParams = {}): Promise<PeriodDates>
Generates start and end timestamps for a given period.
Parameters:
params: MarketTimeParams
- Optional parameters for the period
Returns:
Promise<PeriodDates>
- Start and end timestamps for the period
getStartAndEndDates(params: MarketTimeParams = {}): Promise<{ start: Date; end: Date }>
Gets the start and end dates for a given period.
Parameters:
params: MarketTimeParams
- Optional parameters for the period
Returns:
Promise<{ start: Date; end: Date }>
- Start and end dates for the period
getLastTradingDateYYYYMMDD(): Promise<string>
Gets the last trading date in YYYY-MM-DD format.
Returns:
Promise<string>
- Last trading date in YYYY-MM-DD format
getLastFullTradingDate(): Promise<{ date: Date; YYYYMMDD: string }>
Gets the last full trading date.
Returns:
Promise<{ date: Date; YYYYMMDD: string }>
- Last full trading date
currentTimeET(): Date
Gets the current time in Eastern Time.
Returns:
Date
- Current time in Eastern Time
Formatting Utilities
capitalize(string: string): string
Capitalizes the first letter of a string.
Parameters:
string: string
- The string to capitalize
Returns:
string
- Capitalized string
formatEnum(enumValue: any): string
Formats an enum value for display.
Parameters:
enumValue: any
- The enum value to format
Returns:
string
- Formatted enum value
formatCurrency(value: number): string
Formats a number as currency.
Parameters:
value: number
- The number to format
Returns:
string
- Formatted currency string
formatPercentage(value: number): string
Formats a number as a percentage.
Parameters:
value: number
- The number to format
Returns:
string
- Formatted percentage string
Misc utilities
logIfDebug(message: string, data?: unknown, type: LogType = 'info' | 'warn' | 'error' | 'debug' | 'trace'): void
Debug logging utility that respects environment debug flags.
Parameters:
message: string
- The log messagedata?: unknown
- Optional data to logtype: LogType
- Optional log type (default: 'info')
fetchWithRetry(url: string, options: RequestInit): Promise<Response>
Fetches data from a URL with retry logic.
Parameters:
url: string
- The URL to fetchoptions: RequestInit
- Optional fetch options
Returns:
Promise<Response>
- Fetched response
Crypto Functions
fetchBars(params: CryptoBarsParams): Promise<CryptoBarsResponse>
Fetches historical bar data for crypto trading pairs.
Parameters:
params: CryptoBarsParams
:{ symbols: CryptoPair[]; timeframe: CryptoTimeframe; // '1Min' | '5Min' | '15Min' | '1Hour' | '1Day' | '1Week' | '1Month' start?: Date; end?: Date; limit?: number; page_token?: string; sort?: 'asc' | 'desc'; }
Returns:
Promise<CryptoBarsResponse>
:
where{ bars: { [symbol: string]: CryptoBar[]; }; next_page_token?: string; }
CryptoBar
is:{ t: number; // timestamp o: number; // open h: number; // high l: number; // low c: number; // close v: number; // volume }
fetchNews(params: { symbol: string; start?: Date; sort?: string; includeContent?: boolean; limit?: number }, auth: AlpacaAuth): Promise<AlpacaNewsArticle[]>
Fetches cryptocurrency-related news articles with pagination support.
Parameters:
params: object
:{ symbol: string; start?: Date; sort?: string; includeContent?: boolean; limit?: number; }
auth: AlpacaAuth
- Alpaca API credentials
Returns:
Promise<AlpacaNewsArticle[]>
:{ title: string; url: string; time_published: string; authors: string[]; summary: string; banner_image: string; source: string; category_within_source: string | null; source_domain: string; topics: { topic: string; relevance_score: string; }[]; overall_sentiment_score: number; overall_sentiment_label: string; ticker_sentiment: { ticker: string; relevance_score: string; ticker_sentiment_score: string; ticker_sentiment_label: string; }[]; }[]
Technical Analysis Functions
Bollinger Bands
interface BollingerBandsParams {
period?: number;
standardDeviations?: number;
}
interface BollingerBandsData {
date: string;
middle: number;
upper: number;
lower: number;
close: number;
}
EMA (Exponential Moving Average)
interface EMAParams {
period?: number;
period2?: number;
}
interface EMAData {
date: string;
ema: number;
ema2?: number;
close: number;
}
MACD (Moving Average Convergence Divergence)
interface MACDParams {
shortPeriod?: number;
longPeriod?: number;
signalPeriod?: number;
}
interface MACDData {
date: string;
macd: number;
signal: number;
histogram: number;
close: number;
}
Fibonacci Retracement
interface FibonacciParams {
lookbackPeriod?: number;
retracementLevels?: number[];
extensionLevels?: number[];
reverseDirection?: boolean; // true for downtrend, false for uptrend
}
interface FibonacciLevel {
level: number;
price: number;
type: 'retracement' | 'extension';
}
interface FibonacciData {
date: string;
levels?: FibonacciLevel[];
swingHigh?: number;
swingLow?: number;
trend?: 'uptrend' | 'downtrend';
close: number;
}
RSI (Relative Strength Index)
interface RSIParams {
period?: number;
}
interface RSIData {
date: string;
rsi: number;
close: number;
}
Stochastic Oscillator
interface StochasticParams {
lookbackPeriod?: number;
signalPeriod?: number;
smoothingFactor?: number;
}
interface StochData {
date: string;
slowK: number;
slowD: number;
close: number;
}
Support and Resistance
interface SupportResistanceParams {
windowSize?: number;
sensitivity?: number;
minGapBetweenLevels?: number;
maxLevels?: number;
lookbackPeriod?: number;
}
interface SupportResistanceLevel {
price: number;
strength: number;
type: 'support' | 'resistance';
}
interface SupportResistanceData {
date: string;
levels: SupportResistanceLevel[];
close: number;
}
Alpha Vantage News Types
interface AVNewsArticle {
title: string;
url: string;
time_published: string;
authors: string[];
summary: string;
banner_image: string;
source: string;
category_within_source: string | null;
source_domain: string;
topics: {
topic: string;
relevance_score: string;
}[];
overall_sentiment_score: number;
overall_sentiment_label: string;
ticker_sentiment: {
ticker: string;
relevance_score: string;
ticker_sentiment_score: string;
ticker_sentiment_label: string;
}[];
}
interface AVNewsResponse {
items: number;
sentiment_score_definition: string;
relevance_score_definition: string;
feed: AVNewsArticle[];
}
Asset Overview Types
interface AssetOverview {
id: string;
symbol: string;
[key: string]: any;
}
interface AssetOverviewResponse {
asset: AssetOverview | null;
error: string | null;
success: boolean;
}
Google Sheets Functions
Types
interface GoogleSheetConfig {
spreadsheetId: string;
sheetName: string;
}
interface GoogleSheetCell {
row: number;
column: number;
}
interface GoogleSheetRange {
startCell: GoogleSheetCell;
endCell: GoogleSheetCell;
}
interface GoogleSheetResponse {
success: boolean;
error?: string;
data?: any;
}
interface GoogleSheetAddRowResponse extends GoogleSheetResponse {
data?: {
rowNumber: number;
values: any[];
};
}
interface GoogleSheetAddSheetResponse extends GoogleSheetResponse {
data?: {
sheetId: number;
title: string;
};
}
interface GoogleSheetCellResponse extends GoogleSheetResponse {
data?: {
value: any;
};
}
interface GoogleSheetWriteArrayResponse extends GoogleSheetResponse {
data?: {
updatedRange: string;
updatedRows: number;
updatedColumns: number;
};
}
addRow(config: GoogleSheetConfig, values: any[]): Promise<GoogleSheetAddRowResponse>
Adds a new row to a Google Sheet.
Parameters:
config: GoogleSheetConfig
- Configuration for the target spreadsheet and sheetvalues: any[]
- Array of values to add as a new row
Returns:
Promise<GoogleSheetAddRowResponse>
- Response containing the new row number and values
addSheet(spreadsheetId: string, sheetName: string): Promise<GoogleSheetAddSheetResponse>
Creates a new sheet in an existing spreadsheet.
Parameters:
spreadsheetId: string
- ID of the target spreadsheetsheetName: string
- Name for the new sheet
Returns:
Promise<GoogleSheetAddSheetResponse>
- Response containing the new sheet ID and title
getCell(config: GoogleSheetConfig, cell: GoogleSheetCell): Promise<GoogleSheetCellResponse>
Retrieves the value of a specific cell.
Parameters:
config: GoogleSheetConfig
- Configuration for the target spreadsheet and sheetcell: GoogleSheetCell
- Cell coordinates to read
Returns:
Promise<GoogleSheetCellResponse>
- Response containing the cell value
writeArray(config: GoogleSheetConfig, range: GoogleSheetRange, values: any[][]): Promise<GoogleSheetWriteArrayResponse>
Writes a 2D array of values to a specified range.
Parameters:
config: GoogleSheetConfig
- Configuration for the target spreadsheet and sheetrange: GoogleSheetRange
- Target range for writing valuesvalues: any[][]
- 2D array of values to write
Returns:
Promise<GoogleSheetWriteArrayResponse>
- Response containing update statistics
Polygon Functions
fetchTickerInfo(symbol: string): Promise<{ ticker: string; name: string; type: 'stock' | 'ETF'; exchange: string } | null>
Fetches details about a stock ticker to verify its existence.
Parameters:
symbol: string
- The trading symbol
Returns:
Promise<{ ticker: string; name: string; type: 'stock' | 'ETF'; exchange: string } | null>
- Ticker information or null if not found
fetchLastTrade(symbol: string): Promise<{ price: number; vol: number; time: Date }>
Fetches the most recent trade price, volume, and timestamp.
Parameters:
symbol: string
- The trading symbol
Returns:
Promise<{ price: number; vol: number; time: Date }>
- Last trade information
fetchPrices(params: { ticker: string; start: number; end?: number; multiplier: number; timespan: string; limit?: number }): Promise<PolygonPriceData[]>
Fetches historical price data with pagination support.
Parameters:
params: object
:{ ticker: string; start: number; end?: number; multiplier: number; timespan: string; limit?: number; }
Returns:
Promise<PolygonPriceData[]>
:{ date: string; timeStamp: number; open: number; high: number; low: number; close: number; vol: number; vwap: number; }[]
analysePolygonPriceData(priceData: PolygonPriceData[]): string
Generates a report summarizing key statistics from price data.
Parameters:
priceData: PolygonPriceData[]
- Historical price data
Returns:
string
- Summary report
formatPriceData(priceData: PolygonPriceData[]): string
Formats price data into a readable string with daily OHLCV values.
Parameters:
priceData: PolygonPriceData[]
- Historical price data
Returns:
string
- Formatted price data string
Contributing to the Repository
Contributions are welcome! Please submit a pull request or open an issue for any enhancements or bug fixes.
Author
This project is a product of Lumic.ai.
Thanks for reading this far! Why did the trader bring a ladder to the bar? Because they heard the drinks were on the house!
6 months ago