Dark Theme
Light Theme
Trading Articles
Article Categories
Article Tools
Welcome to NexusFi: the best trading community on the planet, with over 150,000 members Sign Up Now for Free
Genuine reviews from real traders, not fake reviews from stealth vendors
Quality education from leading professional traders
We are a friendly, helpful, and positive community
We do not tolerate rude behavior, trolling, or vendors advertising in posts
We are here to help, just let us know what you need
You'll need to
register in order to view the content of the threads and start contributing to our community.
It's free for basic access, or support us by becoming an Elite Member -- see if you qualify for a discount below.
-- Big Mike, Site Administrator
(If you already have an account, login at the top of the page)
Email Trades code bug
Updated November 21, 2014
Top Posters
looks_one
Mindset
with 3 posts (1 thanks)
looks_two
Quick Summary
with 1 posts (0 thanks)
looks_3
MrTrader
with 1 posts (0 thanks)
looks_4
ratfink
with 1 posts (1 thanks)
trending_up
1,906 views
thumb_up
2 thanks given
group
2 followers
forum
5 posts
attach_file
1 attachments
Email Trades code bug
February 27th, 2014, 08:27 AM
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
Can you help answer these questions from other members on NexusFi?
Best Threads (Most Thanked) in the last 7 days on NexusFi
February 27th, 2014, 09:07 AM
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.
November 19th, 2014, 12:58 PM
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,
November 20th, 2014, 02:17 AM
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!
November 21st, 2014, 03:10 AM
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
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!
Last Updated on November 21, 2014