ASE Home Page Products Download Purchase Support About ASE
ChartDirector Support
Forum HomeForum Home   SearchSearch

Message ListMessage List     Post MessagePost Message

  Finance Demo Chart
Posted by Papa Raihan on Jan-02-2010 20:18
If I would like to use Real Data for FinanceChart Demo instead of Random data, is there any sample of database scheme that I can use?
It's great if there is a sample code on how to integrate it.

I plan to integrate with mysql database

Thank you

Cheers
PR

  Re: Finance Demo Chart
Posted by Peter Kwan on Jan-04-2010 00:25
Hi Papa Raihan,

There are plenty of FinanceChart/MySQL code scattered in this forum. For example, see:

http://www.chartdir.com/forum/download_thread.php?bn=chartdir_support&thread=1244718175

Hope this can help.

Regards
Peter Kwan

  Re: Finance Demo Chart
Posted by Papa Raihan on Jan-04-2010 00:40
Thanks a lot Peter

it was a useful link, Do you have the database scheme? or sample?
for different chart, daily, intraday (minute) would it be different database?

Pls advise, thank you

PR

  Re: Finance Demo Chart
Posted by Peter Kwan on Jan-04-2010 22:54
Hi Papa,

The database design is up to you. Everybody designs database differently.

A simple example is to use tables with 7 columns:

ticker, timeStamp, openValue ,highValue , lowValue, closeValue, volumeValue

If you have different data (for example, daily, and intraday data), you may want to store it in different database tables. You can use the same schema for all tables if you like.

Hope this can help.

Regards
Peter Kwan

  Re: Finance Demo Chart
Posted by Papa Raihan on Jan-07-2010 01:17
Many Thanks Peter,

I will try your advice...

Kind Regards
PR

  Re: Finance Demo Chart
Posted by Papa Raihan on Jan-30-2010 00:20
Dear Mr. Kwan

I tried to modify the simple Finance like below:

<?php
require_once("../lib/FinanceChart.php");

$ticker = 'MSFT';
$SQL= "Select UNIX_TimeStamp(timestamp), openvalue, highvalue, lowvalue,  closevalue, volumevalue From ohlc_eod WHERE ticker='$ticker' ORDER by timestamp";

mysql_connect("localhost", "root", "");
mysql_select_db("testdb");
$result = mysql_query($SQL);

while ($row = mysql_fetch_row($result)) {
#$timeStamps[] = $row[0];
$timeStamps[] = chartTime2($row[0]);
$openData[] = $row[1];
$highData[] = $row[2];
$lowData[] = $row[3];
$closeData[] = $row[4];
$volData[] = $row[5];
}


$resolution = 86400;

# Create a FinanceChart object of width 600 pixels
$c = new FinanceChart(600);

# Add a title to the chart
$c->addTitle($ticker);

# Set the data into the finance chart object
$c->setData($timeStamps, $highData, $lowData, $openData, $closeData, $volData,
    $extraDays);


$c->addSlowStochastic(70, 14, 3, 0x006060, 0x606000);


# Add the main chart with 210 pixels in height
$c->addMainChart(210);

# Add a 5 period simple moving average to the main chart, using brown color
#$c->addSimpleMovingAvg(5, 0x663300);

# Add a 20 period simple moving average to the main chart, using purple color
#$c->addSimpleMovingAvg(20, 0x9900ff);

# Add an HLOC symbols to the main chart, using green/red for up/down days
$c->addCandleStick(0x00ff00, 0xff0000);

# Add 20 days bollinger band to the main chart, using light blue (9999ff) as the
# border and semi-transparent blue (c06666ff) as the fill color
#$c->addBollingerBand(20, 2, 0x9999ff, 0xc06666ff);

# Add a 70 pixels volume bars sub-chart to the bottom of the main chart, using
# green/red/grey for up/down/flat days
$c->addVolBars(70, 0x99ff99, 0xff9999, 0x808080);

# Append a 12-days momentum indicator chart (70 pixels height) using blue (0000ff)
# color.
$c->addMomentum(70, 9, 0x0000ff);

# Append a 14-days RSI indicator chart (70 pixels height) after the main chart. The
# main RSI line is purple (800080). Set threshold region to +/- 20 (that is, RSI = 50
# +/- 25). The upper/lower threshold regions will be filled with red (ff0000)/blue
# (0000ff).
#$c->addRSI(70, 14, 0x800080, 20, 0xff0000, 0x0000ff);



# output the chart
header("Content-type: image/png");
print($c->makeChart2(PNG));
?>

and it was successfull, Thank you...

But when I try to modify the FinanceChart Interactive Demo, I modified the getData function become:

function getData($ticker, $startDate, $endDate, $durationInDays, $extraPoints) {

global $timeStamps, $volData, $highData, $lowData, $openData, $closeData;
    global $startDate, $endDate, $resolution;
    $resolution = 86400;
    $adjustedStartDate = $startDate - fmod2($startDate, 86400) - (int)(($extraPoints * 7 + 4) / 5) * 86400 - 2 * 86400;

$SQL= "Select UNIX_TimeStamp(timestamp), openvalue, highvalue, lowvalue,  closevalue, volumevalue From ohlc_eod WHERE ticker='$ticker' ORDER by timestamp";

mysql_connect("localhost", "root", "");
mysql_select_db("testdb");
$result = mysql_query($SQL);

while ($row = mysql_fetch_row($result)) {
#$timeStamps[] = $row[0];
$timeStamps[] = chartTime2($row[0]);
$openData[] = $row[1];
$highData[] = $row[2];
$lowData[] = $row[3];
$closeData[] = $row[4];
$volData[] = $row[5];
}

}

=> The chart didnt came up, and no error either...

May I know what I missed? Thank You Sir...

  Re: Finance Demo Chart
Posted by Peter Kwan on Jan-30-2010 02:02
Hi Papa,

I am not sure what is "the chart does not come up" mean. Does it mean that you can see the chart (with title and grid lines), but there is no data? If you see a chart but no data, is it possible the $ticker symbol is not correct? Try hard code the $ticker symbol to MSFT to see if you can see any data.

Or does it mean you see a "red X" (broken image symbol). If you see a "red X", please inform me what is the error message inside the "red X". (See http://www.chartdir.com/forum/download_thread.php?site=chartdir&bn=chartdir_faq&thread=1117817200)

If you cannot see any error message but just a blank white page, please check if you have enabled error reporting in PHP (check phpinfo). If error reporting is disabled, please enable it so we can see the error messages. You may also add the following code to the charting script to ensure error reporting is enabled:

ini_set('display_errors',1);
error_reporting(E_ALL);

Regards
Peter Kwan

  Re: Finance Demo Chart
Posted by Papa Raihan on Jan-30-2010 06:59
Thanks Mr. Kwan

after setting the display errors : ON

there was following error:

Notice: Undefined index: CompareWith in D:\\wamp\\www\\fch\\v0.6\\FinanceChart.php on line 351

Fatal error: Call to undefined method MultiChart::getToolTipDateFormat() in D:\\wamp\\www\\fch\\v0.6\\FinanceChart.php on line 706

Seems there are few function need to be modified, not just the getData function?
pls advise, Thank you

Kind Regards
PR

  Re: Finance Demo Chart
Posted by Peter Kwan on Jan-30-2010 21:34
Hi Papa,

Would you mind to clarify what is the file "D:\\wamp\\www\\fch\\v0.6\\FinanceChart.php"? Is it the original "ChartDirector/lib/FinanceChart.php" that comes with ChartDirector, or have you modified it?

If you have modified "FinanceChart.php", the modification is probably causing the error. As I am not sure what modification you have done, you would need to debug your own code. Alternatively, you may use back the original "FinanceChart.php" that comes with ChartDirector.

If you are not sure if the "D:\\wamp\\www\\fch\\v0.6\\FinanceChart.php" has been modified, please attach the file "D:\\wamp\\www\\fch\\v0.6\\FinanceChart.php" so I may verify it.

Hope this can help.

Regards
Peter Kwan

  Re: Finance Demo Chart
Posted by Papa Raihan on Jan-30-2010 22:34
Attachments:
Thanks Mr. Kwan

Got progress now :)

now the error message was:
"No Data available for the specified time period"

I got more 1000 records for the specific ticker code (download from yahoo)...
=> i did "Select count(*) from mytable" :)

I dig those error in this forum, but still unable to solve :(

I attached my code as the following (as requested) Thank you


Appreciate for your help...

Kind Regards
PR
FinanceChart.php
<?php
require_once("../lib/LibRbtsChart.php");

#MODIFIED

# Utility to compute modulus for large positive numbers. Although PHP has a built-in fmod
# function, it is only for PHP >= 4.2.0. So we need to define our own fmod function.
function fmod2($a, $b) { return $a - floor($a / $b) * $b; }


#
# Create a finance chart based on user selections, which are encoded as query
# parameters. This code is designed to work with the financedemo HTML form.
#

# The timeStamps, volume, high, low, open and close data
#
# ** NOTE ** : This sample code is written assuming the time stamps are in
# ChartDirector chartTime format. It is because this format supports dates before
# 1970 (which may be needed in some long term charts). See the ChartDirector
# documentation on chartTime for details. When you retrieve the time stamps from your
# database, please remember to convert them to chartTime.
$timeStamps = null;
$volData = null;
$highData = null;
$lowData = null;
$openData = null;
$closeData = null;

# An extra data series to compare with the close data
$compareData = null;

# The resolution of the data in seconds. 1 day = 86400 seconds.
$resolution = 86400;


#/ <summary>
#/ Get the timeStamps, highData, lowData, openData, closeData and volData.
#/ </summary>
#/ <param name="ticker">The ticker symbol for the data series.</param>
#/ <param name="startDate">The starting date/time for the data series.</param>
#/ <param name="endDate">The ending date/time for the data series.</param>
#/ <param name="durationInDays">The number of trading days to get.</param>
#/ <param name="extraPoints">The extra leading data points needed in order to
#/ compute moving averages.</param>
#/ <returns>True if successfully obtain the data, otherwise false.</returns>
function getData($ticker, $startDate, $endDate, $durationInDays, $extraPoints) {

    global $resolution;

    # This method should return false if the ticker symbol is invalid. In this sample
    # code, as we are using a random number generator for the data, all ticker symbol
    # is allowed, but we still assumed an empty symbol is invalid.
    if ($ticker == "") {
        return false;
    }

    # In this demo, we can get 15 min, daily, weekly or monthly data depending on the
    # time range.
    $resolution = 86400;
    if ($durationInDays <= 10) {
        # 10 days or less, we assume 15 minute data points are available
        $resolution = 900;

        # We need to adjust the startDate backwards for the extraPoints. We assume
        # 6.5 hours trading time per day, and 5 trading days per week.
        $dataPointsPerDay = 6.5 * 3600 / $resolution;
        $adjustedStartDate = $startDate - fmod2($startDate, 86400) - (int)(
            $extraPoints / $dataPointsPerDay * 7 / 5 + 0.9999999) * 86400 - 2 * 86400
            ;

        # Get the required 15 min data
        get15MinData($ticker, $adjustedStartDate, $endDate);

    } else if ($durationInDays >= 4.5 * 360) {
        # 4 years or more - use monthly data points.
        $resolution = 30 * 86400;

        # Adjust startDate backwards to cater for extraPoints
        $YMD = getChartYMD($startDate);
        $currentMonth = (int)($YMD / 100) % 100 - $extraPoints;
        $currentYear = (int)($YMD / 10000);
        while ($currentMonth < 1) {
            $currentYear = $currentYear - 1;
            $currentMonth = $currentMonth + 12;
        }
        $adjustedStartDate = chartTime($currentYear, $currentMonth, 1);

        # Get the required monthly data
        getMonthlyData($ticker, $adjustedStartDate, $endDate);

    } else if ($durationInDays >= 1.5 * 360) {
        # 1 year or more - use weekly points.
        $resolution = 7 * 86400;

        # Adjust startDate backwards to cater for extraPoints
        $adjustedStartDate = $startDate - $extraPoints * 7 * 86400 - 6 * 86400;

        # Get the required weekly data
        getWeeklyData($ticker, $adjustedStartDate, $endDate);

    } else {
        # Default - use daily points
        $resolution = 86400;

        # Adjust startDate backwards to cater for extraPoints. We multiply the days
        # by 7/5 as we assume 1 week has 5 trading days.
        $adjustedStartDate = $startDate - fmod2($startDate, 86400) - (int)((
            $extraPoints * 7 + 4) / 5) * 86400 - 2 * 86400;

        # Get the required daily data
        getDailyData($ticker, $adjustedStartDate, $endDate);
    }

    return true;
}

#/ <summary>
#/ Get 15 minutes data series for timeStamps, highData, lowData, openData, closeData
#/ and volData.
#/ </summary>
#/ <param name="ticker">The ticker symbol for the data series.</param>
#/ <param name="startDate">The starting date/time for the data series.</param>
#/ <param name="endDate">The ending date/time for the data series.</param>
function get15MinData($ticker, $startDate, $endDate) {
    #
    # In this demo, we use a random number generator to generate the data. In
    # practice, you may get the data from a database or by other means. If you do not
    # have 15 minute data, you may modify the "drawChart" method below to not using
    # 15 minute data.
    #
    generateRandomData($ticker, $startDate, $endDate, 900);
}

#/ <summary>
#/ Get daily data series for timeStamps, highData, lowData, openData, closeData
#/ and volData.
#/ </summary>
#/ <param name="ticker">The ticker symbol for the data series.</param>
#/ <param name="startDate">The starting date/time for the data series.</param>
#/ <param name="endDate">The ending date/time for the data series.</param>
function getDailyData($ticker, $startDate, $endDate) {
    #
    # Get the data from a database or by other means.
    #
	#if($timeformat == 'charttime') {
	#	$startDate = chartTimeToDate($startDate, 'Y-m-d');
	#	$endDate = chartTimeToDate($endDate, 'Y-m-d');
	#}
	generateData($ticker, $startDate, $endDate);
}

function getDailyDataOrig($ticker, $startDate, $endDate) {
    #
    # In this demo, we use a random number generator to generate the data. In
    # practice, you may get the data from a database or by other means.
    #
    #generateRandomData($ticker, $startDate, $endDate, 86400);
    generateData($ticker, $startDate, $endDate, 86400);
}

#/ <summary>
#/ Get weekly data series for timeStamps, highData, lowData, openData, closeData
#/ and volData.
#/ </summary>
#/ <param name="ticker">The ticker symbol for the data series.</param>
#/ <param name="startDate">The starting date/time for the data series.</param>
#/ <param name="endDate">The ending date/time for the data series.</param>
function getWeeklyDataOrig($ticker, $startDate, $endDate) {
    #
    # If you do not have weekly data, you may call "getDailyData(startDate, endDate)"
    # to get daily data, then call "convertDailyToWeeklyData()" to convert to weekly
    # data.
    #
    generateRandomData($ticker, $startDate, $endDate, 86400 * 7);
}

function getWeeklyData($ticker, $startDate, $endDate) {
    #
    # If you do not have weekly data, you may call "getDailyData(startDate, endDate)"
    # to get daily data, then call "convertDailyToWeeklyData()" to convert to weekly
    # data.
    #
	getDailyData($ticker, $startDate, $endDate);
	convertDailyToWeeklyData();
}

#/ <summary>
#/ Get monthly data series for timeStamps, highData, lowData, openData, closeData
#/ and volData.
#/ </summary>
#/ <param name="ticker">The ticker symbol for the data series.</param>
#/ <param name="startDate">The starting date/time for the data series.</param>
#/ <param name="endDate">The ending date/time for the data series.</param>
function getMonthlyDataOrig($ticker, $startDate, $endDate) {
    #
    # If you do not have weekly data, you may call "getDailyData(startDate, endDate)"
    # to get daily data, then call "convertDailyToMonthlyData()" to convert to
    # monthly data.
    #
    generateRandomData($ticker, $startDate, $endDate, 86400 * 30);
}

function getMonthlyData($ticker, $startDate, $endDate) {
    #
    # If you do not have weekly data, you may call "getDailyData(startDate, endDate)"
    # to get daily data, then call "convertDailyToMonthlyData()" to convert to
    # monthly data.
    #
	getDailyData($ticker, $startDate, $endDate);
	convertDailyToMonthlyData();
}

#/ <summary>
#/ Data generator designed to generate financial data from database.
#/ </summary>
#/ <param name="ticker">The ticker symbol for the data series.</param>
#/ <param name="startDate">The starting date/time for the data series.</param>
#/ <param name="endDate">The ending date/time for the data series.</param>


function generateData($ticker, $startDate, $endDate) {

	global $timeStamps, $volData, $highData, $lowData, $openData, $closeData;
	global $startDate, $endDate, $resolution;

	$SQL= "Select UNIX_TimeStamp(timestamp), openvalue, highvalue, lowvalue,  closevalue, volumevalue From ohlc_eod WHERE ticker='$ticker' AND timestamp >= '$startDate' AND timestamp <= '$endDate' ORDER by timestamp";

	mysql_connect("localhost", "test", "test");
	mysql_select_db("my_db");
	$result = mysql_query($SQL);

	while ($row = mysql_fetch_row($result)) {
		$timeStamps[] = $row[0];
		#$timeStamps[] = chartTime2($row[0]);
		$openData[] = $row[1];
		$highData[] = $row[2];
		$lowData[] = $row[3];
		$closeData[] = $row[4];
		$volData[] = $row[5];
	}

}


#/ <summary>
#/ A random number generator designed to generate realistic financial data.
#/ </summary>
#/ <param name="ticker">The ticker symbol for the data series.</param>
#/ <param name="startDate">The starting date/time for the data series.</param>
#/ <param name="endDate">The ending date/time for the data series.</param>
#/ <param name="resolution">The period of the data series.</param>
function generateRandomData($ticker, $startDate, $endDate, $resolution) {

    global $timeStamps, $volData, $highData, $lowData, $openData, $closeData;

    $db = new FinanceSimulator($ticker, $startDate, $endDate, $resolution);
    $timeStamps = $db->getTimeStamps();
    $highData = $db->getHighData();
    $lowData = $db->getLowData();
    $openData = $db->getOpenData();
    $closeData = $db->getCloseData();
    $volData = $db->getVolData();
}

#/ <summary>
#/ A utility to convert daily to weekly data.
#/ </summary>
function convertDailyToWeeklyData() {

    global $timeStamps;

    $tmpArrayMath1 = new ArrayMath($timeStamps);
    aggregateData($tmpArrayMath1->selectStartOfWeek());
}

#/ <summary>
#/ A utility to convert daily to monthly data.
#/ </summary>
function convertDailyToMonthlyData() {

    global $timeStamps;

    $tmpArrayMath1 = new ArrayMath($timeStamps);
    aggregateData($tmpArrayMath1->selectStartOfMonth());
}

#/ <summary>
#/ An internal method used to aggregate daily data.
#/ </summary>
function aggregateData(&$aggregator) {

    global $timeStamps, $volData, $highData, $lowData, $openData, $closeData;

    $timeStamps = $aggregator->aggregate($timeStamps, AggregateFirst);
    $highData = $aggregator->aggregate($highData, AggregateMax);
    $lowData = $aggregator->aggregate($lowData, AggregateMin);
    $openData = $aggregator->aggregate($openData, AggregateFirst);
    $closeData = $aggregator->aggregate($closeData, AggregateLast);
    $volData = $aggregator->aggregate($volData, AggregateSum);
}

#/ <summary>
#/ Create a financial chart according to user selections. The user selections are
#/ encoded in the query parameters.
#/ </summary>
function drawChart() {

    global $timeStamps, $volData, $highData, $lowData, $openData, $closeData,
        $compareData, $resolution;

    # In this demo, we just assume we plot up to the latest time. So end date is now.
    $endDate = chartTime2(time());

    # If the trading day has not yet started (before 9:30am), or if the end date is
    # on on Sat or Sun, we set the end date to 4:00pm of the last trading day
    while ((fmod2($endDate, 86400) < 9 * 3600 + 30 * 60) || (getChartWeekDay($endDate
        ) == 0) || (getChartWeekDay($endDate) == 6)) {
        $endDate = $endDate - fmod2($endDate, 86400) - 86400 + 16 * 3600;
    }

    # The duration selected by the user
   	$durationInDays = (int)($_REQUEST["TimeRange"]);
	#$durationInDays = 20;	# default chart 3 bulan

    # Compute the start date by subtracting the duration from the end date.
    $startDate = $endDate;
    if ($durationInDays >= 30) {
        # More or equal to 30 days - so we use months as the unit
        $YMD = getChartYMD($endDate);
        $startMonth = (int)($YMD / 100) % 100 - (int)($durationInDays / 30);
        $startYear = (int)($YMD / 10000);
        while ($startMonth < 1) {
            $startYear = $startYear - 1;
            $startMonth = $startMonth + 12;
        }
        $startDate = chartTime($startYear, $startMonth, 1);
    } else {
        # Less than 30 days - use day as the unit. The starting point of the axis is
        # always at the start of the day (9:30am). Note that we use trading days, so
        # we skip Sat and Sun in counting the days.
        $startDate = $endDate - fmod2($endDate, 86400) + 9 * 3600 + 30 * 60;
        for($i = 1; $i < $durationInDays; ++$i) {
            if (getChartWeekDay($startDate) == 1) {
                $startDate = $startDate - 3 * 86400;
            } else {
                $startDate = $startDate - 86400;
            }
        }
    }

    # The moving average periods selected by the user.
    $avgPeriod1 = 0;
    $avgPeriod1 = (int)($_REQUEST["movAvg1"]);
    $avgPeriod2 = 0;
    $avgPeriod2 = (int)($_REQUEST["movAvg2"]);

    if ($avgPeriod1 < 0) {
        $avgPeriod1 = 0;
    } else if ($avgPeriod1 > 300) {
        $avgPeriod1 = 300;
    }

    if ($avgPeriod2 < 0) {
        $avgPeriod2 = 0;
    } else if ($avgPeriod2 > 300) {
        $avgPeriod2 = 300;
    }

    # We need extra leading data points in order to compute moving averages.
    $extraPoints = 20;
    if ($avgPeriod1 > $extraPoints) {
        $extraPoints = $avgPeriod1;
    }
    if ($avgPeriod2 > $extraPoints) {
        $extraPoints = $avgPeriod2;
    }

    # Get the data series to compare with, if any.
    #$compareKey = trim($_REQUEST["CompareWith"]);
    #$compareData = null;
    #if (getData($compareKey, $startDate, $endDate, $durationInDays, $extraPoints)) {
    #      $compareData = $closeData;
    #}

    # The data series we want to get.
    $tickerKey = trim($_REQUEST["TickerSymbol"]);
    if (!getData($tickerKey, $startDate, $endDate, $durationInDays, $extraPoints)) {
        return errMsg("Please enter a valid ticker symbol" . $tickerKey);
    }

    # We now confirm the actual number of extra points (data points that are before
    # the start date) as inferred using actual data from the database.
    $extraPoints = count($timeStamps);
    for($i = 0; $i < count($timeStamps); ++$i) {
        if ($timeStamps[$i] >= $startDate) {
            $extraPoints = $i;
            break;
        }
    }

    # Check if there is any valid data
    if ($extraPoints >= count($timeStamps)) {
        # No data - just display the no data message.
        $errMsg = new MultiChart(400, 50);
		        $errMsg->addTitle2(Center, "No data available for the specified time period",
		            "arial.ttf", 10);
        return $errMsg;
        #return errMsg("No data available for the specified time period" . $endDate);
    }

    # In some finance chart presentation style, even if the data for the latest day
    # is not fully available, the axis for the entire day will still be drawn, where
    # no data will appear near the end of the axis.
    if ($resolution < 86400) {
        # Add extra points to the axis until it reaches the end of the day. The end
        # of day is assumed to be 16:00 (it depends on the stock exchange).
        $lastTime = $timeStamps[count($timeStamps) - 1];
        $extraTrailingPoints = (int)((16 * 3600 - fmod2($lastTime, 86400)) /
            $resolution);
        for($i = 0; $i < $extraTrailingPoints; ++$i) {
            $timeStamps[] = $lastTime + $resolution * ($i + 1);
        }
    }

    #
    # At this stage, all data are available. We can draw the chart as according to
    # user input.
    #

    #
    # Determine the chart size. In this demo, user can select 4 different chart
    # sizes. Default is the large chart size.
    #
    #$width = 780;
    #$mainHeight = 255;
    #$indicatorHeight = 80;
    $width = 900;
    $mainHeight = 325;
    $indicatorHeight = 90;

    #$size = $_REQUEST["ChartSize"];
    #if ($size == "S") {
    #    # Small chart size
    #    $width = 450;
    #    $mainHeight = 160;
    #    $indicatorHeight = 60;
    #} else if ($size == "M") {
    #    # Medium chart size
    #    $width = 620;
    #    $mainHeight = 215;
    #    $indicatorHeight = 70;
    #} else if ($size == "H") {
    #    # Huge chart size
    #    $width = 1000;
    #    $mainHeight = 320;
    #    $indicatorHeight = 90;
    #}

    # Create the chart object using the selected size
    $m = new FinanceChart($width);

    # Set the data into the chart object
    $m->setData($timeStamps, $highData, $lowData, $openData, $closeData, $volData,
        $extraPoints);

    #
    # We configure the title of the chart. In this demo chart design, we put the
    # company name as the top line of the title with left alignment.
    #
    $m->addPlotAreaTitle(TopLeft, $tickerKey);

    # We displays the current date as well as the data resolution on the next line.
    $resolutionText = "";
    if ($resolution == 30 * 86400) {
        $resolutionText = "Monthly";
    } else if ($resolution == 7 * 86400) {
        $resolutionText = "Weekly";
    } else if ($resolution == 86400) {
        $resolutionText = "Daily";
    } else if ($resolution == 900) {
        $resolutionText = "15-min";
    }

    $m->addPlotAreaTitle(BottomLeft, sprintf(
        "<*font=arial.ttf,size=8*>%s - %s chart", $m->formatValue(chartTime2(time()),
        "mmm dd, yyyy"), $resolutionText));

    # A copyright message at the bottom left corner the title area
    $m->addPlotAreaTitle(BottomRight,
        "<*font=arial.ttf,size=8*>(c) 2010 RbTradingSystem.com");
    #    "<*font=arial.ttf,size=8*>(c) Advanced Software Engineering");

    #
    # Add the first techical indicator according. In this demo, we draw the first
    # indicator on top of the main chart.
    #
    addIndicator($m, $_REQUEST["Indicator1"], $indicatorHeight);

    #
    # Add the main chart
    #
    $m->addMainChart($mainHeight);

    #
    # Set log or linear scale according to user preference
    #
    #if ($_REQUEST["LogScale"] == "1") {
    #    $m->setLogScale(true);
    #}

    #
    # Set axis labels to show data values or percentage change to user preference
    #
    #if ($_REQUEST["PercentageScale"] == "1") {
    #    $m->setPercentageAxis();
    #}

    #
    # Draw any price line the user has selected
    #
    $mainType = $_REQUEST["ChartType"];
    if ($mainType == "Close") {
        $m->addCloseLine(0x000040);
    } else if ($mainType == "TP") {
        $m->addTypicalPrice(0x000040);
    } else if ($mainType == "WC") {
        $m->addWeightedClose(0x000040);
    } else if ($mainType == "Median") {
        $m->addMedianPrice(0x000040);
    }

    #
    # Add comparison line if there is data for comparison
    #
    if ($compareData != null) {
        if (count($compareData) > $extraPoints) {
            $m->addComparison($compareData, 0x0000ff, $compareKey);
        }
    }

    #
    # Add moving average lines.
    #
    addMovingAvg($m, $_REQUEST["avgType1"], $avgPeriod1, 0x663300);
    addMovingAvg($m, $_REQUEST["avgType2"], $avgPeriod2, 0x9900ff);

    #
    # Draw candlesticks or OHLC symbols if the user has selected them.
    #
    if ($mainType == "CandleStick") {
        $m->addCandleStick(0x33ff33, 0xff3333);
    } else if ($mainType == "OHLC") {
        $m->addHLOC(0x008800, 0xcc0000);
    }

    #
    # Add parabolic SAR if necessary
    #
    #if ($_REQUEST["ParabolicSAR"] == "1") {
    #    $m->addParabolicSAR(0.02, 0.02, 0.2, DiamondShape, 5, 0x008800, 0x000000);
    #}

    # Agung TT Dec 2009
    # Add price band/channel/envelop to the chart according to user selection
    #
    $bandType = $_REQUEST["Band"];
    if ($bandType == "BB") {
        $m->addBollingerBand(20, 2, 0x9999ff, 0xc06666ff);
    } else if ($bandType == "PTB") {
    	$m->addPriceChannel3(0x33ff33, 0xff3300, 0xc06666ff);
    	# addPriceChannel3($lineColorUp, $lineColorDown, $fillColor)
    } else if ($bandType == "DC") {
        $m->addDonchianChannel(20, 0x9999ff, 0xc06666ff);
    } else if ($bandType == "Envelop") {
        $m->addEnvelop(20, 0.1, 0x9999ff, 0xc06666ff);
    }

    #
    # Add volume bars to the main chart if necessary
    #
    if ($_REQUEST["Volume"] == "1") {
        $m->addVolBars($indicatorHeight, 0x99ff99, 0xff9999, 0xc0c0c0);
    }

    #
    # Add additional indicators as according to user selection.
    #
    addIndicator($m, $_REQUEST["Indicator2"], $indicatorHeight);
    addIndicator($m, $_REQUEST["Indicator3"], $indicatorHeight);
    addIndicator($m, $_REQUEST["Indicator4"], $indicatorHeight);

	# TAMBAH BACKGROUND Agung TT
	#$m->setWallpaper(dirname(__FILE__)."/tile.gif");

	#$plotarea = $m->getPlotArea();
	#$m->setBackground(0xffffff, 0xe0e0e0);

    return $m;
}

#/ <summary>
#/ Add a moving average line to the FinanceChart object.
#/ </summary>
#/ <param name="m">The FinanceChart object to add the line to.</param>
#/ <param name="avgType">The moving average type (SMA/EMA/TMA/WMA).</param>
#/ <param name="avgPeriod">The moving average period.</param>
#/ <param name="color">The color of the line.</param>
#/ <returns>The LineLayer object representing line layer created.</returns>
function addMovingAvg(&$m, $avgType, $avgPeriod, $color) {
    if ($avgPeriod > 1) {
        if ($avgType == "SMA") {
            return $m->addSimpleMovingAvg($avgPeriod, $color);
        } else if ($avgType == "EMA") {
            return $m->addExpMovingAvg($avgPeriod, $color);
        } else if ($avgType == "TMA") {
            return $m->addTriMovingAvg($avgPeriod, $color);
        } else if ($avgType == "WMA") {
            return $m->addWeightedMovingAvg($avgPeriod, $color);
        }
    }
    return null;
}

#/ <summary>
#/ Add an indicator chart to the FinanceChart object. In this demo example, the
#/ indicator parameters (such as the period used to compute RSI, colors of the lines,
#/ etc.) are hard coded to commonly used values. You are welcome to design a more
#/ complex user interface to allow users to set the parameters.
#/ </summary>
#/ <param name="m">The FinanceChart object to add the line to.</param>
#/ <param name="indicator">The selected indicator.</param>
#/ <param name="height">Height of the chart in pixels</param>
#/ <returns>The XYChart object representing indicator chart.</returns>
function addIndicator(&$m, $indicator, $height) {
    if ($indicator == "RSI") {
        return $m->addRSI($height, 14, 0x800080, 20, 0xff6666, 0x6666ff);
    } else if ($indicator == "NewHigh") {
    	return $m->addNewHigh($height, 0x800080);
    } else if ($indicator == "VolAcc") {
    	return $m->addVolAccumulation($height, 0x800080);
    } else if ($indicator == "StochRSI") {
        return $m->addStochRSI($height, 14, 0x800080, 30, 0xff6666, 0x6666ff);
    } else if ($indicator == "MACD") {
        return $m->addMACD($height, 26, 12, 9, 0x0000ff, 0xff00ff, 0x008000);
    } else if ($indicator == "FStoch") {
        return $m->addFastStochastic($height, 14, 3, 0x006060, 0x606000);
    } else if ($indicator == "SStoch") {
        return $m->addSlowStochastic($height, 14, 3, 0x006060, 0x606000);
    } else if ($indicator == "ATR") {
        return $m->addATR($height, 14, 0x808080, 0x0000ff);
    } else if ($indicator == "ADX") {
        return $m->addADX($height, 14, 0x008000, 0x800000, 0x000080);
    } else if ($indicator == "DCW") {
        return $m->addDonchianWidth($height, 20, 0x0000ff);
    } else if ($indicator == "BBW") {
        return $m->addBollingerWidth($height, 20, 2, 0x0000ff);
    } else if ($indicator == "DPO") {
        return $m->addDPO($height, 20, 0x0000ff);
    } else if ($indicator == "PVT") {
        return $m->addPVT($height, 0x0000ff);
    } else if ($indicator == "Momentum") {
        return $m->addMomentum($height, 12, 0x0000ff);
    } else if ($indicator == "Performance") {
        return $m->addPerformance($height, 0x0000ff);
    } else if ($indicator == "ROC") {
        return $m->addROC($height, 12, 0x0000ff);
    } else if ($indicator == "OBV") {
        return $m->addOBV($height, 0x0000ff);
    } else if ($indicator == "AccDist") {
        return $m->addAccDist($height, 0x0000ff);
    } else if ($indicator == "CLV") {
        return $m->addCLV($height, 0x0000ff);
    } else if ($indicator == "WilliamR") {
        return $m->addWilliamR($height, 14, 0x800080, 30, 0xff6666, 0x6666ff);
    } else if ($indicator == "Aroon") {
        return $m->addAroon($height, 14, 0x339933, 0x333399);
    } else if ($indicator == "AroonOsc") {
        return $m->addAroonOsc($height, 14, 0x0000ff);
    } else if ($indicator == "CCI") {
        return $m->addCCI($height, 20, 0x800080, 100, 0xff6666, 0x6666ff);
    } else if ($indicator == "EMV") {
        return $m->addEaseOfMovement($height, 9, 0x006060, 0x606000);
    } else if ($indicator == "MDX") {
        return $m->addMassIndex($height, 0x800080, 0xff6666, 0x6666ff);
    } else if ($indicator == "CVolatility") {
        return $m->addChaikinVolatility($height, 10, 10, 0x0000ff);
    } else if ($indicator == "COscillator") {
        return $m->addChaikinOscillator($height, 0x0000ff);
    } else if ($indicator == "CMF") {
        return $m->addChaikinMoneyFlow($height, 21, 0x008000);
    } else if ($indicator == "NVI") {
        return $m->addNVI($height, 255, 0x0000ff, 0x883333);
    } else if ($indicator == "PVI") {
        return $m->addPVI($height, 255, 0x0000ff, 0x883333);
    } else if ($indicator == "MFI") {
        return $m->addMFI($height, 14, 0x800080, 30, 0xff6666, 0x6666ff);
    } else if ($indicator == "PVO") {
        return $m->addPVO($height, 26, 12, 9, 0x0000ff, 0xff00ff, 0x008000);
    } else if ($indicator == "PPO") {
        return $m->addPPO($height, 26, 12, 9, 0x0000ff, 0xff00ff, 0x008000);
    } else if ($indicator == "UO") {
        return $m->addUltimateOscillator($height, 7, 14, 28, 0x800080, 20, 0xff6666,
            0x6666ff);
    } else if ($indicator == "Vol") {
        return $m->addVolIndicator($height, 0x99ff99, 0xff9999, 0xc0c0c0);
    } else if ($indicator == "V125") {
        return $m->addVolAvg($height, 0x99ff99, 0xff9999, 0xc0c0c0);
    } else if ($indicator == "RiskLevel") {
    	return $m->addRiskLevel($height, 0x99ff99, 0xff9999, 0xc0c0c0);
    } else if ($indicator == "TRIX") {
        return $m->addTRIX($height, 12, 0x0000ff);
    }
    return null;
}

#/ <summary>
#/ Creates a dummy chart to show an error message.
#/ </summary>
#/ <param name="msg">The error message.
#/ <returns>The BaseChart object containing the error message.</returns>
function errMsg($msg) {
    $m = new MultiChart(400, 200);
    $textBoxObj = $m->addTitle2(Center, $msg, "arial.ttf", 10);
    $textBoxObj->setMaxWidth($m->getWidth());
    return $m;
}

# create the finance chart
$c = drawChart();

#$c->setColors($whiteOnBlackPalette);	# LATAR BELAKANG


#Create the image and save it in a temporary location
$chart1URL = $c->makeSession("chart1");

#Create an image map for the chart
$imageMap = $c->getHTMLImageMap("", "", "title='".$c->getToolTipDateFormat()." {value|G}'");
#m.getHTMLImageMap("", "", "title='" & m.getToolTipDateFormat() & " {value|G}'")

#output the chart
#header("Content-type: image/png");
#print($c->makeChart2(PNG));
?>

<html>
<body leftMargin=0 topMargin=0>
<img src="myimage.php?<?php echo $chart1URL?>" border="0" usemap="#map1">
<map name="map1">
<?php echo $imageMap?>
</map>
</body>
</html>

  Re: Finance Demo Chart
Posted by Papa Raihan on Jan-30-2010 23:01
Dear Mr. Kwan

It would be great if you have sample php file which are ready in accessing the data from database, then I can adjust with configuration of the database (user, host, db) table name, and the attributes such as : timestamps, ticker, openvalue, highvalue, lowvalue, closevalue, and volumevalue.

Thanks Mr. Kwan

Kind Regards
PR

  Re: Finance Demo Chart
Posted by Peter Kwan on Jan-31-2010 14:55
Hi Papa,

There error means that your database query returns no data that are within the requested time period.

Do you know what is your database query? Have you tested if the database query is returning any data that is within the requested time period?

I found that the code that generates your database query is:

$SQL= "Select UNIX_TimeStamp(timestamp), openvalue, highvalue, lowvalue,  closevalue, volumevalue From ohlc_eod WHERE ticker='$ticker' AND timestamp >= '$startDate' AND timestamp <= '$endDate' ORDER by timestamp";

I do not know what are the variables $ticker, $startDate and $endDate that you use. I suggest you print out what is the resulting $SQL, then manually inspect whether the SQL is correct, and try to see if that SQL is returning any data that is within the requested time period (use the SQL in phpmyadmin to test if the query actually works).

If the query is incorrect, please modify your SQL query so that it can return the correct rows.

Just by inspecting your code, I suspect the $startDate and $endDate in the MySQL are incorrect. In PHP, the date/time format is chartTime. In your SQL, you use UNIX_TimeStamp, which seems to suggest the timestamp column is of a date/time type in your database schema. In this case, your MySQL may expect the date/time in ISO 8601 format (depends on your database schema). You would need to convert the $startDate and $endDate to the format expected by your database schema. (Hint: Use getChartYMD to convert the chartTime to yyyymmdd, then convert it to the format expected by your database schema.)

Also, please check if the data in your database really contains data within the selected date range. For example, if your select to show a chart for the last 30 days, but your data are 1 year ago, they will not be used.

Finally, I found that in your code in the attached file contains, you use:

$timeStamps[] = $row[0];
#$timeStamps[] = chartTime2($row[0]);

But in your earlier message, you use:

#$timeStamps[] = $row[0];
$timeStamps[] = chartTime2($row[0]);

Note that the correct code is:

#$timeStamps[] = $row[0];
$timeStamps[] = chartTime2($row[0]);

In other words, chartTime2 should be used, because ChartDirector does not expect date/time in UNIX_Timestamp format.

Hope this can help.

Regards
Peter Kwan

  Re: Finance Demo Chart
Posted by Papa Raihan on Feb-01-2010 18:00
Attachments:
Dear Mr. Kwan,

Thank you, it helps me a lot.

I modified the function generateData to be:
function generateData($ticker, $startDate, $endDate) {

include "konfig.php";
global $timeStamps, $volData, $highData, $lowData, $openData, $closeData;
    global $startDate, $endDate, $resolution;

$startDateYMD = getChartYMD($startDate);
$endDateYMD = getChartYMD($endDate);

$conn = mysql_connect("$hostmysql","$username","$password");
if (!$conn) die ("connection failed");
mysql_select_db($database,$conn) or die ("Database not found");

$SQL= "Select UNIX_TimeStamp(timestamp), openvalue, highvalue, lowvalue,  closevalue, volumevalue From ohlc_eod WHERE ticker='$ticker' AND timestamp >= '$startDateYMD' AND timestamp <= '$endDateYMD' ORDER by timestamp";

$result = mysql_query($SQL);

while ($row = mysql_fetch_row($result)) {
#$timeStamps[] = $row[0];
$timeStamps[] = chartTime2($row[0]);
$openData[] = $row[1];
$highData[] = $row[2];
$lowData[] = $row[3];
$closeData[] = $row[4];
$volData[] = $row[5];
}
}


And it was successful on my test script (attached - test3.php)

But when I incorporate to my dev script, previously I attached, the error still the same, I captured the error, the timeStamps still NULL ( pls see attached - error.png)

Thank you for your prompt reply....

Cheers
PR
test3.php
<?php
require_once("../lib/LibRbtsChart.php");
include "konfig.php";

$endDate = chartTime2(time());
echo "End Date : " . $endDate . "<br>";
$endDateYMD = getChartYMD($endDate);
echo "getChartYMD(End Date) : " . $endDateYMD . "<br>";

$ticker='ANTM';

$durationInDays=30;

# Compute the start date by subtracting the duration from the end date.
$startDate = $endDate;
if ($durationInDays >= 30) {
	# More or equal to 30 days - so we use months as the unit
	$YMD = getChartYMD($endDate);
	$startMonth = (int)($YMD / 100) % 100 - (int)($durationInDays / 30);
	$startYear = (int)($YMD / 10000);
	while ($startMonth < 1) {
		$startYear = $startYear - 1;
		$startMonth = $startMonth + 12;
	}
	$startDate = chartTime($startYear, $startMonth, 1);
} else {
	# Less than 30 days - use day as the unit. The starting point of the axis is
	# always at the start of the day (9:30am). Note that we use trading days, so
	# we skip Sat and Sun in counting the days.
	$startDate = $endDate - fmod2($endDate, 86400) + 9 * 3600 + 30 * 60;
	for($i = 1; $i < $durationInDays; ++$i) {
		if (getChartWeekDay($startDate) == 1) {
			$startDate = $startDate - 3 * 86400;
		} else {
			$startDate = $startDate - 86400;
		}
	}
}



echo "Start Date : " . $startDate . "<br>";
$startDateYMD = getChartYMD($startDate);
echo "getChartYMD(Start Date) : " . $startDateYMD . "<br>";

$timeStamps = NULL;
$openData = NULL;
$highData = NULL;
$lowData = NULL;
$closeData = NULL;
$volData = NULl;

generateData ($ticker, $startDate, $endDate);

$row=0;
while ($row < count($timeStamps)) {
	echo "Date : " .$timeStamps[$row];
	echo " O : " .$openData[$row];
	echo " H : " .$highData[$row];
	echo " L : " .$lowData[$row];
	echo " C : " .$closeData[$row];
	echo " V : " .$volData[$row]. "<br>";

	$row = $row+1;
}


function generateData($ticker, $startDate, $endDate) {

	include "konfig.php";
	global $timeStamps, $volData, $highData, $lowData, $openData, $closeData;
    global $startDate, $endDate, $resolution;

	$startDateYMD = getChartYMD($startDate);
	$endDateYMD = getChartYMD($endDate);

	$conn = mysql_connect("$hostmysql","$username","$password");
	if (!$conn) die ("connection failed");
	mysql_select_db($database,$conn) or die ("Database not found");

	$SQL= "Select UNIX_TimeStamp(timestamp), openvalue, highvalue, lowvalue,  closevalue, volumevalue From ohlc_eod WHERE ticker='$ticker' AND timestamp >= '$startDateYMD' AND timestamp <= '$endDateYMD' ORDER by timestamp";

	$result = mysql_query($SQL);

	while ($row = mysql_fetch_row($result)) {
		#$timeStamps[] = $row[0];
		$timeStamps[] = chartTime2($row[0]);
		$openData[] = $row[1];
		$highData[] = $row[2];
		$lowData[] = $row[3];
		$closeData[] = $row[4];
		$volData[] = $row[5];
	}
}

?>
error.png

  Re: Finance Demo Chart
Posted by Papa Raihan on Feb-01-2010 18:07
Attachments:
Sorry wrong error message attachment...

Here we go (error.png)
error.png

  Re: Finance Demo Chart
Posted by Peter Kwan on Feb-01-2010 23:21
Hi Papa,

If your "test3.php" does output something, it just means the query returns something. It is still not sure if the rows it returned is within the time range.

For testing, may be you can try the following things:

(b) In your "test3.php", as well as in your real code, please change:

function generateData($ticker, $startDate, $endDate) {

to:

$SQL = 0;
function generateData($ticker, $startDate, $endDate) {
      #make the $SQL global, so we can see its value outside the function
      global $SQL;

(b) In your "test3.php", please change the printing code to:

echo "SQL: [[[$SQL]]]<br>";

while ($row < count($timeStamps)) {
echo "Date : " . getChartYMD($timeStamps[$row]);
echo " O : " .$openData[$row];
echo " H : " .$highData[$row];
echo " L : " .$lowData[$row];
echo " C : " .$closeData[$row];
echo " V : " .$volData[$row]. "<br>";

$row = $row+1;
}

Then please inform me what is the result of "test3.php".

(c) In your real code, please change the $errMsg to:

$t = $errMsg->addTitle2(Center, "No data available for the specified time period\\n$SQL\\n".
    "ExtraPoints=$extraPoints\\nTimeStamps=".count($timeStamps), "arial.ttf", 10);
$t->setMaxWidth(350);

Please let me know what is the error message.


Regards
Peter Kwan

  Re: Finance Demo Chart
Posted by Papa Raihan on Feb-02-2010 00:14
Attachments:
Here's the output:
SQL: [[[Select UNIX_TimeStamp(timestamp), openvalue, highvalue, lowvalue, closevalue, volumevalue From ohlc_eod WHERE ticker='ANTM' AND timestamp >= '20100101' AND timestamp <= '20100201' ORDER by timestamp]]]

And Finally I found the problem, I set the variable $startDate and $endDate as Global in the DrawChart function... it display the chart finally :)

Thanks God... Thanks Mr. Kwan :)

Here's the output attached :) (my_image.png)

Kind Regards
PR
myimage.png