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


[Java] Candlestick chart with JFreeChart
Updated: Views / Replies:4,879 / 8
Created: by Nicolas11 Attachments:5

Welcome to futures io.

(If you already have an account, login at the top of the page)

futures io is the largest futures trading community on the planet, with over 90,000 members. At futures io, our goal has always been and always will be to create a friendly, positive, forward-thinking community where members can openly share and discuss everything the world of trading has to offer. The community is one of the friendliest you will find on any subject, with members going out of their way to help others. Some of the primary differences between futures io and other trading sites revolve around the standards of our community. Those standards include a code of conduct for our members, as well as extremely high standards that govern which partners we do business with, and which products or services we recommend to our members.

At futures io, our focus is on quality education. No hype, gimmicks, or secret sauce. The truth is: trading is hard. To succeed, you need to surround yourself with the right support system, educational content, and trading mentors Ė all of which you can find on futures io, utilizing our social trading environment.

With futures io, you can find honest trading reviews on brokers, trading rooms, indicator packages, trading strategies, and much more. Our trading review process is highly moderated to ensure that only genuine users are allowed, so you donít need to worry about fake reviews.

We are fundamentally different than most other trading sites:
  • We are here to help. Just let us know what you need.
  • We work extremely hard to keep things positive in our community.
  • We do not tolerate rude behavior, trolling, or vendors advertising in posts.
  • We firmly believe in and encourage sharing. The holy grail is within you, we can help you find it.
  • 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.

-- Big Mike, Site Administrator

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,729 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 12: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,595 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,729 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,595 received


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,729 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,595 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 10: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,729 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, 12 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)
 

RandBots: AutoTrading Bots to diversify your trading

Oct 24
 

TopstepTrader: Profiting Without Risking Your Own Money

Oct 26

Building Open Source Indicators for NT8 w/Fat Tails @ Lizard Indicators

Elite only
     

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


All times are GMT -4. The time now is 05:48 PM.

Copyright © 2017 by futures io, s.a., Av Ricardo J. Alfaro, Century Tower, Panama, +507 833-9432, info@futures.io
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.
no new posts
Page generated 2017-10-20 in 0.12 seconds with 20 queries on phoenix via your IP 23.20.86.177