Quick Start

ChartIQ’s HTML5 Charting Library is a JavaScript library and web component framework that enables software developers to quickly and easily add powerful charting capabilities to web applications.

Charts created with the ChartIQ library display time series data, such as stock quotes, in your applications. ChartIQ charts run on all contemporary browsers and mobile devices. The library supports the latest web standards and works with the leading web frameworks, including React, Angular, and Vue.

This introduction will guide you through the process of using the ChartIQ library to:

  • Add a chart to a web page
  • Connect a chart to a live data feed
  • Make basic customizations to a chart’s user interface

Set Up a Web Server

In this guide, we’ll install the ChartIQ library on a web server and open sample web pages on the web server.

Set up a local web server accessible through the localhost hostname (IP address 127.0.0.1) or obtain access to a network-based web server at your organization.

Install ChartIQ

To install the ChartIQ library and web component framework on your web server:

  1. Create a folder named “ChartIQ” in the root folder of your web server.

  2. Obtain a copy of your organization’s ChartIQ library archive (zip) file.

  3. Unzip the archive. The extracted files and folders should consist of the following:

    Distribution package folder
  4. Copy the contents of the chartiq folder to the ChartIQ folder on your web server.

    The ChartIQ folder on the web server should contain the following:

    chartiq folder

Create a Chart

The helloworld.html file in the ChartIQ folder creates a basic chart.

Load helloworld.html in your web browser by using the localhost hostname or the hostname (or IP address) of your organization’s web server. For example, enter the following in your browser’s address bar:

localhost:5500/chartiq/helloworld.html

You should see the following candle chart:

Basic chart

Source Code Review

Open the helloworld.html file in an editor. Let’s examine the key elements.

stx-chart.css

<link rel="stylesheet" type="text/css" href="css/stx-chart.css" media="screen" />

The main style sheet for ChartIQ charts is stx-chart.css. The style sheet contains styles for the various elements of the chart, such as backgrounds, titles, and controls. You should always include stx-chart.css in your chart applications.

Note: Do not edit stx-chart.css (or any ChartIQ library CSS file). To change a style that is in stx-chart.css, override the style later in the CSS cascade by subsequently loading a CSS file that contains a revised version of the style or by adding CSS styling directly to HTML elements.

Chart container <div>

<div class="chartContainer" style="width:800px;height:460px;position:relative;"></div>

A ChartIQ chart is contained in a div element on a web page. The div must have a class attribute (typically assigned the value chartContainer) that can be used to query the element. A reference to the element is provided to the ChartIQ library, which creates a chart within the element.

The width and height can be whatever you like; however, the CSS position attribute must be set to absolute or relative so that chart overlays (elements such as crosshairs, zoom controls, or drawn objects) are positioned correctly.

chartiq.js

<script src="js/chartiq.js"></script>

The core ChartIQ library JavaScript file is chartiq.js; it contains everything needed to implement a basic chart. You must always include chartiq.js (or chartiq-lite.js, a lightweight version of chartiq.js) in your chart applications.

Note: Do not edit chartiq.js or any ChartIQ library JavaScript file.

You can also use JavaScript module loaders, such as SystemJS, or module bundlers, such as Webpack or Rollup, to include chartiq.js (and other ChartIQ library JavaScript files) in your applications.

STX_SAMPLE_5MIN.js

<script src="examples/data/STX_SAMPLE_5MIN.js"></script>

ChartIQ charts can display both real-time and static time series data. Later in this guide, we’ll connect a chart to a live data feed; helloworld.html, however, uses a static data source — a JavaScript array containing a simulated time series of data.

The data is contained in the file STX_SAMPLE_5MIN.JS located in the ChartIQ/examples/data folder on your web server. Here’s an excerpt from the file:

var sample5min=[
{"Date":"2015-04-16 16:00","Open":152.13,"High":152.19,"Low":152.08,"Close":152.11,"Volume":4505569},
{"Date":"2015-04-17 09:30","Open":151.76,"High":151.83,"Low":151.65,"Close":151.79,"Volume":2799990},
{"Date":"2015-04-17 09:35","Open":151.79,"High":151.8,"Low":151.6,"Close":151.75,"Volume":1817706},
{"Date":"2015-04-17 09:40","Open":151.74,"High":151.96,"Low":151.74,"Close":151.84,"Volume":2127911},
{"Date":"2015-04-17 09:45","Open":151.84,"High":152.03,"Low":151.79,"Close":151.95,"Volume":1640306},
.
.
.]

The variable sample5min is assigned an array of JSON objects, each of which provides stock data for a sequential five-minute interval of time. (See the time portion of the Date property.) A live feed would provide the same sort of data, only in real time.

Other data formats are also available for more generic charts, which only require a date and a value.

CIQ.ChartEngine

var stxx=new CIQ.ChartEngine({container:document.querySelector(".chartContainer")});

The ChartIQ chart engine takes time series data from a data source and turns that data into a detailed chart. The engine creates the chart in an HTML container element on a web page.

CIQ is the ChartIQ library namespace; it ensures that the names of library classes, functions, variables, and so forth are unique when the ChartIQ library is used in conjunction with other JavaScript libraries.

The sole parameter of the CIQ.ChartEngine constructor function takes an object as an argument. The object contains the starting state of the chart, which (at a minimum) includes a reference to an HTML element used to contain the chart. In helloworld.html, the reference is to the div element identified by the class="chartContainer" CSS selector.

The variable stxx holds a reference to the new chart engine instance. (The name stxx is used by convention in much of the ChartIQ library documentation to identify chart engine instances.)

loadChart()

stxx.loadChart("SPY", {
	masterData: sample5min,
	periodicity: {
		period: 1,
		interval: 5,
		timeUnit: 'minute'
	}
})

The loadChart function of CIQ.ChartEngine loads and renders a chart on a web page.

The first parameter of the function takes a stock symbol as an argument. (SPY is the symbol for a Standard & Poor’s 500 stock fund.)

The second parameter takes an object as an argument. The object can contain a variety of settings that configure the chart, including masterData and periodicity.

masterData

A static data source for the chart is specified by the masterData property. The value sample5min is a reference to the variable in the file STX_SAMPLE_5MIN.JS (see above), which contains simulated time series data.

periodicity

The amount of time represented by a data point on a ChartIQ chart (for example, a candle on a candle chart) is the periodicity of the chart. The chart created by helloworld.html has a periodicity of five minutes (each candle represents five minutes of data). Remember, our data source is the file STX_SAMPLE_5MIN.JS located in the ChartIQ/examples/data folder.

The data looks like this:

var sample5min=[
{"Date":"2015-04-16 16:00","Open":152.13,"High":152.19,"Low":152.08,"Close":152.11,"Volume":4505569},
{"Date":"2015-04-17 09:30","Open":151.76,"High":151.83,"Low":151.65,"Close":151.79,"Volume":2799990},
{"Date":"2015-04-17 09:35","Open":151.79,"High":151.8,"Low":151.6,"Close":151.75,"Volume":1817706},
{"Date":"2015-04-17 09:40","Open":151.74,"High":151.96,"Low":151.74,"Close":151.84,"Volume":2127911},
{"Date":"2015-04-17 09:45","Open":151.84,"High":152.03,"Low":151.79,"Close":151.95,"Volume":1640306},
.
.
.]

Chart periodicity is specified by the periodicity property of the argument passed to the CIQ.ChartEngine.loadChart method. In the periodicity object literal, the unit of time is minutes, the interval (the number of time units) is 5, which agrees with the data in STX_SAMPLE_5MIN.JS.

The ChartIQ library enables you to roll up, or aggregate, periodicity; that is, combine data points. For example, in helloworld.html we could create data points for 10-minute intervals, 15-minute intervals, or any multiple of five minutes, because five minutes is the basis of the data points. We can’t, however, split data points in any way — for example, create a seven-minute interval — because the information just isn’t in the data.

The periodicity object in the loadChart argument has a property named period, which is the factor that multiplies the data point interval (periodicity = interval x period expressed as timeUnit). In helloworld.html, period is 1; and so, each data point from the data source is represented individually on the chart. If period were set to 2, data points would be combined and displayed in groups of two (10-minute time spans). If period were set to 3, data points would be aggregated in groups of three (15-minute time spans).

onload handler

<body onLoad="displayChart()">

The displayChart function contains the loadChart method call, which creates the chart. The function is set as the body element’s onload handler. That way, the chart is created when the page loads.

In Summary

The helloworld.html file contains all the essential elements required to create a basic ChartIQ chart. Use the file as a template for adding charts to your web applications.

Connect a Chart to a Live Data Source

When connected to a live data source, ChartIQ charts pull data from data providers as needed, managing all data exchanges automatically in response to user interaction.

Charts acquire data by means of callbacks, which contain the required code to connect with your data source as specified by the data vendor. The ChartIQ chart engine executes the callbacks whenever the chart needs data, which is whenever the chart

  • loads or reloads in a web page,
  • scrolls forward or backward in time (referred to as pagination), or
  • requires real-time updates.

The callbacks are made available to the chart engine as methods of a JavaScript object known as a quote feed.

About Quote Feeds

A quote feed contains three callback methods:

  • fetchInitialData — Called when the chart loads or reloads
  • fetchPaginationData — Called when the chart paginates (scrolls forward or backward in time)
  • fetchUpdateData — Called when the chart requires real-time updates

The following image depicts the three data acquisition use cases:

Chart data acquisition use cases

The basic JavaScript structure of a quote feed is:

var quoteFeed = {};
quoteFeed.fetchInitialData = function(symbol, startDate, endDate, params, cb) {};
quoteFeed.fetchUpdateData = function(symbol, startDate, params, cb) {};
quoteFeed.fetchPaginationData = function(symbol, startDate, endDate, params, cb) {};

The parameters are similar for the three methods:

Parameter Type Description
symbol string A stock symbol, such as SPY
startDate Date The starting date of the fetched time series data
endDate Date The ending date of the fetched time series data
params object Additional information about the data request, such as:
  • interval — time unit of the data points (minute, day, week, etc.)
  • period — length of the interval (for example, 5)
    Interval and period combine to specify the periodicity of the data; for example, five minutes, where each data point represents a span of five minutes.
  • extended — whether to include extended trading hours data for stock quote feeds
cb function A callback that returns to the chart engine the response from a data provider. The callback takes as its only argument an object that contains an array of data or an error message, either of which may be returned in the response.

The chart engine provides arguments for all of the parameters. The intelligence built into the chart engine enables it to formulate the start and end dates and other values included in the parameters for each of the data acquisition use cases.

A quote feed object is made available to the chart engine as an argument to the engine’s attachQuoteFeed method. The method signature is:

attachQuoteFeed(quoteFeed, behavior)

The quoteFeed parameter takes an object as an argument — the quote feed object. The behavior parameter also takes an object, which contains various settings related to the quote feed, such as the refresh interval (the time span for repeatedly requesting real-time updates).

Create a Quote Feed

You, the developer, create quote feeds to provide your charts with data. You specify the endpoints in the quote feed callback methods. The response of a successful API call contains the requested data, which is returned to the chart engine and displayed on your charts.

Let’s look at an example that uses a RESTful API.

The sampleQuoteFeed.js file in the ChartIQ/examples/feeds folder creates a basic quote feed. Open the file in an editor and examine the source code.

Source Code Review

Let’s look at the key pieces of sampleQuoteFeed.js.

Quote feed object
var quoteFeed = {};

The quote feed object contains the callback methods called by the chart engine. The quote feed object is passed to the chart engine by means of the chart engine’s attachQuoteFeed method.

Quote feed URL
quoteFeed.url = "https://simulator.chartiq.com/datafeed";

The quote feed URL is the endpoint of the HTTP requests made by the quote feed callback methods. The sample quote feed accesses the ChartIQ library’s quote feed simulator, which simulates a real-time stock quote data feed. In your applications, you will set the URL to your data provider.

fetchInitialData
quoteFeed.fetchInitialData = function(symbol, startDate, endDate, params, cb) {
	var queryUrl = this.url +
		"&identifier=" + symbol +
		"&startdate=" + startDate +
		"&enddate=" + endDate +
		"&interval=" + params.interval +
		"&period=" + params.period +
		"&extended=" + 1;

	this.sendAjax(queryUrl, function(status, response) {
		if (status == 200) {
			var newQuotes = quoteFeed.formatChartData(response);
			cb({quotes:newQuotes});
		} else {
			cb({error:response?response:status})
		}
	});
};

The fetchInitialData callback is called when the chart loads or reloads in a web page.

The function adds query parameters to the RESTful API endpoint (which is assigned previously in the script). The query parameters provide the specifications for the requested data. (See the parameter descriptions in “About Quote Feeds” above.)

Note: The quote feed simulator returns data only during U.S. stock market trading hours for symbols traded on those markets. Market hours are typically 9:30 a.m. to 4:00 p.m. U.S. eastern time, Monday through Friday (excluding holidays). The extended parameter controls whether the simulator also returns data during extended trading hours, 6:00 a.m. to 9:30 a.m. and 4:00 p.m. to 8:00 p.m. U.S. eastern time. To enable extended hours, set extended to 1; to disable extended hours, 0.

The request to the data provider is made by means of the sendAjax method, which is a convenience function defined in sampleQuoteFeed.js. The method makes HTTP requests using XMLHttpRequest objects, but you can use any methods required to access your data feed. The arguments provided to the sendAjax method specify the URL of the request and a callback function that is called when the HTTP request returns its response.

The callback first checks whether the request completed successfully (HTTP status 200 OK). If the request was successful, the method formats the response to be compatible with the data format required by the ChartIQ chart engine, and then calls the callback provided by the chart engine, passing an object that contains the data returned from the request. If the request was not successful, the method calls the chart engine’s callback, passing an error message or error code.

fetchUpdateData
quoteFeed.fetchUpdateData = function(symbol, startDate, params, cb) {
	var queryUrl = this.url +
		"&identifier=" + symbol +
		"&startdate=" + startDate +
		"&interval=" + params.interval +
		"&period=" + params.period +
		"&extended=" + 1;

	this.sendAjax(queryUrl, function(status, response) {
		if (status == 200) {
			var newQuotes = quoteFeed.formatChartData(response);
			cb({quotes:newQuotes});
		} else {
			cb({error:response?response:status})
		}
	});
};

The fetchUpdateData callback is called when the chart requires real-time updates.

The function is very similar to the fetchInitialData callback. The only difference is the lack of an end date for the data request, because the callback requests all data from the start date (essentially, the current moment) forward into the future.

fetchPaginationData
quoteFeed.fetchPaginationData = function(symbol, startDate, endDate, params, cb) {
	var queryUrl = this.url +
		"&identifier=" + symbol +
		"&startdate=" + startDate +
		"&enddate=" + endDate +
		"&interval=" + params.interval +
		"&period=" + params.period +
		"&extended=" + 1;

	this.sendAjax(queryUrl, function(status, response) {
		if (status == 200) {
			var newQuotes = quoteFeed.formatChartData(response);
			cb({quotes:newQuotes, moreAvailable:startDate.getTime() > Date.now() - 86400000 * 5});
		} else {
			cb({error:response?response:status})
		}
	});
};

The fetchPaginationData callback is called when the chart scrolls through time — forward or backward.

The important difference in this callback is the moreAvailable property returned to the chart engine in the argument passed to the chart engine’s callback. At some point, as the chart scrolls forward or backward through time, no more data may be available. At that point, your callback needs to inform the chart engine that it can provide no more data; otherwise, the chart engine will continue to make requests. The callback informs the chart engine by setting the property moreAvailable to false.

The fetchPaginationData callback learns that no more data is available when the HTTP request returns a status of 404 or some other status other than success. Different data providers may return different indications of no more data.

The quote feed simulator always returns a status of 200, even when it doesn’t provide any more simulated data; and so, the sample quote feed has been rigged to set moreAvailable to false when more than five days of past data is requested.

Note: The days are chronological, including weekends and holidays (on which no quote data is created). As a result, you should see no more than five days of data as you scroll back through the sample data.

formatChartData
quoteFeed.formatChartData = function(response) {
	var data = JSON.parse(response);
	var newQuotes = [];
	for (var i = 0; i < data.length; i++) {
		newQuotes[i] = {};
		newQuotes[i].DT = data[i].DT;
		newQuotes[i].Open = data[i].Open;
		newQuotes[i].High = data[i].High;
		newQuotes[i].Low = data[i].Low;
		newQuotes[i].Close = data[i].Close;
		newQuotes[i].Volume = data[i].Volume;
	}
	return newQuotes;
};

The ChartIQ chart engine requires quote feed data to be in a specific format. The engine accepts an array of JSON objects formatted as follows:

{
	"Date": "1993-01-29T13:30:00.000Z",
	"Open": 43.97,
	"High": 43.97,
	"Low": 43.75,
	"Close": 43.94,
	"Volume": 1003200
}

The JSON objects represent the chart data points and must be in chronological order in the array based on the Date property.

Date must be an instance of a JavaScript Date object or an ISO 8601 string. All other values must be numbers. Open, High, Low, Close, and Volume represent transaction aspects of stock trades.

You must ensure that the data returned by your data provider is converted to this format. At a minimum, the response (which is typically an array of JSON data) must be converted to an array of JavaScript objects (which is accomplished by the call to JSON.parse() in formatChartData).

Attach a Quote Feed

The helloworld.html web page in the ChartIQ folder on your web server displays a chart using a static data source. Let’s update helloworld.html to use the sample quote feed.

First, include the sample quote feed in the application by adding the following script tag to helloworld.html immediately after the script tag that includes chartiq.js:

<script src="examples/feeds/sampleQuoteFeed.js"></script>

Next, remove the parameter that specifies the data source from the loadChart function call. The resulting function call should look like this:

stxx.loadChart("SPY", {
	periodicity: {
		period: 1,
		interval: 5,
		timeUnit: 'minute'
	}
});

You can also remove the script tag that includes the STX_SAMPLE_5MIN.JS file:

<script src="examples/data/STX_SAMPLE_5MIN.js"></script>

Finally, attach the sample quote feed to the chart engine by adding the following line just after the line that instantiates the chart engine:

stxx.attachQuoteFeed(quoteFeed,{refreshInterval:1});

The refreshInterval setting informs the chart engine to request updates (that is, call fetchUpdateData) every second.

Here’s the revised version of helloworld.html:

<!doctype html>
<html>
<head>
<meta name="viewport" content="user-scalable=no, width=device-width, initial-scale=1, maximum-scale=1">
<link rel="stylesheet" type="text/css" href="css/stx-chart.css" media="screen" />
</head>

<body onload="displayChart()">

<div class="chartContainer" style="width:800px;height:460px;position:relative;"></div>

<script src="js/chartiq.js"></script>
<script src="examples/feeds/sampleQuoteFeed.js"></script>

<script>

var stxx=new CIQ.ChartEngine({container:document.querySelector(".chartContainer")});
stxx.attachQuoteFeed(quoteFeed,{refreshInterval:1});

function displayChart(){
	stxx.loadChart("SPY", {
		periodicity: {
			period: 1,
			interval: 5,
			timeUnit: 'minute'
		}
	});
}

</script>
</body>
</html>

Load the updated helloworld.html file in your web browser. You should see a candle chart containing five days of simulated data (if no weekends or holidays intervene). Swipe the chart to scroll backward and forward through the data.

Note: If your chart doesn’t display data, check whether the stock markets are open. The quote feed simulator returns data only during U.S. stock market trading hours for symbols (such as SPY) traded on those markets; typically, 9:30 a.m. to 4:00 p.m. U.S. eastern time, Monday through Friday (excluding holidays), or 6:00 a.m. to 8:00 p.m. U.S. eastern time if the extended parameter is set to 1 in the quote feed callbacks (see “Create a Quote Feed” above).

In Summary

The sample quote feed is a fully functional example. Assuming you are using a RESTful API in your production environment, replace the quote feed URL with a real data provider and revise the formatChartData function to properly format the returned data, and you’ll have a basic production-ready data feed.

Customize the User Interface

Chart user interfaces enable users to control and interact with charts. The ChartIQ library provides a variety of sample web components and custom tags that application developers can use to quickly create full-featured chart user interfaces that include toolbars, menus, dialogs, titles, legends, and more.

The helloworld.html file we used earlier in this guide created a chart, but the chart lacked a user interface. In this exercise, we’ll use sample-template-advanced.html, a template that creates a chart with a complete UI.

Copy sample-template-advanced.html from the ChartIQ/examples/templates folder on your web server to the ChartIQ folder. For convenience, rename the file chartui.html.

Load the file in your web browser; for example, enter the following in your browser’s address bar:

localhost:5500/chartiq/chartui.html

You should see a chart that looks similar to the following:

Chart with user interface

Note the toolbar along the top of the chart and the stock symbol and other elements in the upper left corner of the chart. These controls and display elements are created with ChartIQ web components; they constitute the chart user interface.

The UI enables users to change the chart in many ways. For example, to change the chart style, select the Display menu, and then select a chart style, such as Colored Bar or Baseline. To change the chart theme, open the Display menu, scroll to the bottom of the menu, and then select Day (under THEMES). Change the theme again by selecting Night.

In this exercise, we’ll add a custom theme to the Display menu.

Source Code Review

Open the chartui.html file in an editor and take a look at the source code. The markup consists mainly of web components and custom semantic tags. ChartIQ web components are custom HTML elements with built-in programming logic; for example, cq-menu and cq-menu-dropdown, which together create conventional drop-down menus. ChartIQ semantic tags are non-standard HTML tags (type HTMLUnknownElement) that serve as presentation elements only; for example, cq-item and cq-heading.

ChartIQ web components and semantic tags begin with the prefix “cq-” and are styled with CSS class selectors whose names typically begin with “ciq-”; for example, ciq-menu and ciq-radio.

The chartui.html file is long and complex. But we’re concerned with only a few pieces.

Display Menu

In your editor, search for <span>Display</span> in chartui.html.

Your search should take you to the following excerpt of code:

<cq-menu class="ciq-menu ciq-display collapse">
	<span>Display</span>
	<cq-menu-dropdown>
		<cq-heading>Chart Style</cq-heading>
		<cq-item stxsetget="Layout.ChartType('candle')">Candle
			<span class="ciq-radio"><span></span></span>
		</cq-item>
		<cq-item stxsetget="Layout.ChartType('bar')">Bar
			<span class="ciq-radio"><span></span></span>
		</cq-item>
		<cq-item stxsetget="Layout.ChartType('colored_bar')">Colored Bar
			<span class="ciq-radio"><span></span></span>
		</cq-item>
		.
		.
		.
		<cq-separator></cq-separator>
		.
		.
		.

Let’s examine some of the main elements.

<cq-menu>

A ChartIQ web component that creates the Display menu.

<span>Display</span>

A standard HTML element that provides the title of the menu.

<cq-menu-dropdown>

A ChartIQ web component that contains the items that make up the menu.

<cq-heading>

A ChartIQ tag that identifies a heading within the drop down menu. (The Display menu contains several headings.)

<cq-item>

A ChartIQ tag that identifies a menu item. Each cq-item tag contains the text of the menu item (such as “Candle”) and a span element styled as a radio button by the ciq-radio CSS class selector’s style rule (which can be found in the chartiq.css file in the ChartIQ/css folder on your web server).

<cq-separator>

A ChartIQ tag that creates a horizontal line used to separate categories of menu items.

Themes Web Component

The Display menu consists of headings, items, separators, and one unique element: <cq-themes>. Scroll down through the Display menu markup or search to find <cq-themes>.

Here’s the themes excerpt from the Display menu markup:

<cq-themes>
	<cq-themes-builtin cq-no-close>
		<template>
			<cq-item></cq-item>
		</template>
	</cq-themes-builtin>
	<cq-themes-custom cq-no-close>
		<template>
			<cq-theme-custom>
				<cq-item>
					<cq-label></cq-label>
					<cq-close></cq-close>
				</cq-item>
			</cq-theme-custom>
		</template>
	</cq-themes-custom>
	<cq-separator cq-partial></cq-separator>
	<cq-item stxtap="newTheme()"><cq-plus></cq-plus>New Theme</cq-item>
</cq-themes>

The key elements of this markup include:

<cq-themes>

A ChartIQ web component that displays the available themes and provides access to a dialog that enables users to create new themes.

<cq-themes-builtin>

A ChartIQ tag that displays the themes that are built into the chart. The component uses HTML templating to create its theme elements programmatically.

<cq-themes-custom>

A ChartIQ tag that displays themes created by users. The component uses HTML templating to create its theme elements programmatically.

<template>

A standard HTML element used to contain other HTML that is rendered by JavaScript.

<cq-theme-custom>

A ChartIQ tag that displays an individual user-defined theme. Users create themes by means of a dialog opened from the final child element of <cq-themes>. See <cq-item stxtap-"newTheme()"> below.

<cq-label>

A ChartIQ tag that styles text; in this case, the text of a menu item.

<cq-close>

A ChartIQ web component that creates a control that closes, or removes, an element; in this case, a custom theme.

<cq-plus>

A ChartIQ tag that styles a plus sign.

<cq-item stxtap="newTheme()">

A ChartIQ item tag that opens a dialog that enables users to create a custom theme by selecting colors for various chart elements.

Create a Built-In Theme

Now that we understand the structure of the Display menu and, in particular, the themes element, let’s add a new built-in theme, which will be available whenever the chart loads.

ChartIQ charts come with two built-in themes (light and dark) called “Day” and “Night.” Each theme sets the colors of various chart elements by means of the CSS styles ciq-day and ciq-night, respectively. The ciq-day style is actually just a class selector; no CSS styling is created for the selector.

Here’s an example of a Night theme style element:

.ciq-night .ciq-chart-area {
	background-color: #151f28;
}

The Day theme is the chart default; when the Day theme is selected, the chart default styling takes effect. Day and Night styles can be found in the chartiq.css file in the ChartIQ/css folder on your web server.

So, our new theme needs some CSS style rules. In the ChartIQ/css folder, create a file named chartui.css.

Add the following style rules to the file:

.my-theme .ciq-chart-area {
	background-color: #175397;
}

.my-theme .chartContainer {
	background-color: #fffdef;
}

.my-theme .ciq-nav {
	background-color: #aad2ff;
}

.my-theme input#symbol {
	background-color: #e8f3ff;
}

More can be added by mimicking the Night theme.

The descendant selectors of the these rules are class selectors (ciq-chart-area, chartContainer, and ciq-nav) or element/ID selectors (input#symbol) of elements in the chart. (You can find them by searching chartui.html.) The parent selector, my-theme, will be programmatically added to the <cq-context> web component of chartui.html by JavaScript that we’ll write next.

You can find <cq-context> just below the <body> tag in chartui.html. The component surrounds all of the markup inside the body. In that way, any class selector assigned to <cq-context> becomes the parent of all other selectors in the file. When a theme is selected from the Display menu, the class selector associated with that theme is assigned to <cq-context>; and so, that theme’s parent/descendant CSS rules take effect.

Link the new CSS file into chartui.html by adding the following link tag:

<link rel="stylesheet" type="text/css" href="css/chartui.css" media="screen" />

Place the link after all the other tags in chartui.html that link to CSS files to ensure that our custom styles come last in the CSS cascade.

UIThemes

Now, let’s add our custom theme to the chart.

The HTML markup — the presentation layer — of the chart user interface is contained in chartui.html. However, the user interface logic is contained in a file called sample-template.js, which is located in the ChartIQ/examples/templates/js folder on your web server. The following script tag in chartui.html includes sample-template.js:

<script src="examples/templates/js/sample-template.js"></script>

Open sample-template.js in an editor, and search for “UIThemes”. Your search should take you to the following JavaScript excerpt:

var UIThemes=topNode.querySelector("cq-themes");
if (UIThemes) UIThemes.initialize({
	builtInThemes: {"ciq-day":"Day","ciq-night":"Night"},
	defaultTheme: "ciq-night",
	nameValueStore: UIStorage,
	id: root.id
});

The variable UIThemes is assigned a reference to the <cq-themes> web component contained in the Display menu markup in chartui.html (topNode is a reference to the <cq-context> element, which contains <cq-themes>).

The web component’s initialize method takes as its only argument an object that contains configuration information for the chart themes. The initialize method does the following:

  • Creates a list of the chart’s built-in themes. The object literal assigned to the builtInThemes property provides the list of themes. Each theme is defined by a key/value pair. The key (for example, ciq-day) is the name of the theme, which identifies the theme programmatically. The key is also the CSS class selector of the theme, which is assigned to the <cq-context> web component. The value (for example, Day) is the text displayed in the Display menu, representing the theme.

  • Sets the default theme for the chart. The value of the defaultTheme property provides the name of the default theme.

  • Sets a reference to the browser’s local storage. The value of the nameValueStore property provides a reference to the local storage object. Local storage is used to store the currently selected theme, which enables the chart to retain the theme whenever the chart is closed and reopened.

    UIStorage is a variable set by the following statement (which in sample-template.js is just above the UIThemes excerpt):

    var UIStorage=new CIQ.NameValueStore();
    

    The CIQ.NameValueStore function returns a reference to the JavaScript Window.localStorage object.

  • Sets a reference to the chart, which is used to identify the chart when multiple charts are on screen simultaneously.

To add our custom theme to the chart, add the theme to the list of built-in themes as follows:

builtInThemes: {"ciq-day":"Day","ciq-night":"Night","my-theme":"My Theme"},

That’s it. Save the file, and load chartui.html in your web browser. “My Theme” should appear on the Display menu (under the THEMES heading). Select “My Theme” to display the new chart colors. Close your browser and reload the chart; “My Theme” should still be in effect.

Finally, let’s add a watermark to our custom theme using CSS styling. Revise the style rule in chartui.css for the .my-theme .chartContainer compound selector as follows:

.my-theme .chartContainer {
	background-color: #fffdef;
	background-image: url(img/watermark.svg);
	background-repeat: no-repeat;
	background-position: center;
}

The watermark.svg file is in the ChartIQ/css/img folder on your web server.

Load chartui.html in your web browser. The result should look something like:

Chart with watermark and customized UI

In Summary

The ChartIQ web component framework enables you to build a full-featured user interface for your charts. The sample-template-advanced.html file in the ChartIQ/examples folder gives you a great start.

But you can also create a UI in React, Angular, Vue, iOS, Android, Java — whatever tools you choose.

Next Steps

This guide has provided a brief introduction to the ChartIQ HTML5 Charting Library. But there’s much more to discover. Explore our documentation web site at https://documentation.chartiq.com to access a variety of in-depth tutorials and the complete API documentation.

Let us know if you have any questions: support@chartiq.com.