Example usage for org.jfree.chart.axis DateAxis setTimeline

List of usage examples for org.jfree.chart.axis DateAxis setTimeline

Introduction

In this page you can find the example usage for org.jfree.chart.axis DateAxis setTimeline.

Prototype

public void setTimeline(Timeline timeline) 

Source Link

Document

Sets the underlying timeline to use for this axis.

Usage

From source file:com.charts.SixMonthChart.java

public SixMonthChart(YStockQuote currentStock) throws ParseException {

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

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

    //Do some setting up, see the API Doc
    renderer.setSeriesPaint(0, Color.BLACK);
    renderer.setDrawVolume(false);/*from w w w  .j av  a2  s  .c  o m*/
    rangeAxis.setAutoRangeIncludesZero(false);

    domainAxis.setDateFormatOverride(new SimpleDateFormat("dd-MM-yy"));
    domainAxis.setTickMarkPosition(DateTickMarkPosition.MIDDLE);

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

    XYPlot plot = (XYPlot) chart.getPlot();

    LegendTitle legend = new LegendTitle(plot);

    chart.addLegend(legend);
    chart.getLegend().setVisible(true);
    chart.getLegend().setPosition(RectangleEdge.BOTTOM);

    ValueAxis yAxis = (ValueAxis) plot.getRangeAxis();
    DateAxis xAxis = (DateAxis) plot.getDomainAxis();
    Date now = new Date();
    SegmentedTimeline segmentedTimeline = SegmentedTimeline.newMondayThroughFridayTimeline();
    Calendar[][] holidays = DayRange.getHolidayDates();
    int len = holidays.length;

    for (int i = 0; i < holidays[0].length; i++) {
        Calendar day = Calendar.getInstance(TimeZone.getTimeZone("EST"));
        day.set(Calendar.YEAR, holidays[0][i].get(Calendar.YEAR));
        day.set(Calendar.MONTH, holidays[0][i].get(Calendar.MONTH));
        day.set(Calendar.DAY_OF_MONTH, holidays[0][i].get(Calendar.DAY_OF_MONTH));
        day.set(Calendar.HOUR_OF_DAY, 9);
        segmentedTimeline.addException(day.getTime());

    }

    xAxis.setTimeline(segmentedTimeline);
    //xAxis.setVerticalTickLabels(true);
    xAxis.setDateFormatOverride(new SimpleDateFormat("MMM y"));
    xAxis.setAutoTickUnitSelection(true);
    xAxis.setAutoRange(true);
    renderer.setAutoWidthFactor(0.5);
    renderer.setUpPaint(Color.green);
    renderer.setDownPaint(new Color(0xc0, 0x00, 0x00));
    renderer.setSeriesPaint(0, Color.black);

    StandardXYItemRenderer renderer1 = new StandardXYItemRenderer();
    renderer1.setSeriesPaint(0, Color.BLUE);
    TimeSeries movingAverage30 = MovingAverage.createMovingAverage(close, "MA(30)", 30, 0);
    Double currMA30 = (Double) movingAverage30.getDataItem(movingAverage30.getItemCount() - 1).getValue();
    currMA30 = Math.round(currMA30 * 100.0) / 100.0;
    movingAverage30.setKey("MA(30): " + currMA30);
    TimeSeriesCollection collection = new TimeSeriesCollection();
    collection.addSeries(movingAverage30);
    plot.setDataset(1, collection);
    plot.setRenderer(1, renderer1);

    chartPanel.revalidate();
    chartPanel.repaint();
    chartPanel.revalidate();
    chartPanel.repaint();
}

From source file:KIDLYFactory.java

/**
 * Creates and returns a default instance of a high-low-open-close chart
 * with a special timeline. This timeline can be a
 * {@link org.jfree.chart.axis.SegmentedTimeline} such as the Monday
 * through Friday timeline that will remove Saturdays and Sundays from
 * the axis./*w  w  w .j av a  2s . co m*/
 *
 * @param title  the chart title (<code>null</code> permitted).
 * @param timeAxisLabel  a label for the time axis (<code>null</code>
 *                       permitted).
 * @param valueAxisLabel  a label for the value axis (<code>null</code>
 *                        permitted).
 * @param dataset  the dataset for the chart (<code>null</code> permitted).
 * @param timeline  the timeline.
 * @param legend  a flag specifying whether or not a legend is required.
 *
 * @return A high-low-open-close chart.
 */
public static JFreeChart createHighLowChart(String title, String timeAxisLabel, String valueAxisLabel,
        OHLCDataset dataset, Timeline timeline, boolean legend) {

    DateAxis timeAxis = new DateAxis(timeAxisLabel);
    timeAxis.setTimeline(timeline);
    NumberAxis valueAxis = new NumberAxis(valueAxisLabel);
    HighLowRenderer renderer = new HighLowRenderer();
    renderer.setBaseToolTipGenerator(new HighLowItemLabelGenerator());
    XYPlot plot = new XYPlot(dataset, timeAxis, valueAxis, renderer);
    JFreeChart chart = new JFreeChart(title, JFreeChart.DEFAULT_TITLE_FONT, plot, legend);
    currentTheme.apply(chart);
    return chart;

}

From source file:net.sourceforge.processdash.ui.web.psp.TimeLogPhaseWaterfallChart.java

private void setupGaps(GapSkipTracker gapTracker, DateAxis dateAxis, XYPlot plot) {
    if (gapTracker.gaps.isEmpty())
        return;//w w  w . ja v  a 2s  .c o m

    SegmentedTimeline timeline = new SegmentedTimeline(1000, 100, 0);
    timeline.setStartTime(gapTracker.leftEnd);

    for (Span gap : gapTracker.gaps) {
        timeline.addException(gap.start + GAP_SPACING, gap.end - 1000);

        long annotationX = gap.start + GAP_SPACING / 2;
        plot.addAnnotation(new XYLineAnnotation(annotationX, VERT_LINE_MIN_Y, annotationX, VERT_LINE_MAX_Y,
                GAP_STROKE, Color.darkGray));

        double boxW = GAP_SPACING * 0.4;
        XYBoxAnnotation box = new XYBoxAnnotation(annotationX - boxW, VERT_LINE_MIN_Y, annotationX + boxW,
                VERT_LINE_MAX_Y, null, null, null);
        String toolTip = resources.format("No_Activity_FMT", gap.getStart(), gap.getEnd());
        box.setToolTipText(toolTip);
        plot.addAnnotation(box);
    }

    dateAxis.setTimeline(timeline);
}

From source file:ch.algotrader.client.chart.ChartTab.java

private void initAxis() {

    DateAxis domainAxis = (DateAxis) getPlot().getDomainAxis();

    // configure the Date Axis (if startTime & endTime is set)
    if (this.chartDefinition.getStartTime() != null && this.chartDefinition.getEndTime() != null
            && !this.chartDefinition.getStartTime().equals(this.chartDefinition.getEndTime())) {

        // creat the SegmentedTimeline
        long startTime = this.chartDefinition.getStartTime().getTime();
        long endTime = this.chartDefinition.getEndTime().getTime();
        if (endTime == -3600000) {
            // adjust 00:00
            endTime += 86400000;//from  w w  w.  ja  v  a2 s  .  c  om
        }
        long segmentSize = 60 * 1000; // minute
        int segmentsIncluded = (int) (endTime - startTime) / (60 * 1000);
        int segmentsExcluded = 24 * 60 - segmentsIncluded;
        SegmentedTimeline timeline = new SegmentedTimeline(segmentSize, segmentsIncluded, segmentsExcluded);

        Date fromDate = domainAxis.getMinimumDate();
        Date toDate = domainAxis.getMaximumDate();
        long fromTime = fromDate.getTime();
        long toTime = toDate.getTime();

        // get year/month/day from fromTime and hour/minute from diagrm.startTime
        Date truncatedDate = DateUtils.truncate(fromDate, Calendar.DAY_OF_MONTH);
        Calendar truncatedCalendar = DateUtils.toCalendar(truncatedDate);
        Calendar startCalendar = DateUtils.toCalendar(this.chartDefinition.getStartTime());
        truncatedCalendar.set(Calendar.HOUR_OF_DAY, startCalendar.get(Calendar.HOUR_OF_DAY));
        truncatedCalendar.set(Calendar.MINUTE, startCalendar.get(Calendar.MINUTE));

        timeline.setStartTime(truncatedCalendar.getTimeInMillis());
        timeline.setBaseTimeline(SegmentedTimeline.newMondayThroughFridayTimeline());
        timeline.addBaseTimelineExclusions(fromTime, toTime);
        timeline.setAdjustForDaylightSaving(true);

        domainAxis.setTimeline(timeline);
    }

    // make sure the markers are within the rangeAxis
    ValueAxis rangeAxis = getPlot().getRangeAxis();
    for (Marker marker : this.markers.values()) {

        if (marker instanceof ValueMarker) {

            ValueMarker valueMarker = (ValueMarker) marker;
            if (marker.getAlpha() > 0 && valueMarker.getValue() != 0.0) {

                if (valueMarker.getValue() < rangeAxis.getLowerBound()) {
                    rangeAxis.setLowerBound(valueMarker.getValue());
                    marker.setLabelAnchor(RectangleAnchor.TOP_RIGHT);
                    marker.setLabelTextAnchor(TextAnchor.BOTTOM_RIGHT);
                }

                if (valueMarker.getValue() > rangeAxis.getUpperBound()) {
                    rangeAxis.setUpperBound(valueMarker.getValue());
                    marker.setLabelAnchor(RectangleAnchor.BOTTOM_RIGHT);
                    marker.setLabelTextAnchor(TextAnchor.TOP_RIGHT);
                }
            }
        } else {

            IntervalMarker intervalMarker = (IntervalMarker) marker;
            if (marker.getAlpha() > 0 && intervalMarker.getStartValue() != 0.0) {

                if (intervalMarker.getStartValue() < rangeAxis.getLowerBound()) {
                    rangeAxis.setLowerBound(intervalMarker.getStartValue());
                    marker.setLabelAnchor(RectangleAnchor.TOP_RIGHT);
                    marker.setLabelTextAnchor(TextAnchor.TOP_RIGHT);
                }

                if (intervalMarker.getEndValue() > rangeAxis.getUpperBound()) {
                    rangeAxis.setUpperBound(intervalMarker.getEndValue());
                    marker.setLabelAnchor(RectangleAnchor.BOTTOM_RIGHT);
                    marker.setLabelTextAnchor(TextAnchor.BOTTOM_RIGHT);
                }
            }
        }
    }
}

From source file:org.trade.ui.chart.CandlestickChart.java

/**
 * Method createChart.//w  ww .j a v a 2  s.  c o m
 * 
 * @param strategyData
 *            StrategyData
 * @param title
 *            String
 * @return JFreeChart
 */
private JFreeChart createChart(StrategyData strategyData, String title, Tradingday tradingday) {

    DateAxis dateAxis = new DateAxis("Date");
    dateAxis.setVerticalTickLabels(true);
    dateAxis.setDateFormatOverride(new SimpleDateFormat("dd/MM hh:mm"));
    dateAxis.setTickMarkPosition(DateTickMarkPosition.START);
    NumberAxis priceAxis = new NumberAxis("Price");
    priceAxis.setAutoRange(true);
    priceAxis.setAutoRangeIncludesZero(false);
    XYPlot pricePlot = new XYPlot(strategyData.getCandleDataset(), dateAxis, priceAxis,
            strategyData.getCandleDataset().getRenderer());
    pricePlot.setOrientation(PlotOrientation.VERTICAL);
    pricePlot.setDomainPannable(true);
    pricePlot.setRangePannable(true);
    pricePlot.setDomainCrosshairVisible(true);
    pricePlot.setDomainCrosshairLockedOnData(true);
    pricePlot.setRangeCrosshairVisible(true);
    pricePlot.setRangeCrosshairLockedOnData(true);
    pricePlot.setRangeGridlinePaint(new Color(204, 204, 204));
    pricePlot.setDomainGridlinePaint(new Color(204, 204, 204));
    pricePlot.setBackgroundPaint(Color.white);

    /*
     * Calculate the number of 15min segments in this trading day. i.e.
     * 6.5hrs/15min = 26 and there are a total of 96 = one day
     */

    int segments15min = (int) (tradingday.getClose().getTime() - tradingday.getOpen().getTime())
            / (1000 * 60 * 15);

    SegmentedTimeline segmentedTimeline = new SegmentedTimeline(SegmentedTimeline.FIFTEEN_MINUTE_SEGMENT_SIZE,
            segments15min, (96 - segments15min));

    Date startDate = tradingday.getOpen();
    Date endDate = tradingday.getClose();

    if (!strategyData.getCandleDataset().getSeries(0).isEmpty()) {
        startDate = ((CandleItem) strategyData.getCandleDataset().getSeries(0).getDataItem(0)).getPeriod()
                .getStart();
        startDate = TradingCalendar.getSpecificTime(tradingday.getOpen(), startDate);
        endDate = ((CandleItem) strategyData.getCandleDataset().getSeries(0)
                .getDataItem(strategyData.getCandleDataset().getSeries(0).getItemCount() - 1)).getPeriod()
                        .getStart();
        endDate = TradingCalendar.getSpecificTime(tradingday.getClose(), endDate);
    }

    segmentedTimeline.setStartTime(startDate.getTime());
    segmentedTimeline.addExceptions(getNonTradingPeriods(startDate, endDate, tradingday.getOpen(),
            tradingday.getClose(), segmentedTimeline));
    dateAxis.setTimeline(segmentedTimeline);

    // Build Combined Plot
    CombinedDomainXYPlot mainPlot = new CombinedDomainXYPlot(dateAxis);
    mainPlot.add(pricePlot, 4);

    int axixIndex = 0;
    int datasetIndex = 0;

    /*
     * Change the List of indicators so that the candle dataset is the first
     * one in the list. The main chart must be plotted first.
     */
    List<IndicatorDataset> indicators = new ArrayList<IndicatorDataset>(0);
    for (IndicatorDataset item : strategyData.getIndicators()) {
        if (IndicatorSeries.CandleSeries.equals(item.getType(0))) {
            indicators.add(item);
        }
    }
    for (IndicatorDataset item : strategyData.getIndicators()) {
        if (!IndicatorSeries.CandleSeries.equals(item.getType(0))) {
            indicators.add(item);
        }
    }
    for (int i = 0; i < indicators.size(); i++) {
        IndicatorDataset indicator = indicators.get(i);
        if (indicator.getDisplaySeries(0)) {

            if (indicator.getSubChart(0)) {
                String axisName = "Price";
                if (IndicatorSeries.CandleSeries.equals(indicator.getType(0))) {
                    axisName = ((CandleSeries) indicator.getSeries(0)).getSymbol();
                } else {
                    org.trade.dictionary.valuetype.IndicatorSeries code = org.trade.dictionary.valuetype.IndicatorSeries
                            .newInstance(indicator.getType(0));
                    axisName = code.getDisplayName();
                }
                NumberAxis subPlotAxis = new NumberAxis(axisName);
                subPlotAxis.setAutoRange(true);
                subPlotAxis.setAutoRangeIncludesZero(false);

                XYPlot subPlot = new XYPlot((XYDataset) indicator, dateAxis, subPlotAxis,
                        indicator.getRenderer());

                subPlot.setOrientation(PlotOrientation.VERTICAL);
                subPlot.setDomainPannable(true);
                subPlot.setRangePannable(true);
                subPlot.setDomainCrosshairVisible(true);
                subPlot.setDomainCrosshairLockedOnData(true);
                subPlot.setRangeCrosshairVisible(true);
                subPlot.setRangeCrosshairLockedOnData(true);
                subPlot.setRangeGridlinePaint(new Color(204, 204, 204));
                subPlot.setDomainGridlinePaint(new Color(204, 204, 204));
                subPlot.setBackgroundPaint(Color.white);
                XYItemRenderer renderer = subPlot.getRendererForDataset((XYDataset) indicator);
                for (int seriesIndex = 0; seriesIndex < ((XYDataset) indicator)
                        .getSeriesCount(); seriesIndex++) {
                    renderer.setSeriesPaint(seriesIndex, indicator.getSeriesColor(seriesIndex));
                }
                mainPlot.add(subPlot, 1);

            } else {
                datasetIndex++;
                pricePlot.setDataset(datasetIndex, (XYDataset) indicator);
                if (IndicatorSeries.CandleSeries.equals(indicator.getType(0))) {
                    // add secondary axis
                    axixIndex++;

                    final NumberAxis axis2 = new NumberAxis(
                            ((CandleSeries) indicator.getSeries(0)).getSymbol());
                    axis2.setAutoRange(true);
                    axis2.setAutoRangeIncludesZero(false);
                    pricePlot.setRangeAxis(datasetIndex, axis2);
                    pricePlot.setRangeAxisLocation(i + 1, AxisLocation.BOTTOM_OR_RIGHT);
                    pricePlot.mapDatasetToRangeAxis(datasetIndex, axixIndex);
                    pricePlot.setRenderer(datasetIndex, new StandardXYItemRenderer());
                } else {
                    pricePlot.setRenderer(datasetIndex, indicator.getRenderer());
                }
                XYItemRenderer renderer = pricePlot.getRendererForDataset((XYDataset) indicator);

                for (int seriesIndex = 0; seriesIndex < ((XYDataset) indicator)
                        .getSeriesCount(); seriesIndex++) {
                    renderer.setSeriesPaint(seriesIndex, indicator.getSeriesColor(seriesIndex));
                }
            }
        }
    }
    JFreeChart jfreechart = new JFreeChart(title, null, mainPlot, true);
    jfreechart.setAntiAlias(false);
    return jfreechart;
}