π οΈ 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 millisecondsend_date- End timestamp in milliseconds (current time)interval- Recommended interval for this duration (e.g., β1mβ, β15mβ, β1hβ, β1Dβ)
Supported Durations:
| Duration | Description | Recommended 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()
| Aspect | Details |
|---|---|
| Purpose | Calculate start/end dates and recommended interval for a duration |
| Input | Duration string (β1Dβ, β5Dβ, β15Dβ, β1Mβ, β3Mβ, β6Mβ, β1Yβ, β5Yβ, βAllβ) |
| Output | Object with start_date, end_date (ms), and interval |
| Use Case | Datafeed implementations, date range calculations |
| Import | import { getDateRangeForDuration } from "@gocharting/chart-sdk" |
Note
Important Notes:
- Timestamps: All timestamps are in milliseconds (JavaScript standard)
- Current Time: The
end_dateis always the current time when the function is called - Recommended Intervals: The returned
intervalis a suggestion based on the duration. You can use a different interval if needed. - Timezone: All calculations are based on the userβs local timezone
- βAllβ Duration: The βAllβ duration returns a very large time range (typically 10+ years)
π Related Documentation
- Datafeed API - Implementing custom data sources
- Configuration API - Chart configuration options
- TypeScript Types - Type definitions including DurationString and DateRangeResult
- Examples - Working code examples
For complete working examples, see the Examples section.
Last updated on