Exemple #1
0
        public override string ToString()
        {
            StringBuilder sb = new StringBuilder(base.ToString());

            sb.Append(" - Symbol:").Append(Symbol);
            sb.Append("; RootSymbol:").Append(RootSymbol);
            sb.Append("; Strike:").Append(Strike);
            sb.Append("; Expiry:").Append(Expiry.ToString("yyyy-MM-dd"));
            sb.Append("; OptionType:").Append(OptionType);
            sb.Append("; Bid:").Append(Bid);
            sb.Append("; Ask:").Append(Ask);
            sb.Append("; Last:").Append(Last);
            sb.Append("; Close:").Append(Close);
            sb.Append("; Change:").Append(Change);
            sb.Append("; Volume:").Append(Volume);
            sb.Append("; Multiplier:").Append(Multiplier);
            sb.Append("; Description:").Append(Description);
            sb.Append("; ExpirationFrequencyCode:").Append(ExpirationFrequencyCode);
            sb.Append("; SettlementStyle:").Append(SettlementStyle);
            sb.Append("; OpenInterest:").Append(OpenInterest);
            sb.Append("; ImpliedVolatility:").Append(ImpliedVolatility);
            sb.Append("; Delta:").Append(Delta);
            sb.Append("; Gamma:").Append(Gamma);
            sb.Append("; Theta:").Append(Theta);
            sb.Append("; Vega:").Append(Vega);
            sb.Append("; TimeValue:").Append(TimeValue);
            return(sb.ToString());
        }
 public void MergeFrom(AuthResponsePacket other)
 {
     if (other == null)
     {
         return;
     }
     if (other.Success != false)
     {
         Success = other.Success;
     }
     if (other.FailureReason != 0)
     {
         FailureReason = other.FailureReason;
     }
     if (other.FailureMessage.Length != 0)
     {
         FailureMessage = other.FailureMessage;
     }
     if (other.SessionId.Length != 0)
     {
         SessionId = other.SessionId;
     }
     if (other.expiry_ != null)
     {
         if (expiry_ == null)
         {
             expiry_ = new global::Google.Protobuf.WellKnownTypes.Timestamp();
         }
         Expiry.MergeFrom(other.Expiry);
     }
     if (other.ExpiresIn != 0)
     {
         ExpiresIn = other.ExpiresIn;
     }
 }
        public override int GetHashCode()
        {
            int hash = 1;

            if (Success != false)
            {
                hash ^= Success.GetHashCode();
            }
            if (FailureReason != 0)
            {
                hash ^= FailureReason.GetHashCode();
            }
            if (FailureMessage.Length != 0)
            {
                hash ^= FailureMessage.GetHashCode();
            }
            if (SessionId.Length != 0)
            {
                hash ^= SessionId.GetHashCode();
            }
            if (expiry_ != null)
            {
                hash ^= Expiry.GetHashCode();
            }
            if (ExpiresIn != 0)
            {
                hash ^= ExpiresIn.GetHashCode();
            }
            return(hash);
        }
        public void MakeTheta()
        {
            var type = _propAssetTree.GetType();
            var t1   = (ITree)Activator.CreateInstance(type);
            var t2   = (ITree)Activator.CreateInstance(type);

            t1.Tau       = Expiry.Subtract(Today).Days / 365.0;
            t1.Gridsteps = Gridsteps;
            t1.Sig       = Sig;
            t1.Spot      = Spot;
            t1.MakeGrid();
            _priceTree.MakeGrid(t1);
            double p1  = _priceTree.Price();
            double tau = Expiry.Subtract(Today).Days / 365.0;
            double t   = tau - 1.00 / 365.00;

            t2.Tau       = t;
            t2.Gridsteps = Gridsteps;
            t2.Sig       = Sig;
            t2.Spot      = Spot;
            t2.MakeGrid();
            _priceTree.MakeGrid(t2);
            double p2 = _priceTree.Price();

            Theta = (p2 - p1);
        }
        public override int GetHashCode()
        {
            int hashCode = SecurityCode.GetHashCode() ^ StrikePrice.GetHashCode() ^
                           Expiry.GetHashCode() ^ PremiumMultiplier.GetHashCode();

            return(hashCode);
        }
        public void MakeDeltaGamma()
        {
            var    type  = _propAssetTree.GetType();
            var    treeD = (ITree)Activator.CreateInstance(type);
            double tau   = Expiry.Subtract(Today).Days / 365.0;

            treeD.Gridsteps = Gridsteps + 2;
            treeD.Spot      = Spot;
            treeD.Sig       = Sig;
            treeD.Tau       = tau * (1 + 2 / Gridsteps);
            treeD.MakeGrid();
            _priceTree.MakeGrid(treeD);
            var s = new double[3];
            var c = new double[3];

            for (int i = 0; i <= 2; ++i)
            {
                s[i] = treeD.GetSpotMatrix(2, i);
                c[i] = _priceTree.GetPriceMatrix(2, i);
            }
            Delta = (s[0] * (2 * s[1] - s[0]) * (c[1] - c[2]) +
                     (s[1] * s[1]) * (c[2] - c[0]) + s[2] * (2 * s[1] - s[2]) * (c[0] - c[1]))
                    / (s[1] - s[0]) / (s[2] - s[0]) / (s[2] - s[1]);

            Gamma = 2 * (s[0] * (c[1] - c[2]) + s[1] * (c[2] - c[0]) + s[2] * (c[0] - c[1]))
                    / (s[1] - s[0]) / (s[2] - s[0]) / (s[2] - s[1]);
        }
Exemple #7
0
 public void DisplayPolicyTemplate()
 {
     Console.WriteLine("Id: " + Id + "\n" + "Effective: " + Effective.ToShortDateString()
                       + "\n" + "Expiry: " + Expiry.ToShortDateString()
                       + "\n" + "Police_No: " + Police_No + "\n" + "Premium: " + Premium + "\n"
                       + "IsValid: " + IsValid);
 }
Exemple #8
0
 public void show()
 {
     Console.WriteLine("Name: \n" + Name);
     Console.WriteLine("Expiry: \n" + Expiry.ToShortDateString());
     Console.WriteLine("Sizes: \n" + Sizes.ToString());
     Console.WriteLine("Data: \n" + Data.Data);
     Console.WriteLine("MyProperty: \n" + MyProperty.ToString());
 }
        public override global::System.Data.DataSet Clone()
        {
            Expiry cln = ((Expiry)(base.Clone()));

            cln.InitVars();
            cln.SchemaSerializationMode = this.SchemaSerializationMode;
            return(cln);
        }
Exemple #10
0
 public Boolean CheckExpiry()
 {
     if (DateTime.UtcNow > Expiry.ToUniversalTime())
     {
         CallExpiredEvent(this.Identifier, this.Guid);
         return(true);
     }
     return(false);
 }
Exemple #11
0
        public string OutputExpiry()
        {
            string str = "";

            for (int i = Expiry.GetLowerBound(0); i < Expiry.GetUpperBound(0); i++)
            {
                str = str + Expiry[i].ToString(CultureInfo.InvariantCulture) + ", ";
            }
            str = str + Expiry[Expiry.GetUpperBound(0)].ToString(CultureInfo.InvariantCulture);
            return(str);
        }
Exemple #12
0
        public double CalculateParRate(IFundingModel Model)
        {
            var rateStart     = Expiry.AddPeriod(RollType.F, Index.HolidayCalendars, Index.FixingOffset);
            var rateEnd       = rateStart.AddPeriod(Index.RollConvention, Index.HolidayCalendars, Index.ResetTenor);
            var forecastCurve = Model.Curves[ForecastCurve];
            var fwdRate       = forecastCurve.GetForwardRate(rateStart, rateEnd, RateType.Linear, Index.DayCountBasis);

            var fairPrice = 100.0 - (fwdRate + ConvexityAdjustment) * 100.0;

            return(fairPrice);
        }
Exemple #13
0
        public double Pv(FundingModel Model, bool updateState)
        {
            var rateStart     = Expiry.AddPeriod(RollType.F, Index.HolidayCalendars, Index.FixingOffset);
            var rateEnd       = rateStart.AddPeriod(Index.RollConvention, Index.HolidayCalendars, Index.ResetTenor);
            var forecastCurve = Model.Curves[ForecastCurve];
            var fwdRate       = forecastCurve.GetForwardRate(rateStart, rateEnd, RateType.Linear, Index.DayCountBasis);

            var fairPrice = 100.0 - (fwdRate + ConvexityAdjustment) * 100.0;
            var PV        = (Price - fairPrice) * Position * ContractSize * DCF;

            return(PV);
        }
        public static global::System.Xml.Schema.XmlSchemaComplexType GetTypedDataSetSchema(global::System.Xml.Schema.XmlSchemaSet xs)
        {
            Expiry ds = new Expiry();

            global::System.Xml.Schema.XmlSchemaComplexType type     = new global::System.Xml.Schema.XmlSchemaComplexType();
            global::System.Xml.Schema.XmlSchemaSequence    sequence = new global::System.Xml.Schema.XmlSchemaSequence();
            global::System.Xml.Schema.XmlSchemaAny         any      = new global::System.Xml.Schema.XmlSchemaAny();
            any.Namespace = ds.Namespace;
            sequence.Items.Add(any);
            type.Particle = sequence;
            global::System.Xml.Schema.XmlSchema dsSchema = ds.GetSchemaSerializable();
            if (xs.Contains(dsSchema.TargetNamespace))
            {
                global::System.IO.MemoryStream s1 = new global::System.IO.MemoryStream();
                global::System.IO.MemoryStream s2 = new global::System.IO.MemoryStream();
                try {
                    global::System.Xml.Schema.XmlSchema schema = null;
                    dsSchema.Write(s1);
                    for (global::System.Collections.IEnumerator schemas = xs.Schemas(dsSchema.TargetNamespace).GetEnumerator(); schemas.MoveNext();)
                    {
                        schema = ((global::System.Xml.Schema.XmlSchema)(schemas.Current));
                        s2.SetLength(0);
                        schema.Write(s2);
                        if ((s1.Length == s2.Length))
                        {
                            s1.Position = 0;
                            s2.Position = 0;
                            for (; ((s1.Position != s1.Length) &&
                                    (s1.ReadByte() == s2.ReadByte()));)
                            {
                                ;
                            }
                            if ((s1.Position == s1.Length))
                            {
                                return(type);
                            }
                        }
                    }
                }
                finally {
                    if ((s1 != null))
                    {
                        s1.Close();
                    }
                    if ((s2 != null))
                    {
                        s2.Close();
                    }
                }
            }
            xs.Add(dsSchema);
            return(type);
        }
        /// <inheritdoc />
        public override int GetHashCode()
        {
            unchecked
            {
                int hashCode = Expiry != null?Expiry.GetHashCode() : 0;

                hashCode = (hashCode * 397) ^ (Retry != null ? Retry.GetHashCode() : 0);
                hashCode = (hashCode * 397) ^ (Logout != null ? Logout.GetHashCode() : 0);
                hashCode = (hashCode * 397) ^ (Takeover != null ? Takeover.GetHashCode() : 0);
                hashCode = (hashCode * 397) ^ (LearnMore != null ? LearnMore.GetHashCode() : 0);
                return(hashCode);
            }
        }
Exemple #16
0
        public override string ToString()
        {
            StringBuilder sb = new StringBuilder(base.ToString());

            sb.Append(" - Strike:").Append(Strike);
            sb.Append("; Multiplier:").Append(Multiplier);
            sb.Append("; Expiry:").Append(Expiry.ToString("yyyy-MM-dd"));
            sb.Append("; Call:{").Append(Call).Append('}');
            sb.Append("; Put:{").Append(Put).Append('}');
            sb.Append("; ExpirationFreqCode:").Append(ExpirationFreqCode);
            sb.Append("; SettlementStyle:").Append(SettlementStyle);
            return(sb.ToString());
        }
Exemple #17
0
        public override Contract ToIbContract()
        {
            var contract = base.ToIbContract();

            if (OptionType != EOptionType.None)
            {
                contract.Right = OptionType == EOptionType.Call ? "C" : "P";
            }
            contract.Expiry     = Expiry < DateTime.Now ? null : Expiry.ToString("yyyyMMdd");
            contract.Strike     = Strike;
            contract.Multiplier = Multiplier.ToString();
            return(contract);
        }
        public double Price()
        {
            _propAssetTree.Spot      = Spot;
            _propAssetTree.Sig       = Sig;
            _propAssetTree.Tau       = Expiry.Subtract(Today).Days / 365.0;
            _propAssetTree.Gridsteps = Gridsteps;
            _propAssetTree.MakeGrid();
            //create PriceTree
            _priceTree = new PriceTree(Strike, Payoff, "Y", Style);
            _priceTree.MakeGrid(_propAssetTree);
            double pr = _priceTree.Price();

            return(pr);
        }
        public string ToJwt(string secret)
        {
            if (string.IsNullOrWhiteSpace(secret))
            {
                throw new ArgumentNullException(nameof(secret), $"The {nameof(secret)} must be provided to encode the token");
            }

            return(new JwtBuilder()
                   .WithAlgorithm(new HMACSHA512Algorithm())
                   .WithSecret(secret)
                   .AddClaim(Claims.Identity, Principal)
                   .AddClaim(Claims.Expiry, Expiry.ToUnixTimeSeconds())
                   .AddClaim(Claims.Resources, Resources)
                   .Encode());
        }
Exemple #20
0
 private async void Pay()
 {
     var token = stripePaymentService.GeneratePaymentToken(new Models.CardModel
     {
         Number         = CardNumber.Replace(" ", string.Empty),
         ExpMonth       = Convert.ToInt16(Expiry.Substring(0, 2)),
         ExpYear        = Convert.ToInt16(Expiry.Substring(3, 2)),
         Cvc            = Cvv,
         Name           = "Brice Devos",
         AddressCity    = "Paris",
         AddressZip     = "75008",
         AddressCountry = "France",
         AddressLine1   = "16 Rue Victor Hugo"
     });
     var success = await stripePaymentService.PayWithCard(new Models.PaymentModel {
         Amount      = Convert.ToInt16(Amount) * 100,
         Token       = token,
         Description = "Stripe test payment subscription"
     });
 }
        public void ExpiryEndOfMonthTests()
        {
            var endOfMonthList = new List <DateTime>();

            var current = new DateTime(2019, 1, 1);
            var end     = new DateTime(2020, 1, 1);

            while (current < end)
            {
                var endOfMonth = Expiry.EndOfMonth(current);
                endOfMonthList.Add(endOfMonth);
                Assert.AreEqual(1, endOfMonth.Day);
                Assert.Greater(endOfMonth, current);
                current = current.AddDays(1);
            }

            var actual = endOfMonthList.Distinct().Count();

            Assert.AreEqual(12, actual);
        }
        public void ExpiryEndOfWeekTests()
        {
            var endOfWeekList = new List <DateTime>();

            var current = new DateTime(2019, 1, 1);
            var end     = new DateTime(2020, 1, 1);

            while (current < end)
            {
                var endOfWeek = Expiry.EndOfWeek(current);
                endOfWeekList.Add(endOfWeek);
                Assert.AreEqual(DayOfWeek.Monday, endOfWeek.DayOfWeek);
                Assert.Greater(endOfWeek, current);
                current = current.AddDays(1);
            }

            var actual = endOfWeekList.Distinct().Count();

            Assert.AreEqual(53, actual);
        }
Exemple #23
0
        public DateTime getExpiryAsDate()
        {
            int yyyy = 1970;
            int mmm  = 1;
            int dd   = 1;
            int hh   = 0;
            int mm   = 0;
            int ss   = 0;

            Int32.TryParse(Expiry.Substring(0, 4), out yyyy);
            Int32.TryParse(Expiry.Substring(5, 2), out mmm);
            Int32.TryParse(Expiry.Substring(8, 2), out dd);
            Int32.TryParse(Expiry.Substring(11, 2), out hh);
            Int32.TryParse(Expiry.Substring(14, 2), out mm);
            Int32.TryParse(Expiry.Substring(17, 2), out ss);

            DateTime dt = new DateTime(yyyy, mmm, dd, hh, mm, ss, DateTimeKind.Utc);

            return(dt);
        }
        public void ExpiryEndOfYearTests()
        {
            var endOfYearList = new List <DateTime>();

            var current = new DateTime(2019, 1, 1);
            var end     = new DateTime(2020, 1, 1);

            while (current < end)
            {
                var endOfYear = Expiry.EndOfYear(current);
                endOfYearList.Add(endOfYear);
                Assert.AreEqual(1, endOfYear.Day);
                Assert.AreEqual(end.Year, endOfYear.Year);
                Assert.Greater(endOfYear, current);
                current = current.AddDays(1);
            }

            var actual = endOfYearList.Distinct().Count();

            Assert.AreEqual(1, actual);
        }
Exemple #25
0
        public void Update(MarketDetailsResponse marketDetails)
        {
            Bid = Convert.ToDouble(marketDetails.snapshot.bid);
            Ask = Convert.ToDouble(marketDetails.snapshot.offer);

            Prime  = (Bid + Ask) / 2;
            Spread = Ask - Bid;

            InterestRate = EuriborHelper.GetInterestRate(Expiry.Subtract(DateTime.Now));

            CurrentPrice = Convert.ToDouble(marketDetails.snapshot.netChange);
            var isCall = Directions == OptionDirections.Call;
            var time   = Expiry.Subtract(DateTime.Now).TotalDays / 365;

            var correctedPrime = Math.Min(Bid + Spread * (Bid / 20), Prime);

            Volatility = BlackScholesHelper.ImpliedVolatility(isCall, CurrentPrice, Strike, time, 0, correctedPrime);

            InterestRate = Math.Round(InterestRate * 100, 2);
            Volatility   = Math.Round(Volatility * 100, 2);
        }
        private double Bisection(double prem, double fwdPrice)
        {
            double right = 0.75;
            double left  = 0.35;
            double mid;
            var    cp         = Payoff.ToLower() == "c" ? 1 : -1;
            int    days       = Expiry.Subtract(Today).Days;
            double t          = days / 365.0;
            var    priceClone = (AmOptionAnalytics)Clone();

            if (fwdPrice <= 0 || Strike <= 0 || t <= 0 || prem <= 0)
            {
                return(0);
            }
            double df = Convert.ToDouble(RateCurve.GetDf(days));

            if (prem < Math.Max(cp * df * (fwdPrice - priceClone.Strike), 0))
            {
                throw new System.Exception("No solution for volatility");
            }
            do
            {
                mid            = (right + left) / 2;
                priceClone.Sig = left;
                double fleft = priceClone.Price() - prem;
                priceClone.Sig = right;
                double fright = priceClone.Price() - prem;
                priceClone.Sig = mid;
                double fmid = priceClone.Price() - prem;
                if (fleft * fmid < 0)
                {
                    right = mid;
                }
                else if (fright * fmid < 0)
                {
                    left = mid;
                }
            } while (Math.Abs(right - left) > 2 * Eps);
            return(mid);
        }
 public Instrument()
 {
     expiry           = new Expiry();
     provider         = "";
     iFSC             = "";
     holder           = new Holder();
     bIC              = "";
     type             = "";
     action           = "";
     mICR             = "";
     verificationCode = "";
     iBAN             = "";
     processor        = "";
     issuance         = new Issuance();
     alias            = "";
     identifier       = "";
     token            = "";
     authentication   = new Authentication();
     subType          = "";
     issuer           = "";
     acquirer         = "";
 }
Exemple #28
0
        public override int GetHashCode()
        {
            int hash = 1;

            if (HasUri)
            {
                hash ^= Uri.GetHashCode();
            }
            if (HasExpiry)
            {
                hash ^= Expiry.GetHashCode();
            }
            if (HasStatusCode)
            {
                hash ^= StatusCode.GetHashCode();
            }
            if (_unknownFields != null)
            {
                hash ^= _unknownFields.GetHashCode();
            }
            return(hash);
        }
Exemple #29
0
        public OptionItem(MarketDetailsResponse marketDetails)
        {
            Epic = marketDetails.instrument.epic;

            Quantity = 1;
            Name     = $"{marketDetails.instrument.name} ({marketDetails.instrument.expiry})";

            var infos = marketDetails.instrument.name.Split(' ');

            var dir    = infos[infos.Length - 1];
            var strike = infos[infos.Length - 2];

            Directions = dir.ToUpper() == "CALL" ? OptionDirections.Call : OptionDirections.Put;
            Strike     = Convert.ToDouble(strike);

            Expiry = Convert.ToDateTime(marketDetails.instrument.expiryDetails.lastDealingDate, CultureInfo.GetCultureInfo("fr-FR"));

            Bid = Convert.ToDouble(marketDetails.snapshot.bid);
            Ask = Convert.ToDouble(marketDetails.snapshot.offer);

            Prime        = (Bid + Ask) / 2;
            CurrentPrime = Prime;
            Spread       = Ask - Bid;

            PrimeString = $"({Ask}/{Bid})";

            InterestRate = EuriborHelper.GetInterestRate(Expiry.Subtract(DateTime.Now));

            CurrentPrice = Convert.ToDouble(marketDetails.snapshot.netChange);
            var isCall = Directions == OptionDirections.Call;
            var time   = Expiry.Subtract(DateTime.Now).TotalDays / 365;

            var correctedPrime = Math.Min(Bid + Spread * (Bid / 20), Prime);

            Volatility = BlackScholesHelper.ImpliedVolatility(isCall, CurrentPrice, Strike, time, 0, correctedPrime);

            InterestRate = Math.Round(InterestRate * 100, 2);
            Volatility   = Math.Round(Volatility * 100, 2);
        }
        private double Newton(double prem, double fwdPrice)
        {
            double dvol;
            var    cp         = Payoff.ToLower() == "c" ? 1 : -1;
            int    days       = Expiry.Subtract(Today).Days;
            double t          = days / 365.0;
            var    priceClone = (AmOptionAnalytics)Clone();

            if (fwdPrice <= 0 || Strike <= 0 || t <= 0 || prem <= 0)
            {
                return(0);
            }
            //double df = Convert.ToDouble(_rateCurve.getDf(days));
            if (prem < Math.Max(cp * (fwdPrice - priceClone.Strike), 0))
            {
                throw new System.Exception("No solution for volatility");
            }
            int idx = 0;

            do
            {
                var price = priceClone.Price();
                priceClone.MakeVega();
                var vega = priceClone.Vega;
                if (vega == 0 || idx > Maxits)
                {
                    throw new System.Exception("No volatility solution");
                }
                dvol            = (price - prem) / (100 * vega);
                priceClone.Sig -= dvol;
                if (priceClone.Sig < 0)
                {
                    priceClone.Sig = 0;
                }
                idx++;
            } while (Math.Abs(dvol) > Eps);
            return(priceClone.Sig);
        }
        public List<Order> GetStandardRRFOrders()
        {
            var client = new ServiceRRFLookupClient();
            var orders = new List<Order>();
            var ginfo = new GeneralInfo();
            ginfo.LoadAll();

            var dataView = gridItemChoiceView.DataSource as DataView;
            if (dataView != null)
            {
                dataView.RowFilter = gridItemChoiceView.ActiveFilterString;
                tblRRF = dataView.ToTable();
            }

            var periods = client.GetCurrentReportingPeriod(ginfo.FacilityID, ginfo.ScmsWSUserName, ginfo.ScmsWSPassword);
            var form = client.GetForms(ginfo.FacilityID, ginfo.ScmsWSUserName, ginfo.ScmsWSPassword);

            var rrfs = client.GetFacilityRRForm(ginfo.FacilityID, form[0].Id, periods[0].Id, 1, ginfo.ScmsWSUserName, ginfo.ScmsWSPassword);
            var formCategories = rrfs.First().FormCategories;
            var chosenCategoryBody = formCategories.First(x => x.Id == 1); //TODO:Hard coding to be removed.
            var items = chosenCategoryBody.Pharmaceuticals;

            var user = new User();
            user.LoadByPrimaryKey(MainWindow.LoggedinId);

            var order = new Order
                            {
                                RequestCompletedDate = DateTime.Now,
                                OrderCompletedBy = user.FullName,
                                RequestVerifiedDate = DateTime.Now,
                                OrderTypeId = STANDARD_ORDER,
                                SubmittedBy = user.FullName,
                                SubmittedDate = DateTime.Now,
                                SupplyChainUnitId = ginfo.FacilityID,
                                OrderStatus = 1, //TODO: hardcoding
                                FormId = form[0].Id, //TODO: hardcoding
                                ReportingPeriodId = periods[0].Id //TODO: hardcoding
                            };

            var details = new List<RRFTransactionService.OrderDetail>();

            foreach (DataRow rrfLine in tblRRF.Rows)
            {
                var detail = new RRFTransactionService.OrderDetail();
                var hcmisItemID = Convert.ToInt32(rrfLine["DSItemID"]);
                var rrFormPharmaceutical = items.SingleOrDefault(x => x.PharmaceuticalId == hcmisItemID);
                if (rrFormPharmaceutical != null && Convert.ToString(rrfLine["Status"]) != "Below EOP")
                {
                        detail.BeginningBalance = Convert.ToInt32(rrfLine["BeginingBalance"]);
                        detail.EndingBalance = Convert.ToInt32(rrfLine["SOH"]);
                        detail.QuantityReceived = Convert.ToInt32(rrfLine["Received"]);
                        detail.QuantityOrdered = Convert.ToInt32(rrfLine["Quantity"]);
                        detail.LossAdjustment = Convert.ToInt32(rrfLine["LossAdj"]);
                        detail.ItemId = rrFormPharmaceutical.ItemId;
                        var rdDoc = new ReceiveDoc();
                        var disposal = new Disposal();

                        rdDoc.GetAllWithQuantityLeft(hcmisItemID, _storeID);
                        disposal.GetLossAdjustmentsForLastRrfPeriod(hcmisItemID, _storeID, periods[0].StartDate,
                                                                    periods[0].EndDate);
                        int receiveDocEntries = rdDoc.RowCount;
                        int disposalEntries = disposal.RowCount;

                        if (rdDoc.RowCount == 0 && detail.EndingBalance == 0)
                            detail.Expiries = null;

                        detail.Expiries = new Expiry[receiveDocEntries];
                        detail.Adjustments = new Adjustment[disposalEntries];

                        rdDoc.Rewind();
                        int expiryAmountTotal = 0;

                        for (int j = 0; j < receiveDocEntries; j++)
                        {
                            var exp = new Expiry
                                          {
                                              Amount = Convert.ToInt32(rdDoc.QuantityLeft)
                                          };
                            expiryAmountTotal += exp.Amount;

                            exp.BatchNo = rdDoc.BatchNo;
                            exp.ExpiryDate = rdDoc.ExpDate;
                            if(exp.ExpiryDate > periods[0].EndDate.AddDays(ExpiryTreshHold))
                                exp.Amount = Convert.ToInt32(rdDoc.QuantityLeft);
                                exp.ExpiryDate = periods[0].EndDate;
                            detail.Expiries[j] = exp;
                            rdDoc.MoveNext();
                        }

                        disposal.Rewind();

                        int lossadjamt = 0;
                        for (int j = 0; j < disposalEntries; j++)
                        {
                            var adj = new Adjustment
                            {
                                Amount = Convert.ToInt32(disposal.Quantity),
                                TypeId = 1,
                                ReasonId = 1
                            };
                            lossadjamt += adj.Amount;

                            if (lossadjamt >= detail.LossAdjustment)
                                detail.LossAdjustment = lossadjamt;

                            detail.Adjustments[j] = adj;
                            disposal.MoveNext();
                        }

                        var stockoutIndexedLists = StockoutIndexBuilder.Builder.GetStockOutHistory(hcmisItemID, _storeID);
                        var DOSPerStockOut = stockoutIndexedLists.Count();
                        detail.DaysOutOfStocks = new DaysOutOfStock[stockoutIndexedLists.Count()];

                        for (int j = 0; j < stockoutIndexedLists.Count(); j++)
                        {
                            var dos = new DaysOutOfStock
                                          {
                                              NumberOfDaysOutOfStock = 5,
                                              StockOutReasonId = 5
                                          };
                            detail.DaysOutOfStocks[j] = dos;
                        }
                }
                else if(rrFormPharmaceutical != null && Convert.ToString(rrfLine["Status"]) == "Below EOP")
                {
                        detail.BeginningBalance = null;
                        detail.EndingBalance = null;
                        detail.QuantityReceived = null;
                        detail.QuantityOrdered = null;
                        detail.LossAdjustment = null;
                        detail.ItemId = rrFormPharmaceutical.ItemId;

                        var rdDoc = new ReceiveDoc();
                        var disposal = new Disposal();
                        rdDoc.GetAllWithQuantityLeft(hcmisItemID, _storeID);
                        disposal.GetLossAdjustmentsForLastRrfPeriod(hcmisItemID, _storeID, periods[0].StartDate,periods[0].EndDate);

                        int receiveDocEntries = rdDoc.RowCount;
                        int disposalEntries = disposal.RowCount;

                        if (rdDoc.RowCount == 0 && detail.EndingBalance == 0)
                            detail.Expiries = null;

                        detail.Expiries = new Expiry[receiveDocEntries];
                        detail.Adjustments = new Adjustment[disposalEntries];

                        rdDoc.Rewind();
                        int expiryAmountTotal = 0;
                        for (int j = 0; j < receiveDocEntries; j++)
                        {
                            var exp = new Expiry {Amount = Convert.ToInt32(rdDoc.QuantityLeft)};
                            expiryAmountTotal += exp.Amount;

                            exp.BatchNo = rdDoc.BatchNo;
                            exp.ExpiryDate = rdDoc.ExpDate;
                            if (expiryAmountTotal >= detail.EndingBalance)
                                if (detail.EndingBalance != null)
                                    exp.Amount = exp.Amount - (expiryAmountTotal - detail.EndingBalance.Value);
                            detail.Expiries[j] = null;
                            rdDoc.MoveNext();
                        }

                        disposal.Rewind();

                        int lossadjamt = 0;
                        for (int j = 0; j < disposalEntries; j++)
                        {
                            var adj = new Adjustment
                            {
                                Amount = Convert.ToInt32(disposal.Quantity),
                                TypeId = 11,
                                ReasonId = 39
                            };
                            lossadjamt += adj.Amount;

                            if (lossadjamt >= detail.LossAdjustment)
                                detail.LossAdjustment = lossadjamt;

                            detail.Adjustments[j] = null;
                            disposal.MoveNext();
                        }

                        var stockoutIndexedLists = StockoutIndexBuilder.Builder.GetStockOutHistory(hcmisItemID, _storeID);
                        var DOSPerStockOut = stockoutIndexedLists.Count();
                        detail.DaysOutOfStocks = new DaysOutOfStock[stockoutIndexedLists.Count()];

                        for (int j = 0; j < stockoutIndexedLists.Count(); j++)
                        {
                            var dos = new DaysOutOfStock();
                            dos.NumberOfDaysOutOfStock = 5;
                            dos.StockOutReasonId = 5;
                            detail.DaysOutOfStocks[j] = null;
                        }
                 }
                details.Add(detail);
            }
            order.OrderDetails = details.ToArray();
            orders.Add(order);
            // loop through each record and create order & order details objects
            return orders;
        }
        public Collection<Order> GetOrders()
        {
            var orders = new Collection<Order>();
            _tblRrf = (DataTable)gridItemsChoice.DataSource;
            tblRRF = (DataTable)gridItemsChoice.DataSource;

            var info = new GeneralInfo();
            info.LoadAll();

            var client1 = new ServiceRRFLookupClient();
            var req = new GetCurrentReportingPeriodRequest
            {
                Password = RRFServiceIntegration.PlitsPassword,
                UserName = RRFServiceIntegration.PlitsUserName,
                Supplychainunitid = RRFServiceIntegration.GetBranchID()
            };

            var branchReq = new GetBranchRRFormRequest
            {
                UserName = RRFServiceIntegration.PlitsUserName,
                Password = RRFServiceIntegration.PlitsPassword,
                Supplychainunitid = RRFServiceIntegration.GetBranchID()
            };

            var formReq = new GetFormsRequest
            {
                Password = RRFServiceIntegration.PlitsPassword,
                UserName = RRFServiceIntegration.PlitsUserName,
                Supplychainunitid = RRFServiceIntegration.GetBranchID()
            };

            var forms = client1.GetForms(formReq).GetFormsResult;
            var formid = forms[0].Id;

            var periods = client1.GetCurrentReportingPeriod(req).GetCurrentReportingPeriodResult;
            var period = periods[0].Id;

            branchReq.Formid = formid;
            branchReq.Reportingperiodid = period;

            var chosenCatId = 91;//RRFHelper.GetRrfCategoryId(cboStores.Text);
            var rrfs = client1.GetBranchRRForm(branchReq).GetBranchRRFormResult;
            var formCategories = rrfs.First().FormCategories;
            var chosenCategoryBody = formCategories.First(x => x.Id == chosenCatId); //Hard coding to be removed.
            var items = chosenCategoryBody.Pharmaceuticals; //Let's just store the items here (May not be required)

            var user = new User();
            user.LoadByPrimaryKey(CurrentContext.LoggedInUser.ID);
            var order = new HCMIS.Desktop.PLITSTransactionalService.Order
            {
                //Id = (int)rrf["Id"],
                RequestCompletedDate = BLL.DateTimeHelper.ServerDateTime,//Convert.ToDateTime(rrf["DateOfSubmissionEth"]),
                OrderCompletedBy = user.FullName,
                RequestVerifiedDate = BLL.DateTimeHelper.ServerDateTime,
                OrderTypeId = 1, //This needs to be changed to constant class or something. 1 - Regular, 2 - Emergency'
                SubmittedBy = user.FullName,
                SubmittedDate = BLL.DateTimeHelper.ServerDateTime,
                SupplyChainUnitId = Helpers.RRFServiceIntegration.GetBranchID(),
                OrderStatus = 1,//TODO: hardcoding
                FormId = formid,//TODO: hardcoding
                ReportingPeriodId = period  //TODO: hardcoding
            };

            // order.OrderTypeId = (int)tblrrf.Rows[i]["RRfTpyeId"];
            // Set order properties

            //order.FormId = rrfForm.Id; //Form.ID? or RRFForm.ID? - doesn't make sense
            //  order.ReportingPeriodId = periods[0].Id; //Asked again here?  Because RRFForm already contains this.

            var details = new Collection<OrderDetail>();
            int i = 0;
            var xx = tblRRF.Rows.Count;

            foreach (DataRow rrfLine in tblRRF.Rows)
            {
                var detail = new PLITSTransactionalService.OrderDetail();
                var hcmisItemID = Convert.ToInt32(rrfLine["ID"]);
                var rrFormPharmaceutical = items.FirstOrDefault(x => x.PharmaceuticalId == Convert.ToInt32(rrfLine["ID"]));
                if (rrfLine != null && rrFormPharmaceutical!=null)
                {

                    detail.BeginningBalance = Convert.ToInt32(rrfLine["BeginingBalance"]);
                    //DaysOutOfStock daysOfStockOut = new DaysOutOfStock() { NumberOfDaysOutOfStock = 1 };
                    //detail.DaysOutOfStocks.Add(daysOfStockOut);//Convert.ToInt32(rrfLine["DaysOutOfStock"]);
                    int eBalance = Convert.ToInt32(rrfLine["SOH"]);
                    detail.EndingBalance = eBalance == 0 ? 1 : eBalance;  //To make sure ending balance is not zero.
                    //detail.ItemId = Convert.ToInt32(rrfLine["ID"]); //Needs to come from the Code column of Items table.
                    detail.QuantityReceived = Convert.ToInt32(rrfLine["Received"]);
                    detail.QuantityOrdered = Convert.ToInt32(rrfLine["Quantity"]);
                    detail.LossAdjustment = Convert.ToInt32(rrfLine["LossAdj"]);

                    if (rrFormPharmaceutical != null)
                        detail.ItemId = rrFormPharmaceutical.ItemId;
                    else
                        throw new Exception("Item ID Mismatch");

                    var rdDoc = new ReceiveDoc();
                    var lossAndAdjustment = new LossAndAdjustment();
                    rdDoc.GetAllWithQuantityLeft(hcmisItemID, _storeID);
                    lossAndAdjustment.GetLossAdjustmentsForLastRRFPeriod(hcmisItemID, _storeID, periods[0].StartDate,
                                                                periods[0].EndDate);
                    int receiveDocEntries = rdDoc.RowCount;
                    int disposalEntries = lossAndAdjustment.RowCount;

                    rdDoc.Rewind();
                    for (var j = 0; j < receiveDocEntries; j++)
                    {
                        var exp = new Expiry
                                      {
                                          Amount = Convert.ToInt32(rdDoc.QuantityLeft),
                                          BatchNo = rdDoc.BatchNo,
                                          ExpiryDate = rdDoc.ExpDate
                                      };
                        detail.Expiries.Add(exp);
                        rdDoc.MoveNext();
                    }

                    lossAndAdjustment.Rewind();
                    for (var j = 0; j < disposalEntries; j++)
                    {
                        var adj = new Adjustment
                                      {Amount = Convert.ToInt32(lossAndAdjustment.Quantity), TypeId = 11, ReasonId = 39};

                        detail.Adjustments.Add(adj);
                        lossAndAdjustment.MoveNext();
                    }

                    var stockoutIndexedLists = StockoutIndexBuilder.Builder.GetStockOutHistory(hcmisItemID, _storeID);

                    for (int j = 0; j < stockoutIndexedLists.Count; j++)
                    {
                        var dos = new DaysOutOfStock
                                      {
                                          NumberOfDaysOutOfStock = stockoutIndexedLists[j].NumberOfDays,
                                          StockOutReasonId = 5
                                      };

                        detail.DaysOutOfStocks.Add(dos);
                    }

                    details.Add(detail);
                }

            }
            order.OrderDetails = details;
            orders.Add(order);

            // loop through each record and create order & order details objects
            return orders;

            //var user = new User();
            //user.LoadByPrimaryKey(NewMainWindow.LoggedInUser.ID);
            //foreach (DataRow rrf in tblRRF.Rows)
            //{
            //    var order = new HCMIS.Desktop.PLITSTransactionalService.Order
            //    {
            //        Id = (int)rrf["Id"],
            //        RequestCompletedDate = DateTime.Now,//Convert.ToDateTime(rrf["DateOfSubmissionEth"]),
            //        OrderCompletedBy = user.FullName,
            //        RequestVerifiedDate = DateTime.Now,
            //        OrderTypeId = 1, //This needs to be changed to constant class or something. 1 - Regular, 2 - Emergency'
            //        SubmittedBy = user.FullName,
            //        SubmittedDate = DateTime.Now,
            //        SupplyChainUnitId = RRFServiceIntegration.BranchID,
            //        OrderStatus = 1,
            //        FormId = formid
            //    };
            //    // order.OrderTypeId = (int)tblrrf.Rows[i]["RRfTpyeId"];
            //    // Set order properties

            //    //order.FormId = rrfForm.Id; //Form.ID? or RRFForm.ID? - doesn't make sense
            //    //  order.ReportingPeriodId = periods[0].Id; //Asked again here?  Because RRFForm already contains this.

            //    var details = new Collection<OrderDetail>();

            //    foreach (DataRow rrfLine in tblRRF.Rows)
            //    {
            //        var detail = new PLITSTransactionalService.OrderDetail();
            //        var rrFormPharmaceutical = items.FirstOrDefault(x => x.ItemId == Convert.ToInt32(rrfLine["ID"]));
            //        if (rrfLine != null && rrFormPharmaceutical != null)
            //        //detail.Adjustments[0].Amount =  (int)rrfLine["Adjustments"];
            //        {
            //            detail.BeginningBalance = Convert.ToInt32(rrfLine["BeginingBalance"]);
            //            //detail.DaysOutOfStocks = Convert.ToInt32(rrfLine["DaysOutOfStock"]);
            //            detail.EndingBalance = Convert.ToInt32(rrfLine["SOH"]);
            //            //detail.ItemId = Convert.ToInt32(rrfLine["ID"]); //Needs to come from the Code column of Items table.
            //            detail.QuantityReceived = Convert.ToInt32(rrfLine["Received"]);
            //            detail.QuantityOrdered = Convert.ToInt32(rrfLine["Quantity"]);
            //            detail.LossAdjustment = Convert.ToInt32(rrfLine["LossAdj"]);

            //            if (rrFormPharmaceutical != null)
            //                detail.PharmaceuticalId = rrFormPharmaceutical.PharmaceuticalId;
            //            //  detail.PharmaceuticalId = Convert.ToInt32(rrfLine["ItemID"]);
            //            // detail.PharmaceuticalId = pharId;

            //        }
            //        details.Add(detail);
            //    }
            //    order.OrderDetails = details;
            //    orders.Add(order);
            //}

            //// loop through each record and create order & order details objects
            //return orders;
        }