[Java] Candlestick chart with JFreeChart - Platforms and Indicators | futures.io
futures.io futures trading


[Java] Candlestick chart with JFreeChart
Started: by Nicolas11 Views / Replies:3,795 / 8
Last Reply: Attachments:5

Welcome to futures.io.

Welcome, Guest!

This forum was established to help traders (especially futures traders) by openly sharing indicators, strategies, methods, trading journals and discussing the psychology of trading.

We are fundamentally different than most other trading forums:
  • We work extremely hard to keep things positive on our forums.
  • We do not tolerate rude behavior, trolling, or vendor advertising in posts.
  • We firmly believe in openness and encourage sharing. The holy grail is within you, it is not something tangible you can download.
  • We expect our members to participate and become a part of the community. Help yourself by helping others.


You'll need to register in order to view the content of the threads and start contributing to our community. It's free and simple, and we will never resell your private information.

-- Big Mike

Reply
 
Thread Tools Search this Thread
 

[Java] Candlestick chart with JFreeChart

  #1 (permalink)
Elite Member
near Paris, France
 
Futures Experience: Beginner
Platform: -
Favorite Futures: -
 
Nicolas11's Avatar
 
Posts: 1,070 since Aug 2011
Thanks: 2,232 given, 1,726 received

[Java] Candlestick chart with JFreeChart or JavaFX

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:
Please register on futures.io to view futures trading content such as post attachment(s), image(s), and screenshot(s).


The above chart is similar to Yahoo Finance chart:
Please register on futures.io to view futures trading content such as post attachment(s), image(s), and screenshot(s).


Nicolas

Attached Thumbnails
[Java] Candlestick chart with JFreeChart-.png  

Last edited by Nicolas11; July 20th, 2016 at 01:03 PM.
Reply With Quote
The following 4 users say Thank You to Nicolas11 for this post:
 
  #2 (permalink)
Quick Summary
Quick Summary Post

Quick Summary is created and edited by users like you... Add FAQ's, Links and other Relevant Information by clicking the edit button in the lower right hand corner of this message.

 
  #3 (permalink)
Elite Member
Lagos, Nigeria
 
Futures Experience: Intermediate
Platform: NinjaTrader, SierraChart
Favorite Futures: Euro Currency & Oil
 
lolu's Avatar
 
Posts: 2,438 since Jun 2009
Thanks: 998 given, 1,591 received



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:
Please register on futures.io to view futures trading content such as post attachment(s), image(s), and screenshot(s).


The above chart is similar to Yahoo Finance chart:
Please register on futures.io to view futures trading content such as post attachment(s), image(s), and screenshot(s).


Nicolas

@nicolas,

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

Lolu

Reply With Quote
 
  #4 (permalink)
Elite Member
near Paris, France
 
Futures Experience: Beginner
Platform: -
Favorite Futures: -
 
Nicolas11's Avatar
 
Posts: 1,070 since Aug 2011
Thanks: 2,232 given, 1,726 received

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

Reply With Quote
The following user says Thank You to Nicolas11 for this post:
 
  #5 (permalink)
Elite Member
Lagos, Nigeria
 
Futures Experience: Intermediate
Platform: NinjaTrader, SierraChart
Favorite Futures: Euro Currency & Oil
 
lolu's Avatar
 
Posts: 2,438 since Jun 2009
Thanks: 998 given, 1,591 received

Futures Edge on FIO

Which products do you trade?

 

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

Reply With Quote
 
  #6 (permalink)
Elite Member
near Paris, France
 
Futures Experience: Beginner
Platform: -
Favorite Futures: -
 
Nicolas11's Avatar
 
Posts: 1,070 since Aug 2011
Thanks: 2,232 given, 1,726 received

@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

Reply With Quote
The following user says Thank You to Nicolas11 for this post:
 
  #7 (permalink)
Elite Member
Lagos, Nigeria
 
Futures Experience: Intermediate
Platform: NinjaTrader, SierraChart
Favorite Futures: Euro Currency & Oil
 
lolu's Avatar
 
Posts: 2,438 since Jun 2009
Thanks: 998 given, 1,591 received


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 !!!

Please register on futures.io to view futures trading content such as post attachment(s), image(s), and screenshot(s).


Thank you once again.

Lolu

Reply With Quote
The following user says Thank You to lolu for this post:
 
  #8 (permalink)
Trading Apprentice
Dallas, TX
 
Futures Experience: Intermediate
Platform: TradeHound
Broker/Data: Forex.com
Favorite Futures: Forex
 
Posts: 2 since Jun 2015
Thanks: 1 given, 2 received

It works, with one exception:

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


Last edited by TradeHound; June 9th, 2015 at 11:19 AM. Reason: I realized my mistake
Reply With Quote
The following user says Thank You to TradeHound for this post:
 
  #9 (permalink)
Elite Member
near Paris, France
 
Futures Experience: Beginner
Platform: -
Favorite Futures: -
 
Nicolas11's Avatar
 
Posts: 1,070 since Aug 2011
Thanks: 2,232 given, 1,726 received

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

Please register on futures.io to view futures trading content such as post attachment(s), image(s), and screenshot(s).

Attached Files
Register to download File Type: zip Ensemble_AdvCandleStickChart.zip (7.1 KB, 7 views)
Reply With Quote
The following user says Thank You to Nicolas11 for this post:

Reply



futures.io > > > [Java] Candlestick chart with JFreeChart

Thread Tools Search this Thread
Search this Thread:

Advanced Search



Upcoming Webinars and Events (4:30PM ET unless noted)
 

Anthony Drager: Pulling the trigger with confidence

Elite only
 

Leo Murphy: The Art and Science of Technical Analysis

Elite only
 

FuturesTrader71: Ask Me Anything

Elite only
     

Similar Threads
Thread Thread Starter Forum Replies Last Post
.NET or Java? LordAlfa Jokes 4 January 13th, 2014 10:41 AM
C++ or java or ......? FKtrader Traders Hideout 53 October 23rd, 2013 01:53 PM
@YM# 240 Minute Candlestick Chart - IQFeed Market Sniper 88 Sierra Chart 4 June 20th, 2012 08:29 AM
Time remaining code for candlestick chart NJ cattlefitter NinjaTrader 3 July 20th, 2011 06:42 PM
Java QuickStart Fat Tails Platforms and Indicators 5 December 8th, 2010 06:47 PM


All times are GMT -4. The time now is 08:42 PM.

no new posts
Page generated 2017-01-22 in 0.15 seconds with 20 queries on phoenix via your IP 54.205.13.200