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
npm install adaptic-utils
Import the functions from the library:
import { adaptic } from 'adaptic-utils';
POLYGON_API_KEY
ALPHA_VANTAGE_API_KEY
-
ALPACA_API_KEY
- Required for crypto data and news -
ALPACA_API_SECRET
- Required for crypto data and news -
GOOGLE_SHEETS_CLIENT_EMAIL
- Required for Google Sheets operations -
GOOGLE_SHEETS_PRIVATE_KEY
- Required for Google Sheets operations (with newlines preserved) -
BACKEND_HTTPS_URL
= for the backend functions -
NODE_ENV
='production' for backend functions to work with a remote server
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');
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 ID -
params: object
-
period?: string
- Optional time period ('1D', '1W', '1M', '3M', '1Y') -
timeframe?: string
- Optional data granularity -
start?: string
- Optional start date -
end?: 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'
});
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
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 }
Fetches historical price data from Polygon.io.
Parameters:
-
symbol: string
- The trading symbol -
params: 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; }[]
Calculates beta and related statistics for a portfolio against a benchmark.
Parameters:
-
returns: number[]
- Array of portfolio returns -
benchmarkReturns: number[]
- Array of benchmark returns
Returns:
-
CalculateBetaResult
:{ beta: number; covariance: number; variance: number; averagePortfolioReturn: number; averageBenchmarkReturn: 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)
Computes daily returns from a series of portfolio values.
Parameters:
-
portfolioValues: number[]
- Array of portfolio values
Returns:
-
number[]
- Array of daily returns as decimals
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; }
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;
}
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
Converts a date to Unix timestamp.
Parameters:
-
date: Date
- The date to convert
Returns:
-
number
- Unix timestamp
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')
Standardizes a date to a consistent format.
Parameters:
-
date: Date
- The date to standardize
Returns:
-
string
- Standardized date string (e.g., '2024-11-09')
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
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
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
Gets the last trading date in YYYY-MM-DD format.
Returns:
-
Promise<string>
- Last trading date in YYYY-MM-DD format
Gets the last full trading date.
Returns:
-
Promise<{ date: Date; YYYYMMDD: string }>
- Last full trading date
Gets the current time in Eastern Time.
Returns:
-
Date
- Current time in Eastern Time
Capitalizes the first letter of a string.
Parameters:
-
string: string
- The string to capitalize
Returns:
-
string
- Capitalized string
Formats an enum value for display.
Parameters:
-
enumValue: any
- The enum value to format
Returns:
-
string
- Formatted enum value
Formats a number as currency.
Parameters:
-
value: number
- The number to format
Returns:
-
string
- Formatted currency string
Formats a number as a percentage.
Parameters:
-
value: number
- The number to format
Returns:
-
string
- Formatted percentage string
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 message -
data?: unknown
- Optional data to log -
type: LogType
- Optional log type (default: 'info')
Fetches data from a URL with retry logic.
Parameters:
-
url: string
- The URL to fetch -
options: RequestInit
- Optional fetch options
Returns:
-
Promise<Response>
- Fetched response
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; }[]; }[]
interface BollingerBandsParams {
period?: number;
standardDeviations?: number;
}
interface BollingerBandsData {
date: string;
middle: number;
upper: number;
lower: number;
close: number;
}
interface EMAParams {
period?: number;
period2?: number;
}
interface EMAData {
date: string;
ema: number;
ema2?: number;
close: number;
}
interface MACDParams {
shortPeriod?: number;
longPeriod?: number;
signalPeriod?: number;
}
interface MACDData {
date: string;
macd: number;
signal: number;
histogram: number;
close: number;
}
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;
}
interface RSIParams {
period?: number;
}
interface RSIData {
date: string;
rsi: number;
close: number;
}
interface StochasticParams {
lookbackPeriod?: number;
signalPeriod?: number;
smoothingFactor?: number;
}
interface StochData {
date: string;
slowK: number;
slowD: number;
close: number;
}
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;
}
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[];
}
interface AssetOverview {
id: string;
symbol: string;
[key: string]: any;
}
interface AssetOverviewResponse {
asset: AssetOverview | null;
error: string | null;
success: boolean;
}
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;
};
}
Adds a new row to a Google Sheet.
Parameters:
-
config: GoogleSheetConfig
- Configuration for the target spreadsheet and sheet -
values: any[]
- Array of values to add as a new row
Returns:
-
Promise<GoogleSheetAddRowResponse>
- Response containing the new row number and values
Creates a new sheet in an existing spreadsheet.
Parameters:
-
spreadsheetId: string
- ID of the target spreadsheet -
sheetName: string
- Name for the new sheet
Returns:
-
Promise<GoogleSheetAddSheetResponse>
- Response containing the new sheet ID and title
Retrieves the value of a specific cell.
Parameters:
-
config: GoogleSheetConfig
- Configuration for the target spreadsheet and sheet -
cell: 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 sheet -
range: GoogleSheetRange
- Target range for writing values -
values: any[][]
- 2D array of values to write
Returns:
-
Promise<GoogleSheetWriteArrayResponse>
- Response containing update statistics
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
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; }[]
Generates a report summarizing key statistics from price data.
Parameters:
-
priceData: PolygonPriceData[]
- Historical price data
Returns:
-
string
- Summary report
Formats price data into a readable string with daily OHLCV values.
Parameters:
-
priceData: PolygonPriceData[]
- Historical price data
Returns:
-
string
- Formatted price data string
Contributions are welcome! Please submit a pull request or open an issue for any enhancements or bug fixes.
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!