/*
** AmiBroker/Win32 scripting Example
**
** File:	 Import2.js
** Created:	 Tomasz Janeczko, February 2nd, 2000
** Purpose:	 Import quotes from Yahoo's CSV history file
** Language: JScript (Windows Scripting Host)
**
** The data is stored in lines with following format
** Date,Open,High,Low,Close,Volume
**
*/


ImportCSV( "aapl.csv"	);

function ImportCSV( filename )
{
	var fso, f, r;
	var ForReading = 1;
	var AmiBroker;
	var ticker;
	var date;
	var quote;
	var fields;
	var stock;

	/* Create AmiBroker app object */
	AmiBroker = new ActiveXObject( "Broker.Application" );

	/* ... and file system object */
	fso = new ActiveXObject( "Scripting.FileSystemObject" );

	/* we use file name ( without extension ) as a ticker name */
	ticker = fso.GetBaseName( filename ).toUpperCase();

    /* add a ticker - this is safe operation, in case that	 */
    /* ticker already exists, AmiBroker returns existing one */
	/* we are doing this outside loop since the file contains */
	/* quotes of single stock only */
    stock = AmiBroker.Stocks.Add( ticker ); 

	/* open ASCII file */
	f = fso.OpenTextFile( filename, ForReading);

    /* notify the user */
	WScript.Echo( "Importing " + ticker );

	/* skip first line which contains format definition */
	f.SkipLine(); 

	/* read the file line by line */
	while ( !f.AtEndOfStream )
	{  
		  r =  f.ReadLine();
		  
		  /* split the lines using comma as a separator */
		  fields = r.split(","); 
		  
		  /* split date at - separator */
		  var datefld = fields[ 0 ].split("-");

		  /* ensure Y2K compliance by converting year to 4 digit number */
		  var year = parseInt( datefld[ 2 ] );
		  year += ( year < 50 ) ? 2000 : 1900;
		  datefld[ 2 ] = year.toString();

		  /* put date back all together */
		  datefld.join(" ");

		  date = new Date( datefld );

		  /* add a new quotation */
		  quote = stock.Quotations.Add( date.getVarDate() );
		  
		  /* put data into it */
		  quote.Open = parseFloat( fields[ 1 ] );
		  quote.High  = parseFloat( fields[ 2 ] );
		  quote.Low   = parseFloat( fields[ 3 ] );
		  quote.Close = parseFloat( fields[ 4 ] );
		  quote.Volume = parseInt( fields[ 5 ] );
		  
	}

	/* refresh ticker list and windows */
	AmiBroker.RefreshAll();

	/* notify the user */
	WScript.Echo( "Finished" );

}

