新数据被放置在旧数据之上 (JavaScript)

New data is being placed on top of old data (JavaScript)

我是 Web 开发领域的新手,所以如果我在这里和那里遗漏了什么或者我描述的问题不正确,请原谅我。

GIF illustrating the issue

基本上,我将 TradingView 的两个或多个图表示例中的不同代码复制到一个 JSFiddle 中,并尝试制作一张图表,该图表可以显示具有代码名称、OHLCV、MA10 值的不同时间范围的烛台。第一次加载图表时一切正常,但当单击按钮更改时间范围时,所有蜡烛图和 MA10 线加载正常,但 OHLCV 和 MA10 值似乎放在旧(初始加载)数据上。 当我第一次尝试时,所有蜡烛图和 MA10 线也重叠,然后我认为必须删除整个图表,以便重新计算 MA10 的值。所以现在烛台和 MA10 加载正常,但 OHLCV 值仍然与之前的值重叠。由于我是 JS 的新手,我无法为我的问题找出正确的关键字,所以我没有得到解决我的问题的结果。 有人可以帮我找出问题所在吗?

谢谢。

我必须删除大部分历史数据以符合 Whosebug 的每个 post 30000 个字符的限制,因此下面的代码片段将无法正常工作。您可以在此处查看代码 https://jsfiddle.net/akshay7892/dhutrgfn/7/

function createSimpleSwitcher(items, activeItem, activeItemChangedCallback) {
    var switcherElement = document.createElement('div');
    switcherElement.classList.add('switcher');

    var intervalElements = items.map(function(item) {
        var itemEl = document.createElement('button');
        itemEl.innerText = item;
        itemEl.classList.add('switcher-item');
        itemEl.classList.toggle('switcher-active-item', item === activeItem);
        itemEl.addEventListener('click', function() {
            onItemClicked(item);
        });
        switcherElement.appendChild(itemEl);
        return itemEl;
    });

    function onItemClicked(item) {
        if (item === activeItem) {
            return;
        }

        intervalElements.forEach(function(element, index) {
            element.classList.toggle('switcher-active-item', items[index] === item);
        });

        activeItem = item;

        activeItemChangedCallback(item);
    }

    return switcherElement;
}




function calculateSMA(data, count){
  var avg = function(data) {
    var sum = 0;
    for (var i = 0; i < data.length; i++) {
       sum += data[i].close;
    }
    return sum / data.length;
  };
  var result = [];
  for (var i=count - 1, len=data.length; i < len; i++){
    var val = avg(data.slice(i - count + 1, i));
    result.push({ time: data[i].time, value: val});
  }
  //console.log(result)
  return result;
}

function calopen(data){
  var open = [];
    for (var i = 0; i < data.length; i++) {
    open.push({ time: data[i].time, value: data[i].open});
  }
  
  return open;
}
//console.log(calopen(data))

function calhigh(data){
  var high = [];
    for (var i = 0; i < data.length; i++) {
    high.push({ time: data[i].time, value: data[i].high});
  }
  
  return high;
}

function callow(data){
  var low = [];
    for (var i = 0; i < data.length; i++) {
    low.push({ time: data[i].time, value: data[i].low});
  }
  
  return low;
}

function calclose(data){
  var close = [];
    for (var i = 0; i < data.length; i++) {
    close.push({ time: data[i].time, value: data[i].close});
  }
  
  return close;
}

function calv(data){
  var vol = [];
    for (var i = 0; i < data.length; i++) {
    vol.push({ time: data[i].time, value: data[i].volume});
  }
  
  return vol;
}

var one_minData = [{"time":1650350460,"open":329.35,"high":329.45,"low":329.1,"close":329.45,"volume":9795},{"time":1650350520,"open":329.45,"high":329.5,"low":329.15,"close":329.15,"volume":20626},{"time":1650350580,"open":329.15,"high":329.45,"low":329.15,"close":329.45,"volume":8762},{"time":1650350640,"open":329.5,"high":330.2,"low":329.25,"close":330.05,"volume":56546},{"time":1650350700,"open":330.15,"high":330.15,"low":329.55,"close":329.8,"volume":23489},{"time":1650350760,"open":329.8,"high":329.9,"low":329.6,"close":329.75,"volume":20630},]

var fifteen_minData = [{"time":1576728900,"open":509.8,"high":512.6,"low":508.9,"close":511.05,"volume":210630},{"time":1576729800,"open":511.0,"high":511.5,"low":509.35,"close":510.25,"volume":109974},{"time":1576730700,"open":510.25,"high":510.25,"low":506.2,"close":507.65,"volume":177816},]

var dayData = [{"time":1564963200,"open":460.0,"high":475.9,"low":455.85,"close":471.95,"volume":1465110},{"time":1565049600,"open":472.0,"high":487.5,"low":468.25,"close":482.15,"volume":795823},{"time":1565136000,"open":484.0,"high":489.95,"low":474.0,"close":477.25,"volume":312625},]

var weekData = 
    [{"time":1529884800,"open":538.35,"high":542.0,"low":508.0,"close":526.55,"volume":590970},{"time":1530489600,"open":530.0,"high":567.8,"low":523.0,"close":544.3,"volume":550127},{"time":1531094400,"open":548.8,"high":588.8,"low":544.5,"close":568.95,"volume":1021330},{"time":1531699200,"open":558.25,"high":706.8,"low":544.55,"close":687.4,"volume":3131754}{"time":1566777600,"open":484.0,"high":497.65,"low":455.15,"close":469.6,"volume":775278},];

var intervals = ['1','15','1D', '1W'];

var seriesesData = new Map([
  ['1', one_minData ],
  ['15', fifteen_minData ],
  ['1D', dayData ],
  ['1W', weekData ],
]);

var switcherElement = createSimpleSwitcher(intervals, intervals[0], syncToInterval);


document.body.style.position = 'relative';

var container = document.createElement('div');
document.body.appendChild(container);
document.body.appendChild(switcherElement);

var width = 600;
var height = 300;



var candleSeries = null;


function syncToInterval(interval) {
    if (candleSeries) {
        chart.remove();
    chart.remove(legend);
    
        //req_data = null;
    
   
    
    }
  chart = LightweightCharts.createChart(container, {
    width: width,
    height: height,
  crosshair: {
        mode: LightweightCharts.CrosshairMode.Normal,
    },
  timeScale: {
        borderVisible: true,
    timeVisible: true,
    secondsVisible: false,},
});
    candleSeries = chart.addCandlestickSeries();
  req_data = seriesesData.get(interval)
  //console.log(data);
  candleSeries.setData(req_data);
  
  
  ////charts time, volume, color data////////
  
    
    
  var smaLine = chart.addLineSeries({
    color: 'rgba(4, 111, 232, 1)',
  
    lineWidth: 2,
        });
    
    var openLine = chart.addLineSeries({
    color: 'rgba(4, 111, 232, 1)',
  visible: false,
    lineWidth:0,
    });

    var highLine = chart.addLineSeries({
    color: 'rgba(4, 111, 232, 1)',
  visible: false,
    lineWidth:0,
    });
    
  var lowLine = chart.addLineSeries({
    color: 'rgba(4, 111, 232, 1)',
  visible: false,
    lineWidth:0,
    });
  
    var closeLine = chart.addLineSeries({
    color: 'rgba(4, 111, 232, 1)',
  visible: false,
    lineWidth:0,
    });
  
  var volumeSeries = chart.addHistogramSeries({
    color: '#26a69a',
    priceFormat: {
        type: 'volume',
    },
    priceScaleId: '',
    scaleMargins: {
        top: 0.8,
        bottom: 0,
    },
    });
    
  var volLine = chart.addLineSeries({
    color: 'rgba(4, 111, 232, 1)',
  visible: false,
    lineWidth:5,
    });

    function setLegend6Text(fysymbol) {
   legend6.innerHTML = '<span style=style="font-size: 24px; margin: 4px 0px; color: #20262E">' + fysymbol + '</span>';
  //console.log("name",fysymbol);
}


function setLegendText(priceValue) {
    let val = 'n/a';
    if (priceValue !== undefined) {
        val = (Math.round(priceValue * 100) / 100).toFixed(2);
    }
  
    legend.innerHTML = '<br/><br/>MA10: <span style="color:rgba(4, 111, 232, 1); margin: 4px 0px;">' + val + '</span>';
}


function setLegendText1(openValue) {
    let openVal = 'n/a';
  if (openValue !== undefined) {
        openVal = (Math.round(openValue * 100) / 100).toFixed(2);
    }
  
    legend1.innerHTML = '<br/>O: <span style="color:rgba(4, 111, 232, 1); margin: 4px 0px;">' + openVal + '</span>';
}

function setLegendText2(highValue) {
    let highVal = 'n/a';
  if (highValue !== undefined) {
        highVal = (Math.round(highValue * 100) / 100).toFixed(2);
    }
  
    legend2.innerHTML = '<br/>H: <span style="color:rgba(4, 111, 232, 1); margin: 4px 0px;">' + highVal + '</span>';
}

function setLegendText3(lowValue) {
    let lowVal = 'n/a';
  if (lowValue !== undefined) {
        lowVal = (Math.round(lowValue * 100) / 100).toFixed(2);
    }
  
    legend3.innerHTML = '<br/>L: <span style="color:rgba(4, 111, 232, 1); margin: 4px 0px;">' + lowVal + '</span>';
}


function setLegendText4(closeValue) {
    let closeVal = 'n/a';
  if (closeValue !== undefined) {
        closeVal = (Math.round(closeValue * 100) / 100).toFixed(2);
    }
  
    legend4.innerHTML = '<br/>C: <span style="color:rgba(4, 111, 232, 1); margin: 4px 0px;">' + closeVal + '</span>';
}


function setLegendText5(volValue) {
    let volVal = 'n/a';
  if (volValue !== undefined) {
        volVal = (Math.round(volValue * 100) / 100).toFixed(2);
    }
  
    legend5.innerHTML = '<br/>V: <span style="color:rgba(4, 111, 232, 1); margin: 4px 0px;">' + (volVal/100000) + 'L' + '</span>';
}
  
  
  

    
  //console.log(lowdata)

    var legend = document.createElement('div');
    legend.className = 'sma-legend';
    container.appendChild(legend);
    legend.style.display = 'block';
    legend.style.left = 3 + 'px';
    legend.style.top = 20 + 'px';

     var legend1 = document.createElement('div');
   legend1.className = 'OHLC-legend';
   container.appendChild(legend1);
   legend1.style.display = 'block';
   legend1.style.left = 3 + 'px';
   legend1.style.top = 10 + 'px';


   var legend2 = document.createElement('div');
   legend2.className = 'OHLC-legend';
   container.appendChild(legend2);
   legend2.style.display = 'block';
   legend2.style.left = 78 + 'px';
   legend2.style.top = 10 + 'px';


   var legend3 = document.createElement('div');
   legend3.className = 'OHLC-legend';
   container.appendChild(legend3);
   legend3.style.display = 'block';
   legend3.style.left = 153 + 'px';
   legend3.style.top = 10 + 'px';


   var legend4 = document.createElement('div');
   legend4.className = 'OHLC-legend';
   container.appendChild(legend4);
   legend4.style.display = 'block';
   legend4.style.left = 228 + 'px';
   legend4.style.top = 10 + 'px';



   var legend5 = document.createElement('div');
   legend5.className = 'V-legend';
   container.appendChild(legend5);
   legend5.style.display = 'block';
   legend5.style.left = 303 + 'px';
   legend5.style.top = 10 + 'px';


   var legend6 = document.createElement('div');
   legend6.className = 'fysymbol-legend';
   container.appendChild(legend6);
   legend6.style.display = 'block';
   legend6.style.left = 3 + 'px';
   legend6.style.top = 0 + 'px';


   var fysymbol = "NSE:SBIN-EQ";
   
   

    voldata = calv(req_data)
  volumeSeries.setData(voldata)
    volLine.setData(voldata);

    smaData = calculateSMA(req_data, 10);
    smaLine.setData(smaData);

    
    opendata = calopen(req_data)
    openLine.setData(opendata);

    
    highdata = calhigh(req_data)
    highLine.setData(highdata);

    lowdata = callow(req_data)
  lowLine.setData(lowdata);

    closedata = calclose(req_data)
    closeLine.setData(closedata);
  
      
   
   var datesForMarkers = [req_data[req_data.length - 39], req_data[req_data.length - 19]];
var indexOfMinPrice = 0;
for (var i = 1; i < datesForMarkers.length; i++) {
    if (datesForMarkers[i].high < datesForMarkers[indexOfMinPrice].high) {
        indexOfMinPrice = i;
    }
}

var markers = [{ time: req_data[req_data.length - 48].time, position: 'aboveBar', color: '#f68410', shape: 'circle', text: 'D' }];
for (var i = 0; i < datesForMarkers.length; i++) {
    if (i !== indexOfMinPrice) {
        markers.push({ time: datesForMarkers[i].time, position: 'aboveBar', color: '#e91e63', shape: 'arrowDown', text: 'Sell @ ' + Math.floor(datesForMarkers[i].high - 1) });
    } else {
        markers.push({ time: datesForMarkers[i].time, position: 'belowBar', color: '#2196F3', shape: 'arrowUp', text: 'Buy @ ' + Math.floor(datesForMarkers[i].low + 1) });
    }
}

candleSeries.setMarkers(markers);
    setLegendText(smaData[smaData.length - 1].value);
   setLegendText1(opendata[opendata.length -1 ].value);
   setLegendText2(highdata[highdata.length -1 ].value);
   setLegendText3(lowdata[lowdata.length -1 ].value);
   setLegendText4(closedata[closedata.length -1 ].value);
   setLegendText5(voldata[voldata.length -1 ].value);
   setLegend6Text(fysymbol);
    chart.subscribeCrosshairMove((param) => {
   setLegendText(param.seriesPrices.get(smaLine)),
   setLegendText1(param.seriesPrices.get(openLine)),
   setLegendText2(param.seriesPrices.get(highLine)),
   setLegendText3(param.seriesPrices.get(lowLine)),
   setLegendText4(param.seriesPrices.get(closeLine)),
   setLegendText5(param.seriesPrices.get(volLine)),
   setLegend6Text(fysymbol);
   });

     

   


}

syncToInterval(intervals[0]);
    
  
   
html,
body {
    font-family: 'Trebuchet MS', Roboto, Ubuntu, sans-serif;
    background: #f9fafb;
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
}

.switcher {
    display: flex;
    align-items: center;
    height: 30px;
    margin-top:8px;
    color: #2196F3;
}

.switcher-item {
    cursor: pointer;
    text-decoration: none;
    display: inline-block;
    padding: 6px 8px;
    font-size: 14px;
    color: #262b3e;
    background-color: transparent;
    margin-right: 8px;
    border: none;
    border-radius: 4px;
    outline: none;
}

.switcher-item:hover {
    background-color: #f2f3f5;
}

.switcher-active-item {
    text-decoration: none;
    cursor: default;
    color: #262b3e;
}

.switcher-active-item,
.switcher-active-item:hover {
    background-color: #e1eff9;
}


.sma-legend {
    width: 96px;
    height: 10px;
    position: absolute;
    padding: 8px;
    font-size: 14px;
    background-color: rgba(255, 255, 255, 0.23);
    text-align: left;
    z-index: 1000;
    pointer-events: none;
  white-space: normal;
}

.OHLC-legend {
    width: 96px;
    height: 10px;
    position: absolute;
    padding: 8px;
    font-size: 16px;
    background-color: rgba(255, 255, 255, 0.23);
    text-align: left;
    z-index: 1000;
    pointer-events: none;
  white-space: normal;
}

.V-legend {
    width: 120px;
    height: 70px;
    position: absolute;
    padding: 8px;
    font-size: 16px;
    background-color: rgba(255, 255, 255, 0.23);
    text-align: left;
    z-index: 1000;
    pointer-events: none;
  white-space: normal;
}


.fysymbol-legend {
    width: 250px;
    height: 70px;
    position: absolute;
    padding: 8px;
    /*font-size: 20px;*/
    background-color: rgba(255, 255, 255, 0.23);
    text-align: left;
    z-index: 1000;
    pointer-events: none;
  white-space: normal
}
<script src="https://unpkg.com/lightweight-charts@3.4.0/dist/lightweight-charts.standalone.production.js"></script>

当某些东西没有按预期工作时(无论您的级别如何!),首先要查看的是开发控制台! 在这里您可以清楚地看到,每次单击按钮时,您不仅会替换“旧”值,还会在前一个值之上添加一个值。

我建议使用初始化函数 and/or 组件和更新函数。