Adjust the size of both the right and left price scales on TradingView Lightweight Charts

Is it possible to set a fixed width for both the right and left price scales on a chart? Let's say, 50 pixels for the right price scale and 70 pixels for the left price scale?

For a working example, please visit https://jsfiddle.net/TradingView/cnbamtuh/ to see the code for the right price scale, and https://jsfiddle.net/TradingView/6s01gdje/ for the left price scale. I've included a comment (//) in the code below with an option that doesn't work but would be helpful. Is there a way to achieve this behavior?

Thank you

    rightPriceScale: {
        scaleMargins: {
            top: 0.3,
            bottom: 0.25,
        },
        borderVisible: false,
        // width: 50
    },
    leftPriceScale: {
        visible: true,
        borderVisible: false,
        // width: 70
    },

Answer №1

This may not be the most ideal solution, but it's a workaround that gets the job done. Simply adjust the sizes of all the charts slightly until the main area is the same size in all charts, matching the smallest size.

Note that this approach assumes the left alignment of the chart element...


        <!--script src="https://unpkg.com/lightweight-charts/dist/lightweight-charts.standalone.production.js"></script-->
        <script src="https://unpkg.com/lightweight-charts/dist/lightweight-charts.standalone.development.js"></script>

        <div class="chart-block" id="prices"></div>
        <script type="text/javascript">

        var all_charts=[
            // {chart:,element:}
        ];
       
        var nerrowest_chart_width;
        function resize_all_charts(){
            nerrowest_chart_width=Math.min(...all_charts.map(({chart})=>chart._private__chartWidget._private__paneWidgets[0]._private__paneCell.offsetWidth))
            all_charts.forEach( (e)=> { 
                e.right_offset=e.chart._private__chartWidget._private__paneWidgets[0]._private__paneCell.offsetWidth-nerrowest_chart_width; 
            })
            
            all_charts.forEach(({chart,element,right_offset})=>{
                chart.resize( element.offsetWidth-right_offset, element.offsetHeight)
            })
        }


        const prices_chart = LightweightCharts.createChart(prices, { 
            timeScale: {
                timeVisible: true,
                secondsVisible: false,
            },
            watermark: {
                visible: true,
                fontSize: 14,
                horzAlign: 'center',
                vertAlign: 'top',
                color: 'rgba(171, 71, 188, 1)',
                text: 'prices',
            },
        });

        var prices_chart_info={chart:prices_chart,element:prices,right_offset:0};
        all_charts.push(prices_chart_info);
                     
        window.addEventListener('resize',  event => {
            prices_chart.resize( prices.offsetWidth-prices_chart_info.right_offset, prices.offsetHeight)
        });

        const prices_lineSeries = prices_chart.addLineSeries({  
            lineType: 1
        });

        let points= ...
        prices_lineSeries.setData(points);
        resize_all_charts();
        </script>

Additionally, there is a function available:


        function sync_all_charts(){
            var found=false;
            for(let e of all_charts){
                let barSpacing = e.chart.timeScale()._private__timeScale._private__barSpacing
                let scrollPosition = e.chart.timeScale().scrollPosition();
                
                if(e.scrollPosition!=scrollPosition|| e.barSpacing!=barSpacing)
                {
                    all_charts.forEach((e)=>{
                        e.chart.timeScale().applyOptions({rightOffset: scrollPosition,barSpacing: barSpacing})
                        e.barSpacing = barSpacing;
                        e.scrollPosition = scrollPosition;
                    })
                    found=true;
                    break;
                }
            }
            return found;
        }

        setInterval(()=>{
            if(sync_all_charts())
                resize_all_charts();
        },1000)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

PlateJS: Transforming HTML into data

Trying to implement a functionality where clicking on a button retrieves an HTML string. The objective is to have this rich text editor within React-Hook-Form, and upon form submission, the value will be saved as HTML for database storage. Below is the pr ...

Calling the `firstValueFrom()` method in RxJS will keep the observable alive and not

Hey there, I'm currently having issues with using firstValueFrom(), lastValueForm(), and Observable.pipe(take(1)) in my TypeScript code with Angular 14 and RxJs 7.8.0. I am working with a Firebase server that provides stored image URLs via an API wit ...

What is the reason for the disappearance of unordered list bullets when using padding: 0?

Updating an older website that contains numerous unordered lists has presented a challenge. When the padding is set to 0, the display markers on the unordered list disappear. The root cause of this issue was traced back to the CSS setting *{padding: 0; ma ...

Inserting blocks of text into a MySQL database

I'm hoping to insert text segments into a MySQL database. Below is an excerpt of my HTML code: <div class="margins3"> <h1>Meal Plan...</h1> <div id='results-container'> <div class='LeanMuscle ...

Modifying input values in AngularJS/HTML

I'm encountering an issue with the ng-repeat function in AngularJS within my HTML code. The problem is that when I change the input with the ID 'add-price' in one cartproduct, it simultaneously changes in all other cartproducts as well. For ...

Using both Promise based architecture and events in Node.js can lead to unexpected behavior and should be avoided

Currently, I am developing a nodejs application that is expected to grow in size. Despite my efforts, I have not been able to find many resources on advanced Nodejs project architecture and structure. I am wondering if it would be considered bad practice ...

Using `popWin()` in conjunction with `echo php` in Javascript

How can I create a JavaScript popup window inside an echo line? I have tried the following code but the popup window does not work: echo '<td> <a href="javascript:popWin(edit.php?id='.$row[id].')">Edit</a></td>&apos ...

Waiting for response in AngularJS Controller and setting callback

I have developed an AngularJS application with controllers.js and factories.js that I am excited about. However, I am facing a challenge when trying to manipulate the values within the controller (retrieved from the factories). The issue is that these val ...

Need to conceal certain images in Isotope, but ensure they can easily be revealed when necessary?

I have a collection of various images on my website coded with isotope. My question is, how can I hide specific images that I don't want to display initially, but have them appear when needed? I have managed to create a "show all" list using the code ...

"The challenge of achieving a transparent background with a PointMaterial texture in ThreeJS

When creating a set of particles with THREE.Points and using a THREE.PointMaterial with texture, I noticed that the transparency of the particles is working only partially. The textures are stroke rectangles created with canvas. Here is what my particles ...

Access the contents of the selected cell in the MUI datagrid

When I choose a row from the datagrid, my attempt to access each cell value in that row always returns "undefined" when using selectedRowData.email. How can I correctly retrieve the data from a selected row's cells? <DataGrid checkboxSe ...

Issue with React and JavaScript: Object is displayed on the console briefly before disappearing

I am having an issue with my sign up page where the console log of the two fields disappears after a second. I would appreciate any assistance on this matter. Below is the code for the sign-up form: export default function SignUp() { const [firstNam ...

React JS is having trouble rendering an object that contains a list as one of its elements

I've been attempting to display the P_words list element with React using map: const f_data = { key: 2412, reviewed: 100, rating:4, P_words: [{ word: "Coolx", freq: 5 }, { word: "Dumbf&quo ...

Is there a way for me to increment the value of 'sessionStorage.fgattempt' whenever either 'fgMade()' or 'threeMade()' are called?

Currently, I am developing a basketball game stat tracker and need to update the field goal attempts every time I make a field goal or three-pointer. Additionally, I am looking for ways to optimize the javascript code provided. The main requirement is to ...

Validation of multiple textboxes can be achieved by utilizing either JavaScript or Angular 1

How can I implement a validation in Angular 1 or JavaScript that will enable the submit button only when there is text in any of the 3 textboxes? If no text is present, the button should be disabled. Below is the code snippet: First name: <br> < ...

When trying to fetch JSON data, the outcome is two pending promises: [ Promise { <pending> }, Promise { <pending> } ]

I am struggling to fetch the JSON data from the API endpoint below: https://api.hatchways.io/assessment/blog/posts When using node.js and making HTTPS requests, I keep getting an array of [ Promise { }, Promise { } ]. The challenge is that I can only se ...

Is there a way to stop the MUI Select component's width from increasing when I choose multiple options?

Please check out the demo I created on codesandbox by clicking here View codesandbox demo I have implemented the MUI Select component with various props to enable multiple options selection without a fixed width constraint. Using a grid layout, I have ev ...

Netlify deployment is failing to display the CSS styling on a website built with Hugo

Currently in the process of creating my own website using the "Call Me Sam" hugo theme. Everything looks great locally but once deployed on Netlify, the CSS styling seems to be completely disregarded. If you want to check out my repository: https://github ...

What are some ways to create a traditional HTML form submission and incorporate jQuery solely for the callbacks?

Given that my page consists solely of a simple "name and email" registration form, I see no reason why I shouldn't stick to the traditional approach: <form action="/Account/Register/" method="POST" id="registration-form"> <fields ...

Having trouble converting a timestamp to a date in JavaScript

My database uses MongoDB and has a timestamp field with unique formats, such as: 1657479170.7300725 1657479170.7301126 1657479170.7301197 1657479170.9120467 1657479170.932398 Converting these timestamps to the date format YYYY-MM-DD yields the correct res ...