Esempio n. 1
0
        public void GetDaysDifferenceZero()
        {
            SimpleDate date = new SimpleDate(31, 01, 1993);
            SimpleDate date2 = new SimpleDate(31, 01, 1993);

            Assert.AreEqual(date2.DaysDifference(date), 0);
        }
Esempio n. 2
0
 public void StoreDate()
 {
     SimpleDate date = new SimpleDate(1, 2, 1993);
     Assert.AreEqual(date.Day, 1);
     Assert.AreEqual(date.Month, 2);
     Assert.AreEqual(date.Year, 1993);
 }
Esempio n. 3
0
        public void GetDaysDifferenceWithLeapYear()
        {
            SimpleDate date = new SimpleDate(31, 01, 1993);
            SimpleDate date2 = new SimpleDate(09, 07, 1998);

            Assert.AreEqual(date.DaysDifference(date2), 1985);
        }
Esempio n. 4
0
        public SimpleDate AfterNumberOfDays(int days)
        {
            SimpleDate newDate = new SimpleDate(this.day, this.month, this.year);
            // Do something here
            int newDay   = this.day;
            int newMonth = this.month;
            int newYear  = this.year;

            int count = 0;

            while (count < days)
            {
                newDay++;
                if (newDay > 30)
                {
                    newDay = 1;
                    newMonth++;
                    if (newMonth > 12)
                    {
                        newMonth = 1;
                        newYear++;
                    }
                }
                count++;
            }

            newDate = new SimpleDate(newDay, newMonth, newYear);

            return(newDate);
        }
Esempio n. 5
0
        public void GetDaysDifference()
        {
            SimpleDate date = new SimpleDate(31, 01, 1993);
            SimpleDate date2 = new SimpleDate(09, 07, 1994);

            Assert.AreEqual(date.DaysDifference(date2), 524);
        }
Esempio n. 6
0
        public void GetDaysDifferenceRevesed()
        {
            SimpleDate date  = new SimpleDate(31, 01, 1993);
            SimpleDate date2 = new SimpleDate(09, 07, 1998);

            Assert.AreEqual(date2.DaysDifference(date), -1985);
        }
 public Customer(int custId, string name, Address address, SimpleDate registrationDate)
 {
     this.custId           = custId;
     this.name             = name;
     this.address          = address;
     this.registrationDate = registrationDate;
 }
Esempio n. 8
0
        /// <summary>
        /// Gets the last day of month.
        /// </summary>
        /// <param name="date">The date.</param>
        /// <returns></returns>
        private static int GetLastDayOfMonth(SimpleDate date)
        {
            switch (date.month)
            {
            case 1:
            case 3:
            case 5:
            case 7:
            case 8:
            case 10:
            case 12:
                return(LONG_MONTH_LEN);

            case 4:
            case 6:
            case 9:
            case 11:
                return(SHORT_MONTH_LEN);
            }
            if (IsLeapYear(date.year))
            {
                return(LONG_FEB_LEN);
            }
            return(SHORT_FEB_LEN);
        }
Esempio n. 9
0
        public void DaysDifferenceTest()
        {
            Dog        testSimpleDateDog = new Dog(1, new SimpleDate(15, 4, 2001), "bassie", new SimpleDate(16, 4, 2001));
            SimpleDate testDate          = new SimpleDate(16, 4, 2001);

            Assert.AreNotEqual(testSimpleDateDog.LastWalkDate.Day, testDate.DaysDifference(testDate));
        }
Esempio n. 10
0
        public Dividend setDate(SimpleDate date)
        {
            Dividend dividend = new Dividend(this.getStock(), this.getAmount(), date);

            dividend.setComment(this.comment);
            return(dividend);
        }
Esempio n. 11
0
        public void GetDaysDifferenceRevesed()
        {
            SimpleDate date = new SimpleDate(31, 01, 1993);
            SimpleDate date2 = new SimpleDate(09, 07, 1998);

            Assert.AreEqual(date2.DaysDifference(date), -1985);
        }
Esempio n. 12
0
        public void TestBadHabits()
        {
            SimpleDate birthday = new SimpleDate(13, 2, 2001);
            Cat        cat      = new Cat(1, birthday, "smokey", "none", "");

            Assert.AreEqual(cat.BadHabits, "none");
        }
Esempio n. 13
0
        public void GetDaysDifferenceZero()
        {
            SimpleDate date  = new SimpleDate(31, 01, 1993);
            SimpleDate date2 = new SimpleDate(31, 01, 1993);

            Assert.AreEqual(date2.DaysDifference(date), 0);
        }
Esempio n. 14
0
        void DownloadOneStock(StockServerFactory fact, int stockId, DateTime startDate, DateTime endDate)
        {
            if (!StockMarketChecker.IsChinaShanghaiStock(stockId))
            {
                return;
            }

            Code curCode = Code.newInstance(StockMarketChecker.ToYahooStockId(stockId));

            Duration           duration = new Duration(startDate, endDate);
            StockHistoryServer history  = fact.getStockHistoryServer(curCode, duration);

            if (history == null)
            {
                return;
            }

            int numberOfDate = history.getNumOfCalendar();

            for (int i = 0; i < numberOfDate; i++)
            {
                SimpleDate dt = history.getCalendar(i);

                DotNetStock.Engine.Stock stock = history.getStock(dt);

                StockData data = StockDataAdapter.ToStockData(stock);

                StockSaver_.Add(data);
            }
        }
Esempio n. 15
0
        /// <summary>
        /// Basis 0, 30/360 date convention
        /// </summary>
        /// <param name="startDateVal">The start date value assumed to be less than or equal to endDateVal.</param>
        /// <param name="endDateVal">The end date value assumed to be greater than or equal to startDateVal.</param>
        /// <returns></returns>
        public static double Basis0(int startDateVal, int endDateVal)
        {
            SimpleDate startDate = CreateDate(startDateVal);
            SimpleDate endDate   = CreateDate(endDateVal);
            int        date1day  = startDate.day;
            int        date2day  = endDate.day;

            // basis zero has funny adjustments to the day-of-month fields when at end-of-month
            if (date1day == LONG_MONTH_LEN && date2day == LONG_MONTH_LEN)
            {
                date1day = SHORT_MONTH_LEN;
                date2day = SHORT_MONTH_LEN;
            }
            else if (date1day == LONG_MONTH_LEN)
            {
                date1day = SHORT_MONTH_LEN;
            }
            else if (date1day == SHORT_MONTH_LEN && date2day == LONG_MONTH_LEN)
            {
                date2day = SHORT_MONTH_LEN;
                // Note: If date2day==31, it STAYS 31 if date1day < 30.
                // Special fixes for February:
            }
            else if (startDate.month == 2 && IsLastDayOfMonth(startDate))
            {
                // Note - these assignments deliberately set Feb 30 date.
                date1day = SHORT_MONTH_LEN;
                if (endDate.month == 2 && IsLastDayOfMonth(endDate))
                {
                    // only adjusted when first date is last day in Feb
                    date2day = SHORT_MONTH_LEN;
                }
            }
            return(CalculateAdjusted(startDate, endDate, date1day, date2day));
        }
Esempio n. 16
0
        public static Tuple <DateTime, DateTime> GetCalendarViewPeriod(DateOptions dateOptions, string calendarScope)
        {
            Tuple <DateTime, DateTime> period;
            SimpleDate selDate = dateOptions.SelectedDate;

            if (calendarScope == "day")
            {
                DateTime dt = new DateTime(selDate.Year, selDate.Month, selDate.Day);
                period = new Tuple <DateTime, DateTime>(dt, dt.AddHours(23).AddMinutes(59).AddSeconds(59).AddMilliseconds(999));
            }
            else
            {
                DateTime firstDayOfCalendarView = (calendarScope == "week") ? new DateTime(selDate.Year, selDate.Month, selDate.Day) : new DateTime(selDate.Year, selDate.Month, 1);
                DateTime lastDayOfCalendarView  = (calendarScope == "week") ? new DateTime(selDate.Year, selDate.Month, selDate.Day) : new DateTime(selDate.Year, selDate.Month, DateTime.DaysInMonth(selDate.Year, selDate.Month));

                // get FIRST date of Calendar view
                while ((int)firstDayOfCalendarView.DayOfWeek != dateOptions.FirstDayOfWeek)
                {
                    firstDayOfCalendarView = firstDayOfCalendarView.AddDays(-1);
                }

                // get LAST date of Calendar view
                do
                {
                    lastDayOfCalendarView = lastDayOfCalendarView.AddDays(1);
                } while ((int)lastDayOfCalendarView.DayOfWeek != dateOptions.FirstDayOfWeek);

                period = new Tuple <DateTime, DateTime>(firstDayOfCalendarView, lastDayOfCalendarView.AddMilliseconds(-1));
            }

            return(period);
        }
Esempio n. 17
0
        public override Task <DialogTurnResult> BeginDialogAsync(DialogContext dc, object options = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            string inputdate      = SimpleDate.GetValue(dc.State);
            int    separatorIndex = inputdate.IndexOf(" ");
            string day            = inputdate.Substring(0, separatorIndex);

            if (day.Length == 1)
            {
                day = "0" + day;
            }
            else if (day.Length > 2)
            {
                day = day.Substring(0, 2);
            }

            DateTime current      = DateTime.Now;
            int      year         = current.Year;
            int      curr_month   = current.Month;
            string   month_string = inputdate.Substring((separatorIndex + 1), (inputdate.Length - separatorIndex - 1));
            int      month        = 0;

            string[] monthsArray = { "januari", "februari", "mars", "april", "maj", "juni", "juli", "augusti", "september", "oktober", "november", "december" };
            month_string = month_string.ToLower();

            for (int i = 0; i < monthsArray.Length; i++)
            {
                if (month_string == monthsArray[i])
                {
                    month = (i + 1);
                    break;
                }
                else
                {
                    month = 0;
                }
            }

            if (curr_month > month && month != 0)
            {
                year++;
            }

            string year_string = year.ToString().Substring(2, 2);

            month_string = month.ToString();

            if (month_string.Length == 1)
            {
                month_string = "0" + month_string;
            }

            string fulldate = year_string + "/" + month_string + "/" + day;

            if (this.DateResult != null)
            {
                dc.State.SetValue(this.DateResult.GetValue(dc.State), fulldate);
            }

            return(dc.EndDialogAsync(result: fulldate, cancellationToken: cancellationToken));
        }
Esempio n. 18
0
        public override bool Equals(object compared)
        {
            // DO SOMETHING HERE
            if (this == compared)
            {
                return(true);
            }

            // if the compared object is null or not of type Book, the objects are not equal
            if ((compared == null) || !this.GetType().Equals(compared.GetType()))
            {
                return(false);
            }
            //

            SimpleDate comparedSimpledate = (SimpleDate)compared;

            if (this.year == comparedSimpledate.year && this.month == comparedSimpledate.month && this.day == comparedSimpledate.day)
            {
                // convert the object to a Book object

                // if the values of the object variables are equal, the objects are, too
                return(true);
            }
            return(false);
        }
Esempio n. 19
0
        public void GetDaysDifferenceWithLeapYear()
        {
            SimpleDate date  = new SimpleDate(31, 01, 1993);
            SimpleDate date2 = new SimpleDate(09, 07, 1998);

            Assert.AreEqual(date.DaysDifference(date2), 1985);
        }
Esempio n. 20
0
        public void GetDaysDifference()
        {
            SimpleDate date  = new SimpleDate(31, 01, 1993);
            SimpleDate date2 = new SimpleDate(09, 07, 1994);

            Assert.AreEqual(date.DaysDifference(date2), 524);
        }
Esempio n. 21
0
        public void TestCatPriceLess20()
        {
            SimpleDate birthday = new SimpleDate(13, 2, 2001);

            Cat cat = new Cat(1, birthday, "Kevin", "heisabitsickandheisabittiredheisabitsickandheisabittiredheisabitsickandheisabittired", "");

            Assert.AreEqual(cat.Price, 20);
        }
Esempio n. 22
0
        public void TestCatPriceLess60()
        {
            SimpleDate birthday = new SimpleDate(13, 2, 2001);

            Cat cat = new Cat(1, birthday, "Kevin", "sick", "");

            Assert.AreEqual(cat.Price, 56);
        }
        public void AddAnimalWithNegativeChipnumber()
        {
            SimpleDate     birthday = new SimpleDate(13, 2, 2001);
            Administration a        = new Administration();
            Cat            cat      = new Cat(-1, birthday, "smokey", "none", "");

            a.Add(cat);
        }
Esempio n. 24
0
        public void StoreDate()
        {
            SimpleDate date = new SimpleDate(1, 2, 1993);

            Assert.AreEqual(date.Day, 1);
            Assert.AreEqual(date.Month, 2);
            Assert.AreEqual(date.Year, 1993);
        }
        public SimpleDate AfterNumberOfDays(int days)
        {
            SimpleDate newDate = new SimpleDate(this.day, this.month, this.year);

            // Do something here
            newDate.Advance(days);
            return(newDate);
        }
Esempio n. 26
0
        public void TestDogLastwalkdate()
        {
            MakeDog();
            SimpleDate expected = new SimpleDate(5, 5, 2016);
            SimpleDate actual   = dogtest.LastWalkDate;

            Assert.AreEqual(expected.ToString(), actual.ToString());
        }
Esempio n. 27
0
        public void IncorrectLastWalkDate()
        {
            SimpleDate testLastWalkDate = new SimpleDate(16, 4, 2001);

            Assert.AreEqual(testLastWalkDate.Day, testHond3.LastWalkDate.Day);
            Assert.AreEqual(testLastWalkDate.Month, testHond3.LastWalkDate.Month);
            Assert.AreNotEqual(testLastWalkDate.Year, testHond3.LastWalkDate.Year);
        }
Esempio n. 28
0
 /// <summary>
 /// Determines whether [is last day of month] [the specified date].
 /// </summary>
 /// <param name="date">The date.</param>
 /// <returns>
 ///     <c>true</c> if [is last day of month] [the specified date]; otherwise, <c>false</c>.
 /// </returns>
 private static bool IsLastDayOfMonth(SimpleDate date)
 {
     if (date.day < SHORT_FEB_LEN)
     {
         return(false);
     }
     return(date.day == GetLastDayOfMonth(date));
 }
Esempio n. 29
0
 private Manager(Gender gender, string firstname, string lastname, SimpleDate dateOfBirth, string country)
 {
     Gender      = gender;
     Firstname   = firstname;
     Lastname    = lastname;
     DateOfBirth = dateOfBirth;
     Country     = country;
 }
Esempio n. 30
0
        public void TestCatDateofbirth()
        {
            MakeCat();
            SimpleDate expected = new SimpleDate(2, 3, 2015);
            SimpleDate actual   = cattest.DateOfBirth;

            Assert.AreEqual(expected.ToString(), actual.ToString());
        }
Esempio n. 31
0
        public void TestDogPrice20002()
        {
            SimpleDate birthday = new SimpleDate(13, 2, 2001);
            SimpleDate walked   = new SimpleDate(15, 2, 2001);
            Dog        dog      = new Dog(200002, birthday, "Kevin", walked, "");

            Assert.AreEqual(dog.Price, 200);
        }
Esempio n. 32
0
        public void TestLastDayWalked()
        {
            SimpleDate birthday = new SimpleDate(13, 2, 2001);
            SimpleDate walked   = new SimpleDate(15, 2, 2001);
            Dog        dog      = new Dog(1, birthday, "Kevin", walked, "");

            Assert.AreEqual(dog.LastWalkDate, walked);
        }
Esempio n. 33
0
        public SimpleDate AfterNumberOfDays(int days)
        {
            SimpleDate newDate = new SimpleDate(/* Do something here?*/);

            // Do something here

            return(newDate);
        }
Esempio n. 34
0
        internal static async Task <IEnumerable <Vote> > GetAndParseVotesAsync(VoteDumpVersion version)
        {
            var url = version == VoteDumpVersion.One ? Constants.VotesDump : Constants.VotesDump2;

            Debug.WriteLine($"Requesting Votes Dump via {url}");
            // .Net Core removed WebClient and Http/WebRequests, so we need to use HttpClient.
            var request = new HttpRequestMessage(HttpMethod.Get, new Uri(url));

            // Manually add the headers every request rather then using the default headers,
            // incase the client was rebuilt with a new name / version mid-application session
            request.Headers.Add("User-Agent", $"{VndbUtils.ClientName} (v{VndbUtils.ClientVersion})");

            var response = await VndbUtils.HttpClient.SendAsync(request);

            response.EnsureSuccessStatusCode();             // Ensure we got data

            var gzipStream = await response.Content.ReadAsStreamAsync();

            var rawContents = await VndbUtils.UnGzip(gzipStream);

            response.Dispose();
            request.Dispose();

            var results = new List <Vote>();

            var votes          = rawContents.Split(new[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);
            var expectedValues = version == VoteDumpVersion.One ? 3 : 4;

            // Resharper "Loop can be converted to LINQ-expression won't work due to inline "out var" declaration
            foreach (var vote in votes)
            {
                var values = vote.Split(new [] { ' ' }, expectedValues, StringSplitOptions.RemoveEmptyEntries);

                if (values.Length != expectedValues)
                {
                    continue;
                }

                SimpleDate date = null;

                if (!UInt32.TryParse(values[0], out var vnId) ||
                    !UInt32.TryParse(values[1], out var uid) ||
                    !Byte.TryParse(values[2], out var value))
                {
                    continue;
                }

                if (version == VoteDumpVersion.Two &&
                    (date = (SimpleDate)SimpleDateConverter.ParseString(values[3])) == null)
                {
                    continue;
                }

                results.Add(new Vote(version, vnId, uid, value, date));
            }

            return(results);
        }
Esempio n. 35
0
        public void ToStringTestDog()
        {
            SimpleDate birthday   = new SimpleDate(13, 2, 2001);
            SimpleDate walked     = new SimpleDate(15, 2, 2001);
            Dog        dog        = new Dog(1, birthday, "Kevin", walked, "");
            string     testString = dog.ToString();

            Assert.AreEqual(testString, "Dog: 1, 13-02-2001, Kevin, not reserved, 200, 15-02-2001");
        }
Esempio n. 36
0
 public void NormallyInsertDate()
 {
     using (var container = new RhetosTestContainer())
     {
         var repository = container.Resolve<Common.DomRepository>();
         var entity = new SimpleDate { Value = new DateTime(2013, 7, 3) };
         repository.TestMaxValue.SimpleDate.Insert(new[] { entity });
     }
 }
Esempio n. 37
0
 public void NormallyInsertDate()
 {
     using (var executionContext = new CommonTestExecutionContext())
     {
         var repository = new Common.DomRepository(executionContext);
         var entity = new SimpleDate { Value = new DateTime(2013, 7, 3) };
         repository.TestMaxValue.SimpleDate.Insert(new[] { entity });
     }
 }
Esempio n. 38
0
 public static double GetCurrentNominal(Trade trade, SimpleDate date, DateTime effectiveDate)
 {
     if (trade.Product != null)
     {
         var nominal = Math.Abs(trade.CurrentNominal(date, effectiveDate, false));
         int sign = 1;
         if (trade.Product.IsMultiplyTraded) sign = trade.Quantity > 0 ? 1 : -1;
         else
         {
             string ss = trade.Product.GetBuySell(trade);
             if (ss != null && ss.Equals("Sell")) sign = -1;
         }
         return sign * nominal;
     }
     return 0;
 }
 public string GenerateFileName(string dir, string fileName, SimpleDate date, DateTime time, IDictionary<string, string> parms)
 {
     string type = fileName;
     var files = Directory.GetFiles(dir, "*" + type + "*");
     DateTime found = DateTime.MinValue;
     string fileFound = null;
     foreach (var file in files)
     {
         var path = Path.Combine(dir, file);
         var dt = File.GetCreationTime(path);
         if (found == DateTime.MinValue || found < dt)
         {
             found = dt;
             fileFound = file;
         }
     }
     return fileFound == null ? null : Path.GetFileName(fileFound);
 }
Esempio n. 40
0
        static public void Main(string[] args)
        {
            var scount = Env.GetOption("-count", args);
            var client = new ClientSession(args);
            client.StartAndConnect("ApplyTermination");
            Logger.Info(".....Apply Termination Started ........................");

            var trade =new Trade(); //Get the Trade for which to apply the Termaition
           var market = new Market(); //Should get the Real Market
           var asOfDate = new DateTime(); //negotiated Trade Date of the Termination/StepOut
            var effDate = new SimpleDate(23,2,2012);
            double fee =10000; //Total Proceeds (Fee > 0, you receive the Amount Fee < 0 you pay to the Counterpary)
            string party = "GS"; //Fill it in case this is a StepOut

            ApplyFullTermination(trade, fee, party, market, asOfDate, effDate);
           
            //Then you can save the Trade 
            if (trade.Id <= 0) Env.Current.Trade.SaveTrade(trade);

            Console.WriteLine("Enter to Exit ...");
            Console.ReadLine();
            Environment.Exit(0);
        }
Esempio n. 41
0
 static public void ApplyExpiry(Trade trade, SimpleDate effectiveDate, Market market)
 {
     var tdate = effectiveDate.ToDateTime();
     var pevent = new ExpiryEvent(trade)
     {
         ClearerId = trade.ClearerId,
         TradeType = trade.TradeType,
         InputTime = tdate,
         ActivityTime = tdate,
         ProcessedTime = tdate,
         Action = TradeEventWorkflowConst.PROCESS
     };
     pevent.ActivityTime = tdate;
     var handler = (ExpiryProductEventHandler)ProductEvent.Handler(pevent.EventType, trade.Product.ProcessingType);
     var newTrades = new List<Trade>();
     var modifiedTrades = new List<Trade>();
     handler.Process(pevent, market, trade, newTrades, modifiedTrades, new List<IProductEvent>());
     trade.Status = "Expired";
 }
Esempio n. 42
0
 virtual protected bool IsBadMaturity(SimpleDate date1, SimpleDate date2, bool isMurex)
 {
     //return false;
     if (!isMurex && date1.Day == 1) return false;
     return Math.Abs(date1 - date2) >= 7;
 }
        protected void AddTrade(Trade initTrade, Trade tradeToAdd, DateTime reconcileDate)
        {
            var valDate = new SimpleDate(reconcileDate);
            var valTime = reconcileDate;
            /*
            if (tradeToAdd.Product is NDF)
            {
                var ndfx = (NDF)tradeToAdd.Product;

                var trades = ndfx.ToFxTrades(tradeToAdd);
                AddTrade(initTrade, trades[0], reconcileDate);
                if (trades.Count == 2)
                {
                    if (ndfx.FXFixingDate <= new SimpleDate(reconcileDate))
                    {
                        var tr = trades[1];
                        tr.Id = -tr.Id;
                        AddTrade(initTrade, tr, reconcileDate);
                    }
                }
                return;
            }*/

            if (initTrade.Product is FX)
            {
                if (initTrade.Id == tradeToAdd.Id)
                {
                    var fx1 = (FX)initTrade.Product;
                    if (tradeToAdd.Quantity > 0) fx1.QuotingAmount = -fx1.QuotingAmount;
                    else fx1.PrimaryAmount = -fx1.PrimaryAmount;
                    return;
                }

                initTrade.Quantity += tradeToAdd.Quantity;
                initTrade.SettleAmount += tradeToAdd.SettleAmount;
                initTrade.Accrual += tradeToAdd.Accrual;
                var fx = (FX)initTrade.Product;
                var ofx = (FX)tradeToAdd.Product;
                if (tradeToAdd.Quantity > 0)
                {
                    fx.PrimaryAmount += ofx.PrimaryAmount;
                    fx.QuotingAmount -= ofx.QuotingAmount;
                }
                else
                {
                    fx.PrimaryAmount -= ofx.PrimaryAmount;
                    fx.QuotingAmount += ofx.QuotingAmount;
                }


            }
            else if (initTrade.Product.IsMultiplyTraded)
            {
                if (initTrade.Id == tradeToAdd.Id) return;
                initTrade.Quantity += tradeToAdd.Quantity;
                initTrade.SettleAmount += tradeToAdd.SettleAmount;
                initTrade.Accrual += tradeToAdd.Accrual;
            }
            else if (initTrade.Product is VolSwap)
            {
                var volswap1 = (VolSwap)initTrade.Product;
                var volswap2 = (VolSwap)tradeToAdd.Product;
                if (initTrade.Id == tradeToAdd.Id)
                {
                    if (volswap1.BuySell == BuySell.Buy)
                    {
                        initTrade.Quantity = volswap1.CurrentNominal(valDate, valTime, false);
                    }
                    else
                    {
                        initTrade.Quantity = -volswap1.CurrentNominal(valDate, valTime, false);
                    }
                }
                else
                {
                    if (volswap2.BuySell == BuySell.Buy)
                    {
                        initTrade.Quantity += volswap2.CurrentNominal(valDate, valTime, false);
                    }
                    else
                    {
                        initTrade.Quantity -= volswap2.CurrentNominal(valDate, valTime, false);
                    }
                }

            }
            else if (initTrade.Product is FXOption)
            {
                if (initTrade.Id == tradeToAdd.Id)
                {
                    var fx1 = (FXOption)initTrade.Product;
                    if (tradeToAdd.Quantity > 0) fx1.QuotingAmount = -fx1.QuotingAmountAsOfDate(valDate, valTime);
                    else fx1.PrimaryAmount = -fx1.PrimaryAmountAsOfDate(valDate, valTime);
                    if (fx1.InitialPremiumPayReceive == PayReceive.Pay)
                        fx1.InitialPremiumAmount = -fx1.InitialPremiumAmount;

                    var fxinfo = fx1.OptionInfo as DigitalInfo;
                    if (fxinfo != null)
                    {
                        if (tradeToAdd.Quantity > 0)
                            fxinfo.SettlementAmount = fxinfo.SettlementAmount;
                        else fxinfo.SettlementAmount = -fxinfo.SettlementAmount;
                    }
                    return;
                }

                var fx = (FXOption)initTrade.Product;
                var ofx = (FXOption)tradeToAdd.Product;
                if (ofx.IsBuy)
                {
                    fx.PrimaryAmount += ofx.PrimaryAmountAsOfDate(valDate, valTime);
                    fx.QuotingAmount -= ofx.QuotingAmountAsOfDate(valDate, valTime);
                }
                else
                {
                    fx.PrimaryAmount -= ofx.PrimaryAmountAsOfDate(valDate, valTime);
                    fx.QuotingAmount += ofx.QuotingAmountAsOfDate(valDate, valTime);
                }
                if (ofx.InitialPremiumPayReceive == PayReceive.Pay)
                    fx.InitialPremiumAmount -= ofx.InitialPremiumAmount;
                else fx.InitialPremiumAmount += ofx.InitialPremiumAmount;
                if (fx.PrimaryAmount < 0)
                {
                    initTrade.Quantity = -1;
                    fx.IsBuy = false;
                }
                else
                {
                    initTrade.Quantity = 1;
                    fx.IsBuy = true;
                }

                var optionInfo = ofx.OptionInfo;
                if (optionInfo != null)
                {

                    if (optionInfo is DigitalInfo)
                    {

                        var fxinfo = fx.OptionInfo as DigitalInfo;
                        if (fxinfo != null)
                        {
                            if (tradeToAdd.Quantity > 0)
                                fxinfo.SettlementAmount += (optionInfo as DigitalInfo).SettlementAmount;
                            else fxinfo.SettlementAmount -= (optionInfo as DigitalInfo).SettlementAmount;
                        }
                    }
                }
            }
            else if (initTrade.Product is MTMCurrencySwap)
            {
                if (initTrade.Id == tradeToAdd.Id)
                {
                    var sw1 = (MTMCurrencySwap)initTrade.Product;
                    if (tradeToAdd.Product.GetBuySellEnum(tradeToAdd) == BuySell.Buy)
                    {
                        initTrade.Quantity = sw1.PayLeg.Notional;
                        initTrade.SettleAmount = sw1.ReceiveLeg.CurrentNominal(valDate, valTime, false);
                    }
                    else
                    {
                        initTrade.Quantity = -sw1.PayLeg.Notional;
                        initTrade.SettleAmount = -sw1.ReceiveLeg.CurrentNominal(valDate, valTime, false);
                    }
                    sw1.PayLeg.Notional = Math.Abs(initTrade.Quantity);
                    sw1.ReceiveLeg.Notional = Math.Abs(initTrade.SettleAmount);
                    initTrade.SettleCurrency = sw1.PayLeg.NotionalCurrency;
                    return;
                }

                var sw = (Swap)initTrade.Product;
                var osw = (Swap)tradeToAdd.Product;
                if (initTrade.SettleCurrency == osw.PayLeg.NotionalCurrency)
                {
                    if (tradeToAdd.Product.GetBuySellEnum(tradeToAdd) == BuySell.Buy)
                    {
                        initTrade.Quantity += osw.PayLeg.CurrentNominal(valDate, valTime, false);
                        initTrade.SettleAmount += osw.ReceiveLeg.CurrentNominal(valDate, valTime, false);
                    }
                    else
                    {
                        initTrade.Quantity -= osw.PayLeg.CurrentNominal(valDate, valTime, false);
                        initTrade.SettleAmount -= osw.ReceiveLeg.CurrentNominal(valDate, valTime, false);

                    }
                    sw.PayLeg.Notional = Math.Abs(initTrade.Quantity);
                    sw.ReceiveLeg.Notional = Math.Abs(initTrade.SettleAmount);
                }
                else
                {
                    if (tradeToAdd.Product.GetBuySellEnum(tradeToAdd) == BuySell.Buy)
                    {
                        initTrade.Quantity += osw.ReceiveLeg.CurrentNominal(valDate, valTime, false);
                        initTrade.SettleAmount += osw.PayLeg.CurrentNominal(valDate, valTime, false);
                    }
                    else
                    {
                        initTrade.Quantity -= osw.ReceiveLeg.CurrentNominal(valDate, valTime, false);
                        initTrade.SettleAmount -= osw.PayLeg.CurrentNominal(valDate, valTime, false);

                    }
                    sw.PayLeg.Notional = Math.Abs(initTrade.Quantity);
                    sw.ReceiveLeg.Notional = Math.Abs(initTrade.SettleAmount);

                }


            }
            else if (initTrade.Product is CurrencySwap)
            {
                if (initTrade.Id == tradeToAdd.Id)
                {
                    var sw1 = (CurrencySwap)initTrade.Product;
                    if (tradeToAdd.Product.GetBuySellEnum(tradeToAdd) == BuySell.Buy)
                    {
                        initTrade.Quantity = sw1.PayLeg.CurrentNominal(valDate, valTime, false);
                        initTrade.SettleAmount = sw1.ReceiveLeg.CurrentNominal(valDate, valTime, false);
                    }
                    else
                    {
                        initTrade.Quantity = -sw1.PayLeg.CurrentNominal(valDate, valTime, false);
                        initTrade.SettleAmount = -sw1.ReceiveLeg.CurrentNominal(valDate, valTime, false);
                    }
                    sw1.PayLeg.Notional = Math.Abs(initTrade.Quantity);
                    sw1.ReceiveLeg.Notional = Math.Abs(initTrade.SettleAmount);
                    initTrade.SettleCurrency = sw1.PayLeg.NotionalCurrency;
                    return;
                }

                var sw = (Swap)initTrade.Product;
                var osw = (Swap)tradeToAdd.Product;
                if (initTrade.SettleCurrency == osw.PayLeg.NotionalCurrency)
                {
                    if (tradeToAdd.Product.GetBuySellEnum(tradeToAdd) == BuySell.Buy)
                    {
                        initTrade.Quantity += osw.PayLeg.CurrentNominal(valDate, valTime, false);
                        initTrade.SettleAmount += osw.ReceiveLeg.CurrentNominal(valDate, valTime, false);
                    }
                    else
                    {
                        initTrade.Quantity -= osw.PayLeg.CurrentNominal(valDate, valTime, false);
                        initTrade.SettleAmount -= osw.ReceiveLeg.CurrentNominal(valDate, valTime, false);

                    }
                    sw.PayLeg.Notional = Math.Abs(initTrade.Quantity);
                    sw.ReceiveLeg.Notional = Math.Abs(initTrade.SettleAmount);
                }
                else
                {
                    if (tradeToAdd.Product.GetBuySellEnum(tradeToAdd) == BuySell.Buy)
                    {
                        initTrade.Quantity += osw.ReceiveLeg.CurrentNominal(valDate, valTime, false);
                        initTrade.SettleAmount += osw.PayLeg.CurrentNominal(valDate, valTime, false);
                    }
                    else
                    {
                        initTrade.Quantity -= osw.ReceiveLeg.CurrentNominal(valDate, valTime, false);
                        initTrade.SettleAmount -= osw.PayLeg.CurrentNominal(valDate, valTime, false);

                    }
                    sw.PayLeg.Notional = Math.Abs(initTrade.Quantity);
                    sw.ReceiveLeg.Notional = Math.Abs(initTrade.SettleAmount);

                }


            }
            else if (initTrade.Product is Swap)
            {
                if (initTrade.Id == tradeToAdd.Id)
                {
                    var sw1 = (Swap)initTrade.Product;
                    if (tradeToAdd.Product.GetBuySellEnum(tradeToAdd) == BuySell.Buy)
                        initTrade.Quantity = initTrade.Product.CurrentNominal(valDate, valTime, false);
                    else initTrade.Quantity = -initTrade.Product.CurrentNominal(valDate, valTime, false);
                    sw1.PayLeg.Notional = Math.Abs(initTrade.Quantity);
                    sw1.ReceiveLeg.Notional = Math.Abs(initTrade.Quantity);
                    return;
                }

                var sw = (Swap)initTrade.Product;
                var osw = (Swap)tradeToAdd.Product;
                if (tradeToAdd.Product.GetBuySellEnum(tradeToAdd) == BuySell.Buy)
                {
                    initTrade.Quantity += osw.CurrentNominal(valDate, valTime, false);
                }
                else
                {
                    initTrade.Quantity -= osw.CurrentNominal(valDate, valTime, false);

                }
                sw.PayLeg.Notional = Math.Abs(initTrade.Quantity);
                sw.ReceiveLeg.Notional = Math.Abs(initTrade.Quantity);


            }
            else if (initTrade.Product is Swaption)
            {
                if (initTrade.Id == tradeToAdd.Id)
                {
                    if (tradeToAdd.Product.GetBuySellEnum(tradeToAdd) == BuySell.Buy)
                        initTrade.Quantity = initTrade.Product.CurrentNominal(valDate, valTime, false);
                    else initTrade.Quantity = -initTrade.Product.CurrentNominal(valDate, valTime, false);
                    return;
                }

                var sw = (Swaption)initTrade.Product;
                var osw = (Swaption)tradeToAdd.Product;
                if (tradeToAdd.Product.GetBuySellEnum(tradeToAdd) == BuySell.Buy)
                {
                    initTrade.Quantity += osw.CurrentNominal(valDate, valTime, false);
                }
                else
                {
                    initTrade.Quantity -= osw.CurrentNominal(valDate, valTime, false);

                }
            }
            else if (initTrade.Product is FRA)
            {
                if (initTrade.Id == tradeToAdd.Id)
                {
                    if (tradeToAdd.Product.GetBuySellEnum(tradeToAdd) == BuySell.Buy)
                        initTrade.Quantity = initTrade.Product.CurrentNominal(valDate, valTime, false);
                    else initTrade.Quantity = -initTrade.Product.CurrentNominal(valDate, valTime, false);
                    return;
                }

                var sw = (FRA)initTrade.Product;
                var osw = (FRA)tradeToAdd.Product;
                if (tradeToAdd.Product.GetBuySellEnum(tradeToAdd) == BuySell.Buy)
                {
                    initTrade.Quantity += osw.CurrentNominal(valDate, valTime, false);
                }
                else
                {
                    initTrade.Quantity -= osw.CurrentNominal(valDate, valTime, false);

                }
            }
        }
        public Trade FromString(string[] items, IDictionary<string, int> headers, IList<Exception> exceps, Market market, CultureInfo info, SimpleDate asOfDate)
        {
            var symInfo = new SymmetryInfo(items, headers, info);



            //Ignore Currency
            if (symInfo.SecurityType.ToLower() == "currency") return null;
            //if (symInfo.Maturity <= asOfDate) return null;
            //if (symInfo.SecurityType.ToLower() != "spot-forward")
            {
                if (Math.Abs(symInfo.CurrentDayPosition - 0) < Utilities.Epsilon) return null;
            }


            var trade = new Trade();
            //Build Security
            Product product = null;
            try
            {
                product = GetProduct(symInfo);

            }
            catch (Exception x)
            {
                Logger.Error(x.Message);
                exceps.Add(
                    new Exception("No Product retrieved for Security Code:" + symInfo.SecurityType + "/" +
                                  symInfo.Security));

            }

            var pr = new SymmetryProduct();
            if (product != null)
            {

                trade.PriceType = QuotationType.Price;
                if (product.QuoteName != null)
                    trade.PriceType = product.QuoteName.QuoteType;

                if (product is FX)
                {
                    var fx = product as FX;
                    double dd = symInfo.CurrentDayPosition;
                    if (symInfo.Currency == "USD")
                    {
                        if (fx.Primary == "USD")
                        {
                            fx.PrimaryAmount = dd;
                            if (dd > 0) trade.Quantity = 1;
                            else trade.Quantity = -1;

                        }
                        else if (fx.Quoting == "USD")
                        {
                            fx.PrimaryAmount = dd;
                            if (dd < 0) trade.Quantity = 1;
                            else trade.Quantity = -1;
                        }

                    }
                    else
                    {
                        if (symInfo.Currency == fx.Quoting)
                        {
                            fx.QuotingAmount = dd;
                            if (dd < 0) trade.Quantity = 1;
                            else trade.Quantity = -1;
                        }
                        else if (symInfo.Currency == fx.Primary)
                        {
                            fx.PrimaryAmount = dd;
                            trade.Quantity = dd;
                        }
                    }
                    fx.PrimarySettleDate = symInfo.Maturity;
                    fx.QuotingSettleDate = symInfo.Maturity;
                    trade.SettlementDate = symInfo.Maturity;
                    pr = null;
                }
                else if (product is FXOption)
                {
                    trade.SetProperty(DPEDescription, symInfo.Security);
                    pr = null;
                }
                else if (product is VolSwap)
                    pr = null;
                else if (product.IsMultiplyTraded) pr = null;

            }
            if (pr != null)
            {

                pr.DetailQuantity = symInfo.CurrentDayPosition;
                pr.DetailCurrCode = symInfo.Currency;
                pr.Security = string.IsNullOrEmpty(symInfo.Security) ?
                    symInfo.Currency + "|" + symInfo.SecurityType + "|" + symInfo.Maturity : symInfo.Security;
                pr.SecurityType = symInfo.SecurityType;
                pr.MaturityDate = symInfo.Maturity;
                if (pr.Security == null) pr.Security = "Unknown";
                if (symInfo.SecurityType != null && symInfo.SecurityType.ToLowerInvariant().Equals("swaptions"))
                {
                    var desc = pr.Security.Split(' ');
                    for (int i = 0; i < desc.Length; i++)
                    {
                        if (desc[i] == "PAY" || desc[i] == "REC")
                        {
                            var strikes = desc[i + 1];
                            pr.Strike = Convert.ToDouble(strikes, CultureInfo.InvariantCulture) / 100;
                            break;
                        }
                    }
                }
                if (pr.Generator != null)
                    trade.SetProperty("Generator", pr.Generator);

            }
            trade.Product = product;
            if (pr != null) trade.Product = pr;

            trade.SettleCurrency = symInfo.Currency;
            if (!(trade.Product is FX))
            {
                trade.Quantity = symInfo.CurrentDayPosition;
                if (trade.Product is Mbs)
                {
                    trade.Quantity /= ((Mbs)trade.Product).GetPrincipalFactorAsOf(asOfDate, asOfDate);
                }
                else if (trade.Product is Bond)
                {
                    trade.Quantity /= ((Bond)trade.Product).Nominal;
                }
                else if (trade.Product is VolSwap)
                {
                    trade.Quantity /= 100;
                }
            }
            trade.SetProperty(ImportRef, symInfo.Security);
            //trade.SettleAmount = Convert.ToDouble(items[DetailLocalCost]);
            //Retrieve Book
            var ss = symInfo.MicroStrategy;
            string bookCode;
            if (Utilities.IsNullOrEmpty(ss))
            {
                var traderName = Env.Current.StaticData.GetAlias(new Alias
                    {
                        EntityId = 0,
                        AliasType = PortfolioAliasType,
                        Source = Source,
                        SourceReference = symInfo.Trader
                    });
                if (traderName != null)
                    bookCode = EntityPrefix + ":" + traderName.Name + ":" + "Default";
                else
                    bookCode = EntityPrefix + ":Default";
            }
            else
            {
                bookCode = EntityPrefix + ":" + ss;
            }
            var book = Env.Current.StaticData.GetPartyByCode(bookCode);
            if (book != null)
            {
                trade.BookId = book.Id;
            }

            return trade;

        }
Esempio n. 45
0
 virtual protected IList<Contract> FindContracts(Feed feed, string ticker, SimpleDate tradeDate)
 {
     if (feed == null) return null;           
     var toSave = new List<Contract>();
     var cts = new Dictionary<Contract, string>();
     var contract = new Contract();
     cts[contract] = ticker;
     var exceptions = new List<Exception>();
     try
     {
         var count = ImportHelper.SnapContracts(cts, feed, exceptions, toSave, tradeDate);
         if (count > 0)
             return toSave;
         else return null;
     }
     catch (Exception ex)
     {
         exceptions.Add(ex);
         return null;
     }
 }
Esempio n. 46
0
 static public void ApplyExercise(TradeInfo info, Trade trade,  SimpleDate exerciseDate, SimpleDate settleDate,double amount, Market market, StringBuilder sb)
 {
    
      var pevent = new ExerciseEvent(trade)
                      {
                          ExerciseTime = exerciseDate.ToDateTime(),
                          EffectiveDate = exerciseDate,
                          AmountCurrency = trade.SettleCurrency,
                          Amount = amount,
                          CashSettlementDate = settleDate
                      };
     pevent.ActivityTime = pevent.ExerciseTime;
     var handler = (ExerciseProductEventHandler)ProductEvent.Handler(pevent.EventType, trade.Product.ProcessingType);
     var newTrades = new List<Trade>();
     var modifiedTrades = new List<Trade>();
     handler.Process(pevent, market, trade, newTrades, modifiedTrades, new List<IProductEvent>());
     if (trade.Fees != null)
     {
         foreach (Fee f in trade.Fees)
         {
             if (f.Date == pevent.CashSettlementDate)
             {
                 f.InputAmount = amount;
             }
         }
     }
     trade.Status = "Exercised";
 }
        static public void Execute(ClientProxy cp, string outputName, DateTime startDate)
        {
            var clientSession = cp.Session;
            

            var now = DateTime.Now; //Here replace by the Date at which you want to load the Trades
            SimpleDate fromDate = new SimpleDate(startDate);

            SimpleDate d2 = SimpleDate.Today;

            var x2 = d2 - fromDate;


            double days = (fromDate.ToDateTime() - d2.ToDateTime()).TotalDays;

            var cal = OrchestradeCommon.Util.CalendarHelper.Get("GBLO");

            const string filterName = "ClearedOTC_GrossNtl";
            const string setupName = "Symmetry";                // for market

            var filter = Env.Current.Trade.GetFilter(filterName) ??
                            new Filter { Name = "_AllCurrency_", Criteria = new List<FilterCriterion>() };

            DataTable tblOut = new DataTable("TimeSeries");
            tblOut.Columns.Add("Entity", typeof(string));
            tblOut.Columns.Add("Portfolio", typeof(string));
            tblOut.Columns.Add("Book", typeof(string));
            tblOut.Columns.Add("Strategy", typeof(string));
            tblOut.Columns.Add("Region", typeof(string));
            tblOut.Columns.Add("Date", typeof(DateTime));
            tblOut.Columns.Add("PositionDate", typeof(DateTime));
            tblOut.Columns.Add("ProductId", typeof(int));
            tblOut.Columns.Add("ProductDescription", typeof(string));
            tblOut.Columns.Add("Currency", typeof(string));
            tblOut.Columns.Add("UnderlierInfo", typeof(string));
            tblOut.Columns.Add("PricingType", typeof(string));
            tblOut.Columns.Add("TotalTradedQuantity", typeof(decimal));
            tblOut.Columns.Add("Current_Notional", typeof(decimal));
            tblOut.Columns.Add("Current_Notional_Base", typeof(decimal));

            tblOut.Columns.Add("MaturityDate", typeof(DateTime));
            tblOut.Columns.Add("ProcessingType", typeof(string));

            tblOut.Columns.Add("Ccp", typeof(decimal));
            tblOut.Columns.Add("Start_Date", typeof(DateTime));
            tblOut.Columns.Add("End_Date", typeof(DateTime));
            tblOut.Columns.Add("Fixed_Rate", typeof(double));
            tblOut.Columns.Add("PayOrReceive", typeof(string));
            tblOut.Columns.Add("Boxed_String1", typeof(string));
            tblOut.Columns.Add("Boxed_String2", typeof(string));
            tblOut.Columns.Add("Boxed_String3", typeof(string));
            tblOut.Columns.Add("Netting_String1", typeof(string));
            tblOut.Columns.Add("Netting_String2", typeof(string));
            tblOut.Columns.Add("Netting_String3", typeof(string));
            tblOut.Columns.Add("Tenor_Bucket", typeof(string));
            tblOut.Columns.Add("PFE_Factor", typeof(double));
            try
            {
                //Load Market First
                var setup = Env.Current.MarketData.GetPricingSetup(setupName);
                if (setup == null)
                {
                    Console.WriteLine("PricingSetup does not exist: " + setupName);
                    return;
                }
                while (fromDate.Year == 2015)
                {
                    if (!fromDate.IsBusinessDay(cal))
                    {
                        fromDate = fromDate.SubtractTenor(Tenor.Parse("1D"));
                        continue;
                    }
                    Console.WriteLine(fromDate.ToDateTime().ToString("dd MMM yyyy"));
                    var toDate = fromDate + 0;
                    var market = new Market {Setup = setup, Time = now};

                    var positions = LoadTradingPositions(filter, market, now, fromDate, toDate);
                    Console.WriteLine("Loading Trading Positions:");

                    var ccyList = getFxQuotes(fromDate, market, positions);


                    var outpos = positions.Select(p => new
                        object[]
                    {
                        p.Book.ParentName, // Entity
                        p.Book.Properties.ContainsKey("Portfolio") ? p.Book.Properties["Portfolio"] : string.Empty,
                        // Portfolio
                        p.Book.Code, // Book
                        p.Book.Properties.ContainsKey("Region") ? p.Book.Properties["Region"] : string.Empty,
                        // Strategy
                        p.Book.Properties.ContainsKey("Strategy") ? p.Book.Properties["Strategy"] : string.Empty,
                        // Region
                        p.Date.ToDateTime(), // Date
                        fromDate.ToDateTime(), // Position Date
                        p.ProductId, // Product Id
                        p.Product.Description, // Product Description
                        p.Product.Currency, // Currency
                        p.Product.UnderlierInfo, // Underlier Info
                        p.Product.PricingType, // Pricing Type
                        p.TotalTraded.Quantity, // Total Traded Quantity
                        Math.Abs(p.TotalTraded.Quantity), // Current Notional
                        // p.TotalTraded.Quantity * ccyList[p.Product.Currency],
                        Math.Abs(p.TotalTraded.Quantity*ccyList[p.Product.Currency]),
                        p.Product.ContractMaturity.ToDateTime(), // Maturity Date
                        p.Product.ProcessingType, // Processing Type
                        //** p.Product.Ccp, // CCP?
                        0,
                        p.Product.StartDate.ToDateTime(), // StartDate
                        p.Product.ContractMaturity.ToDateTime(), // End Date
                        p.Product.FixedRate, // Fixed Rate
                        PayOrReceive(p), // Pay / Rec
                        //Boxed String 1
                        string.Join(":",
                            new string[]
                            {
                                p.Product.Currency, p.Product.ProcessingType, p.Product.UnderlierInfo,
                                p.Product.StartDate.ToString(), p.Product.ContractMaturity.ToString(),
                                p.Book.Properties.ContainsKey("Portfolio")
                                    ? p.Book.Properties["Portfolio"]
                                    : string.Empty,
                                p.Book.Code
                            }),
                        //Boxed String 2
                        string.Join(":",
                            new string[]
                            {
                                p.Product.Currency, p.Product.ProcessingType, p.Product.UnderlierInfo,
                                p.Product.StartDate.ToString(), p.Product.ContractMaturity.ToString(),
                                p.Book.Properties.ContainsKey("Portfolio")
                                    ? p.Book.Properties["Portfolio"]
                                    : string.Empty,
                                p.Book.ParentName
                            }),
                        //Boxed String 3
                        string.Join(":",
                            new string[]
                            {
                                p.Product.Currency, p.Product.ProcessingType, p.Product.UnderlierInfo,
                                p.Product.StartDate.ToString(), p.Product.ContractMaturity.ToString(), p.Book.ParentName
                            }),
                        //Netting String 1
                        string.Join(":",
                            new string[]
                            {
                                p.Product.Currency, p.Product.ProcessingType, p.Product.StartDate.ToString(),
                                p.Product.ContractMaturity.ToString(), p.Product.FixedRate.ToString(),
                                p.Book.Properties.ContainsKey("Portfolio")
                                    ? p.Book.Properties["Portfolio"]
                                    : string.Empty,
                                p.Book.Code
                            }),
                        //Netting String 2
                        string.Join(":",
                            new string[]
                            {
                                p.Product.Currency, p.Product.ProcessingType, p.Product.StartDate.ToString(),
                                p.Product.ContractMaturity.ToString(), p.Product.FixedRate.ToString(),
                                p.Book.Properties.ContainsKey("Portfolio")
                                    ? p.Book.Properties["Portfolio"]
                                    : string.Empty,
                                p.Book.ParentName
                            }),
                        //Netting String 3
                        string.Join(":",
                            new string[]
                            {
                                p.Product.Currency, p.Product.ProcessingType, p.Product.StartDate.ToString(),
                                p.Product.ContractMaturity.ToString(), p.Product.FixedRate.ToString(), p.Book.ParentName
                            }),
                        TenorBucket(p),
                        TenorBucket(p) == ">5y" ? .05 : TenorBucket(p) == "1-5y" ? .005 : 0
                    });
                    foreach (var row in outpos)
                    {
                        tblOut.Rows.Add(row);
                    }


                    fromDate = fromDate.SubtractTenor(Tenor.Parse("1D"));
                }
                tblOut.WriteToCsvFile(outputName);

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

        }
Esempio n. 48
0
        static public void SetUpAllocaitonGrid(string allocName, long blockEntity, long targetEntity, SimpleDate from, double percentage)
        {
            var alloc = Env.Current.StaticData.GetAllocationGridByName(AllocName);
            if (alloc == null)
                alloc = Env.Current.StaticData.SaveAllocationGrid(new AllocationGrid
                    {
                        Name = allocName,
                        BlockEntityId = blockEntity,
                        TargetEntityId = targetEntity,
                        FromDate = from,
                        Percentage = percentage
                    }
                );

        }
Esempio n. 49
0
        static public void ApplyTerm(bool isFull,  Trade trade, SimpleDate tradeDate, SimpleDate effectiveDate,
                            string party, double fee,  Market market, StringBuilder sb)
        {
            CleanUpFees(trade);
            trade.Product.ClearFlows();
            var tradeTime = tradeDate.ToDateTime();
            //tradeTime = tradeTime.AddSeconds(count);
            var settleDate = effectiveDate;
            var stepOutPartyId = GetPartyIdFromCode(party);
            bool isStepout = stepOutPartyId > 0 && stepOutPartyId != trade.PartyId;
            if (isFull)
            {
                TerminationEvent pevent;
                if (isStepout)
                {
                    pevent = new StepOutEvent(trade);
                    (pevent as StepOutEvent).InitialParty = trade.PartyId;
                    (pevent as StepOutEvent).TargetParty = GetPartyIdFromCode(party);
                    pevent.FullCalculationPeriod = true;
                }
                else
                {
                    pevent = new TerminationEvent(trade);
                }
                 pevent.TradeTime = tradeTime;
               // pevent.Price = price;
               // pevent.PriceType = QuotationType.CleanPrice;
                pevent.EffectiveDate = settleDate;
                pevent.AmountCurrency = trade.Product.Currency;
                pevent.Amount = fee;
                pevent.InterestPaymentDate = settleDate;

                //Termination Regular
                var handler = (TerminationProductEventHandler)ProductEvent.Handler(pevent.EventType, trade.Product.ProcessingType);
                var newTrades = new List<Trade>();
                var modifiedTrades = new List<Trade>();
                double accrual = 0;
                try { accrual = handler.ComputeAccrual(trade, tradeTime, pevent.EffectiveDate, market, pevent.FXRate); }
                catch (Exception ac)
                {
                    sb.Append("*** Error computing Acrual for " + trade.Product.GetType().Name + " " +   ac.Message + "\n");
                }
                pevent.Accrual = accrual;

                handler.Process(pevent, market, trade, newTrades, modifiedTrades, new List<IProductEvent>());
                if (trade.Fees != null)
                {
                    foreach (Fee f in trade.Fees)
                    {
                        if (f.Date != pevent.EffectiveDate) continue;
                        if (f.FeeType != FeeType.AccrualOffset) f.InputAmount = accrual + pevent.Amount;
                    }
                }
                trade.Status = "Terminated";
            }
            else
            {
                //Partial
                PartialTerminationEvent pevent;
                var termamount = fee;
                if (isStepout)
                {
                    pevent = new PartialStepOutEvent(trade);
                    (pevent as PartialStepOutEvent).InitialParty = trade.PartyId;
                    (pevent as PartialStepOutEvent).TargetParty = GetPartyIdFromCode(party);
                    pevent.FullCalculationPeriod = true;
                    pevent.PreviousNotional = Math.Abs(trade.Product.CurrentNominal(trade.Product.ContractMaturity, tradeTime.AddSeconds(-1), false));
                     pevent.CurrentNotional = pevent.PreviousNotional - Math.Abs(termamount);
                }
                else
                {
                    pevent = new PartialTerminationEvent(trade)
                    {
                        FullCalculationPeriod = true,
                        PreviousNotional =
                           Math.Abs(trade.Product.CurrentNominal(trade.Product.ContractMaturity, tradeTime.AddSeconds(-1), false))
                    };
                     pevent.CurrentNotional = pevent.PreviousNotional - Math.Abs(termamount);
                }
           
                pevent.EffectiveDate = settleDate;
                pevent.TradeTime = tradeTime;
               // pevent.Price = price;
               // pevent.PriceType = QuotationType.CleanPrice;
                pevent.EffectiveDate = settleDate;
                pevent.AmountCurrency = trade.SettleCurrency;
               // pevent.Amount = -termamount * (pevent.Price - 1);
                pevent.InterestPaymentDate = settleDate;
             
                //Termination Regular
                var handler = (PartialTerminationProductEventHandler)ProductEvent.Handler(pevent.EventType, trade.Product.ProcessingType);
                var newTrades = new List<Trade>();
                var modifiedTrades = new List<Trade>();
                double accrual = 0;
                try { accrual = handler.ComputeAccrual(trade, tradeTime, pevent.EffectiveDate, market, pevent.PreviousNotional, pevent.CurrentNotional, true, pevent.FXRate); }
                catch (Exception ac)
                {
                    sb.Append("*** Error computing Acrual for " + trade.Product.GetType().Name + " " + ac.Message + "\n");
                }
                pevent.Accrual = accrual;
                handler.Process(pevent, market, trade, newTrades, modifiedTrades,  new List<IProductEvent>());
                if (trade.Fees != null)
                {
                    foreach (Fee f in trade.Fees)
                    {
                        if (f.Date == pevent.EffectiveDate && f.FeeType != FeeType.AccrualOffset) f.InputAmount = accrual + pevent.Amount;
                    }
                }
            }
        }
Esempio n. 50
0
 static public string FormatDate(SimpleDate dd)
 {
     if (dd.IsNull) return string.Empty;
     var sb = new StringBuilder();
     if (dd.Month < 10)
         sb.Append("0").Append(dd.Month);
     else sb.Append(dd.Month);
     sb.Append("/");
     if (dd.Day < 10)
         sb.Append("0").Append(dd.Day);
     else sb.Append(dd.Day);
     sb.Append("/");
     sb.Append(dd.Year);
     return sb.ToString();
 }
Esempio n. 51
0
 static public Quote SaveAndLoadQuote(Trade trade, Market market, SimpleDate date, double mp, IList<Exception> exceptions)
 {            
     if (market == null) return null;
     var setup = market.Setup;
     if (setup == null) return null;
     IList<Trade> trades = new List<Trade>();
     Quote theQuote = null;
     trades.Add(trade);
     var time = new DateTime(date.Year, date.Month, date.Day);
     market.Time = time;
     //TradeBlotter.Check(null, trades, market, time, true, false, false, false, null, false);
     var mnames = new List<string> { Measure.Pv };
     var optional = new Set<QuoteId>();
     var quotes = new Set<QuoteId>();
     var toSave = new List<Quote>();
     try 
     {                
         IPricer pricer = setup.Pricer(trade.Product);
         if (pricer == null) return null;
         pricer.Quotes(trade, time, market, pricer.MakeMeasures(mnames), quotes, optional);
         var bond = trade.Product as Bond;
         if (bond != null && bond.IsIlliquid)
         {
             var q = new BondPricer().FindQuote(bond, bond.QuoteName.Name, market, date);
             if (q != null) quotes.Add(q.QuoteId);
         }
         foreach (QuoteId qId in quotes)
         {
             var q = new Quote(setup.ClosingName, qId.Name, date, mp, mp, trade.PriceType);
             toSave.Add(q);
             theQuote = q;
             break;
         }
         Env.Current.MarketData.SaveQuotes(toSave);
         return theQuote;
     }
     catch (Exception x)
     {
         exceptions.Add(x);
         return null;
     }
     
 }
Esempio n. 52
0
        public SimpleDate SettleDate { get; set; } // SETTLEMENT


        public FxInfo(string[] ss, Dictionary<string, int> headers)
            : base(ss, headers)
        {
            //var ss = line.Split(TradeImportHelper.Separators);
            QuotingCcy = TradeInfo.GetValue(ss, headers, "M_XPQTYCUR");
            PrimaryCcy = TradeInfo.GetValue(ss, headers, "M_XPOQTYCUR");
            QuotingAmount = TradeInfo.GetDoubleValue(ss, headers, "M_XPQTY");
            PrimaryAmount = TradeInfo.GetDoubleValue(ss, headers, "M_XPOQTY");
            FixingDate = TradeInfo.GetDateValue(ss, headers, "Fixing Date");
            FixingRate = TradeInfo.GetDoubleValue(ss, headers, "Fixing Rate");
            SettleDate = TradeInfo.GetDateValue(ss, headers, "SETTLEMENT");
        }
Esempio n. 53
0
 public static void GetParamsFromImagine(IDictionary<string, string> symbolDict, string rsymbol, string desc, 
     bool isOption, out string identifier1, out SimpleDate maturity, out double strike)
 {           
     strike = double.NaN;
     maturity = SimpleDate.Null;
     identifier1 = null;
     if (isOption)
     {
         var tokens = desc.Split(' ');
             if (tokens.Length > 2)
             {
                 if (tokens[2].EndsWith("P") || tokens[2].EndsWith("C"))
                     tokens[2] = tokens[2].Substring(0, tokens[2].Length - 1);
                 double.TryParse(tokens[2], out strike);
                 maturity = GetMaturity(tokens[1], rsymbol, tokens[0]);
                 identifier1 = MapIdentifier(symbolDict, tokens[0], true);
             }
     }
     else
     {
         maturity = GetMaturity2(rsymbol.Substring(rsymbol.Length - 2));
         identifier1 = MapIdentifier(symbolDict, rsymbol.Substring(0, rsymbol.Length - 2), false);
     }
 }
 static private Dictionary<string, double> getFxQuotes(SimpleDate refDate, Market market, IList<Position> positions)
 {
     Dictionary<string, double> retList = new Dictionary<string, double>();
     var currencyList = positions.Select(p => p.Product.Currency).Where(c => c != "USD").Distinct();
     retList.Add("USD", 1);
     foreach (var ccy in currencyList)
     {
         var cp = Env.Current.Trade.GetCurrencyPair(ccy, "USD");
         if (cp != null)
         {
             var fxs = new FXSwap { Primary = cp.Primary, Quoting = cp.Quoting };
             var spot = market.FindFx(ccy, "USD", refDate, true);
             retList.Add(ccy, spot.Mid);
         }
     }
     return retList;
 }
 static protected IList<Position> LoadTradingPositions(Filter filter, Market market, DateTime valuationTime, SimpleDate fromDate, SimpleDate toDate)
 {
     var builder = new PositionBuilder { PositionFilter = filter };
     builder.AcceptCurrencySecurity = true;
     builder.IncludeOtc = true;
     builder.ExcludeNonLive = true;
     builder.FromDate = fromDate;
     builder.ToDate = toDate;
     var asOfDate = market.Date(valuationTime);
     return builder.Build(new SimpleDate(asOfDate));
 }
Esempio n. 56
0
 public void ShouldThowUserExceptionOnInsertDate()
 {
     using (var executionContext = new CommonTestExecutionContext())
     {
         var repository = new Common.DomRepository(executionContext);
         var entity = new SimpleDate { Value = new DateTime(2013, 7, 7) };
         repository.TestMaxValue.SimpleDate.Insert(new[] { entity });
     }
 }
 public string GenerateFileName(string dir, string fileName, SimpleDate date, DateTime time,
                                IDictionary<string, string> parms)
 {
     return null;
 }
Esempio n. 58
0
 virtual protected List<SimpleDate> GetExpirations(Feed feed, Contract contract, SimpleDate date)
 {
     var exps = contract.NextExpiries(date, contract.TotalListed, true, true);
     if (exps == null && feed != null && contract.ExpiryMethod.Equals("Manual"))
     {
         exps = new List<SimpleDate>();
         var cexp = FeedImportSecurityTaskExecutor.SnapExpirations(date, contract, feed, new List<Exception>());
         if (cexp != null && cexp.Count > 0)
         {
             foreach (var d in cexp)
             {
                 var contMonth = d.ContractMonth;
                 if (!contMonth.IsNull)
                 {
                     Env.Current.MarketData.SaveContractExpiration(d);
                     exps.Add(d.ContractMonth);
                 }
             }
         }
         exps = contract.NextExpiries(date, contract.TotalListed, true, true);
     }
     return exps;
 }
 public static void GetDates(string security, out SimpleDate start, out SimpleDate end)
 {
     var idx1 = security.IndexOf('(');
     var idx2 = security.IndexOf(')');
     start = SimpleDate.Null;
     end = SimpleDate.Null;
     if (idx1 > 0 && idx2 > 0 && idx2 > idx1)
     {
         var ss = security.Substring(idx1, idx2 - idx1 + 1);
         var dates = ss.Split('-');
         try
         {
             if (dates.Length == 1)
                 end = new SimpleDate(DateTime.ParseExact("dd MMM yyyy", ss, CultureInfo.InvariantCulture));
             else
             {
                 start = new SimpleDate(DateTime.ParseExact("dd MMM yyyy", ss, CultureInfo.InvariantCulture));
                 end = new SimpleDate(DateTime.ParseExact("dd MMM yyyy", ss, CultureInfo.InvariantCulture));
             }
         }
         catch
         {
             return;
         }
     }
 }
 public void SetParams(IDictionary<string, string> pars, Task task, DateTime effectiveTime)
 {
     _params = pars;
     _task = task;
     _params["AsOfDate"] = new SimpleDate(effectiveTime).ToString();
 }