Dark Theme
Light Theme
Trading Articles
Article Categories
Article Tools
Welcome to NexusFi: the best trading community on the planet, with over 150,000 members Sign Up Now for Free
Genuine reviews from real traders, not fake reviews from stealth vendors
Quality education from leading professional traders
We are a friendly, helpful, and positive community
We do not tolerate rude behavior, trolling, or vendors advertising in posts
We are here to help, just let us know what you need
You'll need to
register in order to view the content of the threads and start contributing to our community.
It's free for basic access, or support us by becoming an Elite Member -- see if you qualify for a discount below.
-- Big Mike, Site Administrator
(If you already have an account, login at the top of the page)
[Java] Candlestick chart with JFreeChart
Updated July 20, 2016
Top Posters
looks_one
Nicolas11
with 4 posts (7 thanks)
looks_two
lolu
with 3 posts (1 thanks)
looks_3
Quick Summary
with 1 posts (0 thanks)
looks_4
TradeHound
with 1 posts (1 thanks)
trending_up
12,147 views
thumb_up
9 thanks given
group
3 followers
forum
8 posts
attach_file
5 attachments
[Java] Candlestick chart with JFreeChart
May 8th, 2014, 05:08 PM
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
Can you help answer these questions from other members on NexusFi?
Best Threads (Most Thanked) in the last 7 days on NexusFi
May 18th, 2014, 03:17 PM
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
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
May 18th, 2014, 03:37 PM
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
May 18th, 2014, 04:38 PM
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
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
May 18th, 2014, 05:07 PM
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
May 21st, 2014, 09:52 AM
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
@
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
June 8th, 2015, 09:43 PM
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
July 20th, 2016, 12:01 PM
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
Last Updated on July 20, 2016