Monday, 14 May 2012

13. Trader - The first analyse


Finally, we have information and some formal controls which enable us to write some Japanese candle code. Still, three controls were added for that purpose. Also, string to double conversion was created. Issue is downloaded data are with decimal point, since we use decimal comma. New, constant was introduced commaCountry which could be Yes or No, and so instruct double stringToDouble(string valuE) hot to perform conversion.



I started with simple element colour of trading day where whit means that closing price is higher then opening one. Also, if day closes with the same prices then day has no colour. Pattern analyse is based on such simple steps which together provides possible price direction.


Code:
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\"; // constant is 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;
        }

        public string[] arrDay0 = new string[7];        // working array - today
        public string[] arrDay1 = new string[7];        // working array - yesterday
        public string[] arrDay2 = new string[7];        // working array - day before yesterday
        public string[] arrDay3 = new string[7];        // working array - 3 days before
        public string[] arrDay4 = new string[7];        // working array - 4 days before
        public string commaCountry;                     // if your country uses decimal comma change yeS to nO below

        const string yeS = "Yes";                       // yes constant
        const string nO = "No";                         // no constant
        const string blacK = "Black";                   // black constant
        const string whitE = "White";                   // white constant
       
        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
            makeHistoryHeader();        // header init of historyTable
            commaCountry = yeS;         // change yeS to nO if you do not use decimal comma
        }

        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
            fillWorkingArrays(0,6);                           // fill daily working arrays
            zeroDay.Text = historyGrid[0, 0].Value.ToString(); // show zero day to analyze
            urlHistory.BackColor = Color.White;                     // restore back color
        }

        private void getHistory_Click(object sender, EventArgs e)
        {
            if (urlHistory.Text=="")        // is url entered?
            {MessageBox.Show("URL field is empty.", "No infomation"); // url is not enetred
                goto end1;} // no action. goto end
            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
            urlHistory.BackColor = Color.LightGreen;    // if file was created make BackColor LightGreen
          //  System.Diagnostics.Process.Start(selectedIndices);    // remove comment and result can be seen in text editor
        end1: ;
        }

        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();
        }
       
        private void fillWorkingArrays(int k, int kC)
        {
            for (int m = 0; m <kC ; m++)                                // copy data of kC columns to array
            {
                if (historyGrid.RowCount <= k +kC-1) {                      // we need five more rows from selected
                    MessageBox.Show("No rows","Selection failed" );
                    goto end1;                                           // cause to exit for loop
                }
                arrDay0[m] = historyGrid[m, k].Value.ToString();            // copy days in their arrays
                arrDay1[m] = historyGrid[m, k+1].Value.ToString();
                arrDay2[m] = historyGrid[m, k+2].Value.ToString();
                arrDay3[m] = historyGrid[m, k+3].Value.ToString();
                arrDay4[m] = historyGrid[m, k+4].Value.ToString();
                //historyTable.Rows.CopyTo(arrDay0,1)
            }
        end1: ;
        }

        private void historyGrid_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            int r = e.RowIndex;                                 // get a row index
            zeroDay.Text = historyGrid[0, r].Value.ToString();  // put date in zeroDay field
            fillWorkingArrays(r,6);    // selected raw index will be 0 day -> "today". this is for lates market analyse.
            analyseResults.Items.Clear(); // clear listbox
        }

        private double stringToDouble(string valuE)
        {
            double mla;
            if (commaCountry == yeS)
            { mla = Convert.ToDouble(valuE.Replace(".", ",")); }  // but if you use decimal comma we need fix
            else
            { mla = Convert.ToDouble(valuE); } // convert string to double - open price
            return mla;
        }
        private string dayColor( string[] aR)
        {
            string mE = "Day color : ";              // name of routine
            string coloR;                           // color of the day
            double openP;                           // opening price
            double closeR;                          // closing price
            openP = stringToDouble(aR[1]);          // covert string to double
            closeR=stringToDouble(aR[2]);
            double closeMinusOpen = closeR - openP; // covert string to double
            if (closeMinusOpen > 0)                 // is close price bigger then oper
            {coloR = whitE;}                                // yes, white day
            else if (closeMinusOpen < 0) { coloR = blacK; } // no, black day
            else { coloR = nO; }                            // both prices are the same -> no color
            if (showDetails.Checked) { analyseResults.Items.Add(mE  +aR[0] + " -> " + coloR); }
            return coloR;
        }

        private void analyseDay_Click(object sender, EventArgs e)
        {
            string coloR = dayColor(arrDay0); // let's find color of the day
        }
       
    }
}

No comments:

Post a Comment