Repeat of a previous post, this time with the original code.
I’m creating a SVG candlestick graph but I’m having trouble producing the appropriate height.
The x value is determined by the opening price. In some cases the closing price is greater than the opening price, thus the position needs to be adjusted accordingly.
Because a negative value produces an error, i.e no rectangle at all, I need to take the difference between the opening and closing price and add this value to the x position.
Here is the code I have now. How would I effectively execute this type of adjustment?
I considered a foreach statement, but my php knowledge is limited and I kept running in to errors.
EDITED
X value is incremented. Y value is opening price.
<?php
$open_price = array(5,10,15,20,25,30);
$closing_price = array (3,15,50,15,14);
$svg = '<svg id="main_graph" xmlns="http://www.w3.org/2000/svg" version="1.1" height="400" width="600" style="border:1px solid black;">';
$bars;
for ($i=0, $count = count($open_price); $i<$count; $i++)
{
$calculation = ($open_price[$i])-($closing_price[$i]);
$bars .= '<rect x="'. $i * 5 . '" y="' . $open_price[$i] . '" width="20" height="' . $calculation . '" fill="blue"/>';
};
echo $graph = $svg . $bars . '</svg>';
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Crazy Bars</title>
<style type="text/css">
#main_graph {margin-left: 100px;}
</style>
</head>
<body>
</body>
</html>
You probably want the height to be the
absolute valueof the difference between closing price and opening price. Use php’sabs()function to calculate it.Then, if you wanted the bar to show in a downward direction for negative price movement, you’d want to adjust the y value as well.
This code will keep your x value constant, and cause the bar to show the price range. The bar height will be the absolute value of the price difference, and the bar’s y position will be the lower of the opening or closing price.