using System;
using System.Collections.Generic;
using MarketData.Utils;
using MarketData.Extensions;
using System.Linq;
using MarketData.Generator.Interface;

namespace MarketData.Generator.MGSHMomentum
{
  public class MGSHPosition : IPosition
  {
    public MGSHPosition()
    {
      CurrentPrice=double.NaN;
    }
    public MGSHPosition(MGSHPosition position)
    {
      Symbol = position.Symbol;
      PurchaseDate = position.PurchaseDate;
      SellDate = position.SellDate;
      Shares = position.Shares;
      PurchasePrice = position.PurchasePrice;
      CurrentPrice = position.CurrentPrice;
      Volume = position.Volume;
      Return1D = position.Return1D;
      CumReturn252 = position.CumReturn252;
      IDIndicator = position.IDIndicator;
      Score=position.Score;
      Velocity = position.Velocity;
      PE = position.PE;
      Beta = position.Beta;
      InitialStopLimit = position.InitialStopLimit;
      TrailingStopLimit = position.TrailingStopLimit;
      LastStopAdjustment = position.LastStopAdjustment;
      PositionRiskPercentDecimal = position.PositionRiskPercentDecimal;
      R = position.R;
      if(null!=position.Comment)Comment=new String(position.Comment.ToArray());
    }

    public static MGSHPosition Clone(MGSHPosition positionToClone)
    {
      MGSHPosition position = new MGSHPosition();
      position.Symbol = positionToClone.Symbol;
      position.PurchaseDate = positionToClone.PurchaseDate;
      position.SellDate=positionToClone.SellDate;
      position.Shares=positionToClone.Shares;
      position.PurchasePrice=positionToClone.PurchasePrice;
      position.CurrentPrice=positionToClone.CurrentPrice;
      position.Volume=positionToClone.Volume;
      position.Return1D=positionToClone.Return1D;
      position.CumReturn252=positionToClone.CumReturn252;
      position.IDIndicator=positionToClone.IDIndicator;
      position.Score=positionToClone.Score;
      position.Velocity=positionToClone.Velocity;     
      position.PE=positionToClone.PE;
      position.Beta=positionToClone.Beta;
      position.InitialStopLimit=positionToClone.InitialStopLimit;
      position.TrailingStopLimit=positionToClone.TrailingStopLimit;
      position.LastStopAdjustment=positionToClone.LastStopAdjustment;
      position.PositionRiskPercentDecimal=positionToClone.PositionRiskPercentDecimal;
      position.R=positionToClone.R;
      position.Comment=positionToClone.Comment;
      return position;
    }

    public String Symbol{get;set;}
    public DateTime PurchaseDate{get;set;}
    public DateTime SellDate{get;set;}
    public double Shares{get;set;}
    public double PurchasePrice{get;set;}
    public double CurrentPrice{get;set;}
    public double Exposure{get{return Shares*PurchasePrice;}}
    public double MarketValue{get{return Shares*CurrentPrice;}}
    public long Volume{get;set;}
    public double Return1D{get;set;}
    public double GainLoss{get{return MarketValue-Exposure;}}
    public double GainLossPcnt{get{return (MarketValue-Exposure)/Exposure;}}
    public double CumReturn252{get;set;}
    public double IDIndicator{get;set;}
    public double Score{get;set;}
    public double Velocity{get;set;}
    public double PE{get;set;}
    public double Beta{get;set;}
    public double InitialStopLimit {get; set; }
    public double TrailingStopLimit {get; set; }
    public DateTime LastStopAdjustment {get; set; }
    public double PositionRiskPercentDecimal {get; set; }
    public double R { get; set; }
    public String Comment {get; set; }

    public virtual NVPCollection ToNVPCollection()
    {
      NVPCollection nvpCollection=new NVPCollection();
      nvpCollection.Add(new NVP("Symbol",Symbol.ToString()));
      nvpCollection.Add(new NVP("PurchaseDate",PurchaseDate.ToString()));
      nvpCollection.Add(new NVP("SellDate",SellDate.ToString()));
      nvpCollection.Add(new NVP("Shares",Shares.ToString()));
      nvpCollection.Add(new NVP("PurchasePrice",PurchasePrice.ToString()));
      nvpCollection.Add(new NVP("CurrentPrice",CurrentPrice.ToString()));
      nvpCollection.Add(new NVP("Volume",Volume.ToString()));
      nvpCollection.Add(new NVP("Return1D",Return1D.ToString()));
      nvpCollection.Add(new NVP("CumReturn252",CumReturn252.ToString()));
      nvpCollection.Add(new NVP("IDIndicator",IDIndicator.ToString()));
      nvpCollection.Add(new NVP("Score",Score.ToString()));
      nvpCollection.Add(new NVP("Velocity",Velocity.ToString()));
      nvpCollection.Add(new NVP("PE",PE.ToString()));
      nvpCollection.Add(new NVP("Beta",Beta.ToString()));
      nvpCollection.Add(new NVP("InitialStopLimit", InitialStopLimit.ToString()));
      nvpCollection.Add(new NVP("TrailingStopLimit", TrailingStopLimit.ToString()));
      nvpCollection.Add(new NVP("LastStopAdjustment", LastStopAdjustment.ToString()));
      nvpCollection.Add(new NVP("PositionRiskPercentDecimal", PositionRiskPercentDecimal.ToString()));
      nvpCollection.Add(new NVP("R", R.ToString()));
      nvpCollection.Add(new NVP("Comment", Comment?.ToString()));
      return nvpCollection;
    }
    public static MGSHPosition FromNVPCollection(NVPCollection nvpCollection)
    {
      MGSHPosition position=new MGSHPosition();
      if(0 == nvpCollection.Count) return null;
      NVPDictionary nvpDictionary=nvpCollection.ToDictionary();
      position.Symbol=nvpDictionary["Symbol"].Get<String>();
      position.PurchaseDate=nvpDictionary["PurchaseDate"].Get<DateTime>();
      position.SellDate=nvpDictionary["SellDate"].Get<DateTime>();
      position.Shares=nvpDictionary["Shares"].Get<double>();
      position.PurchasePrice=nvpDictionary["PurchasePrice"].Get<double>();
      position.CurrentPrice=nvpDictionary["CurrentPrice"].Get<double>();
      position.Volume=nvpDictionary["Volume"].Get<long>();
      position.Return1D=nvpDictionary["Return1D"].Get<long>();
      position.CumReturn252=nvpDictionary["CumReturn252"].Get<long>();
      position.IDIndicator=nvpDictionary["IDIndicator"].Get<double>();
      position.Velocity=nvpDictionary["Velocity"].Get<double>();
      position.PE=nvpDictionary["PE"].Get<double>();
      position.Beta=nvpDictionary["Beta"].Get<double>();
      if(nvpDictionary.ContainsKey("Score")) position.Score=nvpDictionary["Score"].Get<double>();
      else position.Score=double.NaN;
      if(nvpDictionary.ContainsKey("InitialStopLimit")) position.InitialStopLimit=nvpDictionary["InitialStopLimit"].Get<double>();
      else position.InitialStopLimit=double.NaN;
      if(nvpDictionary.ContainsKey("TrailingStopLimit")) position.TrailingStopLimit=nvpDictionary["TrailingStopLimit"].Get<double>();
      else position.TrailingStopLimit=double.NaN;
      if(nvpDictionary.ContainsKey("LastStopAdjustment")) position.LastStopAdjustment=nvpDictionary["LastStopAdjustment"].Get<DateTime>();
      else position.LastStopAdjustment=Utility.Epoch;
      if(nvpDictionary.ContainsKey("Comment")) position.Comment=nvpDictionary["Comment"].Get<String>();
      else position.Comment=null;
      if(nvpDictionary.ContainsKey("PositionRiskPercentDecimal")) position.PositionRiskPercentDecimal=nvpDictionary["PositionRiskPercentDecimal"].Get<double>();
      else position.PositionRiskPercentDecimal=double.NaN;
      if(nvpDictionary.ContainsKey("R")) position.R=nvpDictionary["R"].Get<double>();
      else position.R=double.NaN;
      return position;
    }
    public static void DisplayHeader()
    {
      MDTrace.WriteLine(LogLevel.DEBUG, "Symbol,Purchase Date,Shares,Purchase Price,Exposure,Volume,Return1D,Sell Date,Sell Price,Market Value,Gain Loss,Gain Loss(%),CumReturn252,IDIndicator,Score,MaxDrawdown,MaxUpside,Velocity,PE,Beta,SharpeRatio,InitialStopLimit,TrailingStopLimit,LastStopAdjustment,Comment");
    }
    public void Display()
    {
      if (Utility.IsEpoch(SellDate) && double.IsNaN(CurrentPrice))
      {
        MDTrace.WriteLine(LogLevel.DEBUG, String.Format("{0},{1},{2},{3},{4},{5},{6},N/A,N/A,N/A,N/A,N/A,{7},{8},{9},{10},{11},{12},{13},{14},{15},{16}",
          Symbol,
          Utility.DateTimeToStringMMHDDHYYYY(PurchaseDate),
          Shares,
          Utility.AddQuotes(Utility.FormatCurrency(PurchasePrice)),
          Utility.AddQuotes(Utility.FormatCurrency(Exposure)),
          Volume,
          Utility.AddQuotes(Utility.FormatPercent(Return1D)),
          Utility.AddQuotes(Utility.FormatPercent(CumReturn252)),
          Utility.AddQuotes(Utility.FormatNumber(IDIndicator)),
          Utility.AddQuotes(Utility.FormatNumber(Score)),
          Utility.AddQuotes(Utility.FormatPercent(Velocity)),
          Utility.AddQuotes(Utility.FormatNumber(PE)),
          Utility.AddQuotes(Utility.FormatNumber(Beta)),
          Utility.AddQuotes(Utility.FormatNumber(InitialStopLimit,2)),
          Utility.AddQuotes(Utility.FormatNumber(TrailingStopLimit,2)),
          Utility.DateTimeToStringMMHDDHYYYY(LastStopAdjustment),
          Comment
          ));
      }
      else
      {
        MDTrace.WriteLine(LogLevel.DEBUG, String.Format("{0},{1},{2},{3},{4},{5},{6},{7},{8},{9},{10},{11},{12},{13},{14},{15},{16},{17},{18},{19},{20},{21}",
        Symbol,
        Utility.DateTimeToStringMMHDDHYYYY(PurchaseDate),
        Shares,
        Utility.AddQuotes(Utility.FormatCurrency(PurchasePrice)),
        Utility.AddQuotes(Utility.FormatCurrency(Exposure)),
        Volume,
        Utility.AddQuotes(Utility.FormatPercent(Return1D)),
        Utility.DateTimeToStringMMHDDHYYYY(SellDate),
        Utility.AddQuotes(Utility.FormatCurrency(CurrentPrice)),
        Utility.AddQuotes(Utility.FormatCurrency(MarketValue)),
        Utility.AddQuotes(Utility.FormatCurrency(GainLoss)),
        Utility.FormatPercent(GainLossPcnt),
        Utility.AddQuotes(Utility.FormatPercent(CumReturn252)),
        Utility.AddQuotes(Utility.FormatNumber(IDIndicator)),
        Utility.AddQuotes(Utility.FormatNumber(Score)),
        Utility.AddQuotes(Utility.FormatPercent(Velocity)),
        Utility.AddQuotes(Utility.FormatNumber(PE)),
        Utility.AddQuotes(Utility.FormatNumber(Beta)),
        Utility.AddQuotes(Utility.FormatNumber(InitialStopLimit,2)),
        Utility.AddQuotes(Utility.FormatNumber(TrailingStopLimit,2)),
        Utility.DateTimeToStringMMHDDHYYYY(LastStopAdjustment),
        Comment
        ));
      }
    }
  }
// ****************************************************************************************************************************************************************
  public class MGSHPositions : List<MGSHPosition>
  {
    public MGSHPositions()
    {
    }

    public MGSHPositions(MGSHPositions positions)
    {
      foreach(MGSHPosition position in positions)Add(position);
    }

    public MGSHPositions(List<MGSHPosition> positions)
    {
      foreach(MGSHPosition position in positions)Add(position);
    }

    public MGSHPositions(MGSHPosition position)
    {
      Add(position);
    }

    public void Add(MGSHPositions positions)
    {
      foreach(MGSHPosition position in positions)Add(position);
    }

    public double Exposure
    {
      get
      {
        return (from MGSHPosition position in this select position.PurchasePrice*position.Shares).Sum();
      }
    }

    public double MarketValue
    {
      get
      {
        return (from MGSHPosition position in this select position.CurrentPrice*position.Shares).Sum();
      }
    }

    public List<String> Symbols()
    {
      List<String> symbols = new List<string>();
      foreach(MGSHPosition position in this)
      {
        symbols.Add(position.Symbol);
      }
      return symbols;
    }

    public NVPCollections ToNVPCollections()
    {
      NVPCollections nvpCollections=new NVPCollections();
      foreach(MGSHPosition position in this)
      {
        nvpCollections.Add(position.ToNVPCollection());
      }
      return nvpCollections;
    }

    public static MGSHPositions FromNVPCollections(NVPCollections nvpCollections)
    {
      MGSHPositions positions=new MGSHPositions();
      foreach(NVPCollection nvpCollection in nvpCollections)
      {
        positions.Add(MGSHPosition.FromNVPCollection(nvpCollection)); 
      }
      return positions;
    }

    public void DisplayTopFive()
    {
      MGSHPositions positions = new MGSHPositions(this.OrderByDescending(x => x.GainLossPcnt).Take(5).ToList());
      MGSHPosition.DisplayHeader();
      for (int index = 0; index < positions.Count; index++)
      {
        MGSHPosition position = positions[index];
        position.Display();
      }
    }

    public void DisplayBottomFive()
    {
      MGSHPositions positions = new MGSHPositions(this.OrderBy(x => x.GainLossPcnt).Take(5).ToList());
      MGSHPosition.DisplayHeader();
      for (int index = 0; index < positions.Count; index++)
      {
        MGSHPosition position = positions[index];
        position.Display();
      }
    }

    public void Display()
    {
      MGSHPosition.DisplayHeader();
      for(int index=0;index<Count;index++)
      {
        MGSHPosition position=this[index];
        position.Display();
      }
      if(this.Any(x=>Utility.IsEpoch(x.SellDate)||double.IsNaN(x.CurrentPrice)))
      {
        MDTrace.WriteLine(LogLevel.DEBUG, String.Format("EXPOSURE:{0}", Utility.FormatCurrency(this.Exposure)));
      }
      else
      {
        MDTrace.WriteLine(LogLevel.DEBUG, String.Format("GAIN/LOSS {0}", Utility.FormatCurrency(this.Sum(x => x.GainLoss)))); 
      }
      MDTrace.WriteLine(LogLevel.DEBUG,"****************************************************************************************************************************");      
    }
  }
}
