Skip to Content
API ReferenceHelper Functions

πŸ› οΈ Helper Functions

The GoCharting SDK provides utility functions to help with common tasks like calculating date ranges for datafeed implementations.

πŸ“‹ Available Helpers

getDateRangeForDuration()

Calculates start and end dates based on a duration string. This is useful for implementing datafeed methods that need to fetch historical data for specific time periods.

Signature:

function getDateRangeForDuration(duration: DurationString): DateRangeResult type DurationString = "1D" | "5D" | "15D" | "1M" | "3M" | "6M" | "1Y" | "5Y" | "All" type DateRangeResult = { start_date: number; // Start timestamp in milliseconds end_date: number; // End timestamp in milliseconds (current time) interval: string; // Recommended interval for this duration }

Parameters:

  • duration (DurationString): Duration string representing the time period

Returns: Object with:

  • start_date - Start timestamp in milliseconds
  • end_date - End timestamp in milliseconds (current time)
  • interval - Recommended interval for this duration (e.g., β€œ1m”, β€œ15m”, β€œ1h”, β€œ1D”)

Supported Durations:

DurationDescriptionRecommended Interval
"1D"1 day"1m" (1 minute)
"5D"5 days"5m" (5 minutes)
"15D"15 days"15m" (15 minutes)
"1M"1 month"1h" (1 hour)
"3M"3 months"1h" (1 hour)
"6M"6 months"1D" (1 day)
"1Y"1 year"1D" (1 day)
"5Y"5 years"1W" (1 week)
"All"All available data"1M" (1 month)

πŸ’‘ Usage Examples

Example 1: Basic Usage

import { getDateRangeForDuration } from "@gocharting/chart-sdk"; // Get date range for 1 day const { start_date, end_date, interval } = getDateRangeForDuration("1D"); console.log("Start:", new Date(start_date)); // 1 day ago console.log("End:", new Date(end_date)); // Now console.log("Interval:", interval); // "1m"

Example 2: Datafeed Implementation

import { getDateRangeForDuration } from "@gocharting/chart-sdk"; const myDatafeed = { async getBars(symbolInfo, resolution, periodParams) { const { from, to } = periodParams; // Fetch data from your API const response = await fetch( `/api/bars?symbol=${symbolInfo.symbol}&from=${from.getTime()}&to=${to.getTime()}` ); const data = await response.json(); return { bars: data.map(bar => ({ time: bar.timestamp, open: bar.open, high: bar.high, low: bar.low, close: bar.close, volume: bar.volume, })), }; }, resolveSymbol(symbolName, onResolve, onError) { // Use helper to get initial data range const { start_date, end_date, interval } = getDateRangeForDuration("1M"); onResolve({ symbol: symbolName, name: symbolName, type: "stock", session: "24x7", timezone: "Etc/UTC", minmov: 1, pricescale: 100, has_intraday: true, supported_resolutions: ["1m", "5m", "15m", "1h", "1D"], // Use calculated values data_status: "streaming", }); }, };

Example 3: Custom Duration Selector

import { createChart, getDateRangeForDuration } from "@gocharting/chart-sdk"; const durations = ["1D", "5D", "15D", "1M", "3M", "6M", "1Y", "5Y"]; const chart = createChart("#chart", { symbol: "AAPL", interval: "1D", datafeed: myDatafeed, licenseKey: "YOUR_LICENSE_KEY", onReady: (chartInstance) => { // Add duration selector buttons durations.forEach(duration => { document.getElementById(`btn-${duration}`).addEventListener("click", () => { const { start_date, end_date, interval } = getDateRangeForDuration(duration); console.log(`Loading ${duration} of data`); console.log(`From: ${new Date(start_date)}`); console.log(`To: ${new Date(end_date)}`); console.log(`Recommended interval: ${interval}`); // Update chart interval if needed chartInstance.setInterval(interval); // Trigger data reload (implementation depends on your datafeed) // Your datafeed's getBars will be called with the new time range }); }); }, });

Example 4: Pre-loading Data

import { getDateRangeForDuration } from "@gocharting/chart-sdk"; async function preloadChartData(symbol, duration) { const { start_date, end_date, interval } = getDateRangeForDuration(duration); // Pre-fetch data before creating chart const response = await fetch( `/api/bars?symbol=${symbol}&interval=${interval}&from=${start_date}&to=${end_date}` ); const data = await response.json(); console.log(`Pre-loaded ${data.length} bars for ${duration}`); return data; } // Usage const cachedData = await preloadChartData("AAPL", "1M"); const chart = createChart("#chart", { symbol: "AAPL", interval: "1h", datafeed: { async getBars(symbolInfo, resolution, periodParams) { // Use cached data if available if (cachedData) { return { bars: cachedData }; } // Otherwise fetch from API // ... }, resolveSymbol(symbolName, onResolve, onError) { // ... }, }, licenseKey: "YOUR_LICENSE_KEY", });

Example 5: Dynamic Interval Selection

import { getDateRangeForDuration } from "@gocharting/chart-sdk"; function getOptimalInterval(duration) { const { interval } = getDateRangeForDuration(duration); return interval; } // Create chart with optimal interval based on duration const selectedDuration = "1M"; const optimalInterval = getOptimalInterval(selectedDuration); const chart = createChart("#chart", { symbol: "AAPL", interval: optimalInterval, // "1h" for 1 month datafeed: myDatafeed, licenseKey: "YOUR_LICENSE_KEY", });

πŸ“‹ Helper Reference

getDateRangeForDuration()

AspectDetails
PurposeCalculate start/end dates and recommended interval for a duration
InputDuration string (β€œ1D”, β€œ5D”, β€œ15D”, β€œ1M”, β€œ3M”, β€œ6M”, β€œ1Y”, β€œ5Y”, β€œAll”)
OutputObject with start_date, end_date (ms), and interval
Use CaseDatafeed implementations, date range calculations
Importimport { getDateRangeForDuration } from "@gocharting/chart-sdk"
Note

Important Notes:

  1. Timestamps: All timestamps are in milliseconds (JavaScript standard)
  2. Current Time: The end_date is always the current time when the function is called
  3. Recommended Intervals: The returned interval is a suggestion based on the duration. You can use a different interval if needed.
  4. Timezone: All calculations are based on the user’s local timezone
  5. β€œAll” Duration: The β€œAll” duration returns a very large time range (typically 10+ years)

For complete working examples, see the Examples section.

Last updated on