create a candlestick chart

Discussion about JFreeChart related to stockmarket charts.
Locked
gladstone
Posts: 1
Joined: Thu May 01, 2008 6:24 am

create a candlestick chart

Post by gladstone » Thu May 01, 2008 6:29 am

I hava tried hard to create a candlestick chart. I used the source code from jfreechart, and have some unknown problems about creating the dataset.

can anyone paste a full source code of a simple candlestick chart to me as a reference? it would be very helpful for me to start with.

RoyW
Posts: 93
Joined: Wed Apr 23, 2008 7:42 pm
Contact:

Post by RoyW » Sat May 10, 2008 7:52 am

Code: Select all

import org.jfree.chart.*;
import org.jfree.chart.axis.*;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.xy.CandlestickRenderer;
import org.jfree.data.xy.*;

import javax.swing.*;
import java.awt.*;
import java.io.*;
import java.net.URL;
import java.text.*;
import java.util.*;
import java.util.List;

public class CandlestickDemo extends JFrame {
    public CandlestickDemo(String stockSymbol) {
        super("CandlestickDemo");
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        DateAxis    domainAxis       = new DateAxis("Date");
        NumberAxis  rangeAxis        = new NumberAxis("Price");
        CandlestickRenderer renderer = new CandlestickRenderer();
        XYDataset   dataset          = getDataSet(stockSymbol);

        XYPlot mainPlot = new XYPlot(dataset, domainAxis, rangeAxis, renderer);

        //Do some setting up, see the API Doc
        renderer.setSeriesPaint(0, Color.BLACK);
        renderer.setDrawVolume(false);
        rangeAxis.setAutoRangeIncludesZero(false);
        domainAxis.setTimeline( SegmentedTimeline.newMondayThroughFridayTimeline() );

        //Now create the chart and chart panel
        JFreeChart chart = new JFreeChart(stockSymbol, null, mainPlot, false);
        ChartPanel chartPanel = new ChartPanel(chart);
        chartPanel.setPreferredSize(new Dimension(600, 300));

        this.add(chartPanel);
        this.pack();
    }
    protected AbstractXYDataset getDataSet(String stockSymbol) {
        //This is the dataset we are going to create
        DefaultOHLCDataset result = null;
        //This is the data needed for the dataset
        OHLCDataItem[] data;

        //This is where we go get the data, replace with your own data source
        data = getData(stockSymbol);

        //Create a dataset, an Open, High, Low, Close dataset
        result = new DefaultOHLCDataset(stockSymbol, data);

        return result;
    }
    //This method uses yahoo finance to get the OHLC data
    protected OHLCDataItem[] getData(String stockSymbol) {
        List<OHLCDataItem> dataItems = new ArrayList<OHLCDataItem>();
        try {
            String strUrl= "http://ichart.finance.yahoo.com/table.csv?s="+stockSymbol+"&a=0&b=1&c=2008&d=3&e=30&f=2008&ignore=.csv";
            URL url = new URL(strUrl);
            BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
            DateFormat df = new SimpleDateFormat("y-M-d");

            String inputLine;
            in.readLine();
            while ((inputLine = in.readLine()) != null) {
                StringTokenizer st = new StringTokenizer(inputLine, ",");

                Date date       = df.parse( st.nextToken() );
                double open     = Double.parseDouble( st.nextToken() );
                double high     = Double.parseDouble( st.nextToken() );
                double low      = Double.parseDouble( st.nextToken() );
                double close    = Double.parseDouble( st.nextToken() );
                double volume   = Double.parseDouble( st.nextToken() );
                double adjClose = Double.parseDouble( st.nextToken() );

                OHLCDataItem item = new OHLCDataItem(date, open, high, low, close, volume);
                dataItems.add(item);
            }
            in.close();
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        //Data from Yahoo is from newest to oldest. Reverse so it is oldest to newest
        Collections.reverse(dataItems);

        //Convert the list into an array
        OHLCDataItem[] data = dataItems.toArray(new OHLCDataItem[dataItems.size()]);

        return data;
    }

    public static void main(String[] args) {
        new CandlestickDemo("MSFT").setVisible(true);
    }
}

sawo01
Posts: 4
Joined: Wed Jan 14, 2009 4:53 pm

combine charts

Post by sawo01 » Wed Jan 14, 2009 5:06 pm

Is it possible to put Moving Average to this chart?
I can display them in separate window, but I would like to see them on the same diagram, but I don't know, how to do it.
Could anybody help me, please?

RoyW
Posts: 93
Joined: Wed Apr 23, 2008 7:42 pm
Contact:

Post by RoyW » Thu Jan 15, 2009 4:00 pm

Replace this line

Code: Select all

        XYPlot mainPlot = new XYPlot(dataset, domainAxis, rangeAxis, renderer);
with this code

Code: Select all

        XYPlot mainPlot = new XYPlot(dataset, domainAxis, rangeAxis, renderer);

        final long ONE_DAY = 24 * 60 * 60 * 1000;
        XYLineAndShapeRenderer maRenderer = new XYLineAndShapeRenderer(true, false);
        XYDataset              maSataset  = MovingAverage.createMovingAverage(dataset, "MA", 30 * ONE_DAY, 0);
        mainPlot.setRenderer(1, maRenderer);
        mainPlot.setDataset (1, maSataset);
The answer does not come from thinking outside the box, rather the answer comes from realizing the truth; There is no Box. my js site

sawo01
Posts: 4
Joined: Wed Jan 14, 2009 4:53 pm

updating the dataset

Post by sawo01 » Mon Feb 02, 2009 2:15 pm

Thanks, this is amazing. It works fine. :wink:
Is it hard to modify the app and make the dataset refreshable?
I mean, I would like to display more candlesticks, but not in the same time.

I have a big DB with more than 500.000 candlesticks. Can I display in one time just e.g. 200 OHCL bars, put a Theard.sleep(100), and refresh the dataset?

ashokgawas
Posts: 2
Joined: Tue Aug 18, 2009 8:13 am
antibot: No, of course not.

Re: create a candlestick chart

Post by ashokgawas » Tue Aug 18, 2009 8:59 am

I want crosshairs moving with the mouse cursor on the candlestick chart.. can anyone send me an example??

fans_chart
Posts: 1
Joined: Thu Aug 27, 2009 10:32 pm
antibot: No, of course not.

Re: [1.0.13]it doesn't work!!!

Post by fans_chart » Fri Aug 28, 2009 9:36 am

but works on 1.0.9
RoyW wrote:

Code: Select all

import org.jfree.chart.*;
import org.jfree.chart.axis.*;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.xy.CandlestickRenderer;
import org.jfree.data.xy.*;

import javax.swing.*;
import java.awt.*;
import java.io.*;
import java.net.URL;
import java.text.*;
import java.util.*;
import java.util.List;

public class CandlestickDemo extends JFrame {
    public CandlestickDemo(String stockSymbol) {
        super("CandlestickDemo");
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        DateAxis    domainAxis       = new DateAxis("Date");
        NumberAxis  rangeAxis        = new NumberAxis("Price");
        CandlestickRenderer renderer = new CandlestickRenderer();
        XYDataset   dataset          = getDataSet(stockSymbol);

        XYPlot mainPlot = new XYPlot(dataset, domainAxis, rangeAxis, renderer);

        //Do some setting up, see the API Doc
        renderer.setSeriesPaint(0, Color.BLACK);
        renderer.setDrawVolume(false);
        rangeAxis.setAutoRangeIncludesZero(false);
        domainAxis.setTimeline( SegmentedTimeline.newMondayThroughFridayTimeline() );

        //Now create the chart and chart panel
        JFreeChart chart = new JFreeChart(stockSymbol, null, mainPlot, false);
        ChartPanel chartPanel = new ChartPanel(chart);
        chartPanel.setPreferredSize(new Dimension(600, 300));

        this.add(chartPanel);
        this.pack();
    }
    protected AbstractXYDataset getDataSet(String stockSymbol) {
        //This is the dataset we are going to create
        DefaultOHLCDataset result = null;
        //This is the data needed for the dataset
        OHLCDataItem[] data;

        //This is where we go get the data, replace with your own data source
        data = getData(stockSymbol);

        //Create a dataset, an Open, High, Low, Close dataset
        result = new DefaultOHLCDataset(stockSymbol, data);

        return result;
    }
    //This method uses yahoo finance to get the OHLC data
    protected OHLCDataItem[] getData(String stockSymbol) {
        List<OHLCDataItem> dataItems = new ArrayList<OHLCDataItem>();
        try {
            String strUrl= "http://ichart.finance.yahoo.com/table.csv?s="+stockSymbol+"&a=0&b=1&c=2008&d=3&e=30&f=2008&ignore=.csv";
            URL url = new URL(strUrl);
            BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
            DateFormat df = new SimpleDateFormat("y-M-d");

            String inputLine;
            in.readLine();
            while ((inputLine = in.readLine()) != null) {
                StringTokenizer st = new StringTokenizer(inputLine, ",");

                Date date       = df.parse( st.nextToken() );
                double open     = Double.parseDouble( st.nextToken() );
                double high     = Double.parseDouble( st.nextToken() );
                double low      = Double.parseDouble( st.nextToken() );
                double close    = Double.parseDouble( st.nextToken() );
                double volume   = Double.parseDouble( st.nextToken() );
                double adjClose = Double.parseDouble( st.nextToken() );

                OHLCDataItem item = new OHLCDataItem(date, open, high, low, close, volume);
                dataItems.add(item);
            }
            in.close();
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        //Data from Yahoo is from newest to oldest. Reverse so it is oldest to newest
        Collections.reverse(dataItems);

        //Convert the list into an array
        OHLCDataItem[] data = dataItems.toArray(new OHLCDataItem[dataItems.size()]);

        return data;
    }

    public static void main(String[] args) {
        new CandlestickDemo("MSFT").setVisible(true);
    }
}

Jean-Paul
Posts: 1
Joined: Sat Aug 24, 2013 11:44 am
antibot: No, of course not.

Re: create a candlestick chart

Post by Jean-Paul » Sat Aug 24, 2013 11:50 am

BUG IN THE CODE: IMPORTANT FOR EVERYONE USING THE ABOVE CODE

I made an account just to warn everyone trying to use the code above (it took me a lot of hours to find this bug):

You have to use JFreeChart library v1.0.15 or higher or otherwise the JFrame will crash for certain random stock quotes.

If you want to know more, please read the following question I posted: http://stackoverflow.com/questions/1841 ... nce-quotes

I hope I can prevent future trouble for anyone. Good luck and enjoy the beautiful code (kudos to RoyW).

david.gilbert
JFreeChart Project Leader
Posts: 11734
Joined: Fri Mar 14, 2003 10:29 am
antibot: No, of course not.
Contact:

Re: create a candlestick chart

Post by david.gilbert » Thu Aug 29, 2013 8:58 pm

It seems that this bug fix explains the difference in behaviour between 1.0.14 and 1.0.15:

http://sourceforge.net/p/jfreechart/code/2465/
David Gilbert
JFreeChart Project Leader

:idea: Read my blog
:idea: Support JFree via the Github sponsorship program

marioscelba
Posts: 1
Joined: Tue Nov 05, 2013 8:17 am
antibot: No, of course not.

Re: create a candlestick chart

Post by marioscelba » Tue Nov 05, 2013 8:21 am

Good tutorials,I think this is good way for learning.

Locked