Draw one day area chart using lightweight-chart library - javascript

I am trying to plot stock price data for a ticker using lightweight-charts.I can use it in expected way to draw chart for intervals like 1w, 1 month or 3 month etc. But Chart is not drawn as expected for one-day data.
Here are my part of code :
useEffect(() => {
const chart = createChart(ref.current, {
lineVisible: false,
width: 400,
height: 200,
layout: {
background: { color: "#26273000" },
textColor: "rgba(255, 255, 255, 0.9)",
},
leftPriceScale: {
borderVisible: false,
autoScale: true,
},
rightPriceScale: {
borderVisible: false,
autoScale: true,
},
grid: {
horzLines: {
visible: false,
},
vertLines: {
visible: false,
},
},
crosshair: {
mode: CrosshairMode.Magnet,
},
timeScale: {
minBarSpacing: 0.001,
borderVisible: false,
fixLeftEdge: true,
fixRightEdge: true,
},
priceScale: {
fixLeftEdge: true,
fixRightEdge: true,
minBarSpacing: 0.001,
},
localization: {
priceFormatter: (price) => {
return parseInt(price);
},
},
});
const areaSeries = chart.addAreaSeries();
const data = [
{ time: "2022-03-21T09:15:00", value: 502 },
{ time: "2022-03-21T09:30:00", value: 498.1 },
{ time: "2022-03-21T09:45:00", value: 495.6 },
{ time: "2022-03-21T10:00:00", value: 495.35 },
{ time: "2022-03-21T10:15:00", value: 495.6 },
{ time: "2022-03-21T10:30:00", value: 495.7 },
{ time: "2022-03-21T10:45:00", value: 495.5 },
{ time: "2022-03-21T11:00:00", value: 495.7 },
{ time: "2022-03-21T11:15:00", value: 495.5 },
{ time: "2022-03-21T11:30:00", value: 495.65 },
{ time: "2022-03-21T11:45:00", value: 494.1 },
{ time: "2022-03-21T12:00:00", value: 492.45 },
{ time: "2022-03-21T12:15:00", value: 492.7 },
{ time: "2022-03-21T12:30:00", value: 492.3 },
{ time: "2022-03-21T12:45:00", value: 490 },
{ time: "2022-03-21T13:00:00", value: 490.05 },
{ time: "2022-03-21T13:15:00", value: 489.95 },
{ time: "2022-03-21T13:30:00", value: 489.65 },
{ time: "2022-03-21T13:45:00", value: 491.05 },
{ time: "2022-03-21T14:00:00", value: 491.4 },
{ time: "2022-03-21T14:15:00", value: 492.8 },
{ time: "2022-03-21T14:30:00", value: 492.55 },
{ time: "2022-03-21T14:45:00", value: 490.8 },
{ time: "2022-03-21T15:00:00", value: 490.7 },
{ time: "2022-03-21T15:15:00", value: 491.05 },
{ time: "2022-03-21T15:30:00", value: 490.1 },
];
const visibleTimeRange = {};
visibleTimeRange.from = new Date(data[0].time).getTime() - 75000 * 6;
//7.5 minutes offset
visibleTimeRange.to = new Date(data[data.length - 1].time).getTime() + 75000 * 6;
//7.5 minutes offset
chart.timeScale().setVisibleLogicalRange(visibleTimeRange);
}, []);
return <div ref={ref}></div>;
However, the chart does not show time on its timeScale. The chart looks like a straight line drawn on the same day.
Chart for other range looks as expected:
Please help me in fixing this issue. Thanks!
Update-1: After I changed time to their microseconds format using new Date(date).getTime(),then i was able to see plot but time and date on x-axis were not correct.

This question has already been answered here.
Basically you need to properly format your timestamp as explained in the doc.

Related

DatePicker in Columns Syncfusion JavaScript Spreadsheet

I want to open calendar in one of the columns and when use select date, I want to display in MM/dd/yyyy. I want to validate date too on button click.
var sheet = [
{
ranges: [{
dataSource: tradeData
}],
fieldAsColumnHeader: true,
columns: [{
width: 70
}, {
width: 80
}, {
width: 100
}, {
width: 100
},
{
width: 70
}, {
width: 120
}, {
width: 80
}, {
width: 120
},
{
width: 140
}, {
width: 80
}, {
width: 120
}, {
width: 120
}
],
rows: [{
index: 1,
cells: [{
index: 3,
value: '',
validation: {
type: 'List',
value1: trade_types.toString()
}
},
{
index: 8,
value: '',
validation: {
type: 'List',
value1: counter_parties.toString()
}
},
{
index: 10,
value: '',
validation: {
type: 'List',
value1: settlement_methods.toString()
}
}
]
}]
}
];
var spreadsheet = new ej.spreadsheet.Spreadsheet({
showRibbon: false,
showFormulaBar: false,
showSheetTabs: false,
sheets: sheet,
created: () => {
//Add Data validation to range.
}
});
spreadsheet.appendTo('#spreadsheet');

How to filter by date range elastic search query aggregate?

I'm new to Elastic search and trying to adapt my query to build aggregate buckets based on a different date range.
I have two objects that specify the date range prevRange & range, both of them have only two properties {to, from}
My goal is to try filter different aggerations by the date range (e.g. incoming -> rangeStatuses & incoming -> prevRangeStatuses & belongsTo), but I'm not sure how to incorporate the filtering logic
I was trying to use hard_bounds instead of extended_bounds, but it gives me the wrong results. Filters aggregation doesn't seem to have any options to pass date ranges
{
query: {
bool: {
filter: [
{
range: {
createdAt: {
time_zone: timezone,
gte: prevRange.from,
lte: range.to,
},
},
},
],
},
},
aggs: {
incoming: {
terms: { field: 'status' },
aggs: {
rangeStatuses: {
terms: { field: 'status' },
aggs: {
histogram: {
date_histogram: {
field: 'createdAt',
calendar_interval: granularity,
min_doc_count: 0,
time_zone: timezone,
extended_bounds: {
min: range.from.getTime(),
max: range.to.getTime(),
},
},
},
},
},
prevRangeStatuses: {
terms: { field: 'status' },
aggs: {
histogram: {
date_histogram: {
field: 'createdAt',
calendar_interval: granularity,
min_doc_count: 0,
time_zone: timezone,
extended_bounds: {
min: prevRange.from.getTime(),
max: prevRange.to.getTime(),
},
},
},
},
},
},
},
belongsTo: {
filter: {
exists: {
field: 'type',
},
},
aggs: {
activities: {
terms: {
field: 'type',
},
aggs: {
direction: {
terms: {
field: 'direction',
},
aggs: {
histogram: {
date_histogram: {
field: 'createdAt',
time_zone: timezone,
calendar_interval: granularity,
min_doc_count: 0,
extended_bounds: {
min: range.from.getTime(),
max: range.to.getTime(),
},
},
},
},
},
duration: {
date_histogram: {
field: 'createdAt',
time_zone: timezone,
calendar_interval: granularity,
min_doc_count: 0,
extended_bounds: {
min: range.from.getTime(),
max: range.to.getTime(),
},
},
aggs: {
duration: {
sum: {
field: 'duration',
},
},
},
},
},
},
},
},
},
},

Convert json data to object

Good Day Developers!
I'm facing issue in JSON object received from MVC controller to AJAX success request.
The response which received is below.
[
{"name":"ERP Developer","value":2},
{"name":"Software Engineer","value":2},
{"name":"Dot Net Developer","value":2},
{"name":"Apex Developer","value":0},
{"name":"test","value":1}
]
But i want to make it like below.
{
"name": [
"ERP Developer",
"Software Engineer"
],
"Value": [
5,
10
]
}
Problem: Because i'm creating Bar chart using ECHARTS library but i want series name instead of number please see below image for reference.
function loadBarChart(data,title = "JobData",subtext = "Artistic Milliners") {
//var BarDBData = data;
var BarDBData = data;
//var BarDBData = JSON.parse('{"name":["ERP Developer","TEST"],"test":[5,10]}');
console.log(BarDBData);
var chartDom = document.getElementById('BarChart');
var myChart = echarts.init(chartDom);
var option;
option = {
title: {
text: title,
subtext: subtext
},
tooltip: {
trigger: 'axis'
},
toolbox: {
show: true,
feature: {
dataView: { show: true, readOnly: false },
magicType: { show: true, type: ['line', 'bar'] },
saveAsImage: { show: true }
}
},
calculable: true,
xAxis: [
{
type: 'category',
// prettier-ignore
//data: ["ERP Developer", "Software Engineer"],
data: BarDBData,
axisLabel: { interval: 0, rotate: 30 }
}
],
yAxis: [
{
type: 'value'
}
],
dataZoom: [
{
show: true,
start: 04,
end: 100
},
{
type: 'inside',
start: 44,
end: 100
},
{
show: true,
yAxisIndex: 0,
filterMode: 'empty',
width: 30,
height: '80%',
showDataShadow: false,
left: '93%'
}
],
series: [
{
name: "test",
type: 'bar',
data: BarDBData,
//data: [2.0, 4.9, 4, 9, 4],
itemStyle: {
color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
{ offset: 0, color: '#83bff6' },
{ offset: 0.5, color: '#188df0' },
{ offset: 1, color: '#188df0' }
])
},
markPoint: {
data: [
{ type: 'max', name: 'Max' },
{ type: 'min', name: 'Min' }
]
}
}
]
};
option && myChart.setOption(option);
}
you can just map through array and extract values into another array
const result = {}
const arr = [{"name":"ERP Developer","value":2},{"name":"Software Engineer","value":2},{"name":"Dot Net Developer","value":2},{"name":"Apex Developer","value":0},{"name":"test","value":1}]
arr.forEach(row => {
for (let i in row) {
if (result[i]) {
result[i].push(row[i])
} else {
result[i] = [row[i]]
}
}
})
console.log(result)
Just reduce() it into the desired shape:
const response = [
{"name":"ERP Developer","value":2},
{"name":"Software Engineer","value":2},
{"name":"Dot Net Developer","value":2},
{"name":"Apex Developer","value":0},
{"name":"test","value":1}
];
const mapped = response.reduce(
(acc,x) => {
acc.name.push( x.name );
acc.Value.push( x.value );
return acc;
},
{ name: [], Value: [] }
);

How can I change start week day on a graph? (plotly.js)

How can I change start week day on a graph? Now I have only Sundays on xaxis. I need to display only Mondays on xaxis. Thank you. My plotly config is:
...
xaxis: {
type: 'date',
automargin: true,
tickformat: '%d.%m',
maxPadding: 1,
},
yaxis: {
tickmode: 'array',
automargin: true,
showticklabels: false,
showgrid: false,
},
...
I cloned their repo and used your data array As I mentioned in my notes, it's just a matter of formatting what you're feeding your x/axis, I used moment in my example below, I'm sure you can use other ways to get the date format you'd like.
let me know if something about below code needs further clarification. BTW. I'm using react version, but at a quick glance they both looked like the same setup.
const PlotlyClass = (props) => {
let VasilyBasicArray = [{ value: "2020-04-16", count: 100 }, { value: "2020-04-17", count: 200 }, { value: "2020-04-18", count: 300 }, { value: "2020-04-19", count: 400 }, { value: "2020-04-20", count: 500 }, { value: "2020-04-21", count: 600 }, { value: "2020-04-22", count: 700 }, { value: "2020-04-23", count: 800 }, { value: "2020-04-24", count: 100 }, { value: "2020-04-25", count: 200 }, { value: "2020-04-26", count: 300 }, { value: "2020-04-27", count: 400 }, { value: "2020-04-28", count: 500 }, { value: "2020-04-29", count: 600 }, { value: "2020-04-30", count: 700 }]
return (
<Plot
data={[
{
x: VasilyBasicArray.map(rec => moment(rec.value).format('dd-Do')),
y: VasilyBasicArray.map(rec => rec.count),
type: 'scatter',
mode: 'lines+markers',
marker: { color: 'red' },
},
{ type: 'bar', x: VasilyBasicArray.map(rec => moment(rec.value).format('dd-Do')), y: VasilyBasicArray.map(rec => rec.count) },
]}
layout={{ width: 320, height: 240, title: 'A Fancy Plot' }}
/>
);
};
Make a local copy of plotly.
Find text: GregorianCalendar.prototype (or your default calendar).
In this prototype find variable firstDay (there are many firstDay variables in the file) and change value from 0 to 1.
This is not clean solution but it works if you don't need to use other languages.
In this prototype you can rename months and days too if you need.

Highstock granularity of x-axis

My highstock chart chokes on the x-axis labels once I get down any more granular than about 1 day - that is, the data renders properly but the x-axis (time) labels don't seem to update, and become more sparse as I zoom in until they disappear completely. (See images)
Here is a fiddle at a larger time interval where the labels show as expected: http://jsfiddle.net/uhpn8Ljp/2/
Here is a fiddle for the smaller intervals where they don't display: http://jsfiddle.net/4r39730h/1/
I have this as my data setup when the data is received:
return {
chart: {
type: 'areaspline',
zoomType: 'x',
},
credits: {
enabled: false,
},
navigator: {
adaptToUpdatedData: false,
series: {
data: masterSeriesDateValues || dateValues,
},
yAxis: {
gridLineWidth: 0,
startOnTick: false,
endOnTick: false,
minPadding: 0.1,
maxPadding: 0.1,
labels: {
enabled: false,
},
title: {
text: null,
},
tickWidth: 0,
min: 0,
},
},
rangeSelector: {
enabled: true,
inputBoxStyle: { right: '65px', position: 'absolute' },
buttons: [{
type: 'second',
count: 1,
text: '1s',
}, {
type: 'minute',
count: 1,
text: '1min',
}, {
type: 'hour',
count: 1,
text: '1h',
}, {
type: 'day',
count: 1,
text: '1d',
}, {
type: 'month',
count: 1,
text: '1m',
}, {
type: 'year',
count: 1,
text: '1y',
}, {
type: 'all',
text: 'All',
}],
selected: rangeSelectorIndex,
inputDateFormat: dateFormat,
inputEditDateFormat: dateFormat,
inputBoxWidth: 170,
},
exporting: {
enabled: false,
},
xAxis: {
min: xAxisStart,
max: xAxisEnd,
minRange: 1, // one millisecond
},
yAxis: {
min: 0,
},
tooltip: {
formatter: function () {
return `${this.points[0].series.name} : ${(display === 'count' ? this.y : formatBytes(this.y))}`;
},
},
series: [{
id: 'itemSize',
name: display === 'count' ? 'Count of Items' : 'Size of Items',
data: dateValues,
dataGrouping: {
enabled: false,
},
}],
};
I also add a few events and labels on render:
xAxis.events = {
afterSetExtremes: this.afterSetExtremes.bind(this),
};
chart.events = { selection: function (ev) {
that.handleRangeSelection.call(this, ev, that);
} };
chartConfig.tooltip = {
formatter: function () {
let label;
if (display === 'count') {
label = this.points[0].series.name + ': ' + this.y;
} else {
label = this.points[0].series.name + ': ' + formatBytes(this.y);
}
return label;
},
};
In a previous implementation of the app, I was seeing smaller and smaller intervals down to milliseconds, and I just copied and pasted the configuration so I don't understand what could be different.

Categories