Graph stock prices downloaded from the internet in C#

[graph stock prices]

This example uses techniques described in other examples to graph stock prices downloaded from the internet. it’s based on these two examples:

The program contains a Timer that executes once per minute. Its Tick event handler uses code from the first example to get a stock price. The program then uses code from the second example to graph the prices it has saved.

There are some difference in this example, particularly in the graphing code. For example, the earlier graphing example builds its data when it starts. This example builds its data over time.

The program stores its data in the following variables.

// The data.
private List<DateTime> Times = new List<DateTime>();
private List<PointF> Prices = new List<PointF>();

The previous graphing example stored its data as PointF values. This example is graphing time versus price, so its data doesn’t really involve PointF values. To make the graphing easier, the program stores the data in the Prices list. The X values for the points in the list simply increment (0, 1, 2, …) so the program can give each data point a different coordinate.

When it stores a price value, the program also stores the time in the Times list. Later when it’s drawing the graph it uses that list to draw the labels below the X axis.

The other biggest change to the earlier examples is that this example only keeps a limited amount of data. After it’s been running for a while, it will collect too much data too fit on the graph. You could make the program display the graph in a scrolled window, but this example simply deletes the oldest values if it won’t all fit. The following code shows how it does that.

// Make sure we don't have too many values.
const float pix_per_x = 20;
while ((Times.Count - 1) * pix_per_x > (GraphXmax - GraphXmin))
{
    Times.RemoveAt(0);
    Prices.RemoveAt(0);
}

This code compares the amount of horizontal space needed by the data to the space available. As long as there is too much data, the program deletes the oldest time and price data.

This is a complicated example so there’s a lot more happening. See the earlier examples and download the code to learn about additional details.


Download Example   Follow me on Twitter   RSS feed   Donate




About RodStephens

Rod Stephens is a software consultant and author who has written more than 30 books and 250 magazine articles covering C#, Visual Basic, Visual Basic for Applications, Delphi, and Java.
This entry was posted in finance, internet, mathematics, web and tagged , , , , , , , , , , , , , . Bookmark the permalink.

2 Responses to Graph stock prices downloaded from the internet in C#

  1. Nathan says:

    Hi Rod,

    Once again, I’m super-impressed with your work!

    Take care,

    Nathan

Leave a Reply

Your email address will not be published. Required fields are marked *