NexusFi: Find Your Edge


Home Menu

 





Email Trades code bug


Discussion in NinjaTrader

Updated
      Top Posters
    1. looks_one Mindset with 3 posts (1 thanks)
    2. looks_two Quick Summary with 1 posts (0 thanks)
    3. looks_3 MrTrader with 1 posts (0 thanks)
    4. looks_4 ratfink with 1 posts (1 thanks)
    1. trending_up 1,906 views
    2. thumb_up 2 thanks given
    3. group 2 followers
    1. forum 5 posts
    2. attach_file 1 attachments




 
Search this Thread

Email Trades code bug

  #1 (permalink)
 
Mindset's Avatar
 Mindset 
Singapore
 
Experience: Intermediate
Platform: NT
Broker: ib
Trading: MES
Posts: 365 since Sep 2009
Thanks Given: 90
Thanks Received: 291

Edit This does seem to work but it's behaviour is erratic if you have multiple examples of it in different charts.



I downloaded the source code for this indicator from here.
If you haven't used email trades before there are some important setup instructions for popular email clients (gmail,hotmail,etc) outlined there as well.

I have added a toolbar combo box and got the accounts populated in a dropdown list.
When I change accounts - everything changes but the emails stop. Been driving me nuts for two days - can anyone supply the missing bit

ps I should add if I change accounts in the indicator the behaviour of the indicator is correct

 
Code
#region Using declarations
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Xml.Serialization;
using NinjaTrader.Cbi;
using NinjaTrader.Data;
using NinjaTrader.Gui.Chart;
using System.Windows.Forms;

using System.Collections;
#endregion

// This namespace holds all indicators and is required. Do not change it.
namespace NinjaTrader.Indicator
{
	
    /// <summary>
    /// Emails the execution details when a order is filled
    /// </summary>
    [Description("Emails the execution details when an order is filled")]
    public class EmailTrades: Indicator
    {
        #region Variables
        private string fromEmailAddress = @"[email protected]"; 
        private string toEmailAddress = @"[email protected]"; 
        private bool emailPartFilled = false; 
		private Account account = null;
		private string accountName;
			ToolStripComboBox ComboBox;
		ToolStripSeparator tsSeparator = null;
		
	    #endregion
		
		

        /// <summary>
        /// This method is used to configure the indicator and is called once before any bar data is loaded.
        /// </summary>
        protected override void Initialize()
        {
            Overlay				= true;
			ChartOnly = true;
		}
		
		
		protected override void OnStartUp()
		{
				if (ChartControl != null)
			{
				ToolStrip toolstrip = (ToolStrip)ChartControl.Controls["tsrTool"];
				
				if (toolstrip !=null)
				{
					toolstrip.SuspendLayout();	

					//##add separator
					tsSeparator = new ToolStripSeparator();
					tsSeparator.Name = "tsSeparator";
					toolstrip.Items.Add(tsSeparator);
					
				
					ComboBox = new ToolStripComboBox();
//##ComboBox Item
	ComboBox.TextAlign =  ContentAlignment.MiddleCenter;
	ComboBox.Text ="Accounts";
	ComboBox.Width = 72;
	ComboBox.ForeColor = ChartControl.ForeColor;
	ComboBox.DropDownHeight = 255;
	ComboBox.DropDownWidth = 10;
	ComboBox.DropDownStyle = ComboBoxStyle.DropDown;
	ComboBox.FlatStyle = FlatStyle.System;
	ComboBox.BeginUpdate();
foreach (Account acct in Cbi.Globals.Accounts)
{
if(acct.GetType() == typeof(Account))
	ComboBox.Items.Add(acct.Name);
}
	ComboBox.EndUpdate();
	ComboBox.TextChanged += new EventHandler(txtChanged_Event);

toolstrip.Items.Add(ComboBox);
	 toolstrip.ResumeLayout(false);
     toolstrip.PerformLayout();
				}
			}
			
			//have to reinitialze if connection gets lost
			NinjaTrader.Cbi.Globals.Connections.ConnectionStatus += new ConnectionStatusEventHandler(OnConnection);
						
			account = NinjaTrader.Cbi.Globals.Accounts.FindByName(accountName);
			
			//return if cannot find the account
			if (account == null)
			{
				this.DrawTextFixed("msg", "Could not retrieve the account", TextPosition.BottomRight);
				return;
			}
	
			//does not works in market replay connection or simulated data feed
			if (account.Connection.Name == "Market Replay Connection" || account.Connection.Name == "Simulated Data Feed")
			{
				DrawTextFixed("msg", "Email Trades indicator does not works with " + account.Connection.Name, TextPosition.BottomRight);
				account = null;
				return;
				
			}
								
		}
		
        /// <summary>
        /// Called on each bar update event (incoming tick)
        /// </summary>
        protected override void OnBarUpdate()
        {
            
        }
		
		protected void txtChanged_Event (object sender ,EventArgs e)//Second Text Box
		{
		try
			{
				Print("Combo Text = "+ ComboBox.Text);
				accountName = ComboBox.Text.ToString();
				account = NinjaTrader.Cbi.Globals.Accounts.FindByName(accountName);
				Print("Account " + account.Name);
				NinjaTrader.Cbi.Globals.Connections.ConnectionStatus += new ConnectionStatusEventHandler(OnConnection);
				account.Execution += new ExecutionUpdateEventHandler(OnExecution);

			}
			catch
			{Print("Catch txtChanged Event");
			}
		}
		
		private void OnExecution(object sender, ExecutionUpdateEventArgs e)
		{
			if (e.Execution.Order != null)
			{
				
				if (e.Execution.Order.OrderState == OrderState.Filled)
				{
					this.SendMail(fromEmailAddress, toEmailAddress, "NinjaTrader Trade Confirmation", "Trade filled for: " + e.Execution.ToString());
					
					return;
				}
				
				if (emailPartFilled && e.Execution.Order.OrderState == OrderState.PartFilled)
				{
					this.SendMail(fromEmailAddress, toEmailAddress, "NinjaTrader Trade Confirmation", "Trade filled for: " + e.Execution.ToString());
				}
				
			}
		}
		
		
		
		private void OnConnection(object sender, ConnectionStatusEventArgs e)
		{
			if (e.Status == ConnectionStatus.Connected)
			{
				Account a =  e.Connection.Accounts.FindByName(accountName);
				
				if (a != null)
				{
					account = NinjaTrader.Cbi.Globals.Accounts.FindByName(accountName);
						
					if (account != null)
					{
						if (account.Connection.Name == "Market Replay Connection" || account.Connection.Name == "Simulated Data Feed")
							return;
						
						account.Execution += new ExecutionUpdateEventHandler(OnExecution);
						DrawTextFixed("msg", "Sending execution email for account: " + account.Name, TextPosition.BottomRight);
						Log("Subscribing to Email Trades indicator for account " + account.Name, LogLevel.Information);		
						return;
					}
				}
			}
			else if (e.Status == ConnectionStatus.ConnectionLost || e.Status == ConnectionStatus.Disconnected)
			{
				if (account != null && e.Connection.Accounts.Contains(account))
				{
					account.Execution -= new ExecutionUpdateEventHandler(OnExecution);
					account = null;
					Log("Unsubscribing to Email Trades indicator on " + e.Status.ToString(), LogLevel.Information);
				}
			}
		}
		
		
		
		protected override void OnTermination()
		{
			
			NinjaTrader.Cbi.Globals.Connections.ConnectionStatus -= new ConnectionStatusEventHandler(OnConnection);
			
			if (account != null)
			{
				if (!(account.Connection.Name == "Market Replay Connection" || account.Connection.Name == "Simulated Data Feed"))
				{
					account.Execution -= new ExecutionUpdateEventHandler(OnExecution);
					
					Log("Unsubscribing to Email Trades indicator for account " + account.Name, LogLevel.Information);
				}
			}
	
			account = null;
		       				#region Toolbar Dispose			//## ToolStip termination
			
			ToolStrip toolstrip = (ToolStrip)ChartControl.Controls["tsrTool"];
				if (toolstrip != null)
				{
					if (tsSeparator != null) toolstrip.Items.Remove(tsSeparator);
					if(ComboBox != null) toolstrip.Items.Remove(ComboBox);
						ComboBox.TextChanged -= new EventHandler(txtChanged_Event);

				}
			
					#endregion				

		}
		
		public override string ToString()
		{
			return this.Name + " (" + fromEmailAddress + ", " + toEmailAddress + ")";
		}
		
		

        #region Properties

        [Description("Name of the Account")]
        [GridCategory("Parameters")]
		[TypeConverter(typeof(NinjaTrader.Gui.Design.AccountNameConverter))]
		[XmlIgnore()]
        public string AccountName
        {
            get { return accountName; }
            set { accountName = value; }
        }

	
        [Description("From Email Id")]
        [GridCategory("EMail")]
        public string FromEmailAddress
        {
            get { return fromEmailAddress; }
            set 
			{ 
				System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(@"\b[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}\b");
				
				if (reg.IsMatch((string)value))
					fromEmailAddress = value; 
				else
				{
					System.Windows.Forms.MessageBox.Show("Please enter a valid email address");
				}
			
			}
        }

        [Description("To Email id")]
        [GridCategory("EMail")]
		public string ToEmailAddress
        {
            get { return toEmailAddress; }
            set 
			{ 
				System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(@"\b[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}\b");
				
				if (reg.IsMatch((string)value))
					toEmailAddress = value; 
				else
				{
					System.Windows.Forms.MessageBox.Show("Please enter a valid email address");
				}
			}
        }

        [Description("Send mail when order is fully filled")]
        [GridCategory("Parameters")]
        public bool EmailPartFilled
        {
            get { return emailPartFilled; }
            set { emailPartFilled = value; }
        }
        #endregion
    }
}

#region NinjaScript generated code. Neither change nor remove.
// This namespace holds all indicators and is required. Do not change it.
namespace NinjaTrader.Indicator
{
    public partial class Indicator : IndicatorBase
    {
        private EmailTrades[] cacheEmailTrades = null;

        private static EmailTrades checkEmailTrades = new EmailTrades();

        /// <summary>
        /// Emails the execution details when an order is filled
        /// </summary>
        /// <returns></returns>
        public EmailTrades EmailTrades(string accountName, bool emailPartFilled, string fromEmailAddress, string toEmailAddress)
        {
            return EmailTrades(Input, accountName, emailPartFilled, fromEmailAddress, toEmailAddress);
        }

        /// <summary>
        /// Emails the execution details when an order is filled
        /// </summary>
        /// <returns></returns>
        public EmailTrades EmailTrades(Data.IDataSeries input, string accountName, bool emailPartFilled, string fromEmailAddress, string toEmailAddress)
        {
            if (cacheEmailTrades != null)
                for (int idx = 0; idx < cacheEmailTrades.Length; idx++)
                    if (cacheEmailTrades[idx].AccountName == accountName && cacheEmailTrades[idx].EmailPartFilled == emailPartFilled && cacheEmailTrades[idx].FromEmailAddress == fromEmailAddress && cacheEmailTrades[idx].ToEmailAddress == toEmailAddress && cacheEmailTrades[idx].EqualsInput(input))
                        return cacheEmailTrades[idx];

            lock (checkEmailTrades)
            {
                checkEmailTrades.AccountName = accountName;
                accountName = checkEmailTrades.AccountName;
                checkEmailTrades.EmailPartFilled = emailPartFilled;
                emailPartFilled = checkEmailTrades.EmailPartFilled;
                checkEmailTrades.FromEmailAddress = fromEmailAddress;
                fromEmailAddress = checkEmailTrades.FromEmailAddress;
                checkEmailTrades.ToEmailAddress = toEmailAddress;
                toEmailAddress = checkEmailTrades.ToEmailAddress;

                if (cacheEmailTrades != null)
                    for (int idx = 0; idx < cacheEmailTrades.Length; idx++)
                        if (cacheEmailTrades[idx].AccountName == accountName && cacheEmailTrades[idx].EmailPartFilled == emailPartFilled && cacheEmailTrades[idx].FromEmailAddress == fromEmailAddress && cacheEmailTrades[idx].ToEmailAddress == toEmailAddress && cacheEmailTrades[idx].EqualsInput(input))
                            return cacheEmailTrades[idx];

                EmailTrades indicator = new EmailTrades();
                indicator.BarsRequired = BarsRequired;
                indicator.CalculateOnBarClose = CalculateOnBarClose;
#if NT7
                indicator.ForceMaximumBarsLookBack256 = ForceMaximumBarsLookBack256;
                indicator.MaximumBarsLookBack = MaximumBarsLookBack;
#endif
                indicator.Input = input;
                indicator.AccountName = accountName;
                indicator.EmailPartFilled = emailPartFilled;
                indicator.FromEmailAddress = fromEmailAddress;
                indicator.ToEmailAddress = toEmailAddress;
                Indicators.Add(indicator);
                indicator.SetUp();

                EmailTrades[] tmp = new EmailTrades[cacheEmailTrades == null ? 1 : cacheEmailTrades.Length + 1];
                if (cacheEmailTrades != null)
                    cacheEmailTrades.CopyTo(tmp, 0);
                tmp[tmp.Length - 1] = indicator;
                cacheEmailTrades = tmp;
                return indicator;
            }
        }
    }
}

// This namespace holds all market analyzer column definitions and is required. Do not change it.
namespace NinjaTrader.MarketAnalyzer
{
    public partial class Column : ColumnBase
    {
        /// <summary>
        /// Emails the execution details when an order is filled
        /// </summary>
        /// <returns></returns>
        [Gui.Design.WizardCondition("Indicator")]
        public Indicator.EmailTrades EmailTrades(string accountName, bool emailPartFilled, string fromEmailAddress, string toEmailAddress)
        {
            return _indicator.EmailTrades(Input, accountName, emailPartFilled, fromEmailAddress, toEmailAddress);
        }

        /// <summary>
        /// Emails the execution details when an order is filled
        /// </summary>
        /// <returns></returns>
        public Indicator.EmailTrades EmailTrades(Data.IDataSeries input, string accountName, bool emailPartFilled, string fromEmailAddress, string toEmailAddress)
        {
            return _indicator.EmailTrades(input, accountName, emailPartFilled, fromEmailAddress, toEmailAddress);
        }
    }
}

// This namespace holds all strategies and is required. Do not change it.
namespace NinjaTrader.Strategy
{
    public partial class Strategy : StrategyBase
    {
        /// <summary>
        /// Emails the execution details when an order is filled
        /// </summary>
        /// <returns></returns>
        [Gui.Design.WizardCondition("Indicator")]
        public Indicator.EmailTrades EmailTrades(string accountName, bool emailPartFilled, string fromEmailAddress, string toEmailAddress)
        {
            return _indicator.EmailTrades(Input, accountName, emailPartFilled, fromEmailAddress, toEmailAddress);
        }

        /// <summary>
        /// Emails the execution details when an order is filled
        /// </summary>
        /// <returns></returns>
        public Indicator.EmailTrades EmailTrades(Data.IDataSeries input, string accountName, bool emailPartFilled, string fromEmailAddress, string toEmailAddress)
        {
            if (InInitialize && input == null)
                throw new ArgumentException("You only can access an indicator with the default input/bar series from within the 'Initialize()' method");

            return _indicator.EmailTrades(input, accountName, emailPartFilled, fromEmailAddress, toEmailAddress);
        }
    }
}
#endregion

Attached Files
Elite Membership required to download: EmailTradesForum.txt
Started this thread Reply With Quote

Can you help answer these questions
from other members on NexusFi?
Ninja Mobile Trader VPS (ninjamobiletrader.com)
Trading Reviews and Vendors
Online prop firm The Funded Trader (TFT) going under?
Traders Hideout
Deepmoney LLM
Elite Quantitative GenAI/LLM
NexusFi Journal Challenge - April 2024
Feedback and Announcements
Are there any eval firms that allow you to sink to your …
Traders Hideout
 
Best Threads (Most Thanked)
in the last 7 days on NexusFi
Get funded firms 2023/2024 - Any recommendations or word …
61 thanks
Funded Trader platforms
44 thanks
NexusFi site changelog and issues/problem reporting
24 thanks
GFIs1 1 DAX trade per day journal
22 thanks
The Program
19 thanks
  #3 (permalink)
 
Mindset's Avatar
 Mindset 
Singapore
 
Experience: Intermediate
Platform: NT
Broker: ib
Trading: MES
Posts: 365 since Sep 2009
Thanks Given: 90
Thanks Received: 291


ok on testing it - there is some abnormal behaviour - it sends out multiple emails for the same execution. Not straight off - but after a while - totally confused.

Started this thread Reply With Quote
  #4 (permalink)
 MrTrader 
ITAJAI SC/BRAZIL
 
Experience: Intermediate
Platform: NinjaTrader
Broker: Clear Corretora
Trading: DOLFUT, WINFUT
Posts: 332 since Jun 2014
Thanks Given: 1,314
Thanks Received: 225

Hi @Mindset ,


I was looking for some code to add combobox into NT toolstrip and found this thread, thank you!
Did not tested the code yet but occurred to me that perhaps this erratic behavior.. maybe it is correlated with combobox.. I mean, something linked to TextChanged/EventHandler.. then when for some reason the component is released the list is changed, triggering emails... what you think?

BTW, this snipped of code, to add combobox, have you used before or it is the first time?

Regards,

Reply With Quote
  #5 (permalink)
 
Mindset's Avatar
 Mindset 
Singapore
 
Experience: Intermediate
Platform: NT
Broker: ib
Trading: MES
Posts: 365 since Sep 2009
Thanks Given: 90
Thanks Received: 291

Hi Mr Trader

I have added Combo Boxes before so the code is fine for that. The issue with the email code appears to be with the account name and it's link with the Chart Trader. Its just a little bit beyond me at the moment but I am still trying to work it out!

Started this thread Reply With Quote
Thanked by:
  #6 (permalink)
 
ratfink's Avatar
 ratfink 
Birmingham UK
Market Wizard
 
Experience: Intermediate
Platform: NinjaTrader
Broker: TST/Rithmic
Trading: YM/Gold
Posts: 3,633 since Dec 2012
Thanks Given: 17,423
Thanks Received: 8,425


Mindset View Post
Hi Mr Trader

I have added Combo Boxes before so the code is fine for that. The issue with the email code appears to be with the account name and it's link with the Chart Trader. Its just a little bit beyond me at the moment but I am still trying to work it out!


Travel Well
Visit my NexusFi Trade Journal Reply With Quote
Thanked by:




Last Updated on November 21, 2014


© 2024 NexusFi™, s.a., All Rights Reserved.
Av Ricardo J. Alfaro, Century Tower, Panama City, Panama, Ph: +507 833-9432 (Panama and Intl), +1 888-312-3001 (USA and Canada)
All information is for educational use only and is not investment advice. There is a substantial risk of loss in trading commodity futures, stocks, options and foreign exchange products. Past performance is not indicative of future results.
About Us - Contact Us - Site Rules, Acceptable Use, and Terms and Conditions - Privacy Policy - Downloads - Top
no new posts