private int JournalRecordHook_Callback(int code, IntPtr wParam, IntPtr lParam, ref bool callNext) { if (code == HC_ACTION) { EVENTMSG em = (EVENTMSG)Marshal.PtrToStructure(lParam, typeof(EVENTMSG)); JournalMessage jm = JournalMessage.Create(em); if (RecordEvent != null) { RecordEvent(this, new JournalRecordEventArgs(jm)); } } else if (code == HC_SYSMODALON) { if (SystemModalDialogAppeared != null) { SystemModalDialogAppeared(this, new EventArgs()); } } else if (code == HC_SYSMODALOFF) { if (SystemModalDialogDisappeared != null) { SystemModalDialogDisappeared(this, new EventArgs()); } } return(0); }
/// <summary> /// Adds a message to the journal. /// </summary> protected void AppendJournalMessage(JournalMessage message) { messages.Add(message); if (messages.Count > Configs.JournalLength) messages.RemoveRange(0, messages.Count - Configs.JournalLength); UpdateJournal(messages); }
void IEventHandler <ISequencerEntry <ReceiveData> > .OnNext( ISequencerEntry <ReceiveData> data, long sequence, bool endOfBatch) { if (_messageBus != null) { var receivedData = data.GetMessage(); if (receivedData != null) { //neu la control message thi khong can Journal if (receivedData.Message is IControler || receivedData.RawMsg == null) { return; } //neu la control message thi khong can Journal if (!(receivedData.Message is IMessage)) { return; } //thuc hien send Ack message var journal = new JournalMessage() { Tag = receivedData.DeliveryTag, IsAck = true, }; switch (receivedData.QueueType) { case (byte)QueueType.MainQueue: //Check co can gui replicate message hay ko if (_messageBus.RequireReplication) { journal.ReplicateMsg = receivedData.RawMsg; } //Check co can gui save sinker message hay ko if (_messageBus.IsWorkerBStar) { if (receivedData.Message is IMessage) { var bizMsg = receivedData.Message as IMessage; if (!bizMsg.IsNotPersist) { journal.SinkMsg = CreateSinkerMsg(receivedData.RawMsg); } } } _messageBus.Send(journal, (byte)QueueType.MainQueue); break; case (byte)QueueType.ReplicatorQueue: _messageBus.Send(journal, (byte)QueueType.ReplicatorQueue); break; } } } }
private async Task CreateItem(JournalMessage message) { try { await _bodiesContainer.CreateItemAsync(message, new PartitionKey(message.StarSystem)); } catch (CosmosException ex) when(ex.StatusCode == System.Net.HttpStatusCode.Conflict) { await ProcessEventAsync(message); } }
public async Task ProcessEventAsync(JournalMessage message) { var existingItemResponse = await message.CheckIfItemExists(_bodiesContainer, message.StarSystem); if (existingItemResponse == null) { await CreateItem(message); } else { await UpdateItem(message, existingItemResponse); } }
private static void FormatException(Exception exception, JournalMessage logMessage) { logMessage.Append(Exception, exception.Message); logMessage.Append(ExceptionType, exception.GetType().FullName); logMessage.Append(ExceptionStackTrace, exception.StackTrace); Exception innerException = exception.InnerException; if (innerException != null) { logMessage.Append(InnerException, innerException.Message); logMessage.Append(InnerExceptionType, innerException.GetType().FullName); logMessage.Append(InnerExceptionStackTrace, innerException.StackTrace); } }
private async Task UpdateItem(JournalMessage message, ItemResponse <JournalMessage> existingItemResponse) { if (message.ScanType <= existingItemResponse.Resource.ScanType) { return; } try { await _bodiesContainer.UpsertItemAsync(message, new PartitionKey(message.StarSystem), new ItemRequestOptions { IfMatchEtag = existingItemResponse.ETag }); } catch (CosmosException ex) when(ex.StatusCode == System.Net.HttpStatusCode.PreconditionFailed) { await ProcessEventAsync(message); } }
private static void AppendState(string fieldName, object state, JournalMessage message) { if (state is IReadOnlyList <KeyValuePair <string, object> > keyValuePairs) { for (int i = 0; i < keyValuePairs.Count; i++) { var pair = keyValuePairs[i]; if (pair.Key == OriginalFormat) { continue; } message.Append(pair.Key, pair.Value); } } else { message.Append(fieldName, state); } }
void rec_RecordEvent(object sender, JournalRecordEventArgs e) { JournalMessage m = e.RecordedMessage; if (state == MacroState.RECORDING) { m.Time = lastTickCount; lastTickCount = 0; } else if (state == MacroState.RECORDING_DELAY) { int ltc = lastTickCount; lastTickCount = m.Time; m.Time -= ltc; } else { MessageBox.Show("Error: Invalid state"); } macro.Add(m); }
public Task ShareJournalWithUser( string connectionId, string sender, string bodyTitle, string bodyContent, string additionalMessage) { var listOfMessages = bodyContent.Split("--"); JournalMessage journalMessage = new JournalMessage { Corpsno = Int32.Parse(listOfMessages[0]), Corpname = listOfMessages[1], Sdate = Convert.ToDateTime(listOfMessages[2]), Serno = listOfMessages[3], Id = Int32.Parse(listOfMessages[4]), Title = bodyTitle, Sender = sender, AdditaionalMessage = additionalMessage }; return(Clients.Client(connectionId).SendAsync("ReceiveJournalMessage", journalMessage)); }
/// <summary> /// Sets and sends an exit order. /// </summary> private bool DoExitTrade() { string symbol = Data.Symbol; double lots = Data.PositionLots; double price = Data.PositionType == (int) OrderType.Buy ? Data.Bid : Data.Ask; int slippage = Configs.AutoSlippage ? (int) Data.InstrProperties.Spread*6 : Configs.SlippageExit; int ticket = Data.PositionTicket; if (Configs.PlaySounds) Data.SoundOrderSent.Play(); string message = string.Format(symbol + " " + Data.PeriodMtStr + " " + Language.T("An exit order sent") + ": " + Language.T("Close") + " {0} " + LotOrLots(lots) + " " + Language.T("at") + " {1}", lots, price.ToString(Data.Ff)); var jmsg = new JournalMessage(JournalIcons.OrderClose, DateTime.Now, message); AppendJournalMessage(jmsg); Log(message); if (!Data.IsFailedCloseOrder) Data.IsSentCloseOrder = true; Data.CloseOrderTickCounter = 0; bool responseOk = bridge.OrderClose(ticket, lots, price, slippage); if (responseOk) Data.AddBarStats(OperationType.Close, lots, price); else ReportOperationError(); Data.WrongStopLoss = 0; Data.WrongTakeProf = 0; Data.WrongStopsRetry = 0; return responseOk; }
/// <summary> /// Sets SL and TP after wrong execution. /// </summary> private void ResendWrongStops() { string symbol = Data.Symbol; double lots = NormalizeEntrySize(Data.PositionLots); double price = Data.PositionDirection == PosDirection.Long ? Data.Bid : Data.Ask; int ticket = Data.PositionTicket; if (Configs.PlaySounds) Data.SoundOrderSent.Play(); double stoploss = Data.WrongStopLoss; double takeprofit = Data.WrongTakeProf; string stopLoss = "0"; if (stoploss > 0) { double stopLossPrice = 0; if (Data.PositionDirection == PosDirection.Long) stopLossPrice = Data.Bid - stoploss*Data.InstrProperties.Point; else if (Data.PositionDirection == PosDirection.Short) stopLossPrice = Data.Ask + stoploss*Data.InstrProperties.Point; stopLoss = stopLossPrice.ToString(Data.Ff); } string takeProfit = "0"; if (takeprofit > 0) { double takeProfitPrice = 0; if (Data.PositionDirection == PosDirection.Long) takeProfitPrice = Data.Bid + takeprofit*Data.InstrProperties.Point; else if (Data.PositionDirection == PosDirection.Short) takeProfitPrice = Data.Ask - takeprofit*Data.InstrProperties.Point; takeProfit = takeProfitPrice.ToString(Data.Ff); } string message = string.Format(symbol + " " + Data.PeriodMtStr + " " + Language.T("A modify order sent") + ": " + Language.T("Stop Loss") + " {0}, " + Language.T("Take Profit") + " {1}", stopLoss, takeProfit); var jmsg = new JournalMessage(JournalIcons.Warning, DateTime.Now, message); AppendJournalMessage(jmsg); Log(message); string parameters = "TS1=" + 0 + ";BRE=" + 0; bool responseOk = bridge.OrderModify(ticket, price, stoploss, takeprofit, parameters); if (responseOk) { Data.AddBarStats(OperationType.Modify, lots, price); Data.WrongStopLoss = 0; Data.WrongTakeProf = 0; Data.WrongStopsRetry = 0; } else { ReportOperationError(); Data.WrongStopsRetry++; } }
/// <summary> /// Sets and sends an entry order. /// </summary> private void DoEntryTrade(TradeDirection tradeDir) { double price; OrderDirection ordDir; OperationType opType; OrderType type; JournalIcons icon; if (timeLastEntryBar != Data.Time[Data.Bars - 1]) isEnteredLong = isEnteredShort = false; switch (tradeDir) { case TradeDirection.Long: // Buy if (isEnteredLong) return; price = Data.Ask; ordDir = OrderDirection.Buy; opType = OperationType.Buy; type = OrderType.Buy; icon = JournalIcons.OrderBuy; break; case TradeDirection.Short: // Sell if (isEnteredShort) return; price = Data.Bid; ordDir = OrderDirection.Sell; opType = OperationType.Sell; type = OrderType.Sell; icon = JournalIcons.OrderSell; break; default: // Wrong direction of trade. return; } var newPosDir = PosDirection.None; double size = AnalyseEntrySize(ordDir, ref newPosDir); if (size < Data.InstrProperties.MinLot/2) { // The entry trade is cancelled. return; } string symbol = Data.Symbol; double lots = size; int slippage = Configs.AutoSlippage ? (int) Data.InstrProperties.Spread*3 : Configs.SlippageEntry; double stoploss = GetStopLossPips(size); double takeprofit = GetTakeProfitPips(); double point = Data.InstrProperties.Point; string stopLoss = "0"; if (stoploss > 0) { double stopLossPrice = 0; if (newPosDir == PosDirection.Long) stopLossPrice = Data.Bid - stoploss*point; else if (newPosDir == PosDirection.Short) stopLossPrice = Data.Ask + stoploss*point; stopLoss = stopLossPrice.ToString(Data.Ff); } string takeProfit = "0"; if (takeprofit > 0) { double takeProfitPrice = 0; if (newPosDir == PosDirection.Long) takeProfitPrice = Data.Bid + takeprofit*point; else if (newPosDir == PosDirection.Short) takeProfitPrice = Data.Ask - takeprofit*point; takeProfit = takeProfitPrice.ToString(Data.Ff); } if (Configs.PlaySounds) Data.SoundOrderSent.Play(); string message = string.Format(symbol + " " + Data.PeriodMtStr + " " + Language.T("An entry order sent") + ": " + Language.T(ordDir.ToString()) + " {0} " + LotOrLots(lots) + " " + Language.T("at") + " {1}, " + Language.T("Stop Loss") + " {2}, " + Language.T("Take Profit") + " {3}", lots, price.ToString(Data.Ff), stopLoss, takeProfit); var jmsg = new JournalMessage(icon, DateTime.Now, message); AppendJournalMessage(jmsg); Log(message); string parameters = OrderParameters(); int response = bridge.OrderSend(symbol, type, lots, price, slippage, stoploss, takeprofit, parameters); if (response >= 0) { // The order was executed successfully. Data.AddBarStats(opType, lots, price); timeLastEntryBar = Data.Time[Data.Bars - 1]; if (type == OrderType.Buy) isEnteredLong = true; else isEnteredShort = true; Data.WrongStopLoss = 0; Data.WrongTakeProf = 0; Data.WrongStopsRetry = 0; } else { // Error in operation execution. ReportOperationError(); Data.WrongStopLoss = (int) stoploss; Data.WrongTakeProf = (int) takeprofit; } }
/// <summary> /// Pings the server in order to check the connection. /// </summary> private void TimerPingTick(object sender, EventArgs e) { if (DateTime.Now < tickLocalTime.AddSeconds(1)) return; // The last tick was soon enough. lock (lockerTickPing) { PingInfo ping = bridge.GetPingInfo(); if (ping == null && !nullPing) { // Wrong ping. pingAttempt++; if ((pingAttempt == 1 || pingAttempt%10 == 0) && JournalShowSystemMessages) { string message = Language.T("Unsuccessful ping") + " No " + pingAttempt + "."; var jmsgsys = new JournalMessage(JournalIcons.System, DateTime.Now, message); AppendJournalMessage(jmsgsys); Log(message); } if (pingAttempt == 30) { string message = Language.T("There is no connection with MetaTrader."); var jmsgsys = new JournalMessage(JournalIcons.Warning, DateTime.Now, message); AppendJournalMessage(jmsgsys); if (Configs.PlaySounds) Data.SoundError.Play(); Log(message); } if (pingAttempt < 60) { SetConnIcon(pingAttempt < 30 ? 3 : 4); return; } Disconnect(); } else if (ping != null) { // Successful ping. nullPing = false; bool bUpdateData = false; if (!Data.IsConnected || IsChartChangeged(ping.Symbol, (DataPeriod) (int) ping.Period)) { // Disconnected or chart change. pingAttempt = 0; if (JournalShowSystemMessages) { string msgsys = ping.Symbol + " " + ping.Period.ToString() + " " + Language.T("Successful ping."); var jmsgsys = new JournalMessage(JournalIcons.System, DateTime.Now, msgsys); AppendJournalMessage(jmsgsys); Log(msgsys); } StopTrade(); if (!UpdateDataFeedInfo(ping.Time, ping.Symbol, (DataPeriod) (int) ping.Period)) return; Data.Bid = ping.Bid; Data.Ask = ping.Ask; Data.InstrProperties.Spread = ping.Spread; Data.InstrProperties.TickValue = ping.TickValue; Data.IsConnected = true; bUpdateData = true; SetFormText(); SetConnIcon(1); SetTradeStrip(); if (Configs.PlaySounds) Data.SoundConnect.Play(); TerminalInfo te = bridge.GetTerminalInfo(); string connection = Language.T("Connected to a MetaTrader terminal."); if (te != null) { connection = string.Format( Language.T("Connected to") + " {0} " + Language.T("by") + " {1}", te.TerminalName, te.TerminalCompany); Data.ExpertVersion = te.ExpertVersion; Data.LibraryVersion = te.LibraryVersion; Data.TerminalName = te.TerminalName; if (Configs.WriteLogFile) { string fileNameHeader = ping.Symbol + "_" + ping.Period + "_" + "ID" + Data.ConnectionId + "_"; Data.Logger.CreateLogFile(fileNameHeader); } } SetLblConnectionText(connection); string market = string.Format("{0} {1}", ping.Symbol, ping.Period); SetConnMarketText(market); string message = market + " " + connection; var jmsg = new JournalMessage(JournalIcons.Ok, DateTime.Now, message); AppendJournalMessage(jmsg); Log(message); // Check for reconnection. if (IsRestartTrade()) StartTrade(); // Restart trade. } else if (pingAttempt > 0 && JournalShowSystemMessages) { // After a wrong ping. pingAttempt = 0; string message = ping.Symbol + " " + ping.Period.ToString() + " " + Language.T("Successful ping."); var jmsgsys = new JournalMessage(JournalIcons.System, DateTime.Now, message); AppendJournalMessage(jmsgsys); Log(message); } bool isNewPrice = Math.Abs(Data.Bid - ping.Bid) > Data.InstrProperties.Point/2; DateTime dtPingServerTime = tickServerTime.Add(DateTime.Now - tickLocalTime); string sBid = ping.Bid.ToString(Data.Ff); string sAsk = ping.Ask.ToString(Data.Ff); SetLblBidAskText(sBid + " / " + sAsk); Data.Bid = ping.Bid; Data.Ask = ping.Ask; Data.InstrProperties.Spread = ping.Spread; Data.InstrProperties.TickValue = ping.TickValue; Data.ServerTime = ping.Time; bool isAccChanged = Data.SetCurrentAccount(ping.Time, ping.AccountBalance, ping.AccountEquity, ping.AccountProfit, ping.AccountFreeMargin); bool isPosChanged = Data.SetCurrentPosition(ping.PositionTicket, ping.PositionType, ping.PositionLots, ping.PositionOpenPrice, ping.PositionOpenTime, ping.PositionStopLoss, ping.PositionTakeProfit, ping.PositionProfit, ping.PositionComment); ParseAndSetParametrs(ping.Parameters); LogActivated_SL_TP(); SetDataAndCalculate(ping.Symbol, ping.Period, dtPingServerTime, isNewPrice, bUpdateData); SetEquityInfoText(string.Format("{0:F2} {1}", ping.AccountEquity, Data.AccountCurrency)); ShowCurrentPosition(isPosChanged); if (isAccChanged) { string message = string.Format( Language.T("Account Balance") + " {0:F2}, " + Language.T("Equity") + " {1:F2}, " + Language.T("Profit") + " {2:F2}, " + Language.T("Free Margin") + " {3:F2}", ping.AccountBalance, ping.AccountEquity, ping.AccountProfit, ping.AccountFreeMargin); var jmsg = new JournalMessage(JournalIcons.Currency, DateTime.Now, message); AppendJournalMessage(jmsg); Log(message); } if (Data.IsBalanceDataChganged) UpdateBalanceChart(Data.BalanceData, Data.BalanceDataPoints); SetTickInfoText(string.Format("{0} {1} / {2}", ping.Time.ToString("HH:mm:ss"), sBid, sAsk)); SetConnIcon(1); // Sends OrderModify on SL/TP errors if (IsWrongStopsExecution()) ResendWrongStops(); // Check for failed close order. CheckForFailedCloseOrder(ping.PositionLots); } } }
/// <summary> /// Logs operation error in journal and log file. /// </summary> private void ReportOperationError() { if (Configs.PlaySounds) Data.SoundError.Play(); string message; JournalMessage journalMessage; if (bridge.LastError == 0) { message = Language.T("Operation execution") + ": " + Language.T("MetaTrader is not responding!").Replace("MetaTrader", Data.TerminalName); journalMessage = new JournalMessage(JournalIcons.Warning, DateTime.Now, message); } else { message = Language.T("MetaTrader failed to execute order! Returned").Replace("MetaTrader", Data.TerminalName) + ": " + MT4Errors.ErrorDescription(bridge.LastError); journalMessage = new JournalMessage(JournalIcons.Error, DateTime.Now, message); } AppendJournalMessage(journalMessage); Log(message); }
/// <summary> /// Show warning message and start resending. /// </summary> private void ActivateFailedCloseOrder() { string message = Language.T("Activated resending of failed close orders."); var jmsg = new JournalMessage(JournalIcons.Error, DateTime.Now, message); AppendJournalMessage(jmsg); Log(message); ActivateWarningMessage(); }
private static JournalMessage CreateJournalMessage() { return(JournalMessage.Get(isEnabled: true)); }
private static void AppendScope(object scope, JournalMessage message) => AppendState("SCOPE", scope, message);
private int JournalPlaybackHook_Callback(int code, IntPtr wParam, IntPtr lParam, ref bool callNext) { if (code == HC_GETNEXT) { callNext = false; int tick = Environment.TickCount; if (nextEventTime > tick) { return(nextEventTime - tick); } if (nextEvent == null) { nextEventTime = 0; nextEvent = GetNextJournalMessage(ref nextEventTime); if (nextEventTime <= tick) { if (nextEvent == null) { // shutdown the hook Unhook(); return(1); } else { nextEventTime = nextEvent.Time; } } if (nextEventTime > tick) { return(nextEventTime - tick); } } // now we have the next event, which should be sent EVENTMSG em = (EVENTMSG)Marshal.PtrToStructure(lParam, typeof(EVENTMSG)); em.hWnd = nextEvent.HWnd; em.time = nextEvent.Time; em.message = nextEvent.Message; em.paramH = nextEvent.ParamH; em.paramL = nextEvent.ParamL; Marshal.StructureToPtr(em, lParam, false); return(0); } if (code == HC_SKIP) { nextEvent = null; nextEventTime = 0; } else if (code == HC_SYSMODALON) { if (SystemModalDialogAppeared != null) { SystemModalDialogAppeared(this, new EventArgs()); } } else if (code == HC_SYSMODALOFF) { if (SystemModalDialogDisappeared != null) { SystemModalDialogDisappeared(this, new EventArgs()); } } return(0); }
/// <summary> /// Close warning message and stop resending. /// </summary> private void RecoverFailedCloseOrder() { string message = Language.T("Deactivated resending of failed close orders."); var jmsg = new JournalMessage(JournalIcons.Information, DateTime.Now, message); AppendJournalMessage(jmsg); Log(message); DeactivateWarningMessage(); }
/// <summary> /// Copies data to Data and calculates. /// </summary> private void SetDataAndCalculate(string symbol, PeriodType period, DateTime time, bool isPriceChange, bool isUpdateData) { lock (lockerDataFeed) { bool isUpdateChart = isUpdateData; Bars bars = bridge.GetBars(symbol, period); if (bars == null && JournalShowSystemMessages) { isSetRootDataError = true; Data.SoundError.Play(); var jmsgsys = new JournalMessage(JournalIcons.Error, DateTime.Now, symbol + " " + period + " " + Language.T("Cannot receive bars!")); AppendJournalMessage(jmsgsys); Log(jmsgsys.Message); return; } if (bars != null && (bars.Count < MaxBarsCount((int) period) && JournalShowSystemMessages)) { isSetRootDataError = true; Data.SoundError.Play(); var jmsgsys = new JournalMessage(JournalIcons.Error, DateTime.Now, symbol + " " + period + " " + Language.T("Cannot receive enough bars!")); AppendJournalMessage(jmsgsys); Log(jmsgsys.Message); return; } if (isSetRootDataError && JournalShowSystemMessages) { isSetRootDataError = false; var jmsgsys = new JournalMessage(JournalIcons.Information, DateTime.Now, symbol + " " + period + " " + Language.T("Enough bars received!")); AppendJournalMessage(jmsgsys); Log(jmsgsys.Message); } if (bars != null) { int countBars = bars.Count; if (countBars < 400) return; if (Data.Bars != countBars || Data.Time[countBars - 1] != bars.Time[countBars - 1] || Data.Volume[countBars - 1] != bars.Volume[countBars - 1] || Math.Abs(Data.Close[countBars - 1] - bars.Close[countBars - 1]) > Data.InstrProperties.Point/2d) { if (Data.Bars == countBars && Data.Time[countBars - 1] == bars.Time[countBars - 1] && Data.Time[countBars - 10] == bars.Time[countBars - 10]) { // Update the last bar only. Data.Open[countBars - 1] = bars.Open[countBars - 1]; Data.High[countBars - 1] = bars.High[countBars - 1]; Data.Low[countBars - 1] = bars.Low[countBars - 1]; Data.Close[countBars - 1] = bars.Close[countBars - 1]; Data.Volume[countBars - 1] = bars.Volume[countBars - 1]; } else { // Update all the bars. Data.Bars = countBars; Data.Time = new DateTime[countBars]; Data.Open = new double[countBars]; Data.High = new double[countBars]; Data.Low = new double[countBars]; Data.Close = new double[countBars]; Data.Volume = new int[countBars]; bars.Time.CopyTo(Data.Time, 0); bars.Open.CopyTo(Data.Open, 0); bars.High.CopyTo(Data.High, 0); bars.Low.CopyTo(Data.Low, 0); bars.Close.CopyTo(Data.Close, 0); bars.Volume.CopyTo(Data.Volume, 0); } Data.LastClose = Data.Close[countBars - 1]; CalculateStrategy(true); isUpdateChart = true; } } bool isBarChanged = IsBarChanged(Data.Time[Data.Bars - 1]); if (isTrading) { TickType tickType = GetTickType((DataPeriods) (int) period, Data.Time[Data.Bars - 1], time, Data.Volume[Data.Bars - 1]); if (tickType == TickType.Close || isPriceChange || isBarChanged) { if (JournalShowSystemMessages && tickType != TickType.Regular) { var icon = JournalIcons.Warning; string text = string.Empty; if (tickType == TickType.Open) { icon = JournalIcons.BarOpen; text = Language.T("A Bar Open event!"); } else if (tickType == TickType.Close) { icon = JournalIcons.BarClose; text = Language.T("A Bar Close event!"); } else if (tickType == TickType.AfterClose) { icon = JournalIcons.Warning; text = Language.T("A new tick arrived after a Bar Close event!"); } var jmsgsys = new JournalMessage(icon, DateTime.Now, symbol + " " + Data.PeriodMtStr + " " + time.ToString("HH:mm:ss") + " " + text); AppendJournalMessage(jmsgsys); Log(jmsgsys.Message); } if (isBarChanged && tickType == TickType.Regular) { if (JournalShowSystemMessages) { var jmsgsys = new JournalMessage(JournalIcons.Warning, DateTime.Now, symbol + " " + Data.PeriodMtStr + " " + time.ToString("HH:mm:ss") + " A Bar Changed event!"); AppendJournalMessage(jmsgsys); Log(jmsgsys.Message); } tickType = TickType.Open; } if (tickType == TickType.Open && barOpenTimeForLastCloseEvent == Data.Time[Data.Bars - 3]) { if (JournalShowSystemMessages) { var jmsgsys = new JournalMessage(JournalIcons.Warning, DateTime.Now, symbol + " " + Data.PeriodMtStr + " " + time.ToString("HH:mm:ss") + " A secondary Bar Close event!"); AppendJournalMessage(jmsgsys); Log(jmsgsys.Message); } tickType = TickType.OpenClose; } CalculateTrade(tickType); isUpdateChart = true; if (tickType == TickType.Close || tickType == TickType.OpenClose) barOpenTimeForLastCloseEvent = Data.Time[Data.Bars - 1]; } } if (isUpdateChart) UpdateChart(); } }
private void LogActivated_SL_TP() { if (Data.ActivatedStopLoss < Epsilon && Data.ActivatedTakeProfit < Epsilon) { // There is nothing to report. activationReportedAt = 0; return; } if (Data.ActivatedStopLoss > Epsilon && Math.Abs(Data.ActivatedStopLoss - activationReportedAt) < Epsilon || Data.ActivatedTakeProfit > Epsilon && Math.Abs(Data.ActivatedTakeProfit - activationReportedAt) < Epsilon) { // Activation was already reported. return; } if (Data.ActivatedStopLoss > Epsilon && Data.ActivatedTakeProfit > Epsilon) { // Expert was not sure which one was activated, so reported both. Data.AddBarStats(OperationType.Close, Data.Closed_SL_TP_Lots, Data.ActivatedStopLoss); string message = Data.Symbol + " " + Data.PeriodMtStr + " " + Language.T("Position closed at") + " " + Data.ActivatedStopLoss.ToString(Data.Ff) + ", " + Language.T("Closed Lots") + " " + Data.Closed_SL_TP_Lots.ToString("F2"); var msg = new JournalMessage(JournalIcons.Information, DateTime.Now, message); AppendJournalMessage(msg); Log(message); activationReportedAt = Data.ActivatedStopLoss; } else if (Data.ActivatedStopLoss > Epsilon) { // Activated Stop Loss Data.AddBarStats(OperationType.Close, Data.Closed_SL_TP_Lots, Data.ActivatedStopLoss); string message = Data.Symbol + " " + Data.PeriodMtStr + " " + Language.T("Activated Stop Loss at") + " " + Data.ActivatedStopLoss.ToString(Data.Ff) + ", " + Language.T("Closed Lots") + " " + Data.Closed_SL_TP_Lots.ToString("F2"); var msg = new JournalMessage(JournalIcons.Information, DateTime.Now, message); AppendJournalMessage(msg); Log(message); activationReportedAt = Data.ActivatedStopLoss; } else if (Data.ActivatedTakeProfit > Epsilon) { // Activated Take Profit Data.AddBarStats(OperationType.Close, Data.Closed_SL_TP_Lots, Data.ActivatedTakeProfit); string message = Data.Symbol + " " + Data.PeriodMtStr + " " + Language.T("Activated Take Profit at") + " " + Data.ActivatedTakeProfit.ToString(Data.Ff) + ", " + Language.T("Closed Lots") + " " + Data.Closed_SL_TP_Lots.ToString("F2"); var msg = new JournalMessage(JournalIcons.Information, DateTime.Now, message); AppendJournalMessage(msg); Log(message); activationReportedAt = Data.ActivatedTakeProfit; } }
/// <summary> /// Stops connection to MT /// </summary> private void Disconnect() { nullPing = true; pingAttempt = 0; if (Data.IsConnected && Configs.PlaySounds) Data.SoundDisconnect.Play(); Data.IsConnected = false; StopTrade(); string message = Language.T("Not Connected"); var jmsg = new JournalMessage(JournalIcons.Blocked, DateTime.Now, message); AppendJournalMessage(jmsg); Log(message); Data.Bid = 0; Data.Ask = 0; Data.SetCurrentAccount(DateTime.MinValue, 0, 0, 0, 0); bool isPosChanged = Data.SetCurrentPosition(0, -1, 0, 0, DateTime.MinValue, 0, 0, 0, ""); ShowCurrentPosition(isPosChanged); SetEquityInfoText(string.Format("{0} {1}", 0, Data.AccountCurrency)); UpdateBalanceChart(Data.BalanceData, Data.BalanceDataPoints); SetTradeStrip(); SetConnMarketText(Language.T("Not Connected")); SetLblConnectionText(Language.T("Not Connected")); SetConnIcon(0); SetTickInfoText(""); SetLblSymbolText(""); SetFormText(); }
/// <summary> /// Bridge OnTick /// </summary> private void Bridge_OnTick(object source, TickEventArgs tea) { lock (lockerTickPing) { if (pingAttempt > 0 && JournalShowSystemMessages) { string msgsys = tea.Symbol + " " + tea.Period + " " + Language.T("Tick received after an unsuccessful ping."); var jmsgsys = new JournalMessage(JournalIcons.System, DateTime.Now, msgsys); AppendJournalMessage(jmsgsys); Log(msgsys); } pingAttempt = 0; if (!Data.IsConnected) return; tickLocalTime = DateTime.Now; tickServerTime = tea.Time; if (IsChartChangeged(tea.Symbol, (DataPeriod) (int) tea.Period)) { StopTrade(); Data.IsConnected = false; SetFormText(); if (Configs.PlaySounds) Data.SoundDisconnect.Play(); string message = tea.Symbol + " " + tea.Period + " " + Language.T("Tick received from a different chart!"); var jmsg = new JournalMessage(JournalIcons.Warning, DateTime.Now, message); AppendJournalMessage(jmsg); Log(message); return; } bool bNewPrice = Math.Abs(Data.Bid - tea.Bid) > Data.InstrProperties.Point/2; Data.Bid = tea.Bid; Data.Ask = tea.Ask; Data.InstrProperties.Spread = tea.Spread; Data.InstrProperties.TickValue = tea.TickValue; Data.ServerTime = tea.Time; Data.SetTick(tea.Bid); bool isAccChanged = Data.SetCurrentAccount(tea.Time, tea.AccountBalance, tea.AccountEquity, tea.AccountProfit, tea.AccountFreeMargin); bool isPosChanged = Data.SetCurrentPosition(tea.PositionTicket, tea.PositionType, tea.PositionLots, tea.PositionOpenPrice, tea.PositionOpenTime, tea.PositionStopLoss, tea.PositionTakeProfit, tea.PositionProfit, tea.PositionComment); ParseAndSetParametrs(tea.Parameters); LogActivated_SL_TP(); const bool updateData = true; SetDataAndCalculate(tea.Symbol, tea.Period, tea.Time, bNewPrice, updateData); string bidText = tea.Bid.ToString(Data.Ff); string askText = tea.Ask.ToString(Data.Ff); SetLblBidAskText(bidText + " / " + askText); // Tick data label if (JournalShowTicks) { string tickInfo = string.Format("{0} {1} {2} {3} / {4}", tea.Symbol, tea.Period, tea.Time.ToString("HH:mm:ss"), bidText, askText); var jmsg = new JournalMessage(JournalIcons.Globe, DateTime.Now, tickInfo); AppendJournalMessage(jmsg); } UpdateTickChart(Data.InstrProperties.Point, Data.ListTicks.ToArray()); SetEquityInfoText(string.Format("{0:F2} {1}", tea.AccountEquity, Data.AccountCurrency)); ShowCurrentPosition(isPosChanged); if (isAccChanged) { string message = string.Format( Language.T("Account Balance") + " {0:F2}, " + Language.T("Equity") + " {1:F2}, " + Language.T("Profit") + " {2:F2}, " + Language.T("Free Margin") + " {3:F2}", tea.AccountBalance, tea.AccountEquity, tea.AccountProfit, tea.AccountFreeMargin); var jmsg = new JournalMessage(JournalIcons.Currency, DateTime.Now, message); AppendJournalMessage(jmsg); Log(message); } if (Data.IsBalanceDataChganged) UpdateBalanceChart(Data.BalanceData, Data.BalanceDataPoints); SetTickInfoText(string.Format("{0} {1} / {2}", tea.Time.ToString("HH:mm:ss"), bidText, askText)); SetConnIcon(2); // Sends OrderModify on SL/TP errors if (IsWrongStopsExecution()) ResendWrongStops(); // Check for failed close order. CheckForFailedCloseOrder(tea.PositionLots); } }
internal JournalRecordEventArgs(JournalMessage msg) { this.msg = msg; }
public IEventTypeProcessor GetProcessor(JournalMessage journalMessage) => journalMessage.Event switch {
/// <summary> /// Stops trade and shows a message. /// </summary> private void AfterStrategyOpening() { StopTrade(); string message = Language.T("Strategy") + " \"" + Data.Strategy.StrategyName + "\" " + Language.T("loaded successfully."); var jmsg = new JournalMessage(JournalIcons.Information, DateTime.Now, message); AppendJournalMessage(jmsg); Log(message); }
/// <summary> /// Sets the instrument's properties after connecting; /// </summary> private bool UpdateDataFeedInfo(DateTime time, string symbol, DataPeriod period) { lock (lockerDataFeed) { Data.ResetBidAskClose(); Data.ResetAccountStats(); Data.ResetPositionStats(); Data.ResetBarStats(); Data.ResetTicks(); // Reads market info from the chart MT4Bridge.MarketInfo marketInfo = bridge.GetMarketInfoAll(symbol); if (marketInfo == null) { if (JournalShowSystemMessages) { var jmsgsys = new JournalMessage(JournalIcons.System, DateTime.Now, symbol + " " + (PeriodType) (int) period + " " + Language.T("Cannot update market info.")); AppendJournalMessage(jmsgsys); Log(jmsgsys.Message); } return false; } // Sets instrument properties Data.Period = period; Data.InstrProperties.Symbol = symbol; Data.InstrProperties.LotSize = (int) marketInfo.ModeLotSize; Data.InstrProperties.MinLot = marketInfo.ModeMinLot; Data.InstrProperties.MaxLot = marketInfo.ModeMaxLot; Data.InstrProperties.LotStep = marketInfo.ModeLotStep; Data.InstrProperties.Digits = (int) marketInfo.ModeDigits; Data.InstrProperties.Spread = marketInfo.ModeSpread; Data.InstrProperties.SwapLong = marketInfo.ModeSwapLong; Data.InstrProperties.SwapShort = marketInfo.ModeSwapShort; Data.InstrProperties.TickValue = marketInfo.ModeTickValue; Data.InstrProperties.StopLevel = marketInfo.ModeStopLevel; Data.InstrProperties.MarginRequired = marketInfo.ModeMarginRequired; SetNumUpDownLots(marketInfo.ModeMinLot, marketInfo.ModeLotStep, marketInfo.ModeMaxLot); // Sets Market Info var values = new[] { symbol, Data.DataPeriodToString(period), marketInfo.ModeLotSize.ToString(CultureInfo.InvariantCulture), marketInfo.ModePoint.ToString("F" + marketInfo.ModeDigits.ToString(CultureInfo.InvariantCulture)) , marketInfo.ModeSpread.ToString(CultureInfo.InvariantCulture), marketInfo.ModeSwapLong.ToString(CultureInfo.InvariantCulture), marketInfo.ModeSwapShort.ToString(CultureInfo.InvariantCulture) }; UpdateStatusPageMarketInfo(values); Bars bars = bridge.GetBars(symbol, (PeriodType) (int) period); if (bars == null) { if (JournalShowSystemMessages) { Data.SoundError.Play(); var jmsgsys = new JournalMessage(JournalIcons.System, DateTime.Now, symbol + " " + (PeriodType) (int) period + " " + Language.T("Cannot receive bars!")); AppendJournalMessage(jmsgsys); Log(jmsgsys.Message); } return false; } if (bars.Count < MaxBarsCount((int) period)) { if (JournalShowSystemMessages) { Data.SoundError.Play(); var jmsgsys = new JournalMessage(JournalIcons.Error, DateTime.Now, symbol + " " + (PeriodType) (int) period + " " + Language.T("Cannot receive enough bars!")); AppendJournalMessage(jmsgsys); Log(jmsgsys.Message); } return false; } if (JournalShowSystemMessages) { var jmsgsys = new JournalMessage(JournalIcons.System, DateTime.Now, symbol + " " + (PeriodType) (int) period + " " + Language.T("Market data updated, bars downloaded.")); AppendJournalMessage(jmsgsys); Log(jmsgsys.Message); } // Account Information. AccountInfo account = bridge.GetAccountInfo(); if (account == null) { if (JournalShowSystemMessages) { Data.SoundError.Play(); var jmsgsys = new JournalMessage(JournalIcons.Error, DateTime.Now, symbol + " " + (PeriodType) (int) period + " " + Language.T("Cannot receive account information!")); AppendJournalMessage(jmsgsys); Log(jmsgsys.Message); } return false; } if (JournalShowSystemMessages) { var jmsgsys = new JournalMessage(JournalIcons.System, DateTime.Now, symbol + " " + (PeriodType) (int) period + " " + Language.T("Account information received.")); AppendJournalMessage(jmsgsys); Log(jmsgsys.Message); } Data.AccountName = account.Name; Data.IsDemoAccount = account.IsDemo; Data.AccountCurrency = account.Currency; Data.SetCurrentAccount(time, account.Balance, account.Equity, account.Profit, account.FreeMargin); UpdateBalanceChart(Data.BalanceData, Data.BalanceDataPoints); SetTradeStrip(); SetLblSymbolText(symbol); } return true; }
/// <summary> /// Starts the trade. /// </summary> private void StartTrade() { if (Data.Strategy.FirstBar > Data.Bars) { string errorMessage = string.Format("The strategy requires {0} bars, but there are {1} bars loaded.", Data.Strategy.FirstBar, Data.Bars); errorMessage += Environment.NewLine + Language.T("Check \"Trade settings -> Minimum number of bars in the chart\" option."); MessageBox.Show(errorMessage, Language.T("Strategy")); return; } isTrading = true; // Resets trade global variables. InitTrade(); Data.SetStartTradingTime(); string message = Data.Symbol + " " + Data.PeriodMtStr + " " + Language.T("Automatic trade started."); var msg = new JournalMessage(JournalIcons.StartTrading, DateTime.Now, message); AppendJournalMessage(msg); Log(message); symbolReconnect = Data.Symbol; periodReconnect = Data.Period; accountReconnect = Data.AccountNumber; barOpenTimeForLastCloseEvent = Data.Time[Data.Bars - 1]; SetTradeStrip(); }
public async Task ProcessEventAsync(JournalMessage message) { await _signalsContainer.UpsertItemAsync(message, new PartitionKey(message.StarSystem)); }
private static Dictionary <string, string> ReadFields(JournalMessage message) => ReadFields(message.GetData());
/// <summary> /// Manual operation execution. /// </summary> public override void BtnOperationClick(object sender, EventArgs e) { if (!Data.IsConnected) { if (Configs.PlaySounds) Data.SoundError.Play(); return; } var btn = (Button) sender; switch (btn.Name) { case "btnBuy": { const OrderType type = OrderType.Buy; string symbol = Data.Symbol; double lots = NormalizeEntrySize(OperationLots); double price = Data.Ask; int slippage = Configs.AutoSlippage ? (int) Data.InstrProperties.Spread*3 : Configs.SlippageEntry; int stopLossPips; if (OperationStopLoss > 0 && OperationTrailingStop > 0) stopLossPips = Math.Min(OperationStopLoss, OperationTrailingStop); else stopLossPips = Math.Max(OperationStopLoss, OperationTrailingStop); double stoploss = stopLossPips > 0 ? Data.Bid - Data.InstrProperties.Point*stopLossPips : 0; double takeprofit = OperationTakeProfit > 0 ? Data.Bid + Data.InstrProperties.Point*OperationTakeProfit : 0; if (Configs.PlaySounds) Data.SoundOrderSent.Play(); string message = string.Format(symbol + " " + Data.PeriodMtStr + " " + Language.T("An entry order sent") + ": " + Language.T("Buy") + " {0} " + LotOrLots(lots) + " " + Language.T("at") + " {1}, " + Language.T("Stop Loss") + " {2}, " + Language.T("Take Profit") + " {3}", lots, price.ToString(Data.Ff), stoploss.ToString(Data.Ff), takeprofit.ToString(Data.Ff)); var jmsg = new JournalMessage(JournalIcons.OrderBuy, DateTime.Now, message); AppendJournalMessage(jmsg); Log(message); string parameters = "TS1=" + OperationTrailingStop + ";BRE=" + OperationBreakEven; int response = bridge.OrderSend(symbol, type, lots, price, slippage, stopLossPips, OperationTakeProfit, parameters); if (response >= 0) { Data.AddBarStats(OperationType.Buy, lots, price); Data.WrongStopLoss = 0; Data.WrongTakeProf = 0; Data.WrongStopsRetry = 0; } else { // Error in operation execution. ReportOperationError(); Data.WrongStopLoss = stopLossPips; Data.WrongTakeProf = OperationTakeProfit; } } break; case "btnSell": { const OrderType type = OrderType.Sell; string symbol = Data.Symbol; double lots = NormalizeEntrySize(OperationLots); double price = Data.Bid; int slippage = Configs.AutoSlippage ? (int) Data.InstrProperties.Spread*3 : Configs.SlippageEntry; int stopLossPips; if (OperationStopLoss > 0 && OperationTrailingStop > 0) stopLossPips = Math.Min(OperationStopLoss, OperationTrailingStop); else stopLossPips = Math.Max(OperationStopLoss, OperationTrailingStop); double stoploss = stopLossPips > 0 ? Data.Ask + Data.InstrProperties.Point*stopLossPips : 0; double takeprofit = OperationTakeProfit > 0 ? Data.Ask - Data.InstrProperties.Point*OperationTakeProfit : 0; if (Configs.PlaySounds) Data.SoundOrderSent.Play(); string message = string.Format(symbol + " " + Data.PeriodMtStr + " " + Language.T("An entry order sent") + ": " + Language.T("Sell") + " {0} " + LotOrLots(lots) + " " + Language.T("at") + " {1}, " + Language.T("Stop Loss") + " {2}, " + Language.T("Take Profit") + " {3}", lots, price.ToString(Data.Ff), stoploss.ToString(Data.Ff), takeprofit.ToString(Data.Ff)); var jmsg = new JournalMessage(JournalIcons.OrderSell, DateTime.Now, message); AppendJournalMessage(jmsg); Log(message); string parameters = "TS1=" + OperationTrailingStop + ";BRE=" + OperationBreakEven; int response = bridge.OrderSend(symbol, type, lots, price, slippage, stopLossPips, OperationTakeProfit, parameters); if (response >= 0) { Data.AddBarStats(OperationType.Sell, lots, price); Data.WrongStopLoss = 0; Data.WrongTakeProf = 0; Data.WrongStopsRetry = 0; } else { // Error in operation execution. ReportOperationError(); Data.WrongStopLoss = stopLossPips; Data.WrongTakeProf = OperationTakeProfit; } } break; case "btnClose": { string symbol = Data.Symbol; double lots = NormalizeEntrySize(Data.PositionLots); double price = Data.PositionDirection == PosDirection.Long ? Data.Bid : Data.Ask; int slippage = Configs.AutoSlippage ? (int) Data.InstrProperties.Spread*6 : Configs.SlippageExit; int ticket = Data.PositionTicket; if (ticket == 0) { // No position. if (Configs.PlaySounds) Data.SoundError.Play(); return; } if (Configs.PlaySounds) Data.SoundOrderSent.Play(); string message = string.Format(symbol + " " + Data.PeriodMtStr + " " + Language.T("An exit order sent") + ": " + Language.T("Close") + " {0} " + LotOrLots(lots) + " " + Language.T("at") + " {1}", lots, price.ToString(Data.Ff)); var jmsg = new JournalMessage(JournalIcons.OrderClose, DateTime.Now, message); AppendJournalMessage(jmsg); Log(message); bool responseOk = bridge.OrderClose(ticket, lots, price, slippage); if (responseOk) Data.AddBarStats(OperationType.Close, lots, price); else ReportOperationError(); Data.WrongStopLoss = 0; Data.WrongTakeProf = 0; Data.WrongStopsRetry = 0; } break; case "btnModify": { string symbol = Data.Symbol; double lots = NormalizeEntrySize(Data.PositionLots); double price = Data.PositionDirection == PosDirection.Long ? Data.Bid : Data.Ask; int ticket = Data.PositionTicket; double sign = Data.PositionDirection == PosDirection.Long ? 1 : -1; if (ticket == 0) { // No position. if (Configs.PlaySounds) Data.SoundError.Play(); return; } if (Configs.PlaySounds) Data.SoundOrderSent.Play(); int stopLossPips; if (OperationStopLoss > 0 && OperationTrailingStop > 0) stopLossPips = Math.Min(OperationStopLoss, OperationTrailingStop); else stopLossPips = Math.Max(OperationStopLoss, OperationTrailingStop); double stoploss = stopLossPips > 0 ? price - sign*Data.InstrProperties.Point*stopLossPips : 0; double takeprofit = OperationTakeProfit > 0 ? price + sign*Data.InstrProperties.Point*OperationTakeProfit : 0; string message = string.Format(symbol + " " + Data.PeriodMtStr + " " + Language.T("A modify order sent") + ": " + Language.T("Stop Loss") + " {0}, " + Language.T("Take Profit") + " {1}", stoploss.ToString(Data.Ff), takeprofit.ToString(Data.Ff)); var jmsg = new JournalMessage(JournalIcons.Recalculate, DateTime.Now, message); AppendJournalMessage(jmsg); Log(message); string parameters = "TS1=" + OperationTrailingStop + ";BRE=" + OperationBreakEven; bool responseOk = bridge.OrderModify(ticket, price, stopLossPips, OperationTakeProfit, parameters); if (responseOk) { Data.AddBarStats(OperationType.Modify, lots, price); Data.WrongStopLoss = 0; Data.WrongTakeProf = 0; Data.WrongStopsRetry = 0; } else { ReportOperationError(); Data.WrongStopLoss = stopLossPips; Data.WrongTakeProf = OperationTakeProfit; } } break; } }
/// <summary> /// Shows current position on the status bar. /// </summary> private void ShowCurrentPosition(bool showInJournal) { if (!Data.IsConnected) { SetPositionInfoText(null, String.Empty); return; } string format = Data.Ff; string text = Language.T("Square"); var icon = JournalIcons.PosSquare; Image img = Resources.pos_square; if (Data.PositionTicket > 0) { img = (Data.PositionType == 0 ? Resources.pos_buy : Resources.pos_sell); icon = (Data.PositionType == 0 ? JournalIcons.PosBuy : JournalIcons.PosSell); text = string.Format((Data.PositionType == 0 ? Language.T("Long") : Language.T("Short")) + " {0} " + LotOrLots(Data.PositionLots) + " " + Language.T("at") + " {1}, " + Language.T("Stop Loss") + " {2}, " + Language.T("Take Profit") + " {3}, " + Language.T("Profit") + " {4} " + Data.AccountCurrency, Data.PositionLots, Data.PositionOpenPrice.ToString(format), Data.PositionStopLoss.ToString(format), Data.PositionTakeProfit.ToString(format), Data.PositionProfit.ToString("F2")); } SetPositionInfoText(img, text); if (showInJournal) { string message = string.Format(Data.Symbol + " " + Data.PeriodMtStr + " " + text); var jmsg = new JournalMessage(icon, DateTime.Now, message); AppendJournalMessage(jmsg); Log(message); } }
/// <summary> /// Stops the trade. /// </summary> private void StopTrade() { if (!isTrading) return; isTrading = false; DeinitTrade(); Data.SetStopTradingTime(); string message = Data.Symbol + " " + Data.PeriodMtStr + " " + Language.T("Automatic trade stopped."); var msg = new JournalMessage(JournalIcons.StopTrading, DateTime.Now, message); AppendJournalMessage(msg); Log(message); SetTradeStrip(); }
public async Task ProcessEventAsync(JournalMessage message) { message.Region = RegionMap.FindRegion(message.StarPos[0], message.StarPos[1], message.StarPos[2]); await _systemsContainer.UpsertItemAsync(message, message.Region == null?PartitionKey.None : new PartitionKey(message.Region.Name)); }
public Task ProcessEventAsync(JournalMessage message) { return(Task.CompletedTask); }