Ejemplo n.º 1
0
 /// <summary>
 /// Constructor with all data
 /// </summary>
 /// <param name="d"></param>
 public GenericStrategy(AnalysisData d)
 {
     this.data = d;
     this.adviceInfo = new TradePoints();
     this.last_position = 0;
     this.trailing_stop = -1;
 }
Ejemplo n.º 2
0
        /// <summary>
        /// Updated data from the last read/update point
        /// </summary>
        /// <param name="dataObj"></param>
        /// <returns></returns>
        public static int UpdateAnalysisData(AnalysisData dataObj)
        {
            int      lastDataIdx = dataObj.priceDataTbl.Count - 1;
            DateTime lastDateTime;

            if (lastDataIdx < 0)
            {
                lastDateTime = Settings.sysStartDataDate;
            }
            else
            {
                lastDateTime = dataObj.priceDataTbl[lastDataIdx].onDate;
            }

            databases.baseDS.priceDataDataTable tbl = new databases.baseDS.priceDataDataTable();
            databases.DbAccess.LoadData(tbl, dataObj.DataTimeScale.Code, lastDateTime, dataObj.DataStockCode);
            if (tbl.Count > 0)
            {
                //Delete the last data because the updated data will include this one.
                if (lastDataIdx >= 0)
                {
                    dataObj.priceDataTbl[lastDataIdx].ItemArray = tbl[0].ItemArray;
                    common.system.Concat(tbl, 1, dataObj.priceDataTbl);
                }
                else
                {
                    common.system.Concat(tbl, 0, dataObj.priceDataTbl);
                }
            }
            return(dataObj.priceDataTbl.Count - 1 - lastDataIdx);
        }
Ejemplo n.º 3
0
 /// <summary>
 /// Constructor with all data and parameter
 /// </summary>
 /// <param name="d"></param>
 /// <param name="p"></param>
 public GenericStrategy(AnalysisData d, Parameters p)
 {
     this.data = d;
     this.parameters = p;
     if (adviceInfo == null)
         this.adviceInfo = new TradePoints();
     this.last_position = 0;
     this.trailing_stop = -1;
 }
Ejemplo n.º 4
0
 public AnalysisData New(string stockCode)
 {
     AnalysisData newData = new AnalysisData();
     //newData.AccessMode = this.AccessMode;
     newData.AccessMode = commonClass.SysLibs.myAccessMode;
     newData.DataTimeScale = this.DataTimeScale;
     newData.DataTimeRange = this.DataTimeRange;
     newData.DataStockCode = stockCode;
     newData.LoadData();
     return newData;
 }
Ejemplo n.º 5
0
        public AnalysisData New(string stockCode)
        {
            AnalysisData newData = new AnalysisData();

            //newData.AccessMode = this.AccessMode;
            newData.AccessMode    = commonClass.SysLibs.myAccessMode;
            newData.DataTimeScale = this.DataTimeScale;
            newData.DataTimeRange = this.DataTimeRange;
            newData.DataStockCode = stockCode;
            newData.LoadData();
            return(newData);
        }
Ejemplo n.º 6
0
        private void DoRankingDB()
        {
            this.myValueType = ValueTypes.Amount;
            this.Amount2PercentDenominator = Settings.sysStockTotalCapAmt;

            resultTab.TabPages.Clear();
            StringCollection stockCodeList = codeListLb.myValues;
            StringCollection timeRangeList = timeRangeLb.myCheckedValues;

            string[] strategyList = common.system.Collection2List(strategyClb.myCheckedValues);
            progressBar.Value = 0; progressBar.Minimum = 0; progressBar.Maximum = stockCodeList.Count * timeRangeList.Count;

            EstimateOptions estimateOption = new EstimateOptions();

            for (int stockCodeId = 0; stockCodeId < stockCodeList.Count; stockCodeId++)
            {
                string    stockCode      = stockCodeList[stockCodeId].ToString();
                DataTable testRetsultTbl = CreateDataTable(timeRangeList, strategyList);
                common.controls.baseDataGridView resultGrid = CreateResultGrid(stockCode, testRetsultTbl);

                for (int colId = 0; colId < timeRangeList.Count; colId++)
                {
                    try
                    {
                        progressBar.Value++;
                        Application.DoEvents();
                        this.ShowReccount(progressBar.Value.ToString() + "/" + progressBar.Maximum.ToString());

                        AppTypes.TimeRanges      timeRange    = AppTypes.TimeRangeFromCode(timeRangeList[colId]);
                        application.AnalysisData analysisData = new application.AnalysisData(timeRange, timeScaleCb.myValue, stockCode,
                                                                                             commonClass.DataAccessMode.WebService);
                        for (int rowId = 0; rowId < strategyList.Length; rowId++)
                        {
                            testRetsultTbl.Rows[rowId][colId + 1] = 0;
                            //Analysis cached data so we MUST clear cache to ensure the system run correctly
                            application.Strategy.Data.ClearCache();
                            application.Strategy.Data.TradePoints advices = application.Strategy.Libs.Analysis(analysisData, strategyList[rowId]);
                            if (advices != null)
                            {
                                testRetsultTbl.Rows[rowId][colId + 1] =
                                    application.Strategy.Libs.EstimateTrading_Profit(analysisData, application.Strategy.Libs.ToTradePointInfo(advices), estimateOption);
                            }
                        }
                    }
                    catch (Exception er)
                    {
                        this.WriteError(stockCodeList[stockCodeId] + " : " + timeRangeList[colId] + " : " + strategyList[colId], er.Message);
                        //this.ShowError(er);
                    }
                }
            }
        }
Ejemplo n.º 7
0
        private void genDataBtn_Click(object sender, EventArgs e)
        {
            fGenData = !fGenData;
            timer1.Enabled = fGenData;
            timer1.Interval = (int)intervalEd.Value * 1000;
            
            if (myData==null) myData= new AnalysisData();
            myData.DataStockCode = codeEd.Text;

            genDataBtn.Text  = (fGenData ? "Stop" : "Start");
            this.ShowMessage(fGenData? "Running" : "Stopped");
            if (fGenData) Libs.Reset();

            codeEd.Enabled = !fGenData;
            intervalEd.Enabled = !fGenData;
        }
Ejemplo n.º 8
0
        private void DoBackTestUseDB()
        {
            this.myValueType = ValueTypes.Amount;
            this.Amount2PercentDenominator = Settings.sysStockTotalCapAmt;
            StringCollection strategyList   = strategyClb.myCheckedValues;
            StringCollection stockCodeList  = codeSelectLb.myValues;
            DataTable        testRetsultTbl = CreateEstimateTbl(strategyList);

            SetDataGrid(resultDataGrid, testRetsultTbl);

            progressBar.Value = 0; progressBar.Minimum = 0; progressBar.Maximum = stockCodeList.Count;

            EstimateOptions estOptions = new EstimateOptions();

            for (int rowId = 0; rowId < stockCodeList.Count; rowId++)
            {
                application.AnalysisData analysisData = new application.AnalysisData(periodicityEd.myTimeRange, periodicityEd.myTimeScale,
                                                                                     stockCodeList[rowId], commonClass.DataAccessMode.WebService);
                DataRow row = testRetsultTbl.Rows.Add(stockCodeList[rowId]);
                for (int colId = 0; colId < strategyList.Count; colId++)
                {
                    try
                    {
                        //Analysis cached data so we MUST clear cache to ensure the system run correctly
                        application.Strategy.Data.ClearCache();
                        application.Strategy.Data.TradePoints advices = application.Strategy.Libs.Analysis(analysisData, strategyList[colId]);
                        if (advices != null)
                        {
                            row[colId + 1] = application.Strategy.Libs.EstimateTrading_Profit(analysisData, application.Strategy.Libs.ToTradePointInfo(advices), estOptions);
                        }
                        else
                        {
                            row[colId + 1] = 0;
                        }
                    }
                    catch (Exception er)
                    {
                        this.WriteError(stockCodeList[rowId] + " : " + strategyList[colId], er.Message);
                        this.ShowError(er);
                    }
                }
                progressBar.Value++;
                this.ShowReccount(progressBar.Value.ToString() + "/" + progressBar.Maximum.ToString());
                Application.DoEvents();
            }
            SetEstimateDataGrid(application.Strategy.Libs.GetStrategyStats(testRetsultTbl));
        }
Ejemplo n.º 9
0
 public chartTest()
 {
     try
     {
         InitializeComponent();
         cbTimeScale.LoadData();
         cbChartType.LoadData();
         timer1.Interval      = 5000;
         myData               = new application.AnalysisData();
         myData.DataTimeScale = AppTypes.MainDataTimeScale;
         //LoadData();
     }
     catch (Exception er)
     {
         this.ShowError(er);
     }
 }
Ejemplo n.º 10
0
 public chartTest()
 {
     try
     {
         InitializeComponent();
         cbTimeScale.LoadData();
         cbChartType.LoadData();
         timer1.Interval = 5000;
         myData = new application.AnalysisData();
         myData.DataTimeScale  = AppTypes.MainDataTimeScale;
         //LoadData();
     }
     catch (Exception er)
     {
         this.ShowError(er);
     }
 }
Ejemplo n.º 11
0
        private void genDataBtn_Click(object sender, EventArgs e)
        {
            fGenData        = !fGenData;
            timer1.Enabled  = fGenData;
            timer1.Interval = (int)intervalEd.Value * 1000;

            if (myData == null)
            {
                myData = new AnalysisData();
            }
            myData.DataStockCode = codeEd.Text;

            genDataBtn.Text = (fGenData ? "Stop" : "Start");
            this.ShowMessage(fGenData? "Running" : "Stopped");
            if (fGenData)
            {
                Libs.Reset();
            }

            codeEd.Enabled     = !fGenData;
            intervalEd.Enabled = !fGenData;
        }
Ejemplo n.º 12
0
 private CurveItem PlotCandleStick(string curveName, Charts.Controls.baseGraphPanel graphPane, AnalysisData data,
                                   Color barUpColor,Color  barDnColor,Color bullCandleColor,Color bearCandleColor)
 {
     graphPane.myGraphObj.SetSeriesX(data.DateTime.Values, Charts.AxisType.DateAsOrdinal);
     CurveItem curveItem = graphPane.myGraphObj.AddCandleStick(curveName,
                                                               MakeChartValue(data.High),
                                                               MakeChartValue(data.Low),
                                                               MakeChartValue(data.Open),
                                                               MakeChartValue(data.Close),
                                                               MakeChartValue(data.Volume),
                                                               barUpColor,barDnColor,bullCandleColor,bearCandleColor);
     myCurveList.Add(curveItem, curveName, graphPane.myGraphObj.myGraphPane, graphPane.Name);
     return curveItem;
 }
Ejemplo n.º 13
0
        public tradeAnalysis()
        {
            try
            {
                InitializeComponent();
                this.myData = new AnalysisData();
                //Switch to use webservice
                this.myData.AccessMode = commonClass.DataAccessMode.WebService;

                this.SetMasterPane(new Point(0, activeIndicatorLV.Location.Y + activeIndicatorLV.Height));
                activeIndicatorLV.Visible = true;
                this.bgWorker.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(this.bgWorker_RunWorkerCompleted);
            }
            catch (Exception er)
            {
                this.ShowError(er);
            }
        }
Ejemplo n.º 14
0
        private void DoScreeningDB()
        {
            decimal          weight        = 0;
            StringCollection stockCodeList = stockCodeLb.myValues;
            StringCollection strategyList  = new StringCollection();

            for (int idx = 0; idx < tmpDS.screeningCriteria.Count; idx++)
            {
                if (tmpDS.screeningCriteria[idx].code != "" && tmpDS.screeningCriteria[idx].selected)
                {
                    if (strategyList.Contains(tmpDS.screeningCriteria[idx].code))
                    {
                        continue;
                    }
                    strategyList.Add(tmpDS.screeningCriteria[idx].code);
                }
            }
            DataTable testRetsultTbl = CreateDataTable(strategyList);

            SetDataGrid(resultDataGrid, testRetsultTbl);

            progressBar.Value = 0; progressBar.Minimum = 0; progressBar.Maximum = stockCodeList.Count;
            data.tmpDS.stockCodeRow stockCodeRow;
            bool fMatched = false;

            for (int rowId = 0; rowId < stockCodeList.Count; rowId++)
            {
                fMatched     = false;
                stockCodeRow = DataAccess.Libs.myStockCodeTbl.FindBycode(stockCodeList[rowId]);
                if (stockCodeRow == null)
                {
                    continue;
                }
                DataRow row = testRetsultTbl.NewRow();
                row[0] = stockCodeList[rowId];
                application.AnalysisData analysisData = new application.AnalysisData(timeRangeCb.myValue, timeScaleCb.myValue,
                                                                                     stockCodeRow.code, commonClass.DataAccessMode.WebService);
                for (int colId = 0; colId < strategyList.Count; colId++)
                {
                    try
                    {
                        //Analysis cached data so we MUST clear cache to ensure the system run correctly
                        application.Strategy.Data.ClearCache();
                        application.Strategy.Data.TradePoints tradePoints = application.Strategy.Libs.Analysis(analysisData, strategyList[colId]);
                        // BusinessInfo.Weight value is used as estimation value. The higher value, the better chance to match user need.
                        if (tradePoints != null && tradePoints.Count > 0)
                        {
                            weight = (decimal)(tradePoints[tradePoints.Count - 1] as TradePointInfo).BusinessInfo.Weight;
                            DataView criteriaView = new DataView(tmpDS.screeningCriteria);
                            criteriaView.RowFilter = tmpDS.screeningCriteria.codeColumn + "='" + strategyList[colId] + "' AND " +
                                                     tmpDS.screeningCriteria.selectedColumn + "=1";
                            Data.tmpDataSet.screeningCriteriaRow criteriaRow;
                            // If there is more than one criteria for the same code,
                            // matching one criteria is viewed as MATCHED , as OR operaror.
                            for (int idx = 0; idx < criteriaView.Count; idx++)
                            {
                                criteriaRow = (Data.tmpDataSet.screeningCriteriaRow)criteriaView[idx].Row;
                                if (weight < criteriaRow.min || weight > criteriaRow.max)
                                {
                                    continue;
                                }
                                row[colId + 1] = weight;
                                fMatched       = true;
                                break;
                            }
                        }
                    }
                    catch (Exception er)
                    {
                        this.WriteError(stockCodeList[rowId] + " : " + strategyList[colId], er.Message);
                        this.ShowError(er);
                    }
                }
                if (fMatched)
                {
                    testRetsultTbl.Rows.Add(row);
                }
                progressBar.Value++;
                this.ShowReccount(progressBar.Value.ToString() + "/" + progressBar.Maximum);
                Application.DoEvents();
            }
            this.ShowReccount(resultDataGrid.Rows.Count);
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Load stock price data withd some point ahead of the specified date range
        /// </summary>
        /// <param name="stockCode"></param>
        /// <param name="frDate">Start date </param>
        /// <param name="toDate">End date</param>
        /// <param name="timeScale">Time scale</param>
        /// <param name="noUnitAhead">the number of units(minute,day,hour,week...) to read beyond the start time[frDate].</param>
        /// <param name="toTbl">Table keeps loaded data</param>
        /// <param name="startIdx">specify the row where the data in [frDate,toDate] range starts</param>
        public static void LoadBaseAnalysisData(AnalysisData dataObj) 
        {
            int startIdx = dataObj.priceDataTbl.Count;

            int noUnitAhead = constNumberOfReadAheadUnit;

            DateTime toDate = common.Consts.constNullDate;
            DateTime frDate = common.Consts.constNullDate;
            if (!commonClass.AppTypes.GetDate(dataObj.DataTimeRange, out frDate, out toDate)) return;

            dataObj.priceDataTbl.Clear();
            if (noUnitAhead != 0 &&
                frDate != System.DateTime.MinValue && toDate != System.DateTime.MaxValue)
            {
                // Find start date that return sufficient rows as required by [noBarAhead]
                DateTime checkFrDate = common.Consts.constNullDate;
                DateTime checkToDate = frDate.AddSeconds(-1);
                int totalGotRowCount = 0, gotRowCount;
                decimal rangeScale = 1;
                //int loopPass = 0;
                while (true)
                {
                    //loopPass++;
                    switch (dataObj.DataTimeScale.Type)
                    {
                        case commonClass.AppTypes.TimeScaleTypes.Minnute:
                            checkFrDate = checkToDate.AddMinutes(-(int)(noUnitAhead * rangeScale));
                            break;
                        case commonClass.AppTypes.TimeScaleTypes.Hour:
                            checkFrDate = checkToDate.AddHours(-(int)(noUnitAhead * rangeScale));
                            break;
                        case commonClass.AppTypes.TimeScaleTypes.Day:
                            checkFrDate = checkToDate.AddDays(-(int)(noUnitAhead * rangeScale));
                            break;
                        case commonClass.AppTypes.TimeScaleTypes.Week:
                            checkFrDate = checkToDate.AddDays(-(int)(7 * noUnitAhead * rangeScale));
                            break;
                        case commonClass.AppTypes.TimeScaleTypes.Month:
                            checkFrDate = checkToDate.AddMonths(-(int)(noUnitAhead * rangeScale));
                            break;
                        case commonClass.AppTypes.TimeScaleTypes.Year:
                            checkFrDate = checkToDate.AddYears(-(int)(noUnitAhead * rangeScale));
                            break;
                        case commonClass.AppTypes.TimeScaleTypes.RealTime:
                            checkFrDate = checkToDate.AddMinutes(-(int)(commonClass.Settings.sysAutoRefreshInSeconds * noUnitAhead * rangeScale) / 60);
                            break;
                        default: common.system.ThrowException("Invalid parametter in calling to LoadStockPrice()");
                            break;
                    }
                    gotRowCount = DbAccess.GetTotalPriceRow(dataObj.DataTimeScale, checkFrDate, checkToDate, dataObj.DataStockCode);
                    //No more data ??
                    if (checkFrDate < commonClass.Settings.sysStartDataDate)
                        break;
                    //Sufficient data ??
                    totalGotRowCount += gotRowCount;
                    if (totalGotRowCount >= noUnitAhead) break;

                    checkToDate = checkFrDate.AddSeconds(-1);
                    if (gotRowCount == 0) rangeScale = noUnitAhead;
                    else
                    {
                        if ((decimal)(noUnitAhead - totalGotRowCount) / gotRowCount > 0)
                            rangeScale = rangeScale * (decimal)(noUnitAhead - totalGotRowCount) / gotRowCount;
                        if (rangeScale < 1) rangeScale = 1;
                    }
                }
                DbAccess.LoadData(dataObj.priceDataTbl, dataObj.DataTimeScale.Code, checkFrDate, frDate.AddSeconds(-1), dataObj.DataStockCode);
                startIdx = dataObj.priceDataTbl.Count - startIdx;
            }
            DbAccess.LoadData(dataObj.priceDataTbl, dataObj.DataTimeScale.Code, frDate, toDate, dataObj.DataStockCode);
            dataObj.FirstDataStartAt = startIdx;
        }
Ejemplo n.º 16
0
 //virtual public TradePoints Execute(AnalysisData data, double[] paras)
 virtual public TradePoints Execute(AnalysisData data, double[] paras)
 {
     this.data = data;
     parameters = new Parameters(paras);
     //??Bug fixed by Dung 11 Nov 2011
     if (adviceInfo == null)            
         adviceInfo = new TradePoints();
     StrategyExecute();
     return adviceInfo;
 }
Ejemplo n.º 17
0
        //Updated data from the last read/update point
        public static int UpdateAnalysisData(AnalysisData dataObj)
        {
            int lastDataIdx = dataObj.priceDataTbl.Count - 1;
            DateTime lastDateTime;
            if (lastDataIdx < 0) lastDateTime = commonClass.Settings.sysStartDataDate;
            else lastDateTime = dataObj.priceDataTbl[lastDataIdx].onDate;

            data.baseDS.priceDataDataTable tbl = new data.baseDS.priceDataDataTable();
            DbAccess.LoadData(tbl, dataObj.DataTimeScale.Code, lastDateTime, dataObj.DataStockCode);
            if (tbl.Count > 0)
            {
                //Delete the last data because the updated data will include this one.
                if (lastDataIdx >= 0)
                {
                    dataObj.priceDataTbl[lastDataIdx].ItemArray = tbl[0].ItemArray;
                    commonClass.AppLibs.DataConcat(tbl, 1, dataObj.priceDataTbl);
                }
                else commonClass.AppLibs.DataConcat(tbl, 0, dataObj.priceDataTbl);
            }
            return dataObj.priceDataTbl.Count - 1 - lastDataIdx;
        }
Ejemplo n.º 18
0
        private void DoScreeningDB()
        {
            decimal weight = 0;
            StringCollection stockCodeList = stockCodeLb.myValues;
            StringCollection strategyList = new StringCollection();

            for (int idx = 0; idx < tmpDS.screeningCriteria.Count; idx++)
            {
                if (tmpDS.screeningCriteria[idx].code != "" && tmpDS.screeningCriteria[idx].selected) 
                {
                    if (strategyList.Contains(tmpDS.screeningCriteria[idx].code)) continue;
                    strategyList.Add(tmpDS.screeningCriteria[idx].code);
                }
            }
            DataTable testRetsultTbl = CreateDataTable(strategyList);
            SetDataGrid(resultDataGrid, testRetsultTbl);

            progressBar.Value = 0; progressBar.Minimum=0; progressBar.Maximum = stockCodeList.Count;
            data.tmpDS.stockCodeRow stockCodeRow;
            bool fMatched = false;
            for (int rowId = 0; rowId < stockCodeList.Count; rowId++)
            {
                fMatched = false;
                stockCodeRow = DataAccess.Libs.myStockCodeTbl.FindBycode(stockCodeList[rowId]);
                if (stockCodeRow == null) continue;
                DataRow row = testRetsultTbl.NewRow();
                row[0] = stockCodeList[rowId];
                application.AnalysisData analysisData = new application.AnalysisData(timeRangeCb.myValue, timeScaleCb.myValue,
                                                                     stockCodeRow.code, commonClass.DataAccessMode.WebService);
                for (int colId = 0; colId < strategyList.Count; colId++)
                {
                    try
                    {
                        //Analysis cached data so we MUST clear cache to ensure the system run correctly
                        application.Strategy.Data.ClearCache();
                        application.Strategy.Data.TradePoints tradePoints = application.Strategy.Libs.Analysis(analysisData, strategyList[colId]);
                        // BusinessInfo.Weight value is used as estimation value. The higher value, the better chance to match user need.
                        if (tradePoints != null && tradePoints.Count > 0)
                        {
                            weight = (decimal)(tradePoints[tradePoints.Count - 1] as TradePointInfo).BusinessInfo.Weight;
                            DataView criteriaView = new DataView(tmpDS.screeningCriteria);
                            criteriaView.RowFilter = tmpDS.screeningCriteria.codeColumn + "='" + strategyList[colId] + "' AND " +
                                                     tmpDS.screeningCriteria.selectedColumn + "=1";
                            Data.tmpDataSet.screeningCriteriaRow criteriaRow;
                            // If there is more than one criteria for the same code,
                            // matching one criteria is viewed as MATCHED , as OR operaror. 
                            for (int idx = 0; idx < criteriaView.Count; idx++)
                            {
                                criteriaRow = (Data.tmpDataSet.screeningCriteriaRow)criteriaView[idx].Row;
                                if (weight < criteriaRow.min || weight > criteriaRow.max) continue;
                                row[colId + 1] = weight;
                                fMatched = true;
                                break;
                            }
                        }
                    }
                    catch (Exception er)
                    {
                        this.WriteError(stockCodeList[rowId] + " : " + strategyList[colId] , er.Message);
                        this.ShowError(er);
                    }
                }
                if (fMatched) testRetsultTbl.Rows.Add(row);
                progressBar.Value++;
                this.ShowReccount(progressBar.Value.ToString() + "/" + progressBar.Maximum);
                Application.DoEvents();
            }
            this.ShowReccount(resultDataGrid.Rows.Count);
        }
Ejemplo n.º 19
0
        /// <summary>
        /// Load stock price data withd some point ahead of the specified date range
        /// </summary>
        /// <param name="stockCode"></param>
        /// <param name="frDate">Start date </param>
        /// <param name="toDate">End date</param>
        /// <param name="timeScale">Time scale</param>
        /// <param name="noUnitAhead">the number of units(minute,day,hour,week...) to read beyond the start time[frDate].</param>
        /// <param name="toTbl">Table keeps loaded data</param>
        /// <param name="startIdx">specify the row where the data in [frDate,toDate] range starts</param>
        public static void LoadAnalysisData(AnalysisData dataObj)
        {
            int startIdx = dataObj.priceDataTbl.Count;
            if (dataObj.DataTimeRange == AppTypes.TimeRanges.None)
            {
                dataObj.priceDataTbl.Clear();
                databases.DbAccess.LoadData(dataObj.priceDataTbl, dataObj.DataTimeScale.Code, dataObj.DataStockCode, dataObj.DataMaxCount + constNumberOfReadAheadUnit);
                dataObj.FirstDataStartAt = 0;
                return;
            }
            int noUnitAhead = constNumberOfReadAheadUnit;

            DateTime toDate = common.Consts.constNullDate;
            DateTime frDate = common.Consts.constNullDate;
            if (!AppTypes.GetDate(dataObj.DataTimeRange, out frDate, out toDate)) return;

            databases.baseDS.priceDataStatDataTable priceStatTbl = databases.DbAccess.GetPriceDataStat(dataObj.DataTimeScale, dataObj.DataStockCode);
            if (priceStatTbl.Count == 0) return;
            DateTime dataMaxDateTime = priceStatTbl[0].maxDate;
            DateTime dataMinDateTime = priceStatTbl[0].minDate;
            int dataTotalCount = priceStatTbl[0].totalCount;

            if (toDate > dataMaxDateTime) toDate = dataMaxDateTime;
            if (frDate < dataMinDateTime) frDate = dataMinDateTime;
            dataObj.priceDataTbl.Clear();
            if (noUnitAhead != 0)
            {
                // Find start date that return sufficient rows as required by [noBarAhead]
                DateTime checkFrDate = common.Consts.constNullDate;
                DateTime checkToDate = frDate.AddSeconds(-1);
                int totalGotRowCount = 0, gotRowCount;
                decimal rangeScale = 1;
                //int loopPass = 0;
                while (true)
                {
                    //loopPass++;
                    switch (dataObj.DataTimeScale.Type)
                    {
                        case AppTypes.TimeScaleTypes.Minnute:
                            checkFrDate = checkToDate.AddMinutes(-(int)(noUnitAhead * rangeScale));
                            break;
                        case AppTypes.TimeScaleTypes.Hour:
                            checkFrDate = checkToDate.AddHours(-(int)(noUnitAhead * rangeScale));
                            break;
                        case AppTypes.TimeScaleTypes.Day:
                            checkFrDate = checkToDate.AddDays(-(int)(noUnitAhead * rangeScale));
                            break;
                        case AppTypes.TimeScaleTypes.Week:
                            checkFrDate = checkToDate.AddDays(-(int)(7 * noUnitAhead * rangeScale));
                            break;
                        case AppTypes.TimeScaleTypes.Month:
                            checkFrDate = checkToDate.AddMonths(-(int)(noUnitAhead * rangeScale));
                            break;
                        case AppTypes.TimeScaleTypes.Year:
                            checkFrDate = checkToDate.AddYears(-(int)(noUnitAhead * rangeScale));
                            break;
                        case AppTypes.TimeScaleTypes.RealTime:
                            //checkFrDate = checkToDate.AddMinutes(-(int)(commonClass.Settings.sysAutoRefreshInSeconds * noUnitAhead * rangeScale) / 60);
                            checkFrDate = checkToDate.AddMinutes(-(int)(noUnitAhead * rangeScale));
                            break;
                        default: common.system.ThrowException("Invalid parametter in calling to LoadStockPrice()");
                            break;
                    }
                    gotRowCount = databases.DbAccess.GetTotalPriceRow(dataObj.DataTimeScale, checkFrDate, checkToDate, dataObj.DataStockCode);
                    //No more data ??
                    if (checkFrDate < dataMinDateTime) break;
                    //Sufficient data ??
                    totalGotRowCount += gotRowCount;
                    if (totalGotRowCount >= noUnitAhead) break;

                    //No data load means the check range not big enough, increse rangeScale by 5 to make it larger scale
                    if (gotRowCount == 0) rangeScale += 5;
                    else
                    {
                        //Estimate the best range scale 
                        // Increase total left sligtly by 3% with the hope that it can take all need.
                        // 5 and 3% had been tested indifferent cases and see that they are the best value.
                        decimal tmpRangeScale = rangeScale * (decimal)(noUnitAhead - totalGotRowCount + noUnitAhead * 0.03) / gotRowCount;
                        rangeScale = (tmpRangeScale > 0 ? tmpRangeScale : rangeScale + 5);
                    }
                    checkToDate = checkFrDate.AddSeconds(-1);
                }
                databases.DbAccess.LoadData(dataObj.priceDataTbl, dataObj.DataTimeScale.Code, checkFrDate, frDate.AddSeconds(-1), dataObj.DataStockCode);
                startIdx = dataObj.priceDataTbl.Count - startIdx;
            }
            databases.DbAccess.LoadData(dataObj.priceDataTbl, dataObj.DataTimeScale.Code, frDate, toDate, dataObj.DataStockCode);
            dataObj.FirstDataStartAt = startIdx;
        }
Ejemplo n.º 20
0
        private void DoRankingDB()
        {
            this.myValueType = ValueTypes.Amount;
            this.Amount2PercentDenominator = Settings.sysStockTotalCapAmt;

            resultTab.TabPages.Clear();
            StringCollection stockCodeList = codeListLb.myValues;
            StringCollection timeRangeList = timeRangeLb.myCheckedValues;
            string[] strategyList = common.system.Collection2List(strategyClb.myCheckedValues);
            progressBar.Value = 0; progressBar.Minimum = 0; progressBar.Maximum = stockCodeList.Count * timeRangeList.Count;

            EstimateOptions  estimateOption = new EstimateOptions();

            for (int stockCodeId = 0; stockCodeId < stockCodeList.Count; stockCodeId++)
            {
                string stockCode = stockCodeList[stockCodeId].ToString();
                DataTable testRetsultTbl = CreateDataTable(timeRangeList, strategyList);
                common.controls.baseDataGridView resultGrid = CreateResultGrid(stockCode, testRetsultTbl);

                for (int colId = 0; colId < timeRangeList.Count; colId++)
                {
                    try
                    {
                        progressBar.Value++;
                        Application.DoEvents();
                        this.ShowReccount(progressBar.Value.ToString() + "/" + progressBar.Maximum.ToString());

                        AppTypes.TimeRanges timeRange = AppTypes.TimeRangeFromCode(timeRangeList[colId]);
                        application.AnalysisData analysisData = new application.AnalysisData(timeRange, timeScaleCb.myValue, stockCode,
                                                                             commonClass.DataAccessMode.WebService);
                        for (int rowId = 0; rowId < strategyList.Length; rowId++)
                        {
                            testRetsultTbl.Rows[rowId][colId + 1] = 0;
                            //Analysis cached data so we MUST clear cache to ensure the system run correctly
                            application.Strategy.Data.ClearCache();
                            application.Strategy.Data.TradePoints advices = application.Strategy.Libs.Analysis(analysisData, strategyList[rowId]);
                            if (advices != null)
                            {
                                testRetsultTbl.Rows[rowId][colId + 1] = 
                                    application.Strategy.Libs.EstimateTrading_Profit(analysisData,application.Strategy.Libs.ToTradePointInfo(advices),estimateOption);
                            }
                        }
                    }
                    catch (Exception er)
                    {
                        this.WriteError(stockCodeList[stockCodeId] + " : " + timeRangeList[colId] + " : " + strategyList[colId], er.Message);
                        //this.ShowError(er);
                    }
                }
            }
        }
Ejemplo n.º 21
0
        private CurveItem PlotCandleStick(string curveName, Charts.Controls.baseGraphPanel graphPane, application.AnalysisData data,
                                          Color barUpColor, Color barDnColor, Color bullCandleColor, Color bearCandleColor)
        {
            pricePane.myGraphObj.SetSeriesX(data.DateTime.Values, Charts.AxisType.DateAsOrdinal);
            CurveItem curveItem = graphPane.myGraphObj.AddCandleStick(curveName, data.High.Values, data.Low.Values, data.Open.Values, data.Close.Values, data.Volume.Values,
                                                                      barUpColor, barDnColor, bullCandleColor, bearCandleColor);

            return(curveItem);
        }
Ejemplo n.º 22
0
        /// <summary>
        /// Load stock price data withd some point ahead of the specified date range
        /// </summary>
        /// <param name="stockCode"></param>
        /// <param name="frDate">Start date </param>
        /// <param name="toDate">End date</param>
        /// <param name="timeScale">Time scale</param>
        /// <param name="noUnitAhead">the number of units(minute,day,hour,week...) to read beyond the start time[frDate].</param>
        /// <param name="toTbl">Table keeps loaded data</param>
        /// <param name="startIdx">specify the row where the data in [frDate,toDate] range starts</param>
        public static void LoadAnalysisData(AnalysisData dataObj)
        {
            int startIdx = dataObj.priceDataTbl.Count;

            if (dataObj.DataTimeRange == AppTypes.TimeRanges.None)
            {
                dataObj.priceDataTbl.Clear();
                databases.DbAccess.LoadData(dataObj.priceDataTbl, dataObj.DataTimeScale.Code, dataObj.DataStockCode, dataObj.DataMaxCount + constNumberOfReadAheadUnit);
                dataObj.FirstDataStartAt = 0;
                return;
            }
            int noUnitAhead = constNumberOfReadAheadUnit;

            DateTime toDate = common.Consts.constNullDate;
            DateTime frDate = common.Consts.constNullDate;

            if (!AppTypes.GetDate(dataObj.DataTimeRange, out frDate, out toDate))
            {
                return;
            }

            databases.baseDS.priceDataStatDataTable priceStatTbl = databases.DbAccess.GetPriceDataStat(dataObj.DataTimeScale, dataObj.DataStockCode);
            if (priceStatTbl.Count == 0)
            {
                return;
            }
            DateTime dataMaxDateTime = priceStatTbl[0].maxDate;
            DateTime dataMinDateTime = priceStatTbl[0].minDate;
            int      dataTotalCount  = priceStatTbl[0].totalCount;

            if (toDate > dataMaxDateTime)
            {
                toDate = dataMaxDateTime;
            }
            if (frDate < dataMinDateTime)
            {
                frDate = dataMinDateTime;
            }
            dataObj.priceDataTbl.Clear();
            if (noUnitAhead != 0)
            {
                // Find start date that return sufficient rows as required by [noBarAhead]
                DateTime checkFrDate = common.Consts.constNullDate;
                DateTime checkToDate = frDate.AddSeconds(-1);
                int      totalGotRowCount = 0, gotRowCount;
                decimal  rangeScale = 1;
                //int loopPass = 0;
                while (true)
                {
                    //loopPass++;
                    switch (dataObj.DataTimeScale.Type)
                    {
                    case AppTypes.TimeScaleTypes.Minnute:
                        checkFrDate = checkToDate.AddMinutes(-(int)(noUnitAhead * rangeScale));
                        break;

                    case AppTypes.TimeScaleTypes.Hour:
                        checkFrDate = checkToDate.AddHours(-(int)(noUnitAhead * rangeScale));
                        break;

                    case AppTypes.TimeScaleTypes.Day:
                        checkFrDate = checkToDate.AddDays(-(int)(noUnitAhead * rangeScale));
                        break;

                    case AppTypes.TimeScaleTypes.Week:
                        checkFrDate = checkToDate.AddDays(-(int)(7 * noUnitAhead * rangeScale));
                        break;

                    case AppTypes.TimeScaleTypes.Month:
                        checkFrDate = checkToDate.AddMonths(-(int)(noUnitAhead * rangeScale));
                        break;

                    case AppTypes.TimeScaleTypes.Year:
                        checkFrDate = checkToDate.AddYears(-(int)(noUnitAhead * rangeScale));
                        break;

                    case AppTypes.TimeScaleTypes.RealTime:
                        //checkFrDate = checkToDate.AddMinutes(-(int)(commonClass.Settings.sysAutoRefreshInSeconds * noUnitAhead * rangeScale) / 60);
                        checkFrDate = checkToDate.AddMinutes(-(int)(noUnitAhead * rangeScale));
                        break;

                    default: common.system.ThrowException("Invalid parametter in calling to LoadStockPrice()");
                        break;
                    }
                    gotRowCount = databases.DbAccess.GetTotalPriceRow(dataObj.DataTimeScale, checkFrDate, checkToDate, dataObj.DataStockCode);
                    //No more data ??
                    if (checkFrDate < dataMinDateTime)
                    {
                        break;
                    }
                    //Sufficient data ??
                    totalGotRowCount += gotRowCount;
                    if (totalGotRowCount >= noUnitAhead)
                    {
                        break;
                    }

                    //No data load means the check range not big enough, increse rangeScale by 5 to make it larger scale
                    if (gotRowCount == 0)
                    {
                        rangeScale += 5;
                    }
                    else
                    {
                        //Estimate the best range scale
                        // Increase total left sligtly by 3% with the hope that it can take all need.
                        // 5 and 3% had been tested indifferent cases and see that they are the best value.
                        decimal tmpRangeScale = rangeScale * (decimal)(noUnitAhead - totalGotRowCount + noUnitAhead * 0.03) / gotRowCount;
                        rangeScale = (tmpRangeScale > 0 ? tmpRangeScale : rangeScale + 5);
                    }
                    checkToDate = checkFrDate.AddSeconds(-1);
                }
                databases.DbAccess.LoadData(dataObj.priceDataTbl, dataObj.DataTimeScale.Code, checkFrDate, frDate.AddSeconds(-1), dataObj.DataStockCode);
                startIdx = dataObj.priceDataTbl.Count - startIdx;
            }
            databases.DbAccess.LoadData(dataObj.priceDataTbl, dataObj.DataTimeScale.Code, frDate, toDate, dataObj.DataStockCode);
            dataObj.FirstDataStartAt = startIdx;
        }
Ejemplo n.º 23
0
        private void DoBackTestUseDB()
        {
            this.myValueType = ValueTypes.Amount;
            this.Amount2PercentDenominator = Settings.sysStockTotalCapAmt;
            StringCollection strategyList = strategyClb.myCheckedValues;
            StringCollection stockCodeList = codeSelectLb.myValues;
            DataTable testRetsultTbl = CreateEstimateTbl(strategyList);
            SetDataGrid(resultDataGrid, testRetsultTbl);

            progressBar.Value = 0; progressBar.Minimum = 0; progressBar.Maximum = stockCodeList.Count;

            EstimateOptions estOptions = new EstimateOptions();
            for (int rowId = 0; rowId < stockCodeList.Count; rowId++)
            {
                application.AnalysisData analysisData = new application.AnalysisData(periodicityEd.myTimeRange, periodicityEd.myTimeScale,
                                                                     stockCodeList[rowId], commonClass.DataAccessMode.WebService);
                DataRow row = testRetsultTbl.Rows.Add(stockCodeList[rowId]);
                for (int colId = 0; colId < strategyList.Count; colId++)
                {
                    try
                    {
                        //Analysis cached data so we MUST clear cache to ensure the system run correctly
                        application.Strategy.Data.ClearCache();
                        application.Strategy.Data.TradePoints advices = application.Strategy.Libs.Analysis(analysisData, strategyList[colId]);
                        if (advices != null)
                        {
                            row[colId + 1] = application.Strategy.Libs.EstimateTrading_Profit(analysisData, application.Strategy.Libs.ToTradePointInfo(advices), estOptions);
                        }
                        else row[colId + 1] = 0;
                    }
                    catch (Exception er)
                    {
                        this.WriteError(stockCodeList[rowId] + " : " + strategyList[colId], er.Message);
                        this.ShowError(er);
                    }
                }
                progressBar.Value++;
                this.ShowReccount(progressBar.Value.ToString() + "/" + progressBar.Maximum.ToString());
                Application.DoEvents();
            }
            SetEstimateDataGrid(application.Strategy.Libs.GetStrategyStats(testRetsultTbl));
        }
Ejemplo n.º 24
0
 /// <summary>
 /// Get data and store in cache. Depend on forceReadNew, cached data can be used to boost perfomance
 /// </summary>
 /// <param name="timeRange"></param>
 /// <param name="timeScaleCode"></param>
 /// <param name="code"></param>
 /// <param name="forceReadNew"> if true always read from database, ignore the cached data</param>
 /// <returns>Data key used for data accessing</returns>
 public string LoadAnalysisData(AppTypes.TimeRanges timeRange, string timeScaleCode, string code, bool forceReadNew)
 {
     string cacheName = MakeCacheKey(timeRange,timeScaleCode,code);
     if (forceReadNew || sysDataCache.Find(cacheName) == null)
     {
         AnalysisData myData = new AnalysisData(timeRange, AppTypes.TimeScaleFromCode(timeScaleCode), code, DataAccessMode.Local);
         sysDataCache.Add(cacheName, myData);
     }
     return cacheName;
 }