Wednesday, 9 May 2012

9. Trader - Read trading days as needed


New field fillHistoryTableDays and label were added and now we can upload data for stock analyse as needed. Default value is ten days which is more then appropriate. Usually we need five days.
First time, I used ToInt16 conversion and for statement.
void fillHistoryT(int j) now has parameter to provide number of days needed.

Code as usually :-) In bold what was changed.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Net;

namespace Stocker
{
    public partial class Form1 : Form
    {
        DataTable historyTable = new DataTable();   // histroyTable declaration
        public Form1()
        {
            InitializeComponent();
        }
        public string workingPath = @"P:\Private\Analizator\"; // we need this variable as working directory on disk P

        private void Form1_DoubleClick(object sender, EventArgs e)
        {
            Environment.Exit(0);        // double click on form to end application- just for quick exit when testing
        }

        public DataTable makeHistoryHeader() {
            historyTable.Columns.Add(new DataColumn("Date", typeof(string)));
            historyTable.Columns.Add(new DataColumn("Open", typeof(string)));
            historyTable.Columns.Add(new DataColumn("Close", typeof(string)));
            historyTable.Columns.Add(new DataColumn("High", typeof(string)));
            historyTable.Columns.Add(new DataColumn("Low", typeof(string)));
            historyTable.Columns.Add(new DataColumn("Volume", typeof(string)));
            historyGrid.DataSource = historyTable;
            historyGrid.AutoResizeColumns();                    // justify columns acording to header
            return historyTable;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            this.Text = "Stocker2012";  // put title on form bar
            this.Width = 1000;          // set form width
            this.Height = 500;          // set form height
            this.Top = 0;               // set position of form
            this.Left = 0;
            activeOnly.Checked = true;  // by default we would like to work only with active indicies
            // workingPath=@"P:\Private\Analizator\"; // this is my working directory on disk P
            makeHistoryHeader();        // header init of historyTable
        }
        public void getIndicesL()
        {
            string aPath;                       // working string to make path
            if (activeOnly.Checked == true)     // upon a checkbox state
                aPath = workingPath + "ActiveIndices.txt";  // if checked - this file
            else aPath = workingPath + "NonActiveIndices.txt"; // if not - other file

            listIndices.Items.Clear();  // clear listbox before filling

            using (FileStream fs = File.OpenRead(aPath))    // prepare filestream
            using (TextReader reader = new StreamReader(fs)) // use textreader
                while (reader.Peek() > -1)                      // read while end of file is reached
                    listIndices.Items.Add(reader.ReadLine());   // add line to listbox
            listIndices.Sorted = true;
        }

        private void menuStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
           
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Environment.Exit(0);        // quit application
        }

        private void getIndicies_Click(object sender, EventArgs e)
        {
            getIndicesL();
        }

        private void listIndices_SelectedIndexChanged(object sender, EventArgs e)
        {
            string part1bloom = "http://www.
internet.com/apps/data?pid=webpxta&Securities="; // first part of internet url histroy string
            string part2bloom = "&TimePeriod=5Y&Outfields=HDATE,PR006-H,PR007-H,PR008-H,PR005-H,PR013-H,&rnd=421"; // second part of
internet url histroy string
            urlHistory.Text = part1bloom + listIndices.SelectedItem.ToString()+ part2bloom; // construct whole url string
            historyTable.Clear();
            Int16 j = Convert.ToInt16( fillHistoryTableDays.Text);  // convert textbox text to int16
            fillHistoryT(j); // getting data from local disk        // invoke table filling
        }

        private void getHistory_Click(object sender, EventArgs e)
        {
            WebRequest req = WebRequest.Create(urlHistory.Text); // to use WebRequest we need to add "using System.Net;" row
            req.Proxy = null;                                       // i do not use proxy
            string selectedIndices = listIndices.SelectedItem.ToString();   // get selected indice
            selectedIndices=selectedIndices.Replace(":", "-");                      // file name can not contain ":"
            selectedIndices = workingPath + selectedIndices + ".txt";    // make full path,file name and add .txt extension as it is text file
            using (WebResponse res = req.GetResponse())             // get response from internet
            using (Stream s = res.GetResponseStream())              // make a stream
            using (StreamReader sr = new StreamReader(s)) File.WriteAllText(selectedIndices, sr.ReadToEnd()); // save stream to file

          //  System.Diagnostics.Process.Start(selectedIndices);    // remove comment and result can be seen in text editor
 
        }
        void fillHistoryT(int j)
        {
            if (listIndices.SelectedItem == null) //formal control if any indice is selected
            {
                MessageBox.Show("Indice is not selected.", "No infomation"); // no
                goto end1; // no action
            }
            string selectedIndices = listIndices.SelectedItem.ToString();   // get selected indice
            selectedIndices = selectedIndices.Replace(":", "-");                      // file name can not contain ":"
            selectedIndices = workingPath + selectedIndices + ".txt";    // make full path,file name and add .txt extension as it is text file

            if (File.Exists(selectedIndices))
            {
                List<string> fileLines = File.ReadAllLines(selectedIndices).ToList(); // read file to list filelines
                historyTable.Clear();            // clear list before filling
                int fL = fileLines.Count - 2;       // newest date is two rows before end of file
                for (int i=0; i<j; i++)             // be in loop for number of days asked (j)
                {
                    string row = fileLines[fL-i];   // decrement file line number
                    string[] words = row.Split('"'); // words are splitted by " delimiter
                    historyTable.Rows.Add(words[0], words[1].ToString(), words[4].ToString(), words[2].ToString(), words[3].ToString(), words[5].ToString()); // fill table accordingly to header line
                }               
                historyGrid.DataSource = historyTable;  // refresh grid content
                historyGrid.AutoResizeColumns();        // adjust column width
            }
                else MessageBox.Show(selectedIndices + " file does not exist","Download needed");
        end1: ;
        }
        private void fillHistoryTable_Click(object sender, EventArgs e)
        {
            fillHistoryT(Convert.ToInt16(fillHistoryTableDays.Text));
        }

        private void activeOnly_CheckedChanged(object sender, EventArgs e)
        {
            if (activeOnly.Checked == true) // make take appropriate to state
                activeOnly.Text = "activeOnly"; // if checked
            else activeOnly.Text = "all";   // in not checked
            getIndicesL();
        }
       
    }
}


No comments:

Post a Comment