### Navigate to Project and Install Dependencies
Source: https://github.com/project-nv/night-vision/blob/main/docs/docs/guide/intro/getting-started.md
Change into the newly created project directory and install the initial project dependencies using npm.
```sh
cd night-vision-101
```
```sh
npm install
```
--------------------------------
### Install NightVision Package
Source: https://github.com/project-nv/night-vision/blob/main/docs/docs/guide/intro/getting-started.md
Add the NightVision library as a project dependency using npm.
```sh
npm i night-vision
```
--------------------------------
### Run Development Server
Source: https://github.com/project-nv/night-vision/blob/main/docs/docs/guide/intro/getting-started.md
Start the Vite development server to view the created NightVision chart in the browser.
```sh
npm run dev
```
--------------------------------
### Installing NightVision Python Integration Dependencies (Shell)
Source: https://github.com/project-nv/night-vision/blob/main/docs/docs/guide/intro/10-basic-examples.md
Install the necessary Python and Node.js dependencies to run the NightVision Python integration example. This includes the Python 'requests' library and Node.js packages defined in 'package.json'.
```shell
python3 -m pip install requests
npm install
```
--------------------------------
### Initialize NightVision Chart in main.js
Source: https://github.com/project-nv/night-vision/blob/main/docs/docs/guide/intro/getting-started.md
Replace the default content of main.js with code to import NightVision, set up basic HTML, generate sample data, initialize the chart targeting the 'chart-container' element, and assign the generated data.
```js
import './style.css'
import { NightVision } from 'night-vision'
document.querySelector('#app').innerHTML = `
Night Vision Charts
`
// Generate some random data
function data() {
return Array(30).fill(1).map((x, i) => [
new Date(`${i+1} Nov 2022 GMT+0000`).getTime(),
i * Math.random()
])
}
let chart = new NightVision('chart-container')
chart.data = {
panes: [{
overlays: [{
name: 'APE Stock',
type: 'Spline',
data: data(),
settings: {
precision: 2
}
}]
}]
}
```
--------------------------------
### Create Vite Project with Vanilla JS Template
Source: https://github.com/project-nv/night-vision/blob/main/docs/docs/guide/intro/getting-started.md
Use npm, yarn, or pnpm to create a new Vite project directory named 'night-vision-101' with a basic vanilla JavaScript template.
```sh
npm create vite@latest night-vision-101 --template vanilla
```
```sh
npm create vite@latest night-vision-101 -- --template vanilla
```
```sh
yarn create vite night-vision-101 --template vanilla
```
```sh
pnpm create vite night-vision-101 --template vanilla
```
--------------------------------
### Overlay DataView Object Example (JavaScript)
Source: https://github.com/project-nv/night-vision/blob/main/docs/docs/guide/data-struct/overlay-object.md
Provides an example structure for the 'overlay.dataView' object. This object references a subset of the main data array using start and end indices ('i1', 'i2') and includes the subset length and a reference to the source data.
```javascript
// Example of `overlay.dataView`
{
i1: 4148, // Start index
i2: 4199, // End index (included)
length: 52, // length of the section
src: […] // Reference to `overlay.data`
}
```
--------------------------------
### Configuring Area Overlay Type (JavaScript)
Source: https://github.com/project-nv/night-vision/blob/main/docs/docs/guide/intro/10-basic-examples.md
This example shows how to change the overlay type from 'Spline' to 'Area' and customize its appearance using the 'props' object. It demonstrates setting custom colors for the area fill and line.
```javascript
// The main pane
{
"overlays": [
{
"name": "APE / Tether US",
"type": "Area", // We are using a different overlay
"main": true,
"settings": {},
"props": {
"color": "#ba0179", // Setting custom colors
"back1": "#ba017925",
"back2": "#bd11db05"
}
}
]
}
```
--------------------------------
### Configuring Chart Colors (JavaScript)
Source: https://github.com/project-nv/night-vision/blob/main/docs/docs/guide/intro/10-basic-examples.md
Demonstrates how to set a custom color theme for the chart by providing a `colors` object with specific color properties.
```js
colors: {
back: "#1b1b1c",
grid: "#2e2f3099",
candleDw: "#0c5b3bff",
candleUp: "#41a35bff",
// ...
}
```
--------------------------------
### Installing Night Vision Charts with npm
Source: https://github.com/project-nv/night-vision/blob/main/README.md
Command to install the Night Vision charting library using the npm package manager. This is the standard way to add the library to a project.
```Shell
npm i night-vision
```
--------------------------------
### Dynamically Updating Scale Template (JS)
Source: https://github.com/project-nv/night-vision/blob/main/docs/docs/guide/intro/10-basic-examples.md
Provides an example function `onButton1` that modifies the `scaleTemplate` setting based on a condition. After changing the configuration, it calls `chart.update()` to re-render the chart with the new scale layout.
```JavaScript
// Change scale side
function onButton1() {
// ...
if (!template[0].length) {
settings.scaleTemplate = [["A"], ["B"]];
//...
} else {
settings.scaleTemplate = [[], ["A", "B"]];
// ...
}
chart.update();
}
```
--------------------------------
### Example Exotic Data Format (JavaScript)
Source: https://github.com/project-nv/night-vision/blob/main/docs/docs/guide/main-comp/meta-hub.md
Provides an example of a data format where each item is a nested structure containing a timestamp and an object with price and currency, which requires a custom precision sampler for automatic precision detection.
```js
// Example of an "exotic" data format
[
[1648400400000, { price: 100.1, currency: '$' }],
[1648404000000, { price: 100.2, currency: '$' }],
[1648407600000, { price: 99.99, currency: '$' }],
// ...
]
```
--------------------------------
### Calling a Chart Method Example (JS)
Source: https://github.com/project-nv/night-vision/blob/main/docs/docs/guide/api/chart-api.md
Provides a simple example of calling a method on the chart instance, specifically the update() method, which is used to refresh the chart display.
```js
// For example
chart.update()
```
--------------------------------
### NightVision Data Point Structure Example (JavaScript)
Source: https://github.com/project-nv/night-vision/blob/main/docs/docs/guide/main-comp/layout.md
Shows an example of the array-based data structure used by NightVision, illustrating how individual data points (like OHLCV) are represented within the main data array.
```JavaScript
[
[1584428400000,5300,5325,5300,5325,518.94863323],
[1584428400000,5325,5350,5325,5350,518.94863323],
[1584428400000,5350,5375,5350,5375,518.94863323],
[1584428400000,5375,5400,5375,5400,518.94863323],
[1584432000000,5375,5375,5350,5350,710.36249024],
// ...
]
```
--------------------------------
### Defining Chart Overlay Configuration (JavaScript)
Source: https://github.com/project-nv/night-vision/blob/main/docs/docs/guide/intro/10-basic-examples.md
Shows the structure of an overlay configuration object, including properties for name, type, data, settings (like display visibility), and props (like color).
```js
// Overlay object
{
"name": "SMA 1",
"type": "Spline",
"data": […],
"settings": {
"display": false // Hide the overlay
},
"props": {
"color": "#39f"
}
}
```
--------------------------------
### Setting Main Overlay for Grid Calculation (JavaScript)
Source: https://github.com/project-nv/night-vision/blob/main/docs/docs/guide/intro/10-basic-examples.md
Illustrates how to designate a specific pane's overlay as the "main" overlay for grid calculation by setting the `main` property to `true` within the pane's settings.
```js
// Pane object
{
settings: {
main: true
}
}
```
--------------------------------
### Initializing Multiple NightVision Instances (JavaScript)
Source: https://github.com/project-nv/night-vision/blob/main/docs/docs/guide/intro/10-basic-examples.md
To display multiple charts on the same screen, initialize each NightVision instance with a unique DOM element ID. The full code is typically found in a main JavaScript file.
```javascript
// The full code is in 'main.js'
let chart1 = new NightVision({ id: 'nvjs-1'})
let chart2 = new NightVision({ id: 'nvjs-2'})
// ...
```
--------------------------------
### Initializing NightVision Chart with Real-time Data in JavaScript
Source: https://github.com/project-nv/night-vision/blob/main/docs/docs/guide/intro/10-basic-examples.md
Initializes a NightVision chart instance, loads initial historical OHLCV data using DataLoader, sets up infinite scrolling to load more historical data when the user scrolls left, and integrates a WebSocket stream (wsx) to receive trades and update the chart data using ohlcvSampler. Includes periodic checks for loading more data.
```JavaScript
import "./style.css";
import { NightVision } from "./night-vision.js";
import { DataLoader } from "./dataLoader.js";
import wsx from "./wsx.js";
import sampler from "./ohlcvSampler.js";
// ...
let chart = new NightVision("chart-container", {
autoResize: true,
colors: {
back: "#1b1b1c",
grid: "#2e2f3099"
}
});
let dl = new DataLoader();
// Load the first piece of the data
dl.load((data) => {
chart.data = data;
el("loading").hidden = true;
});
// Load deeper into the history
function loadMore() {
if (!chart.hub.mainOv) return;
let data = chart.hub.mainOv.data; // Main OHLCV
let t0 = data[0][0]; // Leftmost timestamp
// Check if we out of data
if (chart.range[0] < t0) {
el("loading").hidden = false;
dl.loadMore(t0 - 1, (chunk) => {
// Add a new chunk at the beginning
data.unshift(...chunk);
// You need to update "range"
// when the data range is changed
chart.update("data");
el("loading").hidden = true;
});
}
}
// Load new data when user scrolls left
chart.events.on("app:$range-update", loadMore);
// Plus check for updates every half-second
setInterval(loadMore, 500);
// Setup a trade data stream
wsx.init(["APE-PERP"]);
wsx.ontrades = (d) => {
if (!chart.hub.mainOv) return;
let data = chart.hub.mainOv.data;
let trade = {
price: d.price,
volume: d.price * d.size
};
if (sampler(data, trade)) {
chart.update("data"); // New candle
} else {
chart.update(); // Candle update
}
};
// ...
```
--------------------------------
### Configuring Pane Scales Settings (JavaScript)
Source: https://github.com/project-nv/night-vision/blob/main/docs/docs/guide/data-struct/pane-object.md
Provides an example of the pane.settings.scales object structure, showing how scale definitions are stored as an associative array, with properties like precision.
```js
// Example of pane.settings.scales
{
A: {
precision: 2
},
B: {
// ...
},
// ...
}
```
--------------------------------
### Initializing NavyJS Overlay (JavaScript)
Source: https://github.com/project-nv/night-vision/blob/main/docs/docs/guide/api/navy-api.md
Called once when the overlay is created. Use this function for one-time setup like adding event listeners. Event listeners should use a unique component ID derived from `core.uuid` to prevent conflicts.
```js
init() {
// Add event listener, which should use an unique component id
$events.on(`rsi-${core.uuid}:some-event`, e => {
console.log(e)
})
}
```
--------------------------------
### Initializing and Setting Data for Night Vision Chart in JavaScript
Source: https://github.com/project-nv/night-vision/blob/main/README.md
Demonstrates how to import the Night Vision library, create a new chart instance linked to a DOM element, generate sample data, and assign the data to the chart's panes and overlays. Requires a DOM element with the specified ID to exist.
```JavaScript
import { NightVision } from 'night-vision'
let chart = new NightVision('')
// Generate some random data
function data() {
return Array(30).fill(1).map((x, i) => [
new Date(`${i+1} Nov 2022 GMT+0000`).getTime(),
i * Math.random()
])
}
// Set the dataset
chart.data = {
panes: [{
overlays: [{
name: 'APE Stock',
type: 'Spline',
data: data(),
settings: {
precision: 2
}
}]
}]
}
```
--------------------------------
### Example of Complex Indexing to Avoid (NavyJS)
Source: https://github.com/project-nv/night-vision/blob/main/docs/docs/guide/navy-js/indicator-scripts.md
Provides an example of a code construction involving complex indexing (brackets inside brackets) that should be avoided in the Script Engine due to potential issues.
```JavaScript
ts1[[i][0] + arr[n]]
```
--------------------------------
### Using NightVision Mapping Functions (JavaScript)
Source: https://github.com/project-nv/night-vision/blob/main/docs/docs/guide/main-comp/layout.md
Provides examples of the mapping functions available on the Layout object to convert between data values (time, price) and screen coordinates (x, y) for chart rendering.
```JavaScript
layout.time2x(t) // time -> x
layout.value2y($) // price -> y
layout.y2value(y) // y -> price
layout.x2time(x) // x -> time
// ...
```
--------------------------------
### Syncing NightVision Chart Ranges (JavaScript)
Source: https://github.com/project-nv/night-vision/blob/main/docs/docs/guide/intro/10-basic-examples.md
Synchronize the time ranges of multiple NightVision chart instances by listening to the 'app:$range-update' event on each instance and setting the range of the other instance accordingly.
```javascript
// Time-range sync
// Subscribing to the events of the first instance
chart1.events.on("app:$range-update", (range) => {
chart2.range = range;
});
// Subscribing to the events of the second instance
chart2.events.on("app:$range-update", (range) => {
chart1.range = range;
});
```
--------------------------------
### Adding/Removing Chart Pane (JavaScript)
Source: https://github.com/project-nv/night-vision/blob/main/docs/docs/guide/intro/10-basic-examples.md
JavaScript function `onButton1` demonstrates how to dynamically add or remove a pane from the chart's data structure and then call `chart.update()` to apply the changes.
```js
// Add/remove pane
function onButton1() {
if (chart.data.panes.length <= 1) {
chart.data.panes.push({ // Pushing a new pane object
settings: {},
overlays: [ovData2]
});
// ...
} else {
chart.data.panes.pop();
// ...
}
chart.update(); // Need to call to apply changes
}
```
--------------------------------
### Configuring Pane Scale Template (JS)
Source: https://github.com/project-nv/night-vision/blob/main/docs/docs/guide/intro/10-basic-examples.md
Demonstrates how to set the `scaleTemplate` property within the `settings` of a pane object. This property defines the arrangement of scales on the chart pane, allowing for multiple scales on different sides or grouped together.
```JavaScript
// Pane object
{
settings: {
// Any config: [['A', 'B'], []] or [['A'], ['A']]
scaleTemplate: [[], ['A', 'B']]
}
}
```
--------------------------------
### Adding/Removing Chart Overlay (JavaScript)
Source: https://github.com/project-nv/night-vision/blob/main/docs/docs/guide/intro/10-basic-examples.md
JavaScript function `onButton2` shows how to add or remove an overlay from the first pane's overlay list and requires calling `chart.update()` to reflect the modification.
```js
// Add/remove overlay
function onButton2() {
let overlays = chart.data.panes[0].overlays;
if (overlays.length <= 2) {
overlays.push(ovData1);
// ...
} else {
overlays.pop();
// ...
}
chart.update(); // Need to call to apply changes
}
```
--------------------------------
### Showing/Hiding Chart Overlays (JavaScript)
Source: https://github.com/project-nv/night-vision/blob/main/docs/docs/guide/intro/10-basic-examples.md
JavaScript function `onButton3` uses the chart's `hub.allOverlays()` helper to iterate through overlays (excluding the main one) and toggle their `display` setting, requiring two calls to `chart.update()` (one for the chart, one specifically for the legend).
```js
// Show/hide overlays
function onButton3() {
// ...
// Here we are using a helper function of DataHub
chart.hub.allOverlays().forEach((x, i) => {
if (i === 0) return; // Except the main
x.settings.display = flag; // (true/false)
});
// IMPORTANT: Here we have to call one more update
// (for the legend)
chart.update();
chart.update("legend");
}
```
--------------------------------
### Assigning Scale to Overlay (JS)
Source: https://github.com/project-nv/night-vision/blob/main/docs/docs/guide/intro/10-basic-examples.md
Shows how to set the `scale` property within the `settings` of an overlay object. This links the overlay's data values to a specific scale defined in the pane's `scaleTemplate`, enabling proper value-to-coordinate mapping.
```JavaScript
// Overlay object
{
settings: {
scale: 'B' // Set or create a scale
}
}
```
--------------------------------
### Defining Custom NavyJS Overlay Script
Source: https://github.com/project-nv/night-vision/blob/main/docs/docs/guide/intro/10-basic-examples.md
This script defines a custom overlay for a chart using the NavyJS framework. It includes metadata, defines a custom property (`radius`), declares a constant, provides a `draw` function to render data points as circles, a `gradient` function for coloring, and a `legend` function to format legend entries.
```NavyJS
// Navy ~ 0.2-lite
// ^^^ First comment should provide a NavyJS version
// Meta tag
[OVERLAY name=Custom, ctx=Canvas, author=ChartMaster, version=1.0.0]
// Define new props
// (the same as in 'settings.props' of Overlay object)
prop('radius', { type: 'number', def: 3 })
// Any variables/constants
const _3Y = 60 * 60 * 24 * 365 * 3 * 1000
// Draw function (called on each update)
// Library provides a lot of useful variables to make
// overlays ($core in the main collection)
draw(ctx) {
ctx.strokeStyle = $props.back
ctx.lineWidth = 1
const layout = $core.layout
const data = $core.data // Full dataset
const view = $core.view // Visible view
const radius = $props.radius
for (var i = view.i1, n = view.i2; i <= n; i++) {
ctx.beginPath()
let p = data[i]
// Mapping function used to transform values into
// coordinates
let x = layout.time2x(p[0])
let y = layout.value2y(p[1])
ctx.fillStyle = gradient(p[1])
ctx.arc(x, y, radius, 0, Math.PI * 2, false)
ctx.fill()
}
}
// Make a gradient depending on the y-value
gradient(val) {
let lo = $core.layout.$lo * 1.01
let hi = $core.layout.$hi * 0.99
let pos = (val - lo) / (hi - lo)
let h = (1.0 - pos) * 240
return "hsl(" + h + ", 90%, 50%)"
}
// Legend formatter, Array of [value, color] pairs
// x represents one data item e.g. [