Email Trades code bug - NinjaTrader Programming | futures io social day trading
futures io futures trading


Email Trades code bug
Updated: Views / Replies:939 / 5
Created: by Mindset Attachments:1

Welcome to futures io.

(If you already have an account, login at the top of the page)

futures io is the largest futures trading community on the planet, with over 90,000 members. At futures io, our goal has always been and always will be to create a friendly, positive, forward-thinking community where members can openly share and discuss everything the world of trading has to offer. The community is one of the friendliest you will find on any subject, with members going out of their way to help others. Some of the primary differences between futures io and other trading sites revolve around the standards of our community. Those standards include a code of conduct for our members, as well as extremely high standards that govern which partners we do business with, and which products or services we recommend to our members.

At futures io, our focus is on quality education. No hype, gimmicks, or secret sauce. The truth is: trading is hard. To succeed, you need to surround yourself with the right support system, educational content, and trading mentors Ė all of which you can find on futures io, utilizing our social trading environment.

With futures io, you can find honest trading reviews on brokers, trading rooms, indicator packages, trading strategies, and much more. Our trading review process is highly moderated to ensure that only genuine users are allowed, so you donít need to worry about fake reviews.

We are fundamentally different than most other trading sites:
  • We are here to help. Just let us know what you need.
  • We work extremely hard to keep things positive in our community.
  • We do not tolerate rude behavior, trolling, or vendors advertising in posts.
  • We firmly believe in and encourage sharing. The holy grail is within you, we can help you find it.
  • We expect our members to participate and become a part of the community. Help yourself by helping others.

You'll need to register in order to view the content of the threads and start contributing to our community.  It's free and simple.

-- Big Mike, Site Administrator

Reply
 
Thread Tools Search this Thread
 

Email Trades code bug

  #1 (permalink)
Elite Member
UK
 
Futures Experience: Intermediate
Platform: NT
Broker/Data: ib
Favorite Futures: Electric Guitar
 
Mindset's Avatar
 
Posts: 355 since Sep 2009
Thanks: 88 given, 285 received

Email Trades code bug

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 = @"from@email.com"; 
        private string toEmailAddress = @"to@email.com"; 
        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
Register to download File Type: txt EmailTradesForum.txt (14.5 KB, 17 views)

Last edited by Mindset; February 28th, 2014 at 03:56 AM.
Reply With Quote
 
  #2 (permalink)
Quick Summary
Quick Summary Post

Quick Summary is created and edited by users like you... Add FAQ's, Links and other Relevant Information by clicking the edit button in the lower right hand corner of this message.

 
  #3 (permalink)
Elite Member
UK
 
Futures Experience: Intermediate
Platform: NT
Broker/Data: ib
Favorite Futures: Electric Guitar
 
Mindset's Avatar
 
Posts: 355 since Sep 2009
Thanks: 88 given, 285 received


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.

Reply With Quote
 
  #4 (permalink)
Elite Member
ITAJAI SC/BRAZIL
 
Futures Experience: Beginner
Platform: NinjaTrader
Broker/Data: Clear Corretora
Favorite Futures: DOLFUT, WINFUT
 
Posts: 184 since Jun 2014
Thanks: 760 given, 132 received

ComboBox

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)
Elite Member
UK
 
Futures Experience: Intermediate
Platform: NT
Broker/Data: ib
Favorite Futures: Electric Guitar
 
Mindset's Avatar
 
Posts: 355 since Sep 2009
Thanks: 88 given, 285 received

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!

Reply With Quote
The following user says Thank You to Mindset for this post:
 
  #6 (permalink)
Elite Member
Birmingham UK
 
Futures Experience: Intermediate
Platform: NinjaTrader
Broker/Data: IG/eSignal
Favorite Futures: Dax
 
ratfink's Avatar
 
Posts: 3,340 since Dec 2012
Thanks: 11,282 given, 7,092 received


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!

https://futures.io/ninjatrader-programming/9230-strategy-monitor-all-account-orders-2.html#post453603

Travel Well
Reply With Quote
The following user says Thank You to ratfink for this post:

Reply



futures io > > > > > Email Trades code bug

Thread Tools Search this Thread
Search this Thread:

Advanced Search



Upcoming Webinars and Events (4:30PM ET unless noted)

Jigsaw Trading: TBA

Elite only

FuturesTrader71: TBA

Elite only

NinjaTrader: TBA

Jan 18

RandBots: TBA

Jan 23

GFF Brokers & CME Group: Futures & Bitcoin

Elite only

Adam Grimes: TBA

Elite only

Ran Aroussi: TBA

Elite only
     

Similar Threads
Thread Thread Starter Forum Replies Last Post
Discretionary trades vs system trades (for elite performers) strikebackfast Traders Hideout 8 July 18th, 2017 07:14 AM
Multicharts Bug merzoil MultiCharts 1 January 9th, 2013 09:52 AM
Code stopping trades into resistance level lincor NinjaTrader 0 November 25th, 2012 09:49 PM
BUG for OnMarketData timmyb NinjaTrader Programming 12 February 5th, 2011 10:32 PM


All times are GMT -4. The time now is 12:39 AM.

Copyright © 2017 by futures io, s.a., Av Ricardo J. Alfaro, Century Tower, Panama, +507 833-9432, info@futures.io
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.
no new posts
Page generated 2017-12-16 in 0.11 seconds with 20 queries on phoenix via your IP 54.226.113.250