using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MySql.Data.MySqlClient;
using MarketData.MarketDataModel;
using MarketData.Utils;

namespace MarketData.DataAccess
{
  public class PortfolioDA
  {
    private PortfolioDA()
    {
    }
// **********************************************************************************************************************************************************************************
// ****************************************************************************************** S T O P   L I M I T S  ****************************************************************
// **********************************************************************************************************************************************************************************
    public static StopLimit GetStopLimit(String symbol)
    {
      MySqlConnection sqlConnection=null;
      MySqlDataReader sqlDataReader=null;
      MySqlCommand sqlCommand=null;
      String strQuery=null;

      try
      {
        StringBuilder sb=new StringBuilder();
        if(null==symbol)return null;
        sqlConnection=SqlUtils.CreateMySqlConnection(MainDataSource.Instance.LocateDataSource("portfolio_data"));
        sb.Append("select symbol,stop_limit,shares,stop_type,active from stoplimits ");
        sb.Append("where symbol='").Append(symbol).Append("'");
        sb.Append(" and active=1");
        strQuery=sb.ToString();
        sqlCommand=new MySqlCommand(strQuery,sqlConnection);
        sqlCommand.CommandTimeout=SqlUtils.COMMAND_TIMEOUT;
        sqlDataReader=sqlCommand.ExecuteReader();
        if(!sqlDataReader.Read())return null;
        StopLimit stopLimit=new StopLimit();
        stopLimit.Symbol=sqlDataReader.GetString(0);
        stopLimit.StopPrice=sqlDataReader.GetDouble(1);
        stopLimit.Shares=sqlDataReader.GetDouble(2);
        stopLimit.StopType=sqlDataReader.GetString(3);
        stopLimit.Active=sqlDataReader.GetInt32(4);
        return stopLimit;
      }
      catch(Exception exception)
      {
        MDTrace.WriteLine(LogLevel.DEBUG,exception);
        return null;
      }
      finally
      {
        if(null!=sqlCommand) sqlCommand.Dispose();
        if(null!=sqlDataReader) sqlDataReader.Close();
        if(null!=sqlConnection) sqlConnection.Close();
      }
    }
    public static bool InsertUpdateStopLimit(StopLimit stopLimit)
    {
      if(null==stopLimit||null==stopLimit.Symbol||double.IsNaN(stopLimit.StopPrice))return false;
      if(!HasStopLimit(stopLimit.Symbol))return InsertStopLimit(stopLimit);
      return UpdateStopLimit(stopLimit);
    }
    private static bool InsertStopLimit(StopLimit stopLimit)
    {
      MySqlConnection sqlConnection=null;
      MySqlTransaction sqlTransaction=null;
      MySqlCommand sqlCommand=null;
      String strQuery=null;

      try
      {
        sqlConnection=SqlUtils.CreateMySqlConnection(MainDataSource.Instance.LocateDataSource("portfolio_data"));
        sqlTransaction=sqlConnection.BeginTransaction(System.Data.IsolationLevel.ReadCommitted);
        StringBuilder sb=new StringBuilder();
        sb.Append("insert into stoplimits(symbol,stop_limit,shares,stop_type,active)values(");
        sb.Append(SqlUtils.AddQuotes(stopLimit.Symbol)).Append(",");
        sb.Append(stopLimit.StopPrice).Append(",");
        sb.Append(stopLimit.Shares).Append(",");
        if(null!=stopLimit.StopType) sb.Append(SqlUtils.AddQuotes(stopLimit.StopType)).Append(",");
        else sb.Append("null").Append(",");
        sb.Append(stopLimit.Active);
        sb.Append(")");
        strQuery=sb.ToString();
        sqlCommand=new MySqlCommand(strQuery,sqlConnection,sqlTransaction);
        sqlCommand.CommandTimeout=SqlUtils.COMMAND_TIMEOUT;
        sqlCommand.ExecuteNonQuery();
        sqlTransaction.Commit();
        return true;
      }
      catch(Exception exception)
      {
        MDTrace.WriteLine(LogLevel.DEBUG,exception);
        return false;
      }
      finally
      {
        if(null!=sqlCommand) sqlCommand.Dispose();
        if(null!=sqlTransaction) sqlTransaction.Dispose();
        if(null!=sqlConnection) sqlConnection.Close();
      }
    }
    private static bool UpdateStopLimit(StopLimit stopLimit)
    {
      MySqlConnection sqlConnection=null;
      MySqlTransaction sqlTransaction=null;
      MySqlCommand sqlCommand=null;
      String strQuery=null;

      try
      {
        sqlConnection=SqlUtils.CreateMySqlConnection(MainDataSource.Instance.LocateDataSource("portfolio_data"));
        sqlTransaction=sqlConnection.BeginTransaction(System.Data.IsolationLevel.ReadCommitted);
        StringBuilder sb=new StringBuilder();
        sb.Append("update stoplimits ");
        sb.Append("set ");
        if(null!=stopLimit.StopType) sb.Append("stop_type=").Append(SqlUtils.AddQuotes(stopLimit.StopType)).Append(", ");
        sb.Append("stop_limit=").Append(stopLimit.StopPrice).Append(", ");
        sb.Append("shares=").Append(stopLimit.Shares).Append(", ");
        sb.Append("active=").Append(stopLimit.Active).Append("");
        sb.Append(" where symbol=").Append(SqlUtils.AddQuotes(stopLimit.Symbol));
        strQuery=sb.ToString();
        sqlCommand=new MySqlCommand(strQuery,sqlConnection,sqlTransaction);
        sqlCommand.CommandTimeout=SqlUtils.COMMAND_TIMEOUT;
        sqlCommand.ExecuteNonQuery();
        sqlTransaction.Commit();
        return true;
      }
      catch(Exception exception)
      {
        MDTrace.WriteLine(LogLevel.DEBUG,exception);
        return false;
      }
      finally
      {
        if(null!=sqlCommand) sqlCommand.Dispose();
        if(null!=sqlConnection) sqlConnection.Close();
        if(null!=sqlTransaction) sqlTransaction.Dispose();
      }
    }
    public static bool HasStopLimit(String symbol)
    {
      MySqlConnection sqlConnection=null;
      MySqlDataReader sqlDataReader=null;
      MySqlCommand sqlCommand=null;
      String strQuery=null;

      try
      {
        StringBuilder sb=new StringBuilder();
        if(null==symbol) return false;
        sqlConnection=SqlUtils.CreateMySqlConnection(MainDataSource.Instance.LocateDataSource("portfolio_data"));
        sb.Append("select count(*) from stoplimits ");
        sb.Append("where symbol='").Append(symbol).Append("'");
        strQuery=sb.ToString();
        sqlCommand=new MySqlCommand(strQuery,sqlConnection);
        sqlCommand.CommandTimeout=SqlUtils.COMMAND_TIMEOUT;
        sqlDataReader=sqlCommand.ExecuteReader();
        if(!sqlDataReader.Read()) return false;
        int count=sqlDataReader.GetInt32(0);
        return count>0?true:false;
      }
      catch(Exception exception)
      {
        MDTrace.WriteLine(LogLevel.DEBUG,exception);
        return false;
      }
      finally
      {
        if(null!=sqlCommand) sqlCommand.Dispose();
        if(null!=sqlDataReader) sqlDataReader.Close();
        if(null!=sqlConnection) sqlConnection.Close();
      }
    }
    public static bool DeleteStopLimit(String symbol)
    {
      MySqlConnection sqlConnection=null;
      MySqlCommand sqlCommand=null;
      String strQuery=null;

      try
      {
        StringBuilder sb=new StringBuilder();
        if(null==symbol) return false;
        sqlConnection=SqlUtils.CreateMySqlConnection(MainDataSource.Instance.LocateDataSource("portfolio_data"));
        sb.Append("delete from stoplimits ");
        sb.Append("where symbol='").Append(symbol).Append("'");
        strQuery=sb.ToString();
        sqlCommand=new MySqlCommand(strQuery,sqlConnection);
        sqlCommand.CommandTimeout=SqlUtils.COMMAND_TIMEOUT;
        sqlCommand.ExecuteNonQuery();
        return true;
      }
      catch(Exception exception)
      {
        MDTrace.WriteLine(LogLevel.DEBUG,exception);
        return false;
      }
      finally
      {
        if(null!=sqlCommand) sqlCommand.Dispose();
        if(null!=sqlConnection) sqlConnection.Close();
      }
    }
// **********************************************************************************************************************************************************************
    public static bool UpdateTrade(PortfolioTrade trade)
    {
      MySqlConnection sqlConnection = null;
      MySqlTransaction sqlTransaction = null;
			MySqlCommand sqlCommand=null;
      String strQuery = null;

      try
      {
        sqlConnection = SqlUtils.CreateMySqlConnection(MainDataSource.Instance.LocateDataSource("portfolio_data"));
        sqlTransaction = sqlConnection.BeginTransaction(System.Data.IsolationLevel.ReadCommitted);
        StringBuilder sb = new StringBuilder();
        sb.Append("update trades ");
        sb.Append("set ");
        sb.Append("symbol=").Append(SqlUtils.AddQuotes(trade.Symbol)).Append(", ");
        sb.Append("trade_date=").Append(SqlUtils.AddQuotes(Utility.DateTimeToStringYYYYHMMHDD(trade.TradeDate))).Append(", ");
        sb.Append("shares=").Append(trade.Shares).Append(", ");
        sb.Append("price=").Append(trade.Price).Append(", ");
        sb.Append("buysell=").Append(SqlUtils.AddQuotes(trade.BuySell)).Append(", ");
        sb.Append("account=").Append(SqlUtils.AddQuotes(trade.Account)).Append(", ");
        sb.Append("status=").Append(SqlUtils.AddQuotes(trade.Status)).Append(", ");
        sb.Append("commission=").Append(trade.Commission);
        if (!Utility.IsEpoch(trade.SellDate))sb.Append(", date_sold=").Append(SqlUtils.AddQuotes(Utility.DateTimeToStringYYYYHMMHDD(trade.SellDate))).Append(" ");
        if (!double.IsNaN(trade.SellPrice) && !double.IsInfinity(trade.SellPrice))sb.Append(", sell_price=").Append(trade.SellPrice).Append(" ");
        sb.Append(" where trade_id=").Append(trade.TradeId);
        strQuery = sb.ToString();
        sqlCommand = new MySqlCommand(strQuery, sqlConnection, sqlTransaction);
        sqlCommand.CommandTimeout = SqlUtils.COMMAND_TIMEOUT;
        sqlCommand.ExecuteNonQuery();
        sqlTransaction.Commit();
        return true;
      }
      catch (Exception exception)
      {
        MDTrace.WriteLine(LogLevel.DEBUG,exception);
        return false;
      }
      finally
      {
				if(null!=sqlCommand)sqlCommand.Dispose();
        if (null != sqlConnection) sqlConnection.Close();
        if (null != sqlTransaction) sqlTransaction.Dispose();
      }
    }
    public static int AddTrade(PortfolioTrade trade)
    {
      MySqlConnection sqlConnection = null;
      MySqlTransaction sqlTransaction = null;
			MySqlCommand sqlCommand=null;
      String strQuery = null;

      try
      {
        sqlConnection = SqlUtils.CreateMySqlConnection(MainDataSource.Instance.LocateDataSource("portfolio_data"));
        sqlTransaction = sqlConnection.BeginTransaction(System.Data.IsolationLevel.ReadCommitted);
        StringBuilder sb = new StringBuilder();
        sb.Append("insert into trades(symbol,trade_date,shares,price,buysell,account,status,commission,date_sold,sell_price)values(");
        sb.Append(SqlUtils.AddQuotes(trade.Symbol)).Append(",");
        sb.Append(SqlUtils.AddQuotes(Utility.DateTimeToStringYYYYHMMHDD(trade.TradeDate))).Append(",");
        sb.Append(trade.Shares).Append(",");
        sb.Append(trade.Price).Append(",");
        sb.Append(SqlUtils.AddQuotes(trade.BuySell)).Append(",");
        sb.Append("'").Append(trade.Account).Append("'").Append(",");
        sb.Append("'").Append(trade.Status).Append("'").Append(",");
        sb.Append("'").Append(trade.Commission).Append("'").Append(",");
        if (!Utility.IsEpoch(trade.SellDate)) sb.Append(SqlUtils.AddQuotes(Utility.DateTimeToStringYYYYHMMHDD(trade.SellDate))).Append(",");
        else sb.Append("null").Append(",");
        if (!double.IsNaN(trade.SellPrice)&&!double.IsInfinity(trade.SellPrice)) sb.Append(trade.SellPrice);
        else sb.Append("null");
        sb.Append(")");
        strQuery = sb.ToString();
        sqlCommand = new MySqlCommand(strQuery, sqlConnection, sqlTransaction);
        sqlCommand.CommandTimeout = SqlUtils.COMMAND_TIMEOUT;
        sqlCommand.ExecuteNonQuery();
        sqlTransaction.Commit();
        return GetMaxTradeId();
      }
      catch (Exception exception)
      {
        MDTrace.WriteLine(LogLevel.DEBUG,exception);
        return -1;
      }
      finally
      {
				if(null!=sqlCommand)sqlCommand.Dispose();
        if (null != sqlTransaction) sqlTransaction.Dispose();
        if (null != sqlConnection) sqlConnection.Close();
      }
    }
    public static PortfolioTrades GetTrades(String symbol=null)
    {
      MySqlConnection sqlConnection = null;
      MySqlDataReader sqlDataReader = null;
			MySqlCommand sqlCommand=null;
      PortfolioTrades portfolioTrades = new PortfolioTrades();
      String strQuery = null;

      try
      {
        StringBuilder sb = new StringBuilder();
        sqlConnection = SqlUtils.CreateMySqlConnection(MainDataSource.Instance.LocateDataSource("portfolio_data"));
        sb.Append("select trade_id,symbol,trade_date,shares,price,buysell,account,status,commission,date_sold,sell_price from trades ");
        if(null!=symbol)sb.Append("where symbol='").Append(symbol).Append("'");
        sb.Append(" order by trade_date asc");
        strQuery = sb.ToString();
        sqlCommand = new MySqlCommand(strQuery, sqlConnection);
        sqlCommand.CommandTimeout = SqlUtils.COMMAND_TIMEOUT;
        sqlDataReader = sqlCommand.ExecuteReader();
        while (sqlDataReader.Read())
        {
          PortfolioTrade portfolioTrade = new PortfolioTrade();
          portfolioTrade.TradeId = sqlDataReader.GetInt32(0);
          portfolioTrade.Symbol = sqlDataReader.GetString(1);
          portfolioTrade.TradeDate = sqlDataReader.GetDateTime(2);
          portfolioTrade.Shares = sqlDataReader.GetDouble(3);
          portfolioTrade.Price = sqlDataReader.GetDouble(4);
          portfolioTrade.BuySell = sqlDataReader.GetString(5);
          portfolioTrade.Account = sqlDataReader.GetString(6);
          portfolioTrade.Status = sqlDataReader.GetString(7);
          portfolioTrade.Commission = sqlDataReader.GetDouble(8);
          if (!sqlDataReader.IsDBNull(9)) portfolioTrade.SellDate = sqlDataReader.GetDateTime(9);
          else portfolioTrade.SellDate = Utility.Epoch;
          if (!sqlDataReader.IsDBNull(10)) portfolioTrade.SellPrice = sqlDataReader.GetDouble(10);
          else portfolioTrade.SellPrice = double.NaN;
          portfolioTrades.Add(portfolioTrade);
        }
        return portfolioTrades;
      }
      catch (Exception exception)
      {
        MDTrace.WriteLine(LogLevel.DEBUG,exception);
        return null;
      }
      finally
      {
				if(null!=sqlCommand)sqlCommand.Dispose();
        if (null != sqlDataReader) sqlDataReader.Close();
        if (null != sqlConnection) sqlConnection.Close();
      }
    }
    public static PortfolioTrades GetTradesForAccount(String account)
    {
      MySqlConnection sqlConnection = null;
      MySqlDataReader sqlDataReader = null;
			MySqlCommand sqlCommand=null;
      PortfolioTrades portfolioTrades = new PortfolioTrades();
      String strQuery = null;

      try
      {
        StringBuilder sb = new StringBuilder();
        sqlConnection = SqlUtils.CreateMySqlConnection(MainDataSource.Instance.LocateDataSource("portfolio_data"));
        sb.Append("select trade_id,symbol,trade_date,shares,price,buysell,account,status,commission,date_sold,sell_price from trades ");
        sb.Append("where account='").Append(account).Append("'");
        sb.Append(" order by trade_date asc");
        strQuery = sb.ToString();
        sqlCommand = new MySqlCommand(strQuery, sqlConnection);
        sqlCommand.CommandTimeout = SqlUtils.COMMAND_TIMEOUT;
        sqlDataReader = sqlCommand.ExecuteReader();
        while (sqlDataReader.Read())
        {
          PortfolioTrade portfolioTrade = new PortfolioTrade();
          portfolioTrade.TradeId = sqlDataReader.GetInt32(0);
          portfolioTrade.Symbol = sqlDataReader.GetString(1);
          portfolioTrade.TradeDate = sqlDataReader.GetDateTime(2);
          portfolioTrade.Shares = sqlDataReader.GetDouble(3);
          portfolioTrade.Price = sqlDataReader.GetDouble(4);
          portfolioTrade.BuySell = sqlDataReader.GetString(5);
          portfolioTrade.Account = sqlDataReader.GetString(6);
          portfolioTrade.Status = sqlDataReader.GetString(7);
          portfolioTrade.Commission = sqlDataReader.GetDouble(8);
          if (!sqlDataReader.IsDBNull(9)) portfolioTrade.SellDate = sqlDataReader.GetDateTime(9);
          else portfolioTrade.SellDate = Utility.Epoch;
          if (!sqlDataReader.IsDBNull(10)) portfolioTrade.SellPrice = sqlDataReader.GetDouble(10);
          else portfolioTrade.SellPrice = double.NaN;
          portfolioTrades.Add(portfolioTrade);
        }
        return portfolioTrades;
      }
      catch (Exception exception)
      {
        MDTrace.WriteLine(LogLevel.DEBUG,exception);
        return null;
      }
      finally
      {
				if(null!=sqlCommand)sqlCommand.Dispose();
        if (null != sqlDataReader) sqlDataReader.Close();
        if (null != sqlConnection) sqlConnection.Close();
      }
    }
    public static PortfolioTrades GetTradesForAccounts(List<String> accounts)
    {
      MySqlConnection sqlConnection = null;
      MySqlDataReader sqlDataReader = null;
			MySqlCommand sqlCommand=null;
      PortfolioTrades portfolioTrades = new PortfolioTrades();
      String strQuery = null;

      try
      {
        StringBuilder sb = new StringBuilder();
        sqlConnection = SqlUtils.CreateMySqlConnection(MainDataSource.Instance.LocateDataSource("portfolio_data"));
        sb.Append("select trade_id,symbol,trade_date,shares,price,buysell,account,status,commission,date_sold,sell_price from trades ");
        sb.Append("where account in ").Append(SqlUtils.CreateInClause(accounts));
        sb.Append(" order by trade_date asc");
        strQuery = sb.ToString();
        sqlCommand = new MySqlCommand(strQuery, sqlConnection);
        sqlCommand.CommandTimeout = SqlUtils.COMMAND_TIMEOUT;
        sqlDataReader = sqlCommand.ExecuteReader();
        while (sqlDataReader.Read())
        {
          PortfolioTrade portfolioTrade = new PortfolioTrade();
          portfolioTrade.TradeId = sqlDataReader.GetInt32(0);
          portfolioTrade.Symbol = sqlDataReader.GetString(1);
          portfolioTrade.TradeDate = sqlDataReader.GetDateTime(2);
          portfolioTrade.Shares = sqlDataReader.GetDouble(3);
          portfolioTrade.Price = sqlDataReader.GetDouble(4);
          portfolioTrade.BuySell = sqlDataReader.GetString(5);
          portfolioTrade.Account = sqlDataReader.GetString(6);
          portfolioTrade.Status = sqlDataReader.GetString(7);
          portfolioTrade.Commission = sqlDataReader.GetDouble(8);
          if (!sqlDataReader.IsDBNull(9)) portfolioTrade.SellDate = sqlDataReader.GetDateTime(9);
          else portfolioTrade.SellDate = Utility.Epoch;
          if (!sqlDataReader.IsDBNull(10)) portfolioTrade.SellPrice = sqlDataReader.GetDouble(10);
          else portfolioTrade.SellPrice = double.NaN;
          portfolioTrades.Add(portfolioTrade);
        }
        return portfolioTrades;
      }
      catch (Exception exception)
      {
        MDTrace.WriteLine(LogLevel.DEBUG,exception);
        return null;
      }
      finally
      {
				if(null!=sqlCommand)sqlCommand.Dispose();
        if (null != sqlDataReader) sqlDataReader.Close();
        if (null != sqlConnection) sqlConnection.Close();
      }
    }
    public static PortfolioTrades GetOpenTrades()
    {
      MySqlConnection sqlConnection = null;
      MySqlDataReader sqlDataReader = null;
			MySqlCommand sqlCommand=null;
      PortfolioTrades portfolioTrades = new PortfolioTrades();
      String strQuery = null;

      try
      {
        StringBuilder sb = new StringBuilder();
        sqlConnection = SqlUtils.CreateMySqlConnection(MainDataSource.Instance.LocateDataSource("portfolio_data"));
        sb.Append("select trade_id,symbol,trade_date,shares,price,buysell,account,status,commission,date_sold,sell_price from trades ");
        sb.Append(" where status='").Append("OPEN").Append("'");
        sb.Append(" order by trade_date asc");
        strQuery = sb.ToString();
        sqlCommand = new MySqlCommand(strQuery, sqlConnection);
        sqlCommand.CommandTimeout = SqlUtils.COMMAND_TIMEOUT;
        sqlDataReader = sqlCommand.ExecuteReader();
        while (sqlDataReader.Read())
        {
          PortfolioTrade portfolioTrade = new PortfolioTrade();
          portfolioTrade.TradeId = sqlDataReader.GetInt32(0);
          portfolioTrade.Symbol = sqlDataReader.GetString(1);
          portfolioTrade.TradeDate = sqlDataReader.GetDateTime(2);
          portfolioTrade.Shares = sqlDataReader.GetDouble(3);
          portfolioTrade.Price = sqlDataReader.GetDouble(4);
          portfolioTrade.BuySell = sqlDataReader.GetString(5);
          portfolioTrade.Account = sqlDataReader.GetString(6);
          portfolioTrade.Status = sqlDataReader.GetString(7);
          portfolioTrade.Commission = sqlDataReader.GetDouble(8);
          if (!sqlDataReader.IsDBNull(9)) portfolioTrade.SellDate = sqlDataReader.GetDateTime(9);
          else portfolioTrade.SellDate = Utility.Epoch;
          if (!sqlDataReader.IsDBNull(10)) portfolioTrade.SellPrice = sqlDataReader.GetDouble(10);
          else portfolioTrade.SellPrice = double.NaN;
          portfolioTrades.Add(portfolioTrade);
        }
        return portfolioTrades;
      }
      catch (Exception exception)
      {
        MDTrace.WriteLine(LogLevel.DEBUG,exception);
        return null;
      }
      finally
      {
				if(null!=sqlCommand)sqlCommand.Dispose();
        if (null != sqlDataReader) sqlDataReader.Close();
        if (null != sqlConnection) sqlConnection.Close();
      }
    }
// Retrieves the symbols for open trades
    public static List<String> GetOpenSymbols()
    {
      try
      {
        PortfolioTrades portfolioTrades=GetOpenTrades();
        if(null==portfolioTrades)return null;
        return portfolioTrades.Symbols;
      }
      catch(Exception)
      {
        return null;
      }
    }
// This is used by ValueAtRisk
// Notes: Added the conditional after "OR" clause.  The reason being that the query was not returning trades which are CLOSED but OPEN on the asOf date. 
// The behaviour was observed while running the VaR and examining 07/30/2019 vs 07/31/2019 and noticing that ENSG, which was still OPEN on 07/30, was not being included in the VaR
    public static PortfolioTrades GetOpenTradesAsOf(DateTime asOf)
    {
      MySqlConnection sqlConnection = null;
      MySqlDataReader sqlDataReader = null;
			MySqlCommand sqlCommand=null;
      PortfolioTrades portfolioTrades = new PortfolioTrades();
      String strQuery = null;

      try
      {
        StringBuilder sb = new StringBuilder();
        sqlConnection = SqlUtils.CreateMySqlConnection(MainDataSource.Instance.LocateDataSource("portfolio_data"));
        sb.Append("select trade_id,symbol,trade_date,shares,price,buysell,account,status,commission,date_sold,sell_price from trades ");
        sb.Append(" where (trade_date<='").Append(Utility.DateTimeToStringYYYYHMMHDD(asOf)).Append("' ").Append(" and status='").Append("OPEN").Append("')");
        sb.Append(" or (trade_date<='").Append(Utility.DateTimeToStringYYYYHMMHDD(asOf)).Append("' and status='CLOSED' and date_sold is not null and date_sold>='").Append(Utility.DateTimeToStringYYYYHMMHDD(asOf)).Append("')");
        sb.Append(" order by trade_date asc");
        strQuery = sb.ToString();
        sqlCommand = new MySqlCommand(strQuery, sqlConnection);
        sqlCommand.CommandTimeout = SqlUtils.COMMAND_TIMEOUT;
        sqlDataReader = sqlCommand.ExecuteReader();
        while (sqlDataReader.Read())
        {
          PortfolioTrade portfolioTrade = new PortfolioTrade();
          portfolioTrade.TradeId = sqlDataReader.GetInt32(0);
          portfolioTrade.Symbol = sqlDataReader.GetString(1);
          portfolioTrade.TradeDate = sqlDataReader.GetDateTime(2);
          portfolioTrade.Shares = sqlDataReader.GetDouble(3);
          portfolioTrade.Price = sqlDataReader.GetDouble(4);
          portfolioTrade.BuySell = sqlDataReader.GetString(5);
          portfolioTrade.Account = sqlDataReader.GetString(6);
          portfolioTrade.Status = sqlDataReader.GetString(7);
          portfolioTrade.Commission = sqlDataReader.GetDouble(8);
          if (!sqlDataReader.IsDBNull(9)) portfolioTrade.SellDate = sqlDataReader.GetDateTime(9);
          else portfolioTrade.SellDate = Utility.Epoch;
          if (!sqlDataReader.IsDBNull(10)) portfolioTrade.SellPrice = sqlDataReader.GetDouble(10);
          else portfolioTrade.SellPrice = double.NaN;
          portfolioTrades.Add(portfolioTrade);
        }
        return portfolioTrades;
      }
      catch (Exception exception)
      {
        MDTrace.WriteLine(LogLevel.DEBUG,exception);
        return null;
      }
      finally
      {
				if(null!=sqlCommand)sqlCommand.Dispose();
        if (null != sqlDataReader) sqlDataReader.Close();
        if (null != sqlConnection) sqlConnection.Close();
      }
    }
    public static PortfolioTrades GetOpenTradesSymbolBetween(String symbol,DateTime minDate,DateTime maxDate)
    {
      MySqlConnection sqlConnection = null;
      MySqlDataReader sqlDataReader = null;
			MySqlCommand sqlCommand=null;
      PortfolioTrades portfolioTrades = new PortfolioTrades();
      String strQuery = null;

      try
      {
        StringBuilder sb = new StringBuilder();
        sqlConnection = SqlUtils.CreateMySqlConnection(MainDataSource.Instance.LocateDataSource("portfolio_data"));
        sb.Append("select trade_id,symbol,trade_date,shares,price,buysell,account,status,commission,date_sold,sell_price from trades ");
        sb.Append(" where trade_date>='").Append(Utility.DateTimeToStringYYYYHMMHDD(minDate)).Append("' ");
        sb.Append(" and trade_date<='").Append(Utility.DateTimeToStringYYYYHMMHDD(maxDate)).Append("' ");
        sb.Append(" and symbol='").Append(symbol).Append("'");
        sb.Append(" and status='").Append("OPEN").Append("'");
        sb.Append(" order by trade_date asc");
        strQuery = sb.ToString();
        sqlCommand = new MySqlCommand(strQuery, sqlConnection);
        sqlCommand.CommandTimeout = SqlUtils.COMMAND_TIMEOUT;
        sqlDataReader = sqlCommand.ExecuteReader();
        while (sqlDataReader.Read())
        {
          PortfolioTrade portfolioTrade = new PortfolioTrade();
          portfolioTrade.TradeId = sqlDataReader.GetInt32(0);
          portfolioTrade.Symbol = sqlDataReader.GetString(1);
          portfolioTrade.TradeDate = sqlDataReader.GetDateTime(2);
          portfolioTrade.Shares = sqlDataReader.GetDouble(3);
          portfolioTrade.Price = sqlDataReader.GetDouble(4);
          portfolioTrade.BuySell = sqlDataReader.GetString(5);
          portfolioTrade.Account = sqlDataReader.GetString(6);
          portfolioTrade.Status = sqlDataReader.GetString(7);
          portfolioTrade.Commission = sqlDataReader.GetDouble(8);
          if (!sqlDataReader.IsDBNull(9)) portfolioTrade.SellDate = sqlDataReader.GetDateTime(9);
          else portfolioTrade.SellDate = Utility.Epoch;
          if (!sqlDataReader.IsDBNull(10)) portfolioTrade.SellPrice = sqlDataReader.GetDouble(10);
          else portfolioTrade.SellPrice = double.NaN;
          portfolioTrades.Add(portfolioTrade);
        }
        return portfolioTrades;
      }
      catch (Exception exception)
      {
        MDTrace.WriteLine(LogLevel.DEBUG,exception);
        return null;
      }
      finally
      {
				if(null!=sqlCommand)sqlCommand.Dispose();
        if (null != sqlDataReader) sqlDataReader.Close();
        if (null != sqlConnection) sqlConnection.Close();
      }
    }
    public static PortfolioTrades GetOpenTradesSymbol(String symbol)
    {
      MySqlConnection sqlConnection = null;
      MySqlDataReader sqlDataReader = null;
			MySqlCommand sqlCommand=null;
      PortfolioTrades portfolioTrades = new PortfolioTrades();
      String strQuery = null;

      try
      {
        StringBuilder sb = new StringBuilder();
        sqlConnection = SqlUtils.CreateMySqlConnection(MainDataSource.Instance.LocateDataSource("portfolio_data"));
        sb.Append("select trade_id,symbol,trade_date,shares,price,buysell,account,status,commission,date_sold,sell_price from trades ");
        sb.Append(" where symbol='").Append(symbol).Append("'");
        sb.Append(" and status='").Append("OPEN").Append("'");
        sb.Append(" order by trade_date asc");
        strQuery = sb.ToString();
        sqlCommand = new MySqlCommand(strQuery, sqlConnection);
        sqlCommand.CommandTimeout = SqlUtils.COMMAND_TIMEOUT;
        sqlDataReader = sqlCommand.ExecuteReader();
        while (sqlDataReader.Read())
        {
          PortfolioTrade portfolioTrade = new PortfolioTrade();
          portfolioTrade.TradeId = sqlDataReader.GetInt32(0);
          portfolioTrade.Symbol = sqlDataReader.GetString(1);
          portfolioTrade.TradeDate = sqlDataReader.GetDateTime(2);
          portfolioTrade.Shares = sqlDataReader.GetDouble(3);
          portfolioTrade.Price = sqlDataReader.GetDouble(4);
          portfolioTrade.BuySell = sqlDataReader.GetString(5);
          portfolioTrade.Account = sqlDataReader.GetString(6);
          portfolioTrade.Status = sqlDataReader.GetString(7);
          portfolioTrade.Commission = sqlDataReader.GetDouble(8);
          if (!sqlDataReader.IsDBNull(9)) portfolioTrade.SellDate = sqlDataReader.GetDateTime(9);
          else portfolioTrade.SellDate = Utility.Epoch;
          if (!sqlDataReader.IsDBNull(10)) portfolioTrade.SellPrice = sqlDataReader.GetDouble(10);
          else portfolioTrade.SellPrice = double.NaN;
          portfolioTrades.Add(portfolioTrade);
        }
        return portfolioTrades;
      }
      catch (Exception exception)
      {
        MDTrace.WriteLine(LogLevel.DEBUG,exception);
        return null;
      }
      finally
      {
				if(null!=sqlCommand)sqlCommand.Dispose();
        if (null != sqlDataReader) sqlDataReader.Close();
        if (null != sqlConnection) sqlConnection.Close();
      }
    }
    public static PortfolioTrades GetTradesSymbol(String symbol)
    {
      MySqlConnection sqlConnection = null;
      MySqlDataReader sqlDataReader = null;
			MySqlCommand sqlCommand =null;
      PortfolioTrades portfolioTrades = new PortfolioTrades();
      String strQuery = null;

      try
      {
        StringBuilder sb = new StringBuilder();
        sqlConnection = SqlUtils.CreateMySqlConnection(MainDataSource.Instance.LocateDataSource("portfolio_data"));
        sb.Append("select trade_id,symbol,trade_date,shares,price,buysell,account,status,commission,date_sold,sell_price from trades ");
        sb.Append(" where symbol='").Append(symbol).Append("'");
        sb.Append(" order by trade_date asc");
        strQuery = sb.ToString();
        sqlCommand = new MySqlCommand(strQuery, sqlConnection);
        sqlCommand.CommandTimeout = SqlUtils.COMMAND_TIMEOUT;
        sqlDataReader = sqlCommand.ExecuteReader();
        while (sqlDataReader.Read())
        {
          PortfolioTrade portfolioTrade = new PortfolioTrade();
          portfolioTrade.TradeId = sqlDataReader.GetInt32(0);
          portfolioTrade.Symbol = sqlDataReader.GetString(1);
          portfolioTrade.TradeDate = sqlDataReader.GetDateTime(2);
          portfolioTrade.Shares = sqlDataReader.GetDouble(3);
          portfolioTrade.Price = sqlDataReader.GetDouble(4);
          portfolioTrade.BuySell = sqlDataReader.GetString(5);
          portfolioTrade.Account = sqlDataReader.GetString(6);
          portfolioTrade.Status = sqlDataReader.GetString(7);
          portfolioTrade.Commission = sqlDataReader.GetDouble(8);
          if (!sqlDataReader.IsDBNull(9)) portfolioTrade.SellDate = sqlDataReader.GetDateTime(9);
          else portfolioTrade.SellDate = Utility.Epoch;
          if (!sqlDataReader.IsDBNull(10)) portfolioTrade.SellPrice = sqlDataReader.GetDouble(10);
          else portfolioTrade.SellPrice = double.NaN;
          portfolioTrades.Add(portfolioTrade);
        }
        return BreakoutTrades(portfolioTrades);
      }
      catch (Exception exception)
      {
        MDTrace.WriteLine(LogLevel.DEBUG,exception);
        return null;
      }
      finally
      {
				if(null!=sqlCommand)sqlCommand.Dispose();
        if (null != sqlDataReader) sqlDataReader.Close();
        if (null != sqlConnection) sqlConnection.Close();
      }
    }
    private static PortfolioTrades BreakoutTrades(PortfolioTrades portfolioTrades)
    {
      PortfolioTrades allTrades = new PortfolioTrades();
      foreach (PortfolioTrade portfolioTrade in portfolioTrades)
      {
        if (portfolioTrade.IsOpen) allTrades.Add(portfolioTrade);
        else
        {
          PortfolioTrade openTrade = new PortfolioTrade();
          PortfolioTrade closedTrade = new PortfolioTrade();
          openTrade.Symbol = portfolioTrade.Symbol;
          openTrade.Shares = portfolioTrade.Shares;
          openTrade.Account = portfolioTrade.Account;
          openTrade.BuySell = "B";
          openTrade.Status = "OPEN";
          openTrade.Commission = 0;
          openTrade.Price = portfolioTrade.Price;
          openTrade.TradeDate = portfolioTrade.TradeDate;
          openTrade.TradeId=portfolioTrade.TradeId;
          allTrades.Add(openTrade);
          closedTrade.Symbol = portfolioTrade.Symbol;
          closedTrade.Shares = portfolioTrade.Shares;
          closedTrade.Account = portfolioTrade.Account;
          closedTrade.BuySell = "S";
          closedTrade.Status = "CLOSED";
          closedTrade.Commission = 0;
          closedTrade.Price = portfolioTrade.SellPrice;      // closed trade gets a price of the sell price
          closedTrade.SellPrice = portfolioTrade.SellPrice;  // closed trade also gets a sell price of sell price.  Ref:CombineLots() function depends on the SellPrice being set.
          closedTrade.TradeDate = portfolioTrade.SellDate;
          closedTrade.TradeId=portfolioTrade.TradeId;
          allTrades.Add(closedTrade);
        }
      }
      return allTrades;
    }
    public static List<DateTime> GetOpenTradeDates()
    {
      Profiler profiler = new Profiler();
      List<DateTime> openTradeDates = new List<DateTime>();
      try
      {
        DateGenerator dateGenerator = new DateGenerator();
        DateTime minTradeDate = GetMinTradeDate();
        DateTime maxTradeDate = PricingDA.GetLatestDate();    // use the latest date for which we have pricing information
        List<DateTime> historicalDates = PricingDA.GetPricingDates(minTradeDate);
        foreach (DateTime historicalDate in historicalDates)
        {
          PortfolioTrades portfolioTrades = GetOpenTradesAsOf(historicalDate);
          if (null == portfolioTrades || 0 == portfolioTrades.Count) continue;
          openTradeDates.Add(historicalDate);
        }
        return openTradeDates;
      }
      catch (Exception exception)
      {
        MDTrace.WriteLine(LogLevel.DEBUG, exception);
        return openTradeDates;
      }
      finally
      {
        MDTrace.WriteLine(LogLevel.DEBUG, String.Format("PortfolioDA.GetOpenTradeDates: Done, took {0}(ms)", profiler.End()));
      }
    }
    public static DateTime GetMinTradeDate()
    {
      MySqlConnection sqlConnection = null;
      MySqlDataReader sqlDataReader = null;
      MySqlCommand sqlCommand = null;
      DateTime minTradeDate=Utility.Epoch;
      String strQuery = null;

      try
      {
        StringBuilder sb = new StringBuilder();
        sqlConnection = SqlUtils.CreateMySqlConnection(MainDataSource.Instance.LocateDataSource("portfolio_data"));
        sb.Append("select min(trade_date) from trades");
        strQuery = sb.ToString();
        sqlCommand = new MySqlCommand(strQuery, sqlConnection);
        sqlCommand.CommandTimeout = SqlUtils.COMMAND_TIMEOUT;
        sqlDataReader = sqlCommand.ExecuteReader();
        if (sqlDataReader.Read()) minTradeDate = sqlDataReader.GetDateTime(0);
        return minTradeDate;
      }
      catch (Exception exception)
      {
        MDTrace.WriteLine(LogLevel.DEBUG, exception);
        return minTradeDate;
      }
      finally
      {
        if (null != sqlCommand) sqlCommand.Dispose();
        if (null != sqlDataReader) sqlDataReader.Close();
        if (null != sqlConnection) sqlConnection.Close();
      }
    }
    public static int GetMaxTradeId()
    {
      MySqlConnection sqlConnection = null;
      MySqlDataReader sqlDataReader = null;
			MySqlCommand sqlCommand=null;
      int tradeId = -1;
      String strQuery = null;

      try
      {
        StringBuilder sb = new StringBuilder();
        sqlConnection = SqlUtils.CreateMySqlConnection(MainDataSource.Instance.LocateDataSource("portfolio_data"));
        sb.Append("select max(trade_id) from trades");
        strQuery = sb.ToString();
        sqlCommand = new MySqlCommand(strQuery, sqlConnection);
        sqlCommand.CommandTimeout = SqlUtils.COMMAND_TIMEOUT;
        sqlDataReader = sqlCommand.ExecuteReader();
        if (sqlDataReader.Read()) tradeId = sqlDataReader.GetInt32(0);
        return tradeId;
      }
      catch (Exception exception)
      {
        MDTrace.WriteLine(LogLevel.DEBUG,exception);
        return -1;
      }
      finally
      {
				if(null!=sqlCommand)sqlCommand.Dispose();
        if (null != sqlDataReader) sqlDataReader.Close();
        if (null != sqlConnection) sqlConnection.Close();
      }
    }
    public static bool DeleteTrade(int tradeId)
    {
      MySqlConnection sqlConnection = null;
			MySqlCommand sqlCommand =null;
      String strQuery = null;

      try
      {
        StringBuilder sb = new StringBuilder();
        sqlConnection = SqlUtils.CreateMySqlConnection(MainDataSource.Instance.LocateDataSource("portfolio_data"));
        sb.Append("delete from trades where trade_id=");
        sb.Append(tradeId.ToString());
        strQuery = sb.ToString();
        sqlCommand = new MySqlCommand(strQuery, sqlConnection);
        sqlCommand.CommandTimeout = SqlUtils.COMMAND_TIMEOUT;
        sqlCommand.ExecuteNonQuery();
        return true;
      }
      catch (Exception exception)
      {
        MDTrace.WriteLine(LogLevel.DEBUG,exception);
        return false;
      }
      finally
      {
				if(null!=sqlCommand)sqlCommand.Dispose();
        if (null != sqlConnection) sqlConnection.Close();
      }
    }
    public static List<String> GetAccounts()
    {
      MySqlConnection sqlConnection = null;
      MySqlDataReader sqlDataReader = null;
			MySqlCommand sqlCommand=null;
      List<String> watchList = new List<String>();
      String strQuery = null;

      try
      {
        StringBuilder sb = new StringBuilder();
        sqlConnection = SqlUtils.CreateMySqlConnection(MainDataSource.Instance.LocateDataSource("portfolio_data"));
        sb.Append("select account from accounts order by 1 desc");
        strQuery = sb.ToString();
        sqlCommand = new MySqlCommand(strQuery, sqlConnection);
        sqlCommand.CommandTimeout = SqlUtils.COMMAND_TIMEOUT;
        sqlDataReader = sqlCommand.ExecuteReader();
        while (sqlDataReader.Read())
        {
          String symbol = sqlDataReader.GetString(0);
          watchList.Add(symbol);
        }
        return watchList;
      }
      catch (Exception exception)
      {
        MDTrace.WriteLine(LogLevel.DEBUG,exception);
        return null;
      }
      finally
      {
				if(null!=sqlCommand)sqlCommand.Dispose();
        if (null != sqlDataReader) sqlDataReader.Close();
        if (null != sqlConnection) sqlConnection.Close();
      }
    }
    public static List<String> GetAccountsWithOpenTrades()
    {
      try
      {
        PortfolioTrades portfolioTrades=GetOpenTrades();
        List<String> accounts=(from portfolioTrade in portfolioTrades select portfolioTrade.Account).Distinct().ToList();
        return accounts;
      }
      catch (Exception exception)
      {
        MDTrace.WriteLine(LogLevel.DEBUG, exception);
        return null;
      }
    }
  }
}
