Данные в режиме реального времени для проблемы с адаптивной диаграммой PayOffChartJavascript

Форум по Javascript
Ответить
Anonymous
 Данные в режиме реального времени для проблемы с адаптивной диаграммой PayOffChart

Сообщение Anonymous »

Я использую приложение на основе класса React .. Из основного компонента, который я передавал данные в качестве chartdata, и я использовал данные в реальном времени, где данные постоянно передаются, и мне нужно было обеспечить плавное нака /> payoffChartComponent.tsx
import Highcharts, { color } from 'highcharts';
import HighchartsReact from 'highcharts-react-official';
import HighchartMore from 'highcharts/highcharts-more'
import { Button } from 'primereact/button';
import * as math from 'mathjs';
import { Utility } from '../../utils/Utility';
import { Calendar, Checkbox, Dropdown, InputNumber, InputText } from 'primereact';
import { WhatIf } from '../../entity/OptData';
import moment from 'moment';
import { PLCalc } from '../../utils/PLCalc';
import 'highcharts/modules/accessibility';

import * as fs from 'fs';

HighchartMore(Highcharts)
interface Props {
passedStateData,
callback,
callbackShow
}

interface State {
price;
farprice;
IV;
days;
finalPrice;
finalIV;
finalDays;
}

export class PayoffChartComponent extends React.Component {
whatif: WhatIf = new WhatIf();

constructor(props) {
super(props);

this.state = {
price: 0,
farprice: 0,
IV: 0,
days: 0,
finalPrice: 0,
finalIV: 0,
finalDays: 0,
// spotPrice: this.props.spotPrice
};

this.whatif.days = 0;
this.whatif.IV = 0;
this.whatif.price = 0;
this.whatif.allowLegAdjustment = false;
}

render() {

if (this.props.passedStateData.chartData == null) return null;
if (this.props.passedStateData.legEntityList.length == 0) return null;
let lastUpdate = this.props.passedStateData?.expiryDataMap[this.props.passedStateData?.selectedExpiryDate]?.lastUpdate;
let spotPrice = this.props.passedStateData?.expiryDataMap[this.props.passedStateData?.selectedExpiryDate]?.spotPrice;
if (spotPrice === undefined) return null;

const { chartData, legEntityList, fundsRequired, selectedsymbol, latestRefreshDate } = this.props.passedStateData;

// console.log("fundsReq",fundsRequired)

if (this.whatif.days == 0) {
let formattedDateTime = new Date(latestRefreshDate);
formattedDateTime.setSeconds(formattedDateTime.getSeconds() + 1);

this.whatif.days = formattedDateTime;
//this.whatif.days = this.props.passedStateData.latestRefreshDate;

}
if (this.whatif.days < lastUpdate) {
let formattedDateTime = new Date(lastUpdate);
formattedDateTime.setSeconds(formattedDateTime.getSeconds() + 1);

this.whatif.days = formattedDateTime;
}

let arr1 = [];
let arr2 = [];

let xAxisData = chartData[0] as Array;
let len = xAxisData.length;
const sd = chartData[3]?.sd || 0;
const farprice = chartData[5]?.farprice || 0;

// Update whatif days if needed
if (!this.whatif.days || this.whatif.days < lastUpdate) {
let formattedDateTime = new Date(lastUpdate);
formattedDateTime.setSeconds(formattedDateTime.getSeconds());
this.whatif.days = formattedDateTime;
}

// Calculate expiration info
const legs = legEntityList;
const allActiveLegs = legs.filter(p => p.enable !== false);
const allActiveExitedLegs = allActiveLegs.filter(p => p.exited === true);
const allNotExitedActiveLegs = allActiveLegs.filter(p => !p.exited);
const leglistActiveStatus = Utility.expiredLegListArrayStatus(allNotExitedActiveLegs);
const neareastExp = PLCalc.GetEarliestExpiryDateDMY_v2(legs);
const minExpiry = moment(neareastExp).format('DDMMMYY').toUpperCase();
const parsedDate = Utility.parseCustomDate(minExpiry);
const year = parsedDate.getFullYear();
const month = (parsedDate.getMonth() + 1).toString().padStart(2, '0');
const day = parsedDate.getDate().toString().padStart(2, '0');
const formattedDate = `${year}-${month}-${day}T15:30:00`;
let isPastDate = new Date(formattedDate) < new Date();

if (!isPastDate) {
if (allActiveLegs.length === allActiveExitedLegs.length || leglistActiveStatus === false) {
isPastDate = true;
}
}

let leftSigma1 = 0;
let leftSigma2 = 0;
let rightSigma1 = 0;
let rightSigma2 = 0;
if (sd > 0) {
let sdMul: number = 2 * sd;
leftSigma1 = parseFloat(spotPrice) - sd;
leftSigma2 = parseFloat(spotPrice) - sdMul;
rightSigma1 = parseFloat(spotPrice) + sdMul;
rightSigma2 = parseFloat(spotPrice) + sd;
}

for (let i = 0; i < len; i++) {
let item1 = [];
let item2 = [];

item1.push(chartData[0], chartData[1]);
arr1.push(item1);

item2.push(chartData[0], chartData[2]);
arr2.push(item2);
}

let options = {
chart: {
zoomType: 'xy',
height: 350,
spacingBottom: 2,
spacingTop: 5,
spacingLeft: 2,
spacingRight: 2,
},

title: {
text: selectedsymbol,
margin: 30,
align: 'center',
x: 50,
style: {
color: 'black',
fontSize: '14px',
}
},
accessibility: {
enabled: false, // Disables accessibility features
},
credits: {
text: 'iCharts.in',
href: '/',
position: {
verticalAlign: 'top',
y: 25

},
style: {
fontSize: '13px'
}
},

xAxis: {
gridLineWidth: 1,
title: {
text: 'Price',
style: {
fontWeight: 'Bold',
color: 'Black'
},

},
labels: {
style: {
color: 'black'
}
},

plotBands: [{
color: 'rgba(197, 210, 200,0.1)',
from: leftSigma1, // Start of the plot band
to: rightSigma1, // End of the plot band
label: {
text: '-1σ',
y: -18,
align: 'left',
style: {
color: '#606060'
}
}
}
, {

color: 'rgba(197, 210, 200,0.1)',
fillOpacity: 0.2,
from: leftSigma1, // Start of the plot band
to: rightSigma1, // End of the plot band
label: {
text: '+2σ',
y: -18,
align: 'right',
style: {
color: '#606060'
}
}
},
{

color: 'rgba(197, 210, 200,0.1)',
from: leftSigma2, // Start of the plot band
to: rightSigma2, // End of the plot band

label: {
text: '-2σ',
// x: 100,
y: -18,
align: 'left',
// rotation: -45,
style: {
color: '#606060'
}
}
},
{

color: 'rgba(197, 210, 200,0.1)',
from: leftSigma2, // Start of the plot band
to: rightSigma2, // End of the plot band
label: {
text: '+1σ',
// x: 100,
y: -18,
align: 'right',

style: {
color: '#606060'
}
}
}],
plotLines: [

{
color: 'red',
fillOpacity: 0.2,
lineWidth: 3,
dashStyle: 'shortdot',
zIndex: 3,
value: spotPrice,
label: {
text: spotPrice,
rotation: 0,
x: -20,
y: 0,
style: {
fontSize: '11.5px',
color: '#606060'
}
}
}
],
crosshair: {
label: {
enabled: true,

padding: 8
}
}
},

yAxis: [

{
gridLineColor: 'rgba(50,205,50,0.15)',
startOnTick: false,
lineWidth: 1,

title: {
text: 'P/L',
style: {
fontWeight: 'Bold',
color: 'Black'
},
},
labels: {

style: {
color: 'black'
},

},
crosshair: {
label: {
enabled: true,
},
dashStyle: 'longdash',
color: 'gray',
},

plotLines: [{
value: 0,
width: 2,
color: '#aaa',

}],

},
{ // Secondary yAxis

gridLineColor: 'rgba(50,205,50,0.15)',

lineWidth: 1,
startOnTick: false,
endOnTick: false,
title: {
text: '',
style: {
fontWeight: 'Bold'
},
},
label: {
enabled: true,
},

opposite: true,
}

],

legend: {
align: 'right',
verticalAlign: 'top',

},

tooltip: {
useHTML: true, // Allows custom HTML content
shared: true, // Show shared tooltip
borderColor: 'grey', // Set border color to grey
borderWidth: 1, // Set border width for better visibility
backgroundColor: 'white', // Optional: Set background color to white

formatter: function (this: Highcharts.TooltipFormatterContextObject) {
let xaxisPoint: any = this.x;
const percentageChange = (((xaxisPoint) / spotPrice) - 1) * 100;
const percentageColor = percentageChange > 0 ? '#02d302' : (percentageChange < 0 ? 'red' : 'black');

let rupeeSymbol = '₹';

return `
${this.x} (${percentageChange.toFixed(2)}%)

${this.points
?.map(
point => {
// Round point.y to the nearest integer
const roundedY = Math.round(point.y);

const fundRequired = fundsRequired !== 0.00 || fundsRequired !== 0 ? `(${((roundedY / fundsRequired) * 100).toFixed(2)}%)` : ``;

return `
\u25CF ${point.series.name}:
${roundedY > 0 ? `${rupeeSymbol} ${roundedY} ${fundRequired}` :
(roundedY === 0 ? `${rupeeSymbol} ${roundedY} ${fundRequired}` : `${rupeeSymbol} ${roundedY} ${fundRequired}`)
}

`;
})
.join('') || ''}
`;
},
valueDecimals: 2, // Specify decimal places for numbers
},

series: [{
showInLegend: false,
type: 'line',
name: 'T+0',
data: arr1,
color: 'rgb(0,0,255)',
fillOpacity: 0.1,
connectNulls: true,
lineWidth: 1.5,
dashStyle: 'shortdot',
marker: {
enabled: false
}
}, {
type: 'area',
name: 'Expiry',
fillOpacity: 0.1,
showInLegend: false,
negativeColor: 'rgb(255,127,127)',
color: 'rgb(50,205,50)',
data: arr2,
connectNulls: true,
lineWidth: 1.5,
marker: {
enabled: false
}
},
]

};

return
Option Chain
Изображение






{
this.whatif.allowLegAdjustment = e.checked;
this.whatif.IV = 0;

this.props.callback(this.whatif);
}} />
{/* Allow Leg IV Adjustments */}
Allow Leg IV Adjustments

{
let inputValue = e.value || e.target?.value || "";

const newValue: number = inputValue;
const oldValue: number = this.whatif.price;
const isIncrement = newValue > oldValue;

this.whatif.price = newValue;
let fp = this.getFarprice(farprice, isIncrement, newValue)

this.whatif.farprice = fp;
this.setState({ price: newValue, farprice: fp },
() => this.props.callback(this.whatif))
}}

onValueChange={(e) => {
// console.log(spotPrice)

const newValue: number = e.value;
const oldValue: number = this.whatif.price;
const isIncrement = newValue > oldValue;

this.whatif.price = newValue;
let fp = this.getFarprice(farprice, isIncrement, newValue)

this.whatif.farprice = fp;
// console.log(this.whatif)
// prefix={`${spotPrice}`}
// prefix={`${spotPrice.toFixed(2)}`}
// prefix = {`${spotPrice.toFixed(2)} (0.1%)`}

this.setState({ price: newValue, farprice: fp },
() => this.props.callback(this.whatif))
}

} showButtons
buttonLayout="horizontal" step={0.1} prefix={`${spotPrice} `} max={20} min={-20}
decrementButtonClassName="p-button-danger" incrementButtonClassName="p-button-success" incrementButtonIcon="pi pi-plus" decrementButtonIcon="pi pi-minus" suffix="%"
/>

{
// console.log(this.whatif.days)
// console.log(e.value)
// console.log(formattedDate)

this.whatif.days = e.value;
// this.setState({ days: e.value },
// () => this.props.callback(this.whatif))
// console.log(this.whatif.days);

this.setState({ days: e.value }, () => this.props.callback(this.whatif))

}}

//`${year}-${month}-${day}

// showTime hourFormat="12" dateFormat="dd/mm/yy" maxDate={new Date(formattedDate)} minDate={new Date()}/>

showTime hourFormat="12" dateFormat="dd/mm/yy" maxDate={new Date(formattedDate)} minDate={new Date()} />

{
this.whatif.IV = e.value;
// console.log(this.whatif)
this.setState({ IV: e.value },
() => this.props.callback(this.whatif))
}
}
onInput={(e) => {
let inputValue = e.value || e.target?.value || "";

this.whatif.IV = inputValue;
// console.log(this.whatif)
this.setState({ IV: inputValue },
() => this.props.callback(this.whatif))
}}
showButtons
buttonLayout="horizontal" step={1} prefix='IV ' max={20} min={-20}
decrementButtonClassName="p-button-danger" incrementButtonClassName="p-button-success"
incrementButtonIcon="pi pi-plus" decrementButtonIcon="pi pi-minus" suffix="%" />

{
this.setState({
price: 0,
IV: 0,
days: 0,
finalPrice: 0,
finalIV: 0,
finalDays: 0
}, () => {

// console.log(this.props.passedStateData.lastUpdate)
let formattedDateTime = new Date(lastUpdate);

formattedDateTime.setSeconds(formattedDateTime.getSeconds() + 1);

// console.log('formattedDateTime reset',formattedDateTime)
this.whatif.days = formattedDateTime;
// this.whatif.days = this.props.passedStateData.markethours;
this.whatif.price = 0;
this.whatif.farprice = farprice;
this.whatif.IV = 0;
this.whatif.allowLegAdjustment = false;
legEntityList.forEach(p => p.iv_adjustment = null);
let Reset = true;
// this.props.callback(this.whatif,this.props.passedStateData.legEntityList,Reset)
if (this.props.passedStateData.whatif !== null) this.props.callback(this.whatif, legEntityList, Reset)

});
}} />





}

getFarprice = (farprice, isIncrement, newPrice) => {
let farPrice: any;
if (isIncrement) {
// alert()
farPrice = parseFloat(farprice + (farprice * newPrice) / 100).toFixed(2);
} else {
farPrice = farprice - (farprice * newPrice) / 100;
}

return farPrice;

}

GetFarExp = (legs) => {

let mexpdt = '';

legs.forEach(optleg => {
let legdt: string = optleg.Expiry
if (mexpdt == "" || Utility.parseFormattedCustomDate(legdt) > Utility.parseFormattedCustomDate(mexpdt)) {
mexpdt = optleg.Expiry;
}
});

// console.log(mexpdt);

return mexpdt;
}
}



Подробнее здесь: https://stackoverflow.com/questions/796 ... sive-issue
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Javascript»