NexusFi: Find Your Edge


Home Menu

 





[Java] Candlestick chart with JFreeChart


Discussion in Platforms and Indicators

Updated
      Top Posters
    1. looks_one Nicolas11 with 4 posts (7 thanks)
    2. looks_two lolu with 3 posts (1 thanks)
    3. looks_3 Quick Summary with 1 posts (0 thanks)
    4. looks_4 TradeHound with 1 posts (1 thanks)
    1. trending_up 12,147 views
    2. thumb_up 9 thanks given
    3. group 3 followers
    1. forum 8 posts
    2. attach_file 5 attachments




 
Search this Thread

[Java] Candlestick chart with JFreeChart

  #1 (permalink)
 
Nicolas11's Avatar
 Nicolas11 
near Paris, France
 
Experience: Beginner
Platform: -
Trading: -
Posts: 1,071 since Aug 2011
Thanks Given: 2,232
Thanks Received: 1,769

Hi,

This is a SSCCE example of code to draw candlestick chart in Java with (free) JFreeChart API.

 
Code
// Inspirations:
// -------------
// a) http://www.roseindia.net/chartgraphs/candle-stick-chart.shtml
// b) 3 times nearly the same code:
// http://www.jfree.org/forum/viewtopic.php?f=10&t=24521
// http://stackoverflow.com/questions/18413534/jfreechart-crashes-when-using-yahoo-finance-quotes
// http://www.jfree.org/forum/viewtopic.php?f=10&t=24521

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Insets;
import java.awt.Toolkit;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.StringTokenizer;
import javax.swing.JFrame;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.DateAxis;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.axis.SegmentedTimeline;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.xy.CandlestickRenderer;
import org.jfree.data.xy.DefaultOHLCDataset;
import org.jfree.data.xy.OHLCDataItem;
import org.jfree.data.xy.OHLCDataset;

public class Exemple144_JFreeChart_Candlestick_Chart {

    public static void main(String args[]) {

        // 1. Download MSFT quotes from Yahoo Finance and store them as OHLCDataItem
        List<OHLCDataItem> dataItems = new ArrayList<OHLCDataItem>();
        try {
            String strUrl = "http://ichart.yahoo.com/table.csv?s=MSFT&a=3&b=1&c=2013&d=3&e=15&f=2050&g=d";
            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());

                // adjust data:
                open = open * adjClose / close;
                high = high * adjClose / close;
                low = low * adjClose / close;

                OHLCDataItem item = new OHLCDataItem(date, open, high, low, adjClose, volume);
                dataItems.add(item);
            }
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        Collections.reverse(dataItems); // Data from Yahoo is from newest to oldest. Reverse so it is oldest to newest.
        //Convert the list into an array
        OHLCDataItem[] data = dataItems.toArray(new OHLCDataItem[dataItems.size()]);
        OHLCDataset dataset = new DefaultOHLCDataset("MSFT", data);

        // 2. Create chart
        JFreeChart chart = ChartFactory.createCandlestickChart("MSFT", "Time", "Price", dataset, false);

        // 3. Set chart background
        chart.setBackgroundPaint(Color.white);

        // 4. Set a few custom plot features
        XYPlot plot = (XYPlot) chart.getPlot();
        plot.setBackgroundPaint(Color.WHITE); // light yellow = new Color(0xffffe0)
        plot.setDomainGridlinesVisible(true);
        plot.setDomainGridlinePaint(Color.lightGray);
        plot.setRangeGridlinePaint(Color.lightGray);
        ((NumberAxis) plot.getRangeAxis()).setAutoRangeIncludesZero(false);

        // 5. Skip week-ends on the date axis
        ((DateAxis) plot.getDomainAxis()).setTimeline(SegmentedTimeline.newMondayThroughFridayTimeline());

        // 6. No volume drawn
        ((CandlestickRenderer) plot.getRenderer()).setDrawVolume(false);

        // 7. Create and display full-screen JFrame
        JFrame myFrame = new JFrame();
        myFrame.setResizable(true);
        myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        myFrame.add(new ChartPanel(chart), BorderLayout.CENTER);
        Toolkit kit = Toolkit.getDefaultToolkit();
        Insets insets = kit.getScreenInsets(myFrame.getGraphicsConfiguration());
        Dimension screen = kit.getScreenSize();
        myFrame.setSize((int) (screen.getWidth() - insets.left - insets.right), (int) (screen.getHeight() - insets.top - insets.bottom));
        myFrame.setLocation((int) (insets.left), (int) (insets.top));
        myFrame.setVisible(true);
    }
}
Output:


The above chart is similar to Yahoo Finance chart:


Nicolas

Attached Thumbnails
Click image for larger version

Name:	a.png
Views:	2805
Size:	175.5 KB
ID:	146263  
Visit my NexusFi Trade Journal Started this thread Reply With Quote
Thanked by:

Can you help answer these questions
from other members on NexusFi?
REcommedations for programming help
Sierra Chart
Exit Strategy
NinjaTrader
ZombieSqueeze
Platforms and Indicators
Trade idea based off three indicators.
Traders Hideout
How to apply profiles
Traders Hideout
 
Best Threads (Most Thanked)
in the last 7 days on NexusFi
Spoo-nalysis ES e-mini futures S&P 500
29 thanks
Just another trading journal: PA, Wyckoff & Trends
25 thanks
Tao te Trade: way of the WLD
24 thanks
Bigger Wins or Fewer Losses?
22 thanks
GFIs1 1 DAX trade per day journal
17 thanks
  #3 (permalink)
 
lolu's Avatar
 lolu 
Lagos, Nigeria
Market Wizard
 
Experience: Intermediate
Platform: NinjaTrader, SierraChart
Trading: Euro Currency & Oil
Frequency: Daily
Duration: Hours
Posts: 2,552 since Jun 2009
Thanks Given: 1,049
Thanks Received: 1,678



Nicolas11 View Post
Hi,

This is a SSCCE example of code to draw candlestick chart in Java with (free) JFreeChart API.

 
Code
// Inspirations:
// -------------
// a) http://www.roseindia.net/chartgraphs/candle-stick-chart.shtml
// b) 3 times nearly the same code:
// http://www.jfree.org/forum/viewtopic.php?f=10&t=24521
// http://stackoverflow.com/questions/18413534/jfreechart-crashes-when-using-yahoo-finance-quotes
// http://www.jfree.org/forum/viewtopic.php?f=10&t=24521

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Insets;
import java.awt.Toolkit;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.StringTokenizer;
import javax.swing.JFrame;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.DateAxis;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.axis.SegmentedTimeline;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.xy.CandlestickRenderer;
import org.jfree.data.xy.DefaultOHLCDataset;
import org.jfree.data.xy.OHLCDataItem;
import org.jfree.data.xy.OHLCDataset;

public class Exemple144_JFreeChart_Candlestick_Chart {

    public static void main(String args[]) {

        // 1. Download MSFT quotes from Yahoo Finance and store them as OHLCDataItem
        List<OHLCDataItem> dataItems = new ArrayList<OHLCDataItem>();
        try {
            String strUrl = "http://ichart.yahoo.com/table.csv?s=MSFT&a=3&b=1&c=2013&d=3&e=15&f=2050&g=d";
            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());

                // adjust data:
                open = open * adjClose / close;
                high = high * adjClose / close;
                low = low * adjClose / close;

                OHLCDataItem item = new OHLCDataItem(date, open, high, low, adjClose, volume);
                dataItems.add(item);
            }
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        Collections.reverse(dataItems); // Data from Yahoo is from newest to oldest. Reverse so it is oldest to newest.
        //Convert the list into an array
        OHLCDataItem[] data = dataItems.toArray(new OHLCDataItem[dataItems.size()]);
        OHLCDataset dataset = new DefaultOHLCDataset("MSFT", data);

        // 2. Create chart
        JFreeChart chart = ChartFactory.createCandlestickChart("MSFT", "Time", "Price", dataset, false);

        // 3. Set chart background
        chart.setBackgroundPaint(Color.white);

        // 4. Set a few custom plot features
        XYPlot plot = (XYPlot) chart.getPlot();
        plot.setBackgroundPaint(Color.WHITE); // light yellow = new Color(0xffffe0)
        plot.setDomainGridlinesVisible(true);
        plot.setDomainGridlinePaint(Color.lightGray);
        plot.setRangeGridlinePaint(Color.lightGray);
        ((NumberAxis) plot.getRangeAxis()).setAutoRangeIncludesZero(false);

        // 5. Skip week-ends on the date axis
        ((DateAxis) plot.getDomainAxis()).setTimeline(SegmentedTimeline.newMondayThroughFridayTimeline());

        // 6. No volume drawn
        ((CandlestickRenderer) plot.getRenderer()).setDrawVolume(false);

        // 7. Create and display full-screen JFrame
        JFrame myFrame = new JFrame();
        myFrame.setResizable(true);
        myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        myFrame.add(new ChartPanel(chart), BorderLayout.CENTER);
        Toolkit kit = Toolkit.getDefaultToolkit();
        Insets insets = kit.getScreenInsets(myFrame.getGraphicsConfiguration());
        Dimension screen = kit.getScreenSize();
        myFrame.setSize((int) (screen.getWidth() - insets.left - insets.right), (int) (screen.getHeight() - insets.top - insets.bottom));
        myFrame.setLocation((int) (insets.left), (int) (insets.top));
        myFrame.setVisible(true);
    }
}
Output:


The above chart is similar to Yahoo Finance chart:


Nicolas

@nicolas,

What are the steps/process to run this Java scripts with the (free) JFreeChart API. I already downloaded the (free) JFreeChart

Lolu

Visit my NexusFi Trade Journal Reply With Quote
  #4 (permalink)
 
Nicolas11's Avatar
 Nicolas11 
near Paris, France
 
Experience: Beginner
Platform: -
Trading: -
Posts: 1,071 since Aug 2011
Thanks Given: 2,232
Thanks Received: 1,769

Hi @lolu ,

In order to avoid any misunderstanding, it is pure Java, and not JavaScript. Even if they both contain "Java" in their names, they are two different beasts.

You need a Java IDE, as Netbeans or Eclipse.

Warning: there is a learning curve. Java is a whole language. Learning Java is like learning C++ or C#. It requires time.

Nicolas

Visit my NexusFi Trade Journal Started this thread Reply With Quote
Thanked by:
  #5 (permalink)
 
lolu's Avatar
 lolu 
Lagos, Nigeria
Market Wizard
 
Experience: Intermediate
Platform: NinjaTrader, SierraChart
Trading: Euro Currency & Oil
Frequency: Daily
Duration: Hours
Posts: 2,552 since Jun 2009
Thanks Given: 1,049
Thanks Received: 1,678


Nicolas11 View Post
Hi @lolu ,

In order to avoid any misunderstanding, it is pure Java, and not JavaScript. Even if they both contain "Java" in their names, they are two different beasts.

You need a Java IDE, as Netbeans or Eclipse.

Warning: there is a learning curve. Java is a whole language. Learning Java is like learning C++ or C#. It requires time.

Nicolas

@nicolas,

I was referring to the Java codes within the Exemple144_JFreeChart_Candlestick_Chart as scripts.

I've been using NetBeans for my PHP applications for sometime now and I know it is an IDE for Java, C++, PHP, etc.

I've successfully launched a few simple java "programs" from my Mac OS X shell (command line interface) by first compiling with the JAVAC command, then followed by the JAVA command. I'd expected that I could do that with your example; but it returned 28 errors, a few of which are "package org.jfree.chart does not exist". So, I decided to run the Exemple144_JFreeChart_Candlestick_Chart on NetBeans, but the Build process returned the same errors. So, that was the reason for my last post.

I'm suited to grasp Java pretty fast 'cos I'm a Programmer, otherwise I'll focus on PHP, R and maybe C++.

Lolu

Visit my NexusFi Trade Journal Reply With Quote
  #6 (permalink)
 
Nicolas11's Avatar
 Nicolas11 
near Paris, France
 
Experience: Beginner
Platform: -
Trading: -
Posts: 1,071 since Aug 2011
Thanks Given: 2,232
Thanks Received: 1,769

@lolu ,

If you are used to NetBeans, that's fine.
Following any tutorial on the Web on how to add library to NetBeans, just add JFreeChart library to your project.

Nicolas

Visit my NexusFi Trade Journal Started this thread Reply With Quote
Thanked by:
  #7 (permalink)
 
lolu's Avatar
 lolu 
Lagos, Nigeria
Market Wizard
 
Experience: Intermediate
Platform: NinjaTrader, SierraChart
Trading: Euro Currency & Oil
Frequency: Daily
Duration: Hours
Posts: 2,552 since Jun 2009
Thanks Given: 1,049
Thanks Received: 1,678


Nicolas11 View Post
@lolu ,

If you are used to NetBeans, that's fine.
Following any tutorial on the Web on how to add library to NetBeans, just add JFreeChart library to your project.

Nicolas

@nicolas,

Got it !!!



Thank you once again.

Lolu

Visit my NexusFi Trade Journal Reply With Quote
Thanked by:
  #8 (permalink)
TradeHound
Dallas, TX
 
Posts: 2 since Jun 2015
Thanks Given: 1
Thanks Received: 2

Thank you Nicolas11,

I got that code to work but I had to delete the part that skips weekends:

// // 5. Skip week-ends on the date axis //tempx 6/8/15 This shows a blank chart, so commented:
// ((DateAxis) plot.getDomainAxis()).setTimeline(SegmentedTimeline.newMondayThroughFridayTimeline());

And I realized that because I'm doing Forex data, it does trade on Sunday, and I was using data that started on Sunday, duh

This is a great start for me to get my charts working, thank you for the post.

-Scott

Reply With Quote
Thanked by:
  #9 (permalink)
 
Nicolas11's Avatar
 Nicolas11 
near Paris, France
 
Experience: Beginner
Platform: -
Trading: -
Posts: 1,071 since Aug 2011
Thanks Given: 2,232
Thanks Received: 1,769

In its last releases, Java relies on JavaFX for creating graphical user interfaces ( GUI).

JavaFX allows creating charts.

An example of candlestick charts is given in Ensemble demo suite ( demo page, source code) provided by Java developers.

I have extracted the part related to candlestick chart in a minimal stand-alone application. See enclosed ZIP containing only 2 files (.java and .css).

Nicolas


Attached Files
Elite Membership required to download: Ensemble_AdvCandleStickChart.zip
Visit my NexusFi Trade Journal Started this thread Reply With Quote
Thanked by:




Last Updated on July 20, 2016


© 2024 NexusFi™, s.a., All Rights Reserved.
Av Ricardo J. Alfaro, Century Tower, Panama City, Panama, Ph: +507 833-9432 (Panama and Intl), +1 888-312-3001 (USA and Canada)
All information is for educational use only and is not investment advice. There is a substantial risk of loss in trading commodity futures, stocks, options and foreign exchange products. Past performance is not indicative of future results.
About Us - Contact Us - Site Rules, Acceptable Use, and Terms and Conditions - Privacy Policy - Downloads - Top
no new posts