private void addBtn_Click(object sender, RoutedEventArgs e) { if (CheckDataAvailability() == true) { StockData newStockData = new StockData(); string addSpace = " "; double addZero = 0.0; newStockData.productName = productNameDataCB.Text; newStockData.vatRate = double.Parse(vatDataCB.Text); newStockData.quantityAvailable = addZero; newStockData.purchaseDate = DateTime.Now; newStockData.quantityPurchased = addZero; newStockData.rate = addZero; newStockData.vendorId = addSpace; newStockData.productId = "Prod-" + DateTime.Now.ToOADate().ToString(); if (OnAddNewStockData != null) OnAddNewStockData(newStockData); ConnectInsertTostockTable(newStockData); this.Close(); } }
public EditStockItemWindow(StockData StockItemToEdit) { InitializeComponent(); _StockItemToEdit = StockItemToEdit; productNameDataCB.Text = _StockItemToEdit.productName; vatDataCB.Text = _StockItemToEdit.vatRate.ToString(); }
private static void GetSiteSymbols(object par) { var symbols = ((TheadPoolParam)par).symbols; DataModel.SiteDTO site = ((TheadPoolParam)par).site; List<StockData> DataList = new List<StockData>(); foreach(var item in symbols) { try { WebClient webClient = new WebClient(); string url = string.Format(site.Url, item.Symbol); var content = webClient.DownloadString(url); StockData data= new StockData(); data.SiteId=site.ID; data.StockSymbolID=item.ID; data.Data=content; data.Date = DateTime.Now; DataList.Add(data); } catch(Exception ex) { StockData data = new StockData(); data.SiteId = site.ID; data.StockSymbolID = item.ID; data.Error = string.Format("Error: {0}, {1}, {2}, ThreadId:{}", ex.Message, ex.InnerException, ex.StackTrace, Thread.CurrentThread.ManagedThreadId); data.ErrorCode = ex.HResult; data.Date = DateTime.Now; DataList.Add(data); log.Error(ex.Message, ex); } if(DataList.Count()>0) { Flexi.EF.Context.StockContext db = new EF.Context.StockContext(); db.SaveChanges(); } } //lets inform the main thread that this method has finished the execution. AutoResetEvent waitHandle = (AutoResetEvent)((TheadPoolParam)par).waitHandle; waitHandle.Set(); }
private void InitializeObservable(StockData stock) { var ticker = GetSimulatedTicker(stock.OpenPrice, stock.variance); // to connect to a real stock ticker, perhaps over websockets, could do: // var stockObs = await WebSocketSubject.Create("ws://localhost:8080", stock.Name); // ... use stockObs instead of 'ticker' ticker .ObserveOnDispatcher() .Subscribe( x => { stock.OpenDelta = FormatDelta(stock.OpenPrice, x, showPercent: true); stock.UpDownIcon = (x - stock.OpenPrice <= 0) ? TREND_DOWN : TREND_UP; stock.TickDelta = FormatDelta(stock.Price, x); stock.Price = x; stock.PriceString = String.Format("{0:0.00}", x); UpdateCombinedStats(); } ); ticker .MovingAverage(TimeSpan.FromSeconds(30)) // 30 second moving average that moves forward every second .ObserveOnDispatcher() .Subscribe( x => stock.MovingAvg30Sec = String.Format("{0:0.00}", x) ); ticker .MovingAverage(TimeSpan.FromSeconds(60)) .ObserveOnDispatcher() .Subscribe( x => stock.MovingAvg1Min = String.Format("{0:0.00}", x) ); }
public async Task <StockData> Get() { StockData stockData = await this.finnhubStockApi.GetRealTimeQuoteData("NASDAQ:AAPL"); return(stockData); }
private Task <List <StockValue> > GetValuesAsync(StockData stockData) { return(Task.Run(() => stockData.GetValues())); }
/// <summary> /// /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void ButtonFile_Click( object sender, EventArgs e ) { char[] codeArray = this.RichTextBoxCode.Text.ToCharArray(); char[] nameArray = this.RichTextBoxName.Text.ToCharArray(); for ( int iIndex = 0; iIndex < m_RandomFileCount; iIndex++ ) { StockInfo stockInfo = new StockInfo(); StringBuilder strCode = new StringBuilder(); for ( int i = 0; i < 6; i++ ) strCode.Append( RandomEx.RandomArray( codeArray ) ); StringBuilder strName = new StringBuilder(); for ( int i = 0; i < 10; i++ ) strName.Append( RandomEx.RandomArray( nameArray ) ); //stockInfo.StockCode = strCode.ToString(); //stockInfo.StockName = strName.ToString(); DateTime[] allTradingTime = this.GetAllTradingTime(); for ( int iIndex2 = 0; iIndex2 < allTradingTime.Length; iIndex2++ ) { StockData stockData = new StockData(); stockData.TradingTime = allTradingTime[iIndex2]; stockData.OpenPrice = this.GetRandomOpenPrice(); stockData.ClosePrice = this.GetRandomClosePrice(); stockData.HighestPrice = this.GetRandomHighestPrice(); stockData.MinimumPrice = this.GetRandomMinimumPrice( (uint)stockData.HighestPrice ); stockData.TradingVolume = this.GetRandomDailyTurnover(); stockData.OpenInterest = this.GetRandomDailyAmount(); //stockInfo.AddStockData( stockData ); } StockInfo.SaveFileFormatForDStock( this.TextBoxFolder.Text + "\\" + stockInfo.StockCode + ".DStock", stockInfo ); } }
private void _DoQuery(object param) { object[] plist = (object[])param; DateTime from = (DateTime)plist[0]; DateTime to = (DateTime)plist[1]; try { if (from != DateTime.MinValue) { LinkedList<Transaction> oldTran = _profolioMgr.GetAggregatedTransaction(typeof(Transaction), txtCode.Text, DateTime.MinValue, from.AddDays(-1)); foreach (Transaction t in oldTran) { if (t.amount != 0) { _prevBalance.Add(t.code, t); Transaction curPostBalance = new Transaction(); curPostBalance.code = t.code; curPostBalance.date = to; curPostBalance.amount = -t.amount; _postBalance.Add(t.code, curPostBalance); } } LinkedList<Transaction> oldFutureTran = _profolioMgr.GetAggregatedTransaction(typeof(FutureTransaction), txtCode.Text, DateTime.MinValue, from.AddDays(-1)); foreach (Transaction ft in oldFutureTran) { if (ft.amount != 0) { SortedDictionary<string, FutureTransaction> curPrevBalanceFutureDict; if (!_prevBalanceFuture.TryGetValue(ft.code, out curPrevBalanceFutureDict)) { curPrevBalanceFutureDict = new SortedDictionary<string, FutureTransaction>(); _prevBalanceFuture.Add(ft.code, curPrevBalanceFutureDict); } curPrevBalanceFutureDict.Add(((FutureTransaction)ft).contractCode, (FutureTransaction)ft); SortedDictionary<string, FutureTransaction> curPostBalanceFutureDict; if (!_postBalanceFuture.TryGetValue(ft.code, out curPostBalanceFutureDict)) { curPostBalanceFutureDict = new SortedDictionary<string, FutureTransaction>(); _postBalanceFuture.Add(ft.code, curPostBalanceFutureDict); } FutureTransaction curPostFutureBalance = new FutureTransaction(); curPostFutureBalance.code = ft.code; curPostFutureBalance.contractCode = ((FutureTransaction)ft).contractCode; curPostFutureBalance.date = to; curPostFutureBalance.amount = -ft.amount; curPostBalanceFutureDict.Add(((FutureTransaction)ft).contractCode, curPostFutureBalance); } } } _tran = _profolioMgr.GetTransaction(typeof(Transaction), txtCode.Text, from, to); _futureTran = _profolioMgr.GetTransaction(typeof(FutureTransaction), txtCode.Text, from, to); } catch (Exception ex) { MessageBox.Show(ex.Message, "錯誤", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } _UpdateTransactionCB updateTranCB = new _UpdateTransactionCB(_UpdateDgvTransaction); List<Transaction> updateTranCbData = new List<Transaction>(); //Process transaction data { LinkedListNode<Transaction> t = _tran.First, ft = _futureTran.First; while (t != null || ft != null) { if (ft == null || (t != null && t.Value.date <= ft.Value.date)) { updateTranCbData.Add(t.Value); List<Transaction> curTransactionLst; if (!_tranDct.TryGetValue(t.Value.code, out curTransactionLst)) { curTransactionLst = new List<Transaction>(); _tranDct.Add(t.Value.code, curTransactionLst); } curTransactionLst.Add(t.Value); t = t.Next; } else { updateTranCbData.Add(ft.Value); SortedDictionary<string, List<FutureTransaction>> curDct; if (!_tranFutureDct.TryGetValue(ft.Value.code, out curDct)) { curDct = new SortedDictionary<string, List<FutureTransaction>>(); _tranFutureDct.Add(ft.Value.code, curDct); } List<FutureTransaction> curTransactionFutureLst; if (!curDct.TryGetValue(((FutureTransaction)ft.Value).contractCode, out curTransactionFutureLst)) { curTransactionFutureLst = new List<FutureTransaction>(); curDct.Add(((FutureTransaction)ft.Value).contractCode, curTransactionFutureLst); } curTransactionFutureLst.Add((FutureTransaction)ft.Value); ft = ft.Next; } } } foreach (KeyValuePair<string, List<Transaction>> kwp in _tranDct) { Transaction curNetTran = new Transaction(); curNetTran.code = kwp.Key; curNetTran.date = to; curNetTran.amount = 0; curNetTran.payment = 0; curNetTran.description = "淨交易"; foreach (Transaction t in kwp.Value) { curNetTran.amount += t.amount; curNetTran.payment += t.payment; } _netTran.Add(curNetTran.code, curNetTran); if (curNetTran.amount != 0) { Transaction curPostBalance; if (!_postBalance.TryGetValue(curNetTran.code, out curPostBalance)) { curPostBalance = new Transaction(); curPostBalance.code = curNetTran.code; curPostBalance.date = to; curPostBalance.amount = 0; _postBalance.Add(curPostBalance.code, curPostBalance); } curPostBalance.amount -= curNetTran.amount; if (curPostBalance.amount == 0) _postBalance.Remove(curPostBalance.code); } } foreach (KeyValuePair<string, SortedDictionary<string, List<FutureTransaction>>> kwp in _tranFutureDct) { FutureTransaction curNetTranFuture = new FutureTransaction(); curNetTranFuture.code = kwp.Key; curNetTranFuture.contractCode = "淨期貨交易"; curNetTranFuture.date = to; curNetTranFuture.amount = 0; curNetTranFuture.payment = 0; curNetTranFuture.description = "淨交易"; foreach (KeyValuePair<string, List<FutureTransaction>> kwp2 in kwp.Value) { double tmpAmount = 0; double tmpPayment = 0; foreach (FutureTransaction ft in kwp2.Value) { tmpAmount += ft.amount; tmpPayment += ft.payment; } curNetTranFuture.amount += tmpAmount; curNetTranFuture.payment += tmpPayment; if (tmpAmount != 0) { SortedDictionary<string, FutureTransaction> curPostBalanceDct; if (!_postBalanceFuture.TryGetValue(kwp.Key, out curPostBalanceDct)) { curPostBalanceDct = new SortedDictionary<string, FutureTransaction>(); _postBalanceFuture.Add(kwp.Key, curPostBalanceDct); } FutureTransaction curPostBalance; if (!curPostBalanceDct.TryGetValue(kwp2.Key, out curPostBalance)) { curPostBalance = new FutureTransaction(); curPostBalance.code = kwp.Key; curPostBalance.contractCode = kwp2.Key; curPostBalance.date = to; curPostBalance.amount = 0; curPostBalanceDct.Add(kwp2.Key, curPostBalance); } curPostBalance.amount -= tmpAmount; if (curPostBalance.amount == 0) curPostBalanceDct.Remove(kwp2.Key); if (curPostBalanceDct.Count == 0) curPostBalanceDct.Remove(kwp.Key); } } _netTranFurture.Add(curNetTranFuture.code, curNetTranFuture); } Invoke(updateTranCB, new object[] { updateTranCbData }); //Process return data if (_prevBalance.Count > 0) { SortedDictionary<Pair<string, string>, double> asset = new SortedDictionary<Pair<string, string>, double>(); foreach (string code in _prevBalance.Keys) asset.Add(new Pair<string, string>(code, "-"), 0); try { _profolioMgr.GetHistorialPrice(asset, from.AddDays(-1)); } catch (Exception ex) { MessageBox.Show(ex.Message, "錯誤", MessageBoxButtons.OK, MessageBoxIcon.Error); } foreach (KeyValuePair<Pair<string, string>, double> kwp in asset) { Transaction curTran = _prevBalance[kwp.Key.First]; curTran.payment = -curTran.amount * kwp.Value; } } if (_prevBalanceFuture.Count > 0) { SortedDictionary<Pair<string, string>, double> asset = new SortedDictionary<Pair<string, string>, double>(); foreach (KeyValuePair<string, SortedDictionary<string, FutureTransaction>> stock in _prevBalanceFuture) { foreach (string contractCode in stock.Value.Keys) asset.Add(new Pair<string, string>(stock.Key, contractCode), 0); } try { _profolioMgr.GetHistorialPrice(asset, from.AddDays(-1)); } catch (Exception ex) { MessageBox.Show(ex.Message, "錯誤", MessageBoxButtons.OK, MessageBoxIcon.Error); } foreach (KeyValuePair<Pair<string, string>, double> kwp in asset) { Transaction curTran = _prevBalanceFuture[kwp.Key.First][kwp.Key.Second]; curTran.payment = -curTran.amount * kwp.Value; } } if (_postBalance.Count > 0) { if (to < DateTime.Today) { SortedDictionary<Pair<string, string>, double> asset = new SortedDictionary<Pair<string, string>, double>(); foreach (string code in _postBalance.Keys) asset.Add(new Pair<string, string>(code, "-"), 0); try { _profolioMgr.GetHistorialPrice(asset, to); } catch (Exception ex) { MessageBox.Show(ex.Message, "錯誤", MessageBoxButtons.OK, MessageBoxIcon.Error); } foreach (KeyValuePair<Pair<string, string>, double> kwp in asset) { Transaction curTran = _postBalance[kwp.Key.First]; curTran.payment = -curTran.amount * kwp.Value; } } else { List<StockData> asset = new List<StockData>(); foreach (string code in _postBalance.Keys) { StockData stockData = new StockData(); stockData.code = code; asset.Add(stockData); } try { _stockMgr.GetQuote(asset.ToArray()); } catch (Exception ex) { MessageBox.Show(ex.Message, "錯誤", MessageBoxButtons.OK, MessageBoxIcon.Error); } foreach (StockData stock in asset) { Transaction curTran = _postBalance[stock.code]; curTran.date = DateTime.Today; curTran.payment = -curTran.amount * stock.close; } } } if (_postBalanceFuture.Count > 0) { SortedDictionary<Pair<string, string>, double> asset = new SortedDictionary<Pair<string, string>, double>(); foreach (KeyValuePair<string, SortedDictionary<string, FutureTransaction>> stock in _postBalanceFuture) { foreach (string contractCode in stock.Value.Keys) asset.Add(new Pair<string, string>(stock.Key, contractCode), 0); } try { _profolioMgr.GetHistorialPrice(asset, to); } catch (Exception ex) { MessageBox.Show(ex.Message, "錯誤", MessageBoxButtons.OK, MessageBoxIcon.Error); } foreach (KeyValuePair<Pair<string, string>, double> kwp in asset) { Transaction curTran = _postBalanceFuture[kwp.Key.First][kwp.Key.Second]; if (to >= DateTime.Today) curTran.date = DateTime.Today; curTran.payment = -curTran.amount * kwp.Value; } } Invoke(new _UpdateReturnCB(_UpdateReturn)); }
protected virtual void OnNewStockData(object sender, StockEventArgs e) { StockData?.Invoke(this, e); }
public StockData[] GetStockDataRangeByTime( DateTime dataTimeStart, DateTime dataTimeEnd ) { ToSortArray(); if ( dataTimeStart <= dataTimeEnd ) return new StockData[0]; int iStart = -1; int iEnd = -1; for ( int iIndex = 0; iStart < m_DateTimeStockData.Length; iIndex++ ) { StockData item = m_DateTimeStockData[iIndex]; if ( item.TradingDate <= dataTimeStart && iStart == 0 ) iStart = iIndex; else if ( item.TradingDate <= dataTimeEnd && iEnd == 0 ) { iEnd = iIndex; break; } } if ( iStart == -1 ) return new StockData[0]; if ( iEnd == -1 ) iEnd = m_DateTimeStockData.Length; StockData[] stockDataArray = new StockData[iEnd - iStart]; Array.Copy( m_DateTimeStockData, iStart, stockDataArray, 0, stockDataArray.Length ); return stockDataArray; }
public async Task <OptionTradeList> Find(Stock stock, DateTime startDate, DateTime endDate) { OptionTradeList tradeList = new OptionTradeList(stock, Api.Interval.Daily); StockData data = await StockDataBase.Get(stock, Api.Interval.Daily); int startIndex = data.FindDateIndex(startDate); int endIndex = data.FindDateIndex(endDate); int period = 40; double priceGainGate = -0.5; double volumeGainGate = 0.5; int tradeHoldLenght = 15; double tradeHoldMaxGain = 0.9; double tradeHoldMaxLoss = -0.25; double portofolioPercentage = 0.8; bool inTrade = false; for (int i = startIndex; i <= endIndex; i++) { if (!inTrade) { { DateTime today = data.TimeSeries.DataPoints[i].DateTime; double open = data.TimeSeries.DataPoints[i].Open; double close = data.TimeSeries.DataPoints[i].Close; double percentageGain = (close - open) / open; if (percentageGain > priceGainGate) { double volume = data.TimeSeries.DataPoints[i].Volume; double volumeSMA = Indicators.GetSMA(data, i, period, PricePoint.Volume); double volumePercentageGain = (volume - volumeSMA) / volumeSMA; if (volumePercentageGain > volumeGainGate) { Option[] options = new Option[2]; options[0] = new Option(stock, OptionType.Call, PositionType.Long, Math.Round(close, 0) - 5, today.AddDays(40)); options[1] = new Option(stock, OptionType.Call, PositionType.Short, Math.Round(close, 0) + 0, today.AddDays(40)); Spread spread = new Spread(options); OptionTrade trade = new OptionTrade { TradeDate = data.TimeSeries.DataPoints[i].DateTime, PortfolioPercentage = portofolioPercentage, Spread = spread }; tradeList.Trades.Add(trade); inTrade = true; } } } } else { OptionTrade lastTrade = tradeList.Trades[tradeList.Trades.Count - 1]; DateTime today = data.TimeSeries.DataPoints[i].DateTime; int dateIndex = data.FindDateIndex(lastTrade.TradeDate); double openPrice = await lastTrade.Spread.Price(lastTrade.TradeDate); double currentPrice = await lastTrade.Spread.Price(today); double percentageGain = (currentPrice - openPrice) / openPrice; if (i - dateIndex >= tradeHoldLenght || lastTrade.Spread.DaysUntilExpiration(today) < 5 || percentageGain > tradeHoldMaxGain || percentageGain < tradeHoldMaxLoss) { OptionTrade trade = new OptionTrade { TradeDate = data.TimeSeries.DataPoints[i].DateTime, PortfolioPercentage = 0, Spread = lastTrade.Spread }; tradeList.Trades.Add(trade); inTrade = false; } } } return(tradeList); }
private DataTable GetStockData(string stockCode, StockData stockData, DataTable dt, string serverUrl, string ID, string strfirstCurrName, string strsecondCurrName) { //string serverUrl = @"http://in.finance.yahoo.com/d/quotes.csv?s=" + stockCode + // "&f=sl1d1t1c1ohgvj1pp2owern&e=.csv"; //string serverUrl = @"http://finance.yahoo.com/d/quotes.csv?s=" + stockCode + // "&f=sl1d1t1c1ohgv&e=.csv"; try { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(serverUrl); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.ASCII); string stockDataString = reader.ReadLine(); string[] stockDataContents = stockDataString.Split(','); //stockData.Code = stockCode; //stockData.Last = stockDataContents[1]; //stockData.Date = stockDataContents[2]; //stockData.Time = stockDataContents[3]; //stockData.Change = stockDataContents[4]; //stockData.Open = stockDataContents[5]; //stockData.High = stockDataContents[6]; //stockData.Low = stockDataContents[7]; //stockData.Volume = stockDataContents[8]; if (ID != "CUR") { //stockData.MarketCapital = stockDataContents[9]; //stockData.PreviousClose = stockDataContents[10]; //stockData.PctChange = stockDataContents[11]; //stockData.AnnRange = stockDataContents[12]; //stockData.Earnings = stockDataContents[13]; //stockData.PERatio = stockDataContents[14]; } DataRow drr = dt.NewRow(); if (ID == "CUR") { drr["ID"] = 0; drr["Name"] = strfirstCurrName.Trim(); drr["Country"] = strsecondCurrName.Trim(); drr["Currency"] = stockDataContents[0].ToString(); drr["Rate"] = stockDataContents[1].ToString(); if (stockDataContents[8].ToString() != "N/A") { drr["ChangePercent"] = stockDataContents[8].ToString().Replace("\"", "").Replace("%", ""); drr["UpdateDateTime"] = Convert.ToDateTime(stockDataContents[2].ToString().Replace("\"", "") + " " + stockDataContents[3].ToString().Replace("\"", "")); } else { drr["ChangePercent"] = "0.00"; drr["UpdateDateTime"] = System.DateTime.Now.ToString("dd-MMM-yyyy"); } } dt.Rows.Add(drr); response.Close(); } catch (Exception ex) { //Response.Write("Error in GetStockData() 2nd :: "+ex.Message.ToString()); } return(dt); }
void FeedstockData(MySql.Data.MySqlClient.MySqlCommand msqlCommand, StockData stockDataObject) { //define the command text msqlCommand.CommandText = "INSERT INTO stock(id,vat_rate,product_name,vendor_id,date_purchased,quantity_purchased,rate,quantity_available)" + "VALUES (@id,@vatRate,@product_name,@vendor_id,@date_purchased,@quantity_purchased,@rate,@quantity_available)"; msqlCommand.Parameters.AddWithValue("@id", stockDataObject.productId); msqlCommand.Parameters.AddWithValue("@vatRate", stockDataObject.vatRate); msqlCommand.Parameters.AddWithValue("@product_name", stockDataObject.productName); msqlCommand.Parameters.AddWithValue("@vendor_id", stockDataObject.vendorId); msqlCommand.Parameters.AddWithValue("@date_purchased", stockDataObject.purchaseDate); msqlCommand.Parameters.AddWithValue("@quantity_purchased", stockDataObject.quantityPurchased); msqlCommand.Parameters.AddWithValue("@rate", stockDataObject.rate); msqlCommand.Parameters.AddWithValue("@quantity_available", stockDataObject.quantityAvailable); msqlCommand.ExecuteNonQuery(); }
public StockData[] GetStockDataRangeByKn( DateTime dataTimeStart, int iKn ) { ToSortArray(); if ( iKn < 3 ) return new StockData[0]; int iStart = -1; int iEnd = -1; for ( int iIndex = 0; iIndex < m_DateTimeStockData.Length; iIndex++ ) { StockData item = m_DateTimeStockData[iIndex]; if (item.TradingDate <= dataTimeStart) { iStart = iIndex; if ( ( iIndex + iKn ) < m_DateTimeStockData.Length ) iEnd = iStart + iKn; else iEnd = m_DateTimeStockData.Length; break; } } if ( iStart == -1 ) return new StockData[0]; if ( iEnd == -1 ) iEnd = m_DateTimeStockData.Length; StockData[] stockDataArray = new StockData[iEnd - iStart]; Array.Copy( m_DateTimeStockData, iStart, stockDataArray, 0, stockDataArray.Length ); return stockDataArray; }
private void UpdateData() { if (_data == null) _data = new StockData<StockValue>(); for (var i = 0; i < _base.Count; i++) { if (i > Count - 1) _data.AddValue(new StockValue {Time = _base[i].Time}); _data[i].Value = _base[i].Value; } }
private void refleshData() { if (_refleshMutex.WaitOne(0)) { _UpdateStatusDelegate updateStatusDele = new _UpdateStatusDelegate(_UpdateStatus); Invoke(updateStatusDele, new object[] { "更新中..." }); StockData[] stocks = new StockData[dgvStockList.Rows.Count]; for (int i = 0; i < dgvStockList.Rows.Count; i++) stocks[i] = new StockData((string)dgvStockList.Rows[i].Cells["colName"].Tag); _stockMgr.RefreshHKIndice(); try { _stockMgr.GetQuote(stocks); } catch (ThreadAbortException) { } catch (Exception ex) { Console.WriteLine(ex.Message); MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } for (int i = 0; i < dgvStockList.Rows.Count; i++) { dgvStockList.Rows[i].DefaultCellStyle.BackColor = StockTool.Layout.getRocColor(stocks[i].ROC); dgvStockList.Rows[i].Cells["colPrice"].Value = stocks[i].close; dgvStockList.Rows[i].Cells["colChange"].Value = stocks[i].change; dgvStockList.Rows[i].Cells["colROC"].Value = stocks[i].ROC; if (!float.IsNaN(stocks[i].low) && !float.IsNaN(stocks[i].high)) dgvStockList.Rows[i].Cells["colTodayHL"].Value = stocks[i].low.ToString("F3") + " - " + stocks[i].high.ToString("F3"); else dgvStockList.Rows[i].Cells["colTodayHL"].Value = null; } Invoke(updateStatusDele, new object[] { "" }); _refleshMutex.ReleaseMutex(); _refleshThread = null; } }
private void txtUnderlyingPrice_Leave(object sender, EventArgs e) { if (!string.IsNullOrEmpty(txtUnderlyingPrice.Text) && txtUnderlyingPrice.Text[0] == '=' && txtUnderlyingPrice.Text.Length > 1) { StockData stock = new StockData(stockMgr.StockData.CodeFromString(txtUnderlyingPrice.Text.Substring(1))); try { _stockMgr.GetQuote(stock); } catch (Exception ex) { MessageBox.Show(ex.Message, "錯誤", MessageBoxButtons.OK, MessageBoxIcon.Error); } txtUnderlyingPrice.Text = stock.close.ToString("0.000"); } }
public static bool LoadFileFormatForMetaStock( string stockName, string stockSymbol, string strFilePath, ref StockInfo stockInfo ) { MSFL.MSFLSecurityInfo[] msflSecurityInfoArray = null; if ( GlobalSetting.TryLoadMsflSecurityInfo( strFilePath, out msflSecurityInfoArray ) == false ) return false; int iErr = (int)MSFL.MSFL_ERR.MSFL_NO_ERR; StringBuilder dateString = new StringBuilder( MSFL.MSFL_MAX_NAME_LENGTH + 1 ); for ( int iIndex = 0; iIndex < msflSecurityInfoArray.Length; iIndex++ ) { MSFL.MSFLSecurityInfo msflSecurityInfo = msflSecurityInfoArray[iIndex]; if ( msflSecurityInfo.szName == stockName && msflSecurityInfo.szSymbol == stockSymbol ) { stockInfo.m_StockCode = GlobalSetting.GetStockCode( msflSecurityInfo.szName, msflSecurityInfo.szSymbol ); stockInfo.m_StockName = msflSecurityInfo.szName; stockInfo.m_StockSymbol = msflSecurityInfo.szSymbol; stockInfo.m_Periodicity = msflSecurityInfo.cPeriodicity; iErr = MSFL.MSFL1_FormatDate( dateString, (ushort)dateString.Capacity, msflSecurityInfo.lFirstDate ); stockInfo.m_FirstDate = DateTime.Parse( dateString.ToString() ); iErr = MSFL.MSFL1_FormatDate( dateString, (ushort)dateString.Capacity, msflSecurityInfo.lLastDate ); stockInfo.m_LastDate = DateTime.Parse( dateString.ToString() ); iErr = MSFL.MSFL1_FormatTime( dateString, (ushort)dateString.Capacity, msflSecurityInfo.lFirstTime, true ); string strFirstTime = dateString.ToString(); strFirstTime = strFirstTime.Substring( 0, strFirstTime.Length - 1 ); stockInfo.m_FirstTime = DateTime.Parse( strFirstTime ); iErr = MSFL.MSFL1_FormatTime( dateString, (ushort)dateString.Capacity, msflSecurityInfo.lLastTime, true ); string strLastTime = dateString.ToString(); strLastTime = strLastTime.Substring( 0, strLastTime.Length - 1 ); stockInfo.m_LastTime = DateTime.Parse( strLastTime ); iErr = MSFL.MSFL1_FormatTime( dateString, (ushort)dateString.Capacity, msflSecurityInfo.lStartTime, false ); stockInfo.m_StartTime = DateTime.Parse( dateString.ToString() ); iErr = MSFL.MSFL1_FormatTime( dateString, (ushort)dateString.Capacity, msflSecurityInfo.lEndTime, false ); stockInfo.m_EndTime = DateTime.Parse( dateString.ToString() ); iErr = MSFL.MSFL1_FormatDate( dateString, (ushort)dateString.Capacity, msflSecurityInfo.lCollectionDate ); stockInfo.m_CollectionDate = DateTime.Parse( dateString.ToString() ); MSFL.MSFLPriceRecord[] msflPriceInfoArray = null; if ( GlobalSetting.TryLoadMsflPriceInfo( stockName, stockSymbol, strFilePath, out msflPriceInfoArray ) == false ) return true; // numbers for summing price info float fOpenSum = 0.0f, fHighSum = 0.0f, fLowSum = 0.0f, fCloseSum = 0.0f, fVolumeSum = 0.0f, fOpenIntSum = 0.0f; StringBuilder szBuf = new StringBuilder( MSFL.MSFL_MAX_NAME_LENGTH + 1 ); for ( int iIndex2 = 0; iIndex2 < msflPriceInfoArray.Length; iIndex2++ ) { MSFL.MSFLPriceRecord msflPriceRecord = msflPriceInfoArray[iIndex2]; StockData stockData = new StockData(); if ( ( msflPriceRecord.wDataAvailable & MSFL.MSFL_DATA_DATE ) == MSFL.MSFL_DATA_DATE ) { iErr = MSFL.MSFL1_FormatDate( szBuf, (ushort)szBuf.Capacity, msflPriceRecord.lDate ); stockData.TradingDate = DateTime.Parse( szBuf.ToString() ); } if ( ( msflPriceRecord.wDataAvailable & MSFL.MSFL_DATA_TIME ) == MSFL.MSFL_DATA_TIME ) { iErr = MSFL.MSFL1_FormatTime( szBuf, (ushort)szBuf.Capacity, msflPriceRecord.lTime, true ); string strTradingTime = szBuf.ToString(); strTradingTime = strLastTime.Substring( 0, strTradingTime.Length - 1 ); stockData.TradingTime = DateTime.Parse( strTradingTime ); } stockData.TradingDateTime = stockData.TradingDate + stockData.TradingTime.TimeOfDay; //Debug.WriteLine( stockData.TradingDateTime.ToString() ); if ( ( msflPriceRecord.wDataAvailable & MSFL.MSFL_DATA_OPEN ) == MSFL.MSFL_DATA_OPEN ) { fOpenSum += msflPriceRecord.fOpen; stockData.OpenPrice = msflPriceRecord.fOpen; } if ( ( msflPriceRecord.wDataAvailable & MSFL.MSFL_DATA_HIGH ) == MSFL.MSFL_DATA_HIGH ) { fHighSum += msflPriceRecord.fHigh; stockData.HighestPrice = msflPriceRecord.fHigh; } if ( ( msflPriceRecord.wDataAvailable & MSFL.MSFL_DATA_LOW ) == MSFL.MSFL_DATA_LOW ) { fLowSum += msflPriceRecord.fLow; stockData.MinimumPrice = msflPriceRecord.fLow; } if ( ( msflPriceRecord.wDataAvailable & MSFL.MSFL_DATA_CLOSE ) == MSFL.MSFL_DATA_CLOSE ) { fCloseSum += msflPriceRecord.fClose; stockData.ClosePrice = msflPriceRecord.fClose; } if ( ( msflPriceRecord.wDataAvailable & MSFL.MSFL_DATA_VOLUME ) == MSFL.MSFL_DATA_VOLUME ) { fVolumeSum += msflPriceRecord.fVolume; stockData.TradingVolume = msflPriceRecord.fVolume; } if ( ( msflPriceRecord.wDataAvailable & MSFL.MSFL_DATA_OPENINT ) == MSFL.MSFL_DATA_OPENINT ) { fOpenIntSum += msflPriceRecord.fOpenInt; stockData.OpenInterest = msflPriceRecord.fOpenInt; } stockInfo.AddStockData( stockData ); } return true; } } return false; }
private void AddStockData( StockData stockData ) { m_DateTimeDictionary.Add(stockData.TradingDateTime, stockData); m_StockDataArray.Add( stockData ); m_IsDataChange = true; }
static void Main(string[] args) { List<StockData> stockDataList = new List<StockData>(100); string path = @"mbk.csv"; string content = File.ReadAllText(path, Encoding.UTF8); foreach (String line in content.Split("\n")) { /* * wiersz jest parsowany zwracany jest jako tablica zawierająca na indeksie: * 0 - data notowania * 1 - kurs otwarcia * 2 - kurs najwyszy * 3 - kurs najnizszy * 4 - kurs zamkniecia * 5 - wolumen akcji */ string[] items = line.Trim().Split(","); if (items.Length >= 6) { StockData sd = new StockData (items[0], Convert.ToDouble(items[1], CultureInfo.InvariantCulture), Convert.ToDouble(items[2], CultureInfo.InvariantCulture), Convert.ToDouble(items[3], CultureInfo.InvariantCulture), Convert.ToDouble(items[4], CultureInfo.InvariantCulture), Convert.ToInt32(items[5], CultureInfo.InvariantCulture) ); stockDataList.Add(sd); } } Console.WriteLine("Items in list {0}", stockDataList.Count()); Hashtable htMax = new Hashtable(); Hashtable htMin = new Hashtable(); //parsowanie w poszukiwaniu maks. i min. miesięcznych foreach (var stock in stockDataList) { String ym = stock.GetYearMonth(); Double close = stock.GetClose(); if (!htMax.ContainsKey(ym)) { htMax.Add(ym, close); } else { if (close > (double)htMax[ym]) htMax[ym] = close; } if (!htMin.ContainsKey(ym)) { htMin.Add(ym, close); } else { if (close < (double)htMin[ym]) htMin[ym] = close; } } Console.WriteLine("Maksima:"); foreach (string k in htMax.Keys) { Console.WriteLine(k + ": " + htMax[k]); } Console.WriteLine("\nMinima:"); foreach (string k in htMin.Keys) { Console.WriteLine(k + ": " + htMin[k]); } }
private void ConnectInsertTostockTable(StockData stockDataObject) { //define the connection reference and initialize it msqlConnection = new MySql.Data.MySqlClient.MySqlConnection("server=localhost;user id=root;Password=technicise;database=sptdb;persist security info=False"); try { //define the command reference MySql.Data.MySqlClient.MySqlCommand msqlCommand = new MySql.Data.MySqlClient.MySqlCommand(); //define the connection used by the command object msqlCommand.Connection = msqlConnection; //open the connection if (msqlConnection.State != System.Data.ConnectionState.Open) msqlConnection.Open(); FeedstockData(msqlCommand, stockDataObject); } catch (Exception er) { MessageBox.Show(er.Message); } finally { msqlConnection.Close(); } }
private void SetPeriod(int period) { if (period < 1) throw new ArgumentOutOfRangeException("period"); _period = period; _p = 2.0/(_period + 1); _data = new StockData<StockValue>(); UpdateData(); }
public SubBoard1(StockData myStock) { stock = myStock; stock.registerObserver(this); }
private void DrawCandles(StockData stockData, int startIndex, int count) { if (count > 0 && stockData.TimeSeries.DataPoints.Count >= startIndex + count) { double relativeRange = _priceHighest - _priceLowest; _candleWidth = (int)(_renderWidth - _candleMargin * 2f) / count - _candleMargin; if (_candleWidth < 0) { _candleWidth = 0; } if (relativeRange > 0 && _candleWidth > 0) { int drawBottom = _renderHeight - _candleMargin * 2; int drawSpace = _renderHeight - _candleMargin * 4; double pixelsPerPoint = drawSpace / relativeRange; for (int i = 0; i < count; i++) { double change = stockData.TimeSeries.DataPoints[startIndex + i].Close - stockData.TimeSeries.DataPoints[startIndex + i].Open; double relativeOpen = stockData.TimeSeries.DataPoints[startIndex + i].Open - _priceLowest; double relativeHigh = stockData.TimeSeries.DataPoints[startIndex + i].High - _priceLowest; double relativeClose = stockData.TimeSeries.DataPoints[startIndex + i].Close - _priceLowest; double relativeLow = stockData.TimeSeries.DataPoints[startIndex + i].Low - _priceLowest; if (change < 0) { float x = _candleMargin + i * (_candleWidth + _candleMargin); float y = (float)(drawBottom - relativeOpen * pixelsPerPoint); float height = (float)(change * -1 * pixelsPerPoint); if (height < 1) { height = 1; } float wickLength = (float)((relativeHigh - relativeOpen) * pixelsPerPoint); float tailLenght = (float)((relativeClose - relativeLow) * pixelsPerPoint); //Draw the candle base _graphGraphics.FillRectangle(_negCandleBrush, x, y, _candleWidth, height); //Draw wick _graphGraphics.DrawLine(_negCandlePen, x + _candleWidth * 0.5f, y - wickLength, x + _candleWidth * 0.5f, y); //Draw tail _graphGraphics.DrawLine(_negCandlePen, x + _candleWidth * 0.5f, y + height, x + _candleWidth * 0.5f, y + height + tailLenght); } else { float x = _candleMargin + i * (_candleWidth + _candleMargin); float y = (float)(drawBottom - relativeClose * pixelsPerPoint); float height = (float)(change * pixelsPerPoint); if (height < 1) { height = 1; } float wickHeight = (float)((relativeHigh - relativeClose) * pixelsPerPoint); float tailLenght = (float)((relativeOpen - relativeLow) * pixelsPerPoint); //Draw the candle base _graphGraphics.FillRectangle(_posCandleBrush, x, y, _candleWidth, height); //Draw wick _graphGraphics.DrawLine(_posCandlePen, x + _candleWidth * 0.5f, y - wickHeight, x + _candleWidth * 0.5f, y); //Draw tail _graphGraphics.DrawLine(_posCandlePen, x + _candleWidth * 0.5f, y + height, x + _candleWidth * 0.5f, y + height + tailLenght); } } } } }
public override bool Qualified(DataRowCollection rows, int index, StockData currentPrice, StockData beforePrice, StockData afterPrice) { if (currentPrice == null) { return(false); } var top = currentPrice.close.Value; var bottom = currentPrice.open.Value; if (currentPrice.close < currentPrice.open) { bottom = currentPrice.close.Value; top = currentPrice.open.Value; } //下影线必须超过实体的2.2倍 if (Math.Abs(bottom - currentPrice.low.Value) < Math.Abs(top - bottom) * multiplier1 || Math.Abs(bottom - currentPrice.low.Value) == 0 || Math.Abs(top - bottom) == 0) { return(false); } //上影线必须很短 if (currentPrice.high.Value - top > top * multiplier2) { return(false); } return(true); }
private void fetchevendorData() { msqlConnection = new MySql.Data.MySqlClient.MySqlConnection("server=localhost;user id=root;Password=technicise;database=sptdb;persist security info=False"); try { //define the command reference MySql.Data.MySqlClient.MySqlCommand msqlCommand = new MySql.Data.MySqlClient.MySqlCommand(); msqlCommand.Connection = msqlConnection; if (msqlConnection.State != System.Data.ConnectionState.Open) msqlConnection.Open(); msqlCommand.CommandText = "Select * from stock;"; MySql.Data.MySqlClient.MySqlDataReader msqlReader = msqlCommand.ExecuteReader(); _stockCollection.Clear(); while (msqlReader.Read()) { StockData stockDataObject = new StockData(); //stockDataObject.serialNo = GetCurrentSerialNumber(); stockDataObject.productId = msqlReader.GetString("id"); stockDataObject.purchaseDate = msqlReader.GetDateTime("date_purchased"); stockDataObject.productName = msqlReader.GetString("product_name"); stockDataObject.quantityPurchased = msqlReader.GetDouble("quantity_purchased"); stockDataObject.vendorId = msqlReader.GetString("vendor_id"); stockDataObject.rate = msqlReader.GetDouble("rate"); stockDataObject.vatRate = msqlReader.GetDouble("vat_rate"); stockDataObject.quantityAvailable = msqlReader.GetDouble("quantity_available"); _stockCollection.Add(stockDataObject); } } catch (Exception er) { MessageBox.Show(er.Message); } finally { //always close the connection msqlConnection.Close(); } }
private static int GetStockInfoHighReturnKN( StockData[] StockInfo ) { int iHigh = 0; float iHighV = 0F; for ( int iIndex = 0; iIndex < StockInfo.Length; iIndex++ ) { StockData stockInfo = StockInfo[iIndex]; if ( stockInfo.HighestPrice >= iHighV ) { iHighV = stockInfo.HighestPrice; iHigh = iIndex; } } return iHigh + 1; }
public void LoadFromDatabase() { int iRow = 0; try { SqlConnection conn = new SqlConnection(connStr); conn.Open(); //string strTicker = "select distinct ticker from v_HistPrices07 where intDate=20140731 and ticker='000762' order by ticker"; //string strData = "select * from v_HistPrices07 where intDate=20140731 and ticker='000762' order by ticker, intDate, intTime"; string strTicker = "select distinct ticker from v_HistPrices07 order by ticker"; string strData = "select * from v_HistPrices07 order by ticker, intDate, intTime"; SqlCommand cmd = new SqlCommand(); cmd.Connection = conn; cmd.CommandType = CommandType.Text; cmd.CommandText = strTicker; cmd.CommandTimeout = 0; SqlDataReader dr = cmd.ExecuteReader(); //执行SQL,返回一个“流” while (dr.Read()) { TickerList.Add(dr["Ticker"].ToString()); } dr.Close(); cmd.CommandText = strData; string prevTk = "", currTk = ""; int prevDate = 0, currDate = 0; int drTime; double drPrice; StockData sd = null; DailyData dd = null; dr = cmd.ExecuteReader(); while (dr.Read()) { currTk = dr["Ticker"].ToString(); currDate = Convert.ToInt32(dr["intDate"].ToString()); drTime = Convert.ToInt32(dr["intTime"].ToString()); drPrice = Convert.ToDouble(dr["LastPrice"].ToString()); if (iRow == 0) { prevTk = currTk; prevDate = currDate; sd = new StockData(currTk); dd = new DailyData(currDate); dd.AddToEnd(drTime, drPrice); iRow++; continue; } if ((currTk == prevTk) && (currDate == prevDate)) //同一股票,同一日期 { dd.AddToEnd(drTime, drPrice); } else if ((currTk == prevTk) && (currDate != prevDate)) //同一股票,不同日期 { sd.AddToEnd(dd); dd = new DailyData(currDate); dd.AddToEnd(drTime, drPrice); prevDate = currDate; } else //不同股票,可以是同一日期,也可以不同 { sd.AddToEnd(dd); HistoricalData.TryAdd(sd.Ticker, sd); sd = new StockData(currTk); dd = new DailyData(currDate); dd.AddToEnd(drTime, drPrice); prevTk = currTk; prevDate = currDate; } iRow++; } //最后一行未处理 sd.AddToEnd(dd); HistoricalData.TryAdd(sd.Ticker, sd); logStr = logStr + "Total Records:" + iRow.ToString() + "\r\n"; dr.Close(); conn.Close(); // 关闭数据库连接 conn.Dispose(); // 释放数据库连接对象 } catch (Exception ex) { logStr = logStr + "Total Records:" + ex.Message + "\r\n"; return; } WriteLog(this, null); return; //DataAdapter的效率远不及DataReader /* * SqlDataAdapter da = new SqlDataAdapter(sqlStr, conn); * DataSet ds = new DataSet(); * string dsTable = "PriceHist"; * da.Fill(ds, dsTable); * * DataTable dt = ds.Tables[dsTable]; * foreach (DataRow dr in dt.Rows) * { * foreach (DataColumn dc in dt.Columns) * { * Console.WriteLine(dr[dc]); //遍历表中的每个单元格 * } * } * * ds.Dispose(); // 释放DataSet对象 * da.Dispose(); // 释放SqlDataAdapter对象 */ }
private static int GetStockInfoLow2ReturnKN( StockData[] StockInfo, int iIndexEnd ) { int iLow = 0; float iLowV = float.MaxValue; for ( int iIndex = 0; iIndex < iIndexEnd; iIndex++ ) { StockData stockInfo = StockInfo[iIndex]; if ( stockInfo.MinimumPrice < iLowV ) { iLowV = stockInfo.MinimumPrice; iLow = iIndex; } } return iLow + 1; }
public MainBoard(StockData myStock) { stock = myStock; stock.registerObserver(this); }
public static bool IsPassGeneral( StockData[] stockDataArray, Demo.Stock.X.Common.StockInfo stockInfo, U50Filtrate filtrateInfo, U50Extend extendInfo, ref U50ReportSub reportSub ) { if ( stockDataArray == null ) return false; if ( stockDataArray.Length < 3 ) return false; // IsPassGeneral int iSKn = 1; int iH1Kn = GetStockInfoHighReturnKN( stockDataArray ); if ( iH1Kn <= iSKn ) // iH1Kn > iSKn return false; int iL1Kn = GetStockInfoLowReturnKN( stockDataArray ); if ( iL1Kn < iH1Kn ) // iL1Kn >= iH1Kn return false; int iL2Kn = GetStockInfoLow2ReturnKN( stockDataArray, iH1Kn - 1 ); if ( iL2Kn < iSKn ) // iL2Kn >= iSKn return false; if ( iL2Kn >= iH1Kn ) // iL2Kn < iH1Kn return false; StockData stockDataS = stockDataArray[0]; StockData stockDataH1 = stockDataArray[iH1Kn - 1]; StockData stockDataL1 = stockDataArray[iL1Kn - 1]; StockData stockDataL2 = stockDataArray[iL2Kn - 1]; if ( stockDataL1.MinimumPrice >= stockDataL2.MinimumPrice ) return false; if ( stockDataL1.MinimumPrice >= stockDataH1.HighestPrice ) return false; if ( stockDataL1.MinimumPrice >= stockDataS.HighestPrice ) return false; if ( stockDataL2.MinimumPrice >= stockDataH1.HighestPrice ) return false; if ( stockDataL2.MinimumPrice >= stockDataS.HighestPrice ) return false; if ( stockDataS.HighestPrice >= stockDataH1.HighestPrice ) { float fRatio = ( stockDataS.HighestPrice - stockDataH1.HighestPrice ) / ( stockDataS.HighestPrice - stockDataL2.MinimumPrice ); if ( fRatio >= 0.5 ) return false; } // IsPassFiltrate float fP_Up = stockDataH1.HighestPrice - stockDataL1.MinimumPrice; // 主升浪价格幅度 float fP_Down = stockDataH1.HighestPrice - stockDataL2.MinimumPrice; // 下跌浪价格幅度 float fP_Con = stockDataS.HighestPrice - stockDataL2.MinimumPrice; // 盘整浪价格幅度 int iKn_Up = iL1Kn - iH1Kn + 1; // 主升浪K线总数 int iKn_Down = iH1Kn - iL2Kn + 1; // 下跌浪的K线总数 int iKn_Con = iL2Kn - iSKn + 1; // 盘整浪的K线总数 int iKn_Conf = iH1Kn - iSKn + 1; // 整理区间的K线数量 int iKn_U50 = iL1Kn; // U50形态的总K线数 float fVa_Up = 0F; // 主升浪平均成交量 for ( int i = 0; i < iKn_Up; i++ ) { StockData stockData = stockDataArray[( iH1Kn - 1 ) + i]; fVa_Up += stockData.TradingVolume; } fVa_Up = fVa_Up / iKn_Up; float fVa_Down = 0F; // 下跌浪平均成交量 for ( int i = 0; i < iKn_Down; i++ ) { StockData stockData = stockDataArray[( iL2Kn - 1 ) + i]; fVa_Down += stockData.TradingVolume; } fVa_Down = fVa_Down / iKn_Down; float fVa_Con = 0F; // 盘整浪的平均成交量 for ( int i = 0; i < iKn_Con; i++ ) { StockData stockData = stockDataArray[( iSKn - 1 ) + i]; fVa_Con += stockData.TradingVolume; } fVa_Con = fVa_Con / iKn_Con; float fVa_Conf = 0F; // 整理区间平均成交量 for ( int i = 0; i < iKn_Conf; i++ ) { StockData stockData = stockDataArray[( iSKn - 1 ) + i]; fVa_Conf += stockData.TradingVolume; } fVa_Conf = fVa_Conf / iKn_Conf; float fVa_U50 = 0F; // U50形态平均成交量 for ( int i = 0; i < iKn_U50; i++ ) { StockData stockData = stockDataArray[( iSKn - 1 ) + i]; fVa_U50 += stockData.TradingVolume; } fVa_U50 = fVa_U50 / iKn_U50; // 下面是价格比 float fRatioPDU = ( fP_Down / fP_Up ) * 100; if ( filtrateInfo.PDU.Enabled == true ) { if ( filtrateInfo.PDU.Select == U50SelectType.Big ) { if ( fRatioPDU <= filtrateInfo.PDU.Big ) return false; } else if ( filtrateInfo.PDU.Select == U50SelectType.Small ) { if ( fRatioPDU >= filtrateInfo.PDU.Small ) return false; } else if ( filtrateInfo.PDU.Select == U50SelectType.BigAndSmall ) { if ( fRatioPDU <= filtrateInfo.PDU.Big2 || fRatioPDU >= filtrateInfo.PDU.Small2 ) return false; } } float fRatioPCU = ( fP_Con / fP_Down ) * 100; if ( filtrateInfo.PCU.Enabled == true ) { if ( filtrateInfo.PCU.Select == U50SelectType.Big ) { if ( fRatioPCU <= filtrateInfo.PCU.Big ) return false; } else if ( filtrateInfo.PCU.Select == U50SelectType.Small ) { if ( fRatioPCU >= filtrateInfo.PCU.Small ) return false; } else if ( filtrateInfo.PCU.Select == U50SelectType.BigAndSmall ) { if ( fRatioPCU <= filtrateInfo.PCU.Big2 || fRatioPCU >= filtrateInfo.PCU.Small2 ) return false; } } // 下面是K线比 float fRatioTDU = ( (float)iKn_Down / (float)iKn_Up ) * 100; if ( filtrateInfo.TDU.Enabled == true ) { if ( filtrateInfo.TDU.Select == U50SelectType.Big ) { if ( fRatioTDU <= filtrateInfo.TDU.Big ) return false; } else if ( filtrateInfo.TDU.Select == U50SelectType.Small ) { if ( fRatioTDU >= filtrateInfo.TDU.Small ) return false; } else if ( filtrateInfo.TDU.Select == U50SelectType.BigAndSmall ) { if ( fRatioTDU <= filtrateInfo.TDU.Big2 || fRatioTDU >= filtrateInfo.TDU.Small2 ) return false; } } float fRatioTCD = ( (float)iKn_Con / (float)iKn_Down ) * 100; if ( filtrateInfo.TCD.Enabled == true ) { if ( filtrateInfo.TCD.Select == U50SelectType.Big ) { if ( fRatioTCD <= filtrateInfo.TCD.Big ) return false; } else if ( filtrateInfo.TCD.Select == U50SelectType.Small ) { if ( fRatioTCD >= filtrateInfo.TCD.Small ) return false; } else if ( filtrateInfo.TCD.Select == U50SelectType.BigAndSmall ) { if ( fRatioTCD <= filtrateInfo.TCD.Big2 || fRatioTCD >= filtrateInfo.TCD.Small2 ) return false; } } float fRatioTBU = ( (float)iKn_Conf / (float)iKn_Up ) * 100; if ( filtrateInfo.TBU.Enabled == true ) { if ( filtrateInfo.TBU.Select == U50SelectType.Big ) { if ( fRatioTBU <= filtrateInfo.TBU.Big ) return false; } else if ( filtrateInfo.TBU.Select == U50SelectType.Small ) { if ( fRatioTBU >= filtrateInfo.TBU.Small ) return false; } else if ( filtrateInfo.TBU.Select == U50SelectType.BigAndSmall ) { if ( fRatioTBU <= filtrateInfo.TBU.Big2 || fRatioTBU >= filtrateInfo.TBU.Small2 ) return false; } } // 下面是成交量比 float fRatioVac_UC = ( fVa_Up / fVa_Con ) * 100; if ( filtrateInfo.VacUC.Enabled == true ) { if ( filtrateInfo.VacUC.Select == U50SelectType.Big ) { if ( fRatioVac_UC <= filtrateInfo.VacUC.Big ) return false; } else if ( filtrateInfo.VacUC.Select == U50SelectType.Small ) { if ( fRatioVac_UC >= filtrateInfo.VacUC.Small ) return false; } else if ( filtrateInfo.VacUC.Select == U50SelectType.BigAndSmall ) { if ( fRatioVac_UC <= filtrateInfo.VacUC.Big2 || fRatioVac_UC >= filtrateInfo.VacUC.Small2 ) return false; } } // IsPassExtend // H1的价格数据 if ( extendInfo.Info01.Enabled == true ) { if ( extendInfo.Info01.Select == U50ExtendInfo01Type.High ) { StockData[] stockDataArray2 = stockInfo.GetStockDataRangeByTime( stockDataL1.TradingDate ); foreach ( StockData stockData in stockDataArray2 ) { if ( stockDataH1.HighestPrice <= stockData.HighestPrice ) return false; } } else if ( extendInfo.Info01.Select == U50ExtendInfo01Type.HighNumber ) { StockData[] stockDataArray2 = stockInfo.GetStockDataRangeByKn( stockDataL1.TradingDate, extendInfo.Info01.HighNumber ); foreach ( StockData stockData in stockDataArray2 ) { if ( stockDataH1.HighestPrice <= stockData.HighestPrice ) return false; } } } // U50形态的平均成交量 if ( extendInfo.Info02.Enabled == true ) { if ( extendInfo.Info02.Select == U50SelectType.Big ) { if ( fVa_U50 <= extendInfo.Info02.Big ) return false; } else if ( extendInfo.Info02.Select == U50SelectType.Small ) { if ( fVa_U50 >= extendInfo.Info02.Small ) return false; } else if ( extendInfo.Info02.Select == U50SelectType.BigAndSmall ) { if ( fVa_U50 <= extendInfo.Info02.Big2 || fVa_U50 >= extendInfo.Info02.Small2 ) return false; } } // 当日成交量与U50形态平均成交量比值 if ( extendInfo.Info03.Enabled == true ) { float fVsc = ( stockDataH1.TradingVolume / fVa_U50 ) * 100; if ( extendInfo.Info03.Select == U50SelectType.Big ) { if ( fVsc <= extendInfo.Info03.Big ) return false; } else if ( extendInfo.Info03.Select == U50SelectType.Small ) { if ( fVsc >= extendInfo.Info03.Small ) return false; } else if ( extendInfo.Info03.Select == U50SelectType.BigAndSmall ) { if ( fVsc <= extendInfo.Info03.Big2 || fVsc >= extendInfo.Info03.Small2 ) return false; } } // PS≧PH1? if ( extendInfo.Info04.Enabled == true ) { if ( extendInfo.Info04.Select == U50ExtendInfo04Type.No ) { if ( stockDataS.HighestPrice > stockDataH1.HighestPrice ) // PS <= PH1 return false; } else if ( extendInfo.Info04.Select == U50ExtendInfo04Type.Yes ) { if ( stockDataS.HighestPrice < stockDataH1.HighestPrice ) // PS >= PH1 return false; } } // S点所属K线的收盘价 if ( extendInfo.Info05.Enabled == true ) { if ( extendInfo.Info05.Select == U50SelectType.Big ) { if ( stockDataS.ClosePrice <= extendInfo.Info05.Big ) return false; } else if ( extendInfo.Info05.Select == U50SelectType.Small ) { if ( stockDataS.ClosePrice >= extendInfo.Info05.Small ) return false; } else if ( extendInfo.Info05.Select == U50SelectType.BigAndSmall ) { if ( stockDataS.ClosePrice <= extendInfo.Info05.Big2 || stockDataS.ClosePrice >= extendInfo.Info05.Small2 ) return false; } } reportSub.Q_U50 = 0; reportSub.KLineNumber = iKn_U50; reportSub.Va_U50 = fVa_U50; reportSub.Vsc = stockDataS.TradingVolume; reportSub.Close = stockDataS.ClosePrice; Debug.WriteLine( " " ); Debug.WriteLine( " " ); Debug.WriteLine( " " ); Debug.WriteLine( " --- --- --- --- ---" ); Debug.WriteLine( "StockSymbol: --- " + " stockInfo.StockSymbol = " + stockInfo.StockSymbol ); Debug.WriteLine( "H1TradingDateTime: --- " + " stockDataH1.TradingDateTime = " + stockDataH1.TradingDateTime.ToString() ); Debug.WriteLine( "L1TradingDateTime: --- " + " stockDataL1.TradingDateTime = " + stockDataL1.TradingDateTime.ToString() ); Debug.WriteLine( "L2TradingDateTime: --- " + " stockDataL2.TradingDateTime = " + stockDataL2.TradingDateTime.ToString() ); Debug.WriteLine( "fP_Down: --- " + " stockDataH1.HighestPrice = " + stockDataH1.HighestPrice.ToString() + " stockDataL2.MinimumPrice = " + stockDataL2.MinimumPrice.ToString() ); Debug.WriteLine( "fP_Up: --- " + " stockDataH1.HighestPrice = " + stockDataH1.HighestPrice.ToString() + " stockDataL1.MinimumPrice = " + stockDataL1.MinimumPrice.ToString() ); Debug.WriteLine( "fRatioPDU: --- " + " fP_Down = " + fP_Down.ToString() + " fP_Up = " + fP_Up.ToString() + " fRatioPDU = " + fRatioPDU.ToString() ); Debug.WriteLine( "PDU.Small: --- " + "Select = " + filtrateInfo.PDU.Select.ToString() + " filtrateInfo.PDU.Small = " + filtrateInfo.PDU.Small.ToString() ); Debug.WriteLine( "stockDataS.Close: --- " + "reportSub.Close = " + reportSub.Close.ToString() ); Debug.WriteLine( "Kn_U50: --- " + "reportSub.KLineNumber= " + reportSub.KLineNumber.ToString() ); Debug.WriteLine( " --- --- --- --- ---" ); return true; }
public static async Task <StockData> Get(Stock stock, Api.Interval interval) { StockData stockData = await Get(stock, interval, _dataRefreshRate); return(stockData); }
void IRuleInterface.Compute(StockData aStockData) { throw new NotImplementedException(); }
public void Add(StockData data) { StockMongoDB.GetInstance().AddStockData(data); }
public virtual void Compute(StockData aStockData) { }
private void UpdatePrice(StockData obj) { Price = obj.StockPrice; }
public void SetUpRow(UIMarketPanel marketPanel, StockData stockData) { this.marketPanel = marketPanel; this.stockData = stockData; backgroundImage.color = stockData.StockType.Color; }
public override bool Qualified(DataRowCollection rows, int index, StockData currentPrice, StockData beforePrice, StockData afterPrice) { if (currentPrice == null || beforePrice == null) { return(false); } if (!BeforeHasTrend(rows, index)) { return(false); } var previousTop = beforePrice.close > beforePrice.open ? beforePrice.close : beforePrice.open; var previousBottom = beforePrice.close > beforePrice.open ? beforePrice.open : beforePrice.close; var currentTop = currentPrice.close > currentPrice.open ? currentPrice.close : currentPrice.open; var currentBottom = beforePrice.close > beforePrice.open ? beforePrice.open : beforePrice.close; //current top must be greater than previous top if (currentTop < previousTop) { return(false); } //current bottom must be less than previous bottom if (currentBottom > previousBottom) { return(false); } //current price direction must be opposite to previous if ((currentPrice.open - currentPrice.close) * (beforePrice.open - beforePrice.close) > 0) { return(false); } return(true); }
/// <summary> /// Creates a FinancialDataBaseViewModel instance from a FinancialData instance. /// </summary> /// <param name="data">The FinancialData instance.</param> public StockDataViewModel(StockData data) { SetFinancialData(data); }
private void EditStockItem(StockData _StockItemToEdit) { msqlConnection = new MySql.Data.MySqlClient.MySqlConnection("server=localhost;user id=root;Password=technicise;database=sptdb;persist security info=False"); try { //define the command reference MySql.Data.MySqlClient.MySqlCommand msqlCommand = new MySql.Data.MySqlClient.MySqlCommand(); msqlCommand.Connection = msqlConnection; msqlConnection.Open(); msqlCommand.CommandText = "UPDATE stock SET product_name='" + _StockItemToEdit.productName + "',vat_rate='" + _StockItemToEdit.vatRate + "' WHERE id='" + _StockItemToEdit.productId + "'; "; msqlCommand.ExecuteNonQuery(); } catch (Exception er) { MessageBox.Show(er.Message); } finally { //always close the connection msqlConnection.Close(); } }
private static PriceTrend GetTrend(StockData data, int index, int period, PricePoint pricePoint) { int startIndex = index + 1 - period; PriceTrend result = PriceTrend.Flat; if (startIndex >= 0) { int sectorCount = 3; int sectorSize = period / sectorCount; double[] sectorSMAs = new double[sectorCount]; int remaininglastSector = period % sectorSize; //get sector SMAs for (int i = 0; i < sectorCount; i++) { switch (pricePoint) { case PricePoint.Close: sectorSMAs[i] = GetAverage(data, startIndex + i * sectorSize, sectorSize + remaininglastSector, PricePoint.Close); break; case PricePoint.Low: sectorSMAs[i] = GetAverage(data, startIndex + i * sectorSize, sectorSize + remaininglastSector, PricePoint.Low); break; case PricePoint.High: sectorSMAs[i] = GetAverage(data, startIndex + i * sectorSize, sectorSize + remaininglastSector, PricePoint.High); break; case PricePoint.Open: sectorSMAs[i] = GetAverage(data, startIndex + i * sectorSize, sectorSize + remaininglastSector, PricePoint.Open); break; } } //compare sector SMAs double lastSMA = sectorSMAs[0]; bool isUp = true; bool isDown = true; for (int i = 1; i < sectorCount; i++) { if (sectorSMAs[i] < lastSMA) { isUp = false; } if (sectorSMAs[i] > lastSMA) { isDown = false; } lastSMA = sectorSMAs[i]; } if (isUp) { result = PriceTrend.Up; } if (isDown) { result = PriceTrend.Down; } } return(result); }
CompanyTradingData GetCompanyTradingData(StockData newData, DateTime current) { CompanyTradingData ctd = new CompanyTradingData(newData, ""); return(ctd); }
//################################################################################ #region Constructor public StockUpdateEventArgs(StockData stockData) { StockData = stockData; }
public override bool Qualified(DataRowCollection rows, int index, StockData currentPrice, StockData beforePrice, StockData afterPrice) { if (currentPrice == null || beforePrice == null) { return(false); } if (!BeforeHasTrend(rows, index)) { return(false); } //Before trend must be Down if (AnalysisCommon.CheckBeforeTrendDirection(rows, index, _trendPeriod) != AnalysisCommon.TrendDirection.Down) { return(false); } //Previous day must be down if (beforePrice.open < beforePrice.close) { return(false); } //Current day must be up if (currentPrice.open > currentPrice.close) { return(false); } //Current Open must be less than previous close if (currentPrice.open > beforePrice.close) { return(false); } //Current close must be greater than previous close if (currentPrice.close < beforePrice.close) { return(false); } //Shadow line must be very short for previous if ((beforePrice.high - beforePrice.close) > (beforePrice.high - beforePrice.low) * multiplier) { return(false); } if ((beforePrice.open - beforePrice.low) > (beforePrice.high - beforePrice.low) * multiplier) { return(false); } //Shadow line must be very short for current if ((currentPrice.high - currentPrice.open) > (currentPrice.high - currentPrice.low) * multiplier) { return(false); } if ((currentPrice.close - currentPrice.low) > (currentPrice.high - currentPrice.low) * multiplier) { return(false); } //current close must be in body of previous bar for more than 60% if ((currentPrice.close - beforePrice.close) < (beforePrice.open - beforePrice.close) * multiplier2) { return(false); } return(true); }
public async Task <StockTradeList> Find(Stock stock, DateTime startDate, DateTime endDate) { StockTradeList tradeList = new StockTradeList(Api.Interval.Daily); StockData data = await StockDataBase.Get(stock, Api.Interval.Daily); int startIndex = data.FindDateIndex(startDate); int period = 40; double priceGainGate = -0.5; double volumeGainGate = 0.5; int tradeHoldLenght = 15; double tradeHoldMaxGain = 0.04; double tradeHoldMaxLoss = -0.04; bool inTrade = false; for (int i = startIndex; i < data.TimeSeries.DataPoints.Count; i++) { if (!inTrade) { { double open = data.TimeSeries.DataPoints[i].Open; double close = data.TimeSeries.DataPoints[i].Close; double percentageGain = (close - open) / open; if (percentageGain > priceGainGate) { double volume = data.TimeSeries.DataPoints[i].Volume; double volumeSMA = Indicators.GetSMA(data, i, period, PricePoint.Volume); double volumePercentageGain = (volume - volumeSMA) / volumeSMA; if (volumePercentageGain > volumeGainGate) { StockTrade trade = new StockTrade { DataIndex = i, PortfolioPercentage = 1, Stock = stock, Type = StockTradeType.LongStock }; tradeList.Trades.Add(trade); inTrade = true; } } } } else { StockTrade lastTrade = tradeList.Trades[tradeList.Trades.Count - 1]; double posOpen = data.TimeSeries.DataPoints[lastTrade.DataIndex].Close; double currentPrice = data.TimeSeries.DataPoints[i].Close; double percentageGain = (currentPrice - posOpen) / posOpen; if (i - lastTrade.DataIndex >= tradeHoldLenght) { StockTrade trade = new StockTrade { DataIndex = i, PortfolioPercentage = 0, Stock = stock, Type = StockTradeType.LongStock }; tradeList.Trades.Add(trade); inTrade = false; } else if (percentageGain > tradeHoldMaxGain || percentageGain < tradeHoldMaxLoss) { StockTrade trade = new StockTrade { DataIndex = i, PortfolioPercentage = 0, Stock = stock, Type = StockTradeType.LongStock }; tradeList.Trades.Add(trade); inTrade = false; } } } return(tradeList); }
public string getCurrencies() { String strImagPath = ConfigurationManager.AppSettings["Image_Path"].ToString(); int rowcount = 0; int tdcount = 0; string strScriptName = ""; System.Text.StringBuilder strBuilBody = new System.Text.StringBuilder(); try { //DataTable dt = new DataTable(); //dt.Columns.Add("ID", typeof(int)); //dt.Columns.Add("Name", typeof(string)); //dt.Columns.Add("Country", typeof(string)); //dt.Columns.Add("Currency", typeof(string)); //dt.Columns.Add("Rate", typeof(decimal)); //dt.Columns.Add("ChangePercent", typeof(string)); //dt.Columns.Add("UpdateDateTime", typeof(DateTime)); //Hashtable hashCode = new Hashtable(); //Hashtable hashName = new Hashtable(); //Hashtable hashSecondndCurrName = new Hashtable(); //XmlDocument xmldoc = new XmlDocument(); //xmldoc.Load(strImagPath + "XML/Currencies.xml"); ////xmldoc.Load("E:/MoneyJugglerss/XML/Currencies.xml"); //XmlNodeList nodeList = xmldoc.GetElementsByTagName("Stock"); //for (int i = 0; i < nodeList.Count; i++) //{ // hashCode.Add("code" + i, (object)nodeList[i].Attributes.Item(0).ChildNodes[0].InnerText.ToString()); // hashName.Add("name" + i, (object)nodeList[i].Attributes.Item(1).ChildNodes[0].InnerText.ToString()); // hashSecondndCurrName.Add("SecondndCurrName" + i, (object)nodeList[i].Attributes.Item(2).ChildNodes[0].InnerText.ToString()); //} //int stockCount = 0; //if (hashCode.Count < 5) //{ // stockCount = hashCode.Count; //} //else //{ // stockCount = 5; //} //StockData m_Index2Data = new StockData(); //string serverUrl = ""; //for (int i = 0; i < stockCount; i++) //{ // serverUrl = @"http://finance.yahoo.com/d/quotes.csv?s=" + hashCode["code" + i].ToString() + // "&f=sl1d1t1c1ohgv&e=.csv"; // dt = GetStockData(hashCode["code" + i].ToString(), m_Index2Data, dt, serverUrl, "CUR", hashName["name" + i].ToString(), hashSecondndCurrName["SecondndCurrName" + i].ToString()); //} DataTable dt = new DataTable(); dt.Columns.Add("ID", typeof(int)); dt.Columns.Add("Name", typeof(string)); dt.Columns.Add("Country", typeof(string)); //Country is second currency name dt.Columns.Add("Currency", typeof(string)); //Currency is first currency name dt.Columns.Add("Rate", typeof(decimal)); dt.Columns.Add("ChangePercent", typeof(string)); dt.Columns.Add("UpdateDateTime", typeof(DateTime)); Hashtable hashCode = new Hashtable(); Hashtable hashName = new Hashtable(); Hashtable hashSecondndCurrName = new Hashtable(); XmlDocument xmldoc = new XmlDocument(); xmldoc.Load(strImagPath + "XML/Currencies.xml"); XmlNodeList nodeList = xmldoc.GetElementsByTagName("Stock"); for (int i = 0; i < nodeList.Count; i++) { hashCode.Add("code" + i, (object)nodeList[i].Attributes.Item(0).ChildNodes[0].InnerText.ToString()); hashName.Add("name" + i, (object)nodeList[i].Attributes.Item(1).ChildNodes[0].InnerText.ToString()); hashSecondndCurrName.Add("SecondndCurrName" + i, (object)nodeList[i].Attributes.Item(2).ChildNodes[0].InnerText.ToString()); } StockData m_Index2Data = new StockData(); string serverUrl = ""; for (int i = 0; i < hashCode.Count; i++) { serverUrl = @"http://finance.yahoo.com/d/quotes.csv?s=" + hashCode["code" + i].ToString() + "&f=sl1d1t1c1ohgv&e=.csv"; // dt = GetStockData(hashCode["code" + i].ToString(), m_Index2Data, dt, serverUrl, "CUR", hashName["name" + i].ToString(), hashSecondndCurrName["SecondndCurrName" + i].ToString()); // dt = GetStockData(hashCode["code" + i].ToString(), m_Index2Data, dt, serverUrl, "CUR", hashName["name" + i].ToString(), hashSecondndCurrName["SecondndCurrName" + i].ToString()); dt = GetStockData(hashCode["code" + i].ToString(), m_Index2Data, dt, serverUrl, "CUR"); } int ii = 0; if (dt.Rows.Count < 5) { for (int j = 0; j < 5 - (dt.Rows.Count);) { ii = (dt.Rows.Count - 1) + 1; DataRow drr = dt.NewRow(); drr["ID"] = 0; drr["Name"] = "------"; drr["Country"] = 0; drr["Currency"] = "-----"; drr["Rate"] = 0.00; drr["ChangePercent"] = 0.00; dt.Rows.Add(drr); } } if (dt.Rows.Count > 0) { //strBuilBody.Append("<h3 class=\"captalHead\">"); //strBuilBody.Append("Currencies </h3>"); strBuilBody.Append("<table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\">"); strBuilBody.Append("<tr>"); strBuilBody.Append("<td width=\"50%\" align=\"center\" valign=\"top\" class=\"companybg\">"); strBuilBody.Append("Symbol"); strBuilBody.Append("</td>"); strBuilBody.Append("<td width=\"50%\" align=\"center\" valign=\"top\" class=\"companybg noborder\">"); strBuilBody.Append("Rate</td>"); strBuilBody.Append("</tr>"); for (int i = 0; i < 5; i++) { if (dt.Rows[i]["Name"].ToString().Length >= 11) { strScriptName = dt.Rows[i]["Name"].ToString().Substring(0, 11); } else { strScriptName = dt.Rows[i]["Name"].ToString(); } strBuilBody.Append("<tr>"); strBuilBody.Append("<td width=\"50%\" align=\"center\" valign=\"top\" class=\"captext\">"); strBuilBody.Append("" + strScriptName + "</td>"); strBuilBody.Append("<td width=\"50%\" align=\"center\" valign=\"top\" class=\"captext\">"); strBuilBody.Append("1-" + dt.Rows[i]["Rate"].ToString() + "</td>"); strBuilBody.Append("</tr>"); } strBuilBody.Append("<tr>"); strBuilBody.Append("<td colspan=\"2\" align=\"right\" valign=\"top\"><a target=_blank href=\"http://www.moneyjugglers.com/infomine_view_more.aspx?name=currencies\" title=\"view more\" class=\"captextbtn\">view more »</a></td>"); strBuilBody.Append("<tr>"); strBuilBody.Append("</table>"); dt.Dispose(); dt.Clear(); } } catch (Exception ex) { strBuilBody.Remove(0, strBuilBody.Length); Response.Write(ex.Message); } finally { } return(strBuilBody.ToString()); }
public void Test_ExtractTickerData_Returns_Valid_Ticker_Data() { //Arrange Mock <IStockDataRepository> mockStockDataRepository = new Mock <IStockDataRepository>(); IParseRawStockData parseRawData = new ParseRawStockData(mockStockDataRepository.Object); var dt = new Datatable { data = new List <List <object> >(), columns = new List <Column>() }; StockData stockData = new StockData() { datatable = new Datatable { data = new List <List <object> > { new List <object> { "COF", "2017-01-03", 88.55, 89.6, 87.79, 88.87, 3441067.0, 0.0, 1.0, 87.30123847595, 88.336431027048, 86.551956248488, 87.616725729618, 3441067.0 }, new List <object> { "COF", "2017-01-04", 89.13, 90.77, 89.13, 90.3, 2630905.0, 0.0, 1.0, 87.873059123223, 89.489931298271, 87.873059123223, 89.026559394447, 2630905.0 }, new List <object> { "MSFT", "2017-01-03", 62.79, 62.84, 62.125, 62.58, 20694101.0, 0.0, 1.0, 62.064301929466, 62.113724052359, 61.406987694984, 61.856729013314, 20694101.0 }, new List <object> { "MSFT", "2017-01-04", 62.48, 62.75, 62.12, 62.3, 21339969.0, 0.0, 1.0, 61.757884767527, 62.024764231151, 61.402045482695, 61.579965125111, 21339969.0 } }, columns = new List <Column>() }, meta = new Meta() }; var dailyData = stockData.datatable.data.Select(x => new DailySummary(x)).ToList(); //expected result IDictionary <string, IList <DailySummary> > expectedResult = new Dictionary <string, IList <DailySummary> >(); var msData = new List <DailySummary> { new DailySummary(new List <object> { "MSFT", "2017-01-03", 62.79, 62.84, 62.125, 62.58, 20694101.0, 0.0, 1.0, 62.064301929466, 62.113724052359, 61.406987694984, 61.856729013314, 20694101.0 }), new DailySummary(new List <object> { "MSFT", "2017-01-04", 62.48, 62.75, 62.12, 62.3, 21339969.0, 0.0, 1.0, 61.757884767527, 62.024764231151, 61.402045482695, 61.579965125111, 21339969.0 }) }; var cofData = new List <DailySummary> { new DailySummary(new List <object> { "COF", "2017-01-03", 88.55, 89.6, 87.79, 88.87, 3441067.0, 0.0, 1.0, 87.30123847595, 88.336431027048, 86.551956248488, 87.616725729618, 3441067.0 }), new DailySummary(new List <object> { "COF", "2017-01-04", 89.13, 90.77, 89.13, 90.3, 2630905.0, 0.0, 1.0, 87.873059123223, 89.489931298271, 87.873059123223, 89.026559394447, 2630905.0 }) }; expectedResult.Add("COF", cofData); expectedResult.Add("MSFT", msData); //Act var actualResult = parseRawData.ExtractTickerData(dailyData); //Assert Assert.AreEqual(expectedResult.Count(), actualResult.Count()); }
private void ShowProductNames() { MySql.Data.MySqlClient.MySqlCommand msqlCommand = new MySql.Data.MySqlClient.MySqlCommand(); msqlConnection = new MySql.Data.MySqlClient.MySqlConnection("server=localhost;user id=root;Password=technicise;database=sptdb;persist security info=False"); //define the connection used by the command object msqlCommand.Connection = msqlConnection; if (msqlConnection.State != System.Data.ConnectionState.Open) msqlConnection.Open(); msqlCommand.CommandText = "SELECT product_name,id,rate,quantity_available,vat_rate FROM stock group by product_name"; MySql.Data.MySqlClient.MySqlDataReader msqlReader = msqlCommand.ExecuteReader(); _purchaseProductCollection.Clear(); while (msqlReader.Read()) { StockData currentStock = new StockData(); currentStock.productName = msqlReader.GetString("product_name"); currentStock.rate = msqlReader.GetDouble("rate"); currentStock.productId = msqlReader.GetString("id"); currentStock.quantityAvailable = msqlReader.GetDouble("quantity_available"); currentStock.vatRate = msqlReader.GetDouble("vat_rate"); _purchaseProductCollection.Add(currentStock); } msqlConnection.Close(); }
public void Test_ParseRawStockData_Returns_Parsed_Data() { //Arrange Mock <IStockDataRepository> mockStockDataRepository = new Mock <IStockDataRepository>(); IParseRawStockData parseRawData = new ParseRawStockData(mockStockDataRepository.Object); var dt = new Datatable { data = new List <List <object> >(), columns = new List <Column>() }; StockData stockData = new StockData() { datatable = new Datatable { data = new List <List <object> > { new List <object> { "MSFT", "2017-01-03", 62.79, 62.84, 62.125, 62.58, 20694101.0, 0.0, 1.0, 62.064301929466, 62.113724052359, 61.406987694984, 61.856729013314, 20694101.0 }, new List <object> { "MSFT", "2017-01-04", 62.48, 62.75, 62.12, 62.3, 21339969.0, 0.0, 1.0, 61.757884767527, 62.024764231151, 61.402045482695, 61.579965125111, 21339969.0 }, new List <object> { "MSFT", "2017-01-05", 62.19, 62.66, 62.03, 62.3, 24875968.0, 0.0, 1.0, 61.471236454746, 61.935804409943, 61.313085661487, 61.579965125111, 24875968.0 }, new List <object> { "MSFT", "2017-01-06", 62.3, 63.15, 62.04, 62.84, 19922919.0, 0.0, 1.0, 61.579965125111, 62.420141214298, 61.322970086066, 62.113724052359, 19922919.0 }, new List <object> { "MSFT", "2017-01-09", 62.76, 63.08, 62.54, 62.64, 20382730.0, 0.0, 1.0, 62.03464865573, 62.350950242247, 61.817191314999, 61.916035560786, 20382730.0 }, new List <object> { "MSFT", "2017-01-10", 62.73, 63.07, 62.28, 62.62, 18593004.0, 0.0, 1.0, 62.004995381994, 62.341065817669, 61.560196275954, 61.896266711629, 18593004.0 }, new List <object> { "MSFT", "2017-01-11", 62.61, 63.23, 62.43, 63.19, 21517335.0, 0.0, 1.0, 61.88638228705, 62.499216610927, 61.708462644634, 62.459678912613, 21517335.0 }, }, columns = new List <Column>() }, meta = new Meta() }; var expectedResult = stockData.datatable.data.Select(x => new DailySummary(x)).ToList(); mockStockDataRepository.Setup(x => x.GetRawData(It.IsAny <string>())).Returns(Task.FromResult(stockData)); //Act var result = parseRawData.ExtractDailyData("http://localhost:8000").ToList(); //Assert Assert.IsNotNull(result); Assert.AreEqual(result.Count(), expectedResult.Count()); for (int i = 0; i < expectedResult.Count(); i++) { Assert.AreEqual(expectedResult[i].Ticker, result[i].Ticker); Assert.AreEqual(expectedResult[i].Date, result[i].Date); Assert.AreEqual(expectedResult[i].Open, result[i].Open); Assert.AreEqual(expectedResult[i].High, result[i].High); Assert.AreEqual(expectedResult[i].Low, result[i].Low); Assert.AreEqual(expectedResult[i].Close, result[i].Close); Assert.AreEqual(expectedResult[i].Volume, result[i].Volume); Assert.AreEqual(expectedResult[i].Ex_Dividend, result[i].Ex_Dividend); Assert.AreEqual(expectedResult[i].Split_Ratio, result[i].Split_Ratio); Assert.AreEqual(expectedResult[i].Adj_Open, result[i].Adj_Open); Assert.AreEqual(expectedResult[i].Adj_High, result[i].Adj_High); Assert.AreEqual(expectedResult[i].Adj_Low, result[i].Adj_Low); Assert.AreEqual(expectedResult[i].Adj_Close, result[i].Adj_Close); Assert.AreEqual(expectedResult[i].Adj_Volume, result[i].Adj_Volume); } }
private void DrawStockInfo(StockData stockData) { _graphGraphics.DrawString(stockData.MetaData.Symbol, new Font(FontFamily.GenericSansSerif, 8), Brushes.White, 10, 10); }
async void HandleGetStock(object sender, EventArgs e) { //USER INPUT string UserInput; UserInput = GetStock.Text; //User input that is used to retrieve the desired company ancronym //adding the user input to the api endpoint, and converting it to a URI variable string StockApiEndpoint = "https://www.alphavantage.co/query?function=TIME_SERIES_DAILY" + "&symbol=" + UserInput + "&apikey=" + key; Uri StockApiUri = new Uri(StockApiEndpoint); //A class instance that is used to send HTTP requests and receive HTTP responses HttpClient client = new HttpClient(); //gets data from api HttpResponseMessage response = await client.GetAsync(StockApiUri); //string string jsonContent = await response.Content.ReadAsStringAsync(); //parse into an object according to data model var stockData = StockData.FromJson(jsonContent); //if an error wasn't returned if (jsonContent != GlobalVariables.ErrorString) { //convert dictionary to list GlobalVariables.StockList = stockData.TimeSeriesDaily.Values.ToList(); GlobalVariables.DatesList = stockData.TimeSeriesDaily.Keys.ToList(); List <DayData> DayList = new List <DayData>(); for (int i = 0; i < 30; i++) { //data model equal to api equivalent. //reminder parsing means to take one form of data and converting it to another //data model defines how information is stoed and retrieced to support solution. dailydata.date = GlobalVariables.DatesList[i]; dailydata.high = double.Parse(GlobalVariables.StockList[i].The2High); dailydata.low = double.Parse(GlobalVariables.StockList[i].The3Low); dailydata.close = double.Parse(GlobalVariables.StockList[i].The4Close); //add dailydata to list DayList.Add(dailydata); dailydata = new DayData(); } historyListView.ItemsSource = DayList; //populate rest of the fields ins the page populatePage(); GlobalVariables.retreived = true; entries.Clear(); ChartView.Chart = new LineChart { Entries = entries, BackgroundColor = SKColors.Transparent }; FillChart(); ChartView.Chart = new LineChart { Entries = entries, BackgroundColor = SKColors.Transparent, }; } else { await DisplayAlert("ERROR", "Invalid Stock Symbol", "OK"); } }
void editWindow_OnEditStockItemData(StockData returnEditedStockItemData) { //finding the element StockData vData = _stockCollection.Where(item => item.productId.Equals(returnEditedStockItemData.productId)).First(); //finding the element position int itemIdex = _stockCollection.IndexOf(vData); //remove the element so that the list gets refreshed _stockCollection.RemoveAt(itemIdex); //insert the edited element at same position _stockCollection.Insert(itemIdex, returnEditedStockItemData); }
private void StockDownload(ref StockData aStockData) { QueryController nController = new QueryController(); nController.QueryStockData(ref aStockData); }
void newStock_OnAddNewStockData(StockData returnStockData) { //returnStockData.serialNo = GetCurrentSerialNumber(); _stockCollection.Add(returnStockData); }
public StockData[] GetStockDataRangeByTime( DateTime dataTimeStart ) { ToSortArray(); int iStart = -1; for ( int iIndex = 0; iIndex < m_DateTimeStockData.Length; iIndex++ ) { StockData item = m_DateTimeStockData[iIndex]; if ( item.TradingDate <= dataTimeStart ) { iStart = iIndex; break; } } if ( iStart == -1 ) return new StockData[0]; StockData[] stockDataArray = new StockData[m_DateTimeStockData.Length - iStart]; Array.Copy( m_DateTimeStockData, iStart, stockDataArray, 0, stockDataArray.Length ); return stockDataArray; }