public void SetCurrentSession(FUTINFO.session sess, DateTime SrvTmLocal, int timeTolMS) { SessionNumber = sess.sess_id; if (CUtilTime.InTmInterval(SrvTmLocal, sess.begin, sess.end, timeTolMS)) { SessionBegin = sess.begin; SessionEnd = sess.end; SessionType = EnmSessionTypes.SessDay; _client.GUIBox.UpdateSessionString(SessionBegin, SessionEnd); } else if (sess.eve_on == 1 && CUtilTime.InTmInterval(SrvTmLocal, sess.eve_begin, sess.eve_end, timeTolMS)) { SessionBegin = sess.eve_begin; SessionEnd = sess.eve_end; SessionType = EnmSessionTypes.SessEvening; _client.GUIBox.UpdateSessionString(SessionBegin, SessionEnd); } else if (sess.mon_on == 1 && CUtilTime.InTmInterval(SrvTmLocal, sess.mon_begin, sess.mon_end, timeTolMS)) { SessionBegin = sess.mon_begin; SessionEnd = sess.mon_end; SessionType = EnmSessionTypes.SessMorningAdditional; _client.GUIBox.UpdateSessionString(SessionBegin, SessionEnd); } }
public static bool WasClosed_M5_M15_M30_TF(DateTime dtPrev, DateTime dtCurr, List <int> lstScale, ref DateTime dtFrom, ref DateTime dtTo) { int i = -1; while (lstScale[i + 1] <= dtPrev.Minute) { i++; } dtFrom = CUtilTime.NormalizeMinutes(/*dtCurr*/ dtPrev, lstScale[i]); dtTo = CUtilTime.NormalizeMinutes(/*dtCurr*/ dtPrev, lstScale[i + 1]); if (dtFrom.Day == 23 && dtFrom.Hour == 18 && dtFrom.Minute == 55) { int tmp = 1; } if ((dtPrev.Date == dtCurr.Date && dtPrev.Hour == dtCurr.Hour && i + 1 < lstScale.Count && dtCurr.Minute >= lstScale[i + 1]) || (dtPrev.Date == dtCurr.Date && dtCurr.Hour > dtPrev.Hour) || (dtPrev.Date < dtCurr.Date)) { return(true); } return(false); }
public void SetTF(EnmTF tf) { TF = tf; if (TF == EnmTF.M1) { DateTF = CUtilTime.NormalizeSeconds(Date); } else if (TF == EnmTF.M5) { DateTF = CUtilTime.NormalizeToM5(Date); } else if (TF == EnmTF.M15) { DateTF = CUtilTime.NormalizeToM15(Date); } else if (TF == EnmTF.M30) { DateTF = CUtilTime.NormalizeToM30(Date); } else if (TF == EnmTF.H1) { DateTF = CUtilTime.NormalizeHour(Date); } else if (TF == EnmTF.D1) { DateTF = CUtilTime.NormalizeDay(Date); } else { DateTF = Date; } }
private void CheckForNewSessions(string stTime) { //TODO from global variable, from config //int mscOffset = -2; DateTime dt = CASTSConv.ASTSTimeToDateTime(stTime); DateTime dtBegin = GetSessionStartNormalTime(); DateTime dtEnd = GetSessionEndNormalTime(); int tolMs = 2000; if (CUtilTime.IsEqual(dt, dtBegin, tolMs)) { _currSession = new CDBSession { DtBegin = dtBegin, DtEnd = dtEnd, stock_exchange_id = _client.StockExchId }; _lstSessions.Add(_currSession); } CUtil.TaskStart(InsertUnsavedSessions); }
public void SetSessionBeginEnd(Dictionary <string, object> data) { DtSessionBegin = (DateTime)data["DtBegin"]; DtSessionEnd = (DateTime)data["DtEnd"]; //TODO get from DB (and set to it previously) //this is for work for demo and real FORTS //but values are not correct now DtEveSessionBegin = DtSessionBegin; if (_useRealServer) { DtDaySessionBegin = CUtilTime.NormalizeDay(DtSessionEnd).AddHours(9).AddMinutes(0); } else { DtDaySessionBegin = CUtilTime.NormalizeDay(DtSessionEnd).AddHours(7).AddMinutes(0); } DtEveSessionEnd = CUtilTime.NormalizeDay(DtEveSessionBegin).AddHours(23).AddMinutes(45); DtDaySessionEnd = DtSessionEnd; }
private int GenSessionId() { //DateTime _dt = _client.ServerTime; long ls = CUtilTime.GetCurrentUnixTimestampSeconds(); return((int)ls); }
/// <summary> /// Checks if RawDeal is later than Open posittion. /// Disabled 2017-10-19 /// </summary> /// <param name="botID"></param> /// <param name="instrument"></param> /// <param name="rdTimeMili">Time in millisecs of raw deal</param> /// <returns></returns> private bool IsRawDealLaterThenOpenedPos(int botID, string instrument, long rdTimeMili) { lock (LckDictPositionsOfBots) { CBotPos bp = GetBotPos(botID, instrument); //no opened pos rd is later if (bp.Amount == 0) { return(true); } long botposTimeMili = CUtilTime.GetUnixTimestampMillis(bp.DtOpen); if (rdTimeMili > botposTimeMili) { return(true); } return(false); } }
public bool IsNewData(CRawDeal rd) { DateTime rd_date = CUtilTime.NormalizeDay(rd.Moment.Date); if (!this.ContainsKey("M1")) { return(true); } if (!this["M1"].ContainsKey(rd_date)) { return(true); } if (this["M1"][rd_date].ListTimeFrameInfo.Count == 0) { return(true); } DateTime dt = this["M1"][rd_date].ListTimeFrameInfo.Last().Dt;//.AddMinutes(1); if (rd.Moment > dt) { return(true); } return(false); }
static void Log(string msg) { string msgCons = String.Format("[{0}] {1}", CUtilTime.GetDateTimeString(DateTime.Now), msg); Console.WriteLine(msgCons); }
private string GetFileName() { string dir = GetDataDirectory(); string path = dir + _instrument.ToString() + "_" + CUtilTime.GeDateString(DateTime.Now).ToString() + ".dat"; return(path); }
public void TestBfxTimes() { DateTime dt = CUtilTime.DateTimeFromUnixTimestampMillis(1518516579415); if (dt != null) { System.Threading.Thread.Sleep(0); } }
public void Update(ResponseTrades[] rt) { for (int i = rt.Length - 1; i >= 0; i--) { ResponseTrades trade = rt[i]; Log(trade.ToString()); DateTime dtCreate = CUtilTime.DateTimeFromUnixTimestampMillis( Convert.ToInt64(trade.MtsCreate)); if ((DateTime.UtcNow - dtCreate).TotalHours > _parHourOld) { continue; } if (_lst.Find(el => el.Id == trade.Id) == null) //not found { long botId = _client.GetBotIdBfxRest(trade.OrderId); if (botId > 0)// botId found { CDBBfxTrades bfxTrade = new CDBBfxTrades { Id = trade.Id, BotId = botId, MtsCreate = trade.MtsCreate, OrderId = trade.OrderId, Pair = trade.Pair.Remove(0, 1), ExecAmount = Convert.ToDecimal(trade.ExecAmount), ExecPrice = Convert.ToDecimal(trade.ExecPrice), Maker = trade.Maker, Fee = Convert.ToDecimal(trade.Fee), FeeCurrency = trade.FeeCurrency, OrderPrice = Convert.ToDecimal(trade.OrderPrice), DtCreate = dtCreate }; _lst.Add(bfxTrade); _client.DBCommunicator.QueueData(bfxTrade); if (_lst.Count > 0) { if ((DateTime.UtcNow - _lst[0].DtCreate).TotalHours > _parHourOld) { _lst.RemoveAt(0); Log(String.Format("Remove first. Count={0}", _lst.Count)); } } } } } }
private static void TestTime() { DateTime dt = CUtilTime.MscToLocal(DateTime.Now); if (dt != null) { System.Threading.Thread.Sleep(0); } }
private void ProcessTradeExecute(string inpInstrWithPrefix, JArray jarrTe) { string instrument = CBfxUtils.RemoveFirstT(inpInstrWithPrefix); int decimalVolume = GetDecimalVolume(instrument); long lngMilis = (long)jarrTe[1]; decimal dcmlAmountRaw = (decimal)jarrTe[2]; decimal dcmlAmount = Math.Abs(dcmlAmountRaw); decimal dcmlPrice = (decimal)jarrTe[3]; long amount = CUtilConv.GetIntVolume(dcmlAmount, decimalVolume); //2018-02-22 //Amount is too small. Not possible to understand how it //could be. Was seen on LTC. For now just ignore these trades if (amount == 0) { return; } DateTime dt = CUtilTime.DateTimeFromUnixTimestampMillis(lngMilis); CRawDeal rd = new CRawDeal { Amount = amount, Price = dcmlPrice, Moment = dt }; if (dcmlAmountRaw > 0) { rd.Id_ord_buy = 1; } else { rd.Id_ord_sell = 1; } _client.UpdateDeal(instrument, rd); /* DateTime dtCurr = DateTime.Now; * double ddt = (dtCurr - dt).TotalSeconds; * * if (ddt != 00) * Thread.Sleep(0); * */ }
public void WriteAllDataToDisk() { //TO DO older 2 days // if (bCopyIsBusy) // return; bCopyIsBusy = true; CopyDictTFArray(ref CopyDict); //m_timeFrameAnalyzer.Plaza2Connector.Log("ElapsedMilliseconds=" + sw.ElapsedMilliseconds + " " + m_timeFrameAnalyzer.IsinDir); // CDictTFArray cp = (CDictTFArray) this.MemberwiseClone(); try { foreach (KeyValuePair <string, SortedDictionary <DateTime, CTimeFrameArray> > kv in CopyDict)// this) { string tf = kv.Key; foreach (KeyValuePair <DateTime, CTimeFrameArray> kv2 in kv.Value) { DateTime dt = kv2.Key; CTimeFrameArray tfa = kv2.Value; if (!CUtilTime.OlderThanTwoWorkDays(dt)) { tfa.FileName = m_timeFrameAnalyzer.GetFileName(tf, dt); // tfa.mxLockFile.WaitOne(); this.m_timeFrameAnalyzer.CreateDirectoriesIfNeed(); CSerializator.Write <CTimeFrameArray>(ref tfa); tfa.DtLastWrite = DateTime.Now; // TaskCopyBackup(tfa.FileName); // tfa.mxLockFile.ReleaseMutex(); } } } } catch (Exception e) { Error("WriteAllDataToDisk", e); } bCopyIsBusy = false; }
public void ProcessManualClearing() { LogMethEntry("ProcessManualClearing"); Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-us"); ProcessClearingDataBlock(CUtilTime.GetUnixTimestampMillis(_client.ServerTime), 0, 2, (int)_client.StockExchId); _client.UpdateMoneyData(); CleanPosAndDeals(); LogMethExit("ProcessManualClearing"); }
protected virtual bool IsNeedUpdateUserDealsLog(CRawUserDeal rd, Dictionary <int, Dictionary <string, CLatestTradeData> > dataWithTime) { int iExt_id_buy = (int)rd.Ext_id_buy; int iExt_id_sell = (int)rd.Ext_id_sell; if (iExt_id_buy == 0 && iExt_id_sell == 0) { Error("Non user deal ! replId=" + rd.ReplId); return(false);; } long rdTimeMili = CUtilTime.GetUnixTimestampMillis(rd.Moment); int userId; if (dataWithTime.ContainsKey(iExt_id_buy) && iExt_id_buy != 0) { userId = iExt_id_buy; //continue check } else if (dataWithTime.ContainsKey(iExt_id_sell) && iExt_id_sell != 0) { userId = iExt_id_sell; //continue check } else { return(true); //out } string instrument = rd.Instrument; //UserDealsPosBoxClient. GetTicker(rd.Isin_Id); if (!dataWithTime[userId].ContainsKey(instrument)) { return(true); } if ((rdTimeMili > dataWithTime[userId][instrument].Dt_timestamp_ms) || (rdTimeMili == dataWithTime[userId][instrument].Dt_timestamp_ms && rd.ReplId > dataWithTime[userId][instrument].ReplId) ) { return(true); } return(false); }
private static void GenMillis() { DateTime dt1 = DateTime.Now.AddHours(-2); // DateTime dt2 = dt1.AddSeconds(1); long t = CUtilTime.GetUnixTimestampMillis(dt1); if (t != 0) { System.Threading.Thread.Sleep(0); } }
public void UpdateAxis() { try { const int MAX_CNT = 80; int cnt = 0; cnt = m_plaza2Connector.GUIBox.GUICandleBox[m_isin][tf][dt].Count - 1; DateTime maxDate = m_plaza2Connector.GUIBox.GUICandleBox[m_isin][tf][dt][cnt].Date; DateTime minDate0 = m_plaza2Connector.GUIBox.GUICandleBox[m_isin][tf][dt][0].Date; DateTime minDate = GetMinDate(maxDate, dictIntervalTypes[tf], MAX_CNT * dictIntervals[tf]); //Plaza2Connector.GUIBox.GUICandleBox[isin][tf][dt][first].Date; minDate = CUtilTime.MaxDate(minDate0, minDate); minAbs = m_plaza2Connector.GUIBox.GUICandleBox[m_isin][tf][dt].GetMinimumFromDate(minDate); maxAbs = m_plaza2Connector.GUIBox.GUICandleBox[m_isin][tf][dt].GetMaximumFromDate(minDate); CreateOrUpdateAxis(); System.Windows.Controls.DataVisualization.Charting.DateTimeAxis axis_X = ((System.Windows.Controls.DataVisualization.Charting.DateTimeAxis)Chart.SeriesHost.Axes[0]); CorrectMinMax(dictIntervalTypes[tf], dictIntervals [tf], ref minDate, ref maxDate); axis_X.Minimum = minDate; axis_X.Maximum = maxDate; axis_X.IntervalType = dictIntervalTypes[tf]; axis_X.Interval = dictIntervals[tf]; } catch (Exception e) { m_plaza2Connector.Alarmer.Error("UpdateAxis", e); } }
/// <summary> /// Calling on "te" (TradeExecute) bifinex events. /// Ask UserOrderBoxCrypto to get botId based on OrderId. /// If BotId found -do call Update if not do save to /// _lstNotProcessedDeals for using this data later. /// /// /// Call from CBitfinexWebSockConnector.ProcessUserTradeExecute /// </summary> /// <param name="rt"></param> public void UpdateUserDeals(ResponseTrades rt) { Log("[UpdateUserDeals] " + rt.ToString()); EnmOrderDir dir = rt.ExecAmount > 0 ? EnmOrderDir.Buy : EnmOrderDir.Sell; string instrument = rt.Pair.Remove(0, 1); //remove 't' //long iAmount = CUtilConv.GetIntVolume(Convert.ToDecimal(rt.ExecAmount), GetDecimalVolume(instrument)); decimal dcmlAmount = Convert.ToDecimal(rt.ExecAmount); DateTime moment = CUtilTime.DateTimeFromUnixTimestampMillis(rt.MtsCreate); int botId = _userOrderBoxCrypto.GetBotIdOfOrder(instrument, rt.OrderId); if (botId > 0) //botId found { Log("[UpdateUserDeals] botId=" + botId); _userDealsPosBoxCrypto.Update(rt.Id, rt.OrderId, instrument, dir, dcmlAmount, botId, Convert.ToDecimal(rt.ExecPrice), moment, rt.MtsCreate, (decimal)rt.Fee); //2018-06-13 common situation - remember that no fee //to remove it if fee will be recieved and get from rest if not if ((decimal)rt.Fee == 0) { lock (_lstDealsWithNoFee) _lstDealsWithNoFee.Add(rt); } } else //botId not found { //Write error for now (debugging). In the future - remove error msg. Error("UpdateUserDeals. Bot id not found"); //Put to list of deals to process it later (on "tu") _lstNotProcessedDeals.Add(rt); //add 2018-05-24 AddDealNoBotId(rt); // _lstDealsNoBotId.Add(rt); } }
private bool RetrieveInstTF(string buttName, ref string isin, ref string tf, ref string stDt) { Regex reg = new Regex(@"([\w0-9\-\.]+)_([\w0-9]+)"); Match m = reg.Match(buttName); if (m.Groups.Count > 2) { isin = Convert.ToString(m.Groups[1]); tf = Convert.ToString(m.Groups[2]); DateTime dt = Plaza2Connector.ServerTime; stDt = CUtilTime.NormalizeDay(dt).ToString(); return(true); } return(false); }
private void UpdateTimeLastDeal(DateTime dt) { try { if (m_plaza2Connector.IsDealsOnline) { if (!CUtilTime.IsEqualTimesSecondsAcc(dt, TimeLastDeal)) { // m_plaza2Connector.GUIBox.ExecuteWindowsUpdate(new Action(() => TimeLastDeal = dt)); m_plaza2Connector.GUIBox.ExecuteWindowsDealsUpdate(new Action(() => TimeLastDeal = dt)); } } // TimeLastDeal = dt; } catch (Exception e) { Error("UpdateTimeLastDeal", e); } }
/// <summary> /// Updates latest botpos /// </summary> /// <param name="botId"></param> /// <param name="instrument"></param> /// <param name="botPos"></param> private void UpdateLatestBotPos(int botId, string instrument, CBotPos botPos) { try { long timeMili = CUtilTime.GetUnixTimestampMillis(botPos.DtClose); LatestBotPosData.Update(botId, instrument, new CLatestTradeData { Dt_timestamp_ms = timeMili, ReplId = botPos.ReplIdClosed } ); } catch (Exception e) { } }
private void ProcessSynchroniseTime(byte[] arrMsgBody) { Log("[TimeSynchro]"); bool needSynchro = false; lock (_kernelTerminal.TerminalConfig) needSynchro = _kernelTerminal.TerminalConfig.NeedTimeSynchro; //TODO send moscow time flag or not (or Timezone) on datamessage CTimeSynchroClass ts = CUtilProto.DeserializeProto <CTimeSynchroClass>(arrMsgBody); //removed 2018-03-28 to remove message "Time syncro dtMS=" from error log /* * if (needSynchro) * { * * int dtMS = (int)(DateTime.Now - ts.DtCurrentTime).TotalMilliseconds; * * int param = 20; * if (Math.Abs(dtMS) > param) * { * CTimeChanger tch = new CTimeChanger(-dtMS); * Error("Time syncro dtMS=" + dtMS); * } * } */ DateTime dtMsc = CUtilTime.LocalToMsc(ts.DtCurrentTime); try { _terminalViewModel.StockClock = dtMsc.ToString("HH:mm:ss"); } catch (Exception e) { Thread.Sleep(0); } }
static void Main(string[] args) { //upd 2018-04-22 if (args.Length < 1) { Console.WriteLine("Invalid arguments. Usage: "); Console.WriteLine("MySQLDumper DATABASE_NAME"); return; } string dbName = args[0]; Process proc = new Process(); ProcessStartInfo startInfo = new ProcessStartInfo(); string path = Environment.GetEnvironmentVariable("DB_BACKUPS_PATH"); string tm = CUtilTime.GeDateString(DateTime.Now); string dirName = String.Format("{0}\\{1}\\{2}\\{3}", path, DateTime.Now.Year.ToString("D4"), DateTime.Now.Month.ToString("D2"), tm); CUtil.CreateDirIfNotExist(dirName); if (Directory.Exists(dirName)) { Directory.CreateDirectory(dirName); } string tmCurrent = CUtilTime.GetDateTimeString(DateTime.Now); string fname = String.Format("{0}\\fulldump_{1}.sql", dirName, tmCurrent); startInfo.FileName = @"C:\Program Files\MySQL\MySQL Server 5.7\bin\mysqldump.exe"; startInfo.Arguments = String.Format(@"--user=root --password=profinvest --routines --complete-insert {0} --result-file {1}", dbName, fname); proc.StartInfo = startInfo; proc.Start(); }
public void Test() { CBitfenixWebSockConnector bfxWebSock = new CBitfenixWebSockConnector(this, GenListInstrument(), true, "fVgyf0Rk4hDDDdXAzys7yN0vnGcRPUVYRTLoOxTyDIL", "MDqroztPvZzFIaKKspozdyeAD274OFAZnEZy2nv3eUE"); ThreadPool.SetMinThreads(100, 100); // System.Threading.Thread.Sleep(60000); //string path = @"e:\ATFS\Logs\TradeSystemCrypto\2018_06_27\BfxRaw_public___07_32_41.txt"; string path = @"e:\temp993\1.txt"; string [] lines = File.ReadAllLines(path); DateTime dtStart = DateTime.Now; Console.WriteLine("started" + CUtilTime.GetDateTimeString(dtStart)); for (int i = 0; i < lines.Length; i++) { if (lines[i].Contains("== STARTED ===")) { continue; } string msg = lines[i].Remove(0, 27); bfxWebSock.ProcessData(msg); } DateTime dtEnd = DateTime.Now; double sec = (dtEnd - dtStart).TotalSeconds; Console.WriteLine("Sec=" + sec); Console.ReadKey(); }
private void CheckSpecialTimeStamp(string col, object obj) { if (!col.Contains("_timestamp_ms")) //special case for time { return; } int num = col.IndexOf("_timestamp_ms"); if (num > -1) { string colDt = col.Substring(0, num); var prop = obj.GetType().GetProperty(colDt); if (prop != null) { string val = CMySQLConv.ToMySQLFormat(CUtilTime.GetUnixTimestampMillis((DateTime)prop.GetValue(obj, null))); _sqlInsertQuery._2_SetColumns.Add(col, val); } } }
public static void TestDateTime() { DateTime dt = DateTime.Now; long ltm = CUtilTime.GetUnixTimestampMillis(dt) + 1; if (ltm != null) { System.Threading.Thread.Sleep(0); } DateTime dt2 = CUtilTime.DateTimeFromUnixTimestampMillis(ltm); if (CUtilTime.IsEqualTimesMillisAcc(dt, dt2)) //(DateTime.Equals(dt,dt2))//(dt == dt2) { System.Threading.Thread.Sleep(0); } }
/// <summary> /// Add new "position change" fragment to closed list. /// 2018-03-11 added idDeal /// </summary> public void AddClosedCostHist(long idDeal, decimal price, decimal amount, decimal fee, decimal feeDealing, decimal feeStock, EnmDealDir dir, DateTime moment, long replId) { long bpDtOpenTimeStampMs = CUtilTime.GetUnixTimestampMillis(DtOpen); //TODO check add fee ? ListClosingPosChanges.Add(new CPosChangeFrag { IdDeal = idDeal, Dir = dir, Moment = moment, ReplId = replId, Price = price, Amount = amount, Fee = fee, FeeDealing = feeDealing, Fee_Stock = feeStock, BP_DtOpen_timestamp_ms = bpDtOpenTimeStampMs }); m_userDealsPosBox.BindDealBotPos(idDeal, bpDtOpenTimeStampMs); }
private void AnalyzeDiskTFDays() { try { if (!m_dictTFArray.ContainsKey(EnmTF.H1.ToString())) { return; } foreach (KeyValuePair <DateTime, CTimeFrameArray> kvp in m_dictTFArray[EnmTF.H1.ToString()]) //all dates of low TF array { try { CTimeFrameArray M_low_TF_Array = kvp.Value; DateTime dt = CUtilTime.NormalizeDay(M_low_TF_Array.ListTimeFrameInfo[0].Dt.Date); if (m_dictTFArray.IsContainTimeFrameInfo(EnmTF.D1, dt)) { continue; } CTimeFrameInfo ntfi = m_dictTFArray.GetNewTimeFrameInfo(m_isin, EnmTF.D1, dt); Analyze_D1(dt); } catch (Exception e) { } } } catch (Exception e) { Error("AnalyzeDiskTFDays", e); } }