Example #1
0
 public FundPositionHistorical(IFundPortfolioHistorical parent, InstrumentSize size, Price price, Decimal rate)
 {
     this.Parent = parent;
     this.Size = size;
     this.Price = price;
     this.rate = rate;
 }
Example #2
0
        /// <summary>
        /// Constructor for creating a test FeeClient object
        /// </summary>
        /// <param name="account"></param>
        /// <param name="instrument"></param>
        /// <param name="side"></param>
        /// <param name="actiontype"></param>
        /// <param name="transactionDate"></param>
        /// <param name="issizebased"></param>
        /// <param name="orderValue"></param>
        /// <param name="amount"></param>
        /// <param name="price"></param>
        /// <param name="ordercurrency"></param>
        /// <param name="isValueInclComm"></param>
        public CommClient(IAccountTypeInternal account,IInstrument instrument, Side side, OrderActionTypes actiontype, 
                         DateTime transactionDate, bool issizebased, InstrumentSize orderValue, Money amount, Price price,
                         ICurrency ordercurrency, bool isValueInclComm)
        {
            if (account == null)
                throw new ApplicationException("It is not possible to calculate the commission when the account is unknown.");

            if (instrument == null)
                throw new ApplicationException("It is not possible to calculate the commission when the instrument value is unknown.");

            this.account = account;
            this.instrument = instrument;
            this.Side = side;
            this.ActionType = actiontype;
            this.TransactionDate = transactionDate;
            this.IsSizeBased = issizebased;
            this.OriginalOrderType = issizebased ? BaseOrderTypes.SizeBased : BaseOrderTypes.AmountBased;
            this.Value = orderValue;
            this.amount = amount;
            this.Price = price;
            this.OrderCurrency = ordercurrency;
            this.IsValueInclComm = isValueInclComm;

            type = CommClientType.Test;
        }
Example #3
0
 public CrumbleTransaction(IOrder order, ICrumbleAccount acctA, IAccount acctB,
         InstrumentSize valueSize, Price price, decimal exRate, DateTime transactionDate,
         DateTime transactionDateTime, Decimal ServiceChargePercentage, Side txSide, ITradingJournalEntry tradingJournalEntry,
         IGLLookupRecords lookups, ListOfTransactionComponents[] components)
     : base(order, acctA, acctB, valueSize, price, exRate, transactionDate, transactionDateTime, ServiceChargePercentage,
         txSide, tradingJournalEntry, lookups, components)
 {
 }
Example #4
0
 public InstrumentConversion(IAccountTypeInternal acctA, IAccount acctB,
         InstrumentSize valueSize, InstrumentSize convertedInstrumentSize,
         decimal exRate, IInstrumentHistory instrumentTransformation, 
         ITradingJournalEntry tradingJournalEntry)
     : this(acctA, acctB, valueSize, convertedInstrumentSize, null,
         exRate, instrumentTransformation, tradingJournalEntry, null)
 {
 }
Example #5
0
        /// <summary>
        /// This method tries to find a commission rule based on the parameters entered
        /// </summary>
        /// <param name="saccount">Account number</param>
        /// <param name="sinstrument">Instrument</param>
        /// <param name="sordervalue">Order value</param>
        /// <param name="samount">Amount</param>
        /// <param name="sprice">Price</param>
        public static string CalculateAccruedInterest(int instrumentId,
            DateTime settlementDate, BaseOrderTypes orderType,
            decimal amountQuantity, decimal sizeQuantity, decimal priceQuantity,
            int exchangeId)
        {
            string result = "";

            try
            {

                using (IDalSession session = NHSessionFactory.CreateSession())
                {
                    InstrumentSize size = null;
                    IBond instrument = (IBond)InstrumentMapper.GetInstrument(session, instrumentId);
                    IExchange exchange = null;
                    if (instrument == null)
                        throw new ApplicationException("select a valid bond");

                    if (exchangeId != 0 && exchangeId != int.MinValue)
                        exchange = ExchangeMapper.GetExchange(session, exchangeId);

                    ICurrency defcurrency = instrument.CurrencyNominal;
                    Price price = null;
                    if (priceQuantity != 0M)
                        price = new Price(priceQuantity, defcurrency, instrument);
                    else if (instrument.CurrentPrice != null)
                        price = instrument.CurrentPrice.Price;

                    if (!(price != null && price.IsNotZero))
                        throw new ApplicationException("There is no price");

                    if (orderType == BaseOrderTypes.AmountBased)
                    {
                        Money amount = new Money(amountQuantity, defcurrency);
                        size = instrument.CalculateSizeBackwards(amount, price, settlementDate);
                    }
                    else
                        size = new InstrumentSize(sizeQuantity, instrument);

                    AccruedInterestDetails accInt = instrument.AccruedInterest(size, settlementDate, exchange);
                    Money calcAmount = size.CalculateAmount(price);

                    if (accInt.IsRelevant)
                        result = accInt.DisplayString + string.Format("<br>Size: {0}<br>Amount: {1}<br>Settlement Date: {2}",
                        size.Quantity, calcAmount.Quantity, settlementDate.ToString("dd-MM-yyyy"));
                    else
                        result = "Accrued interest is not relevant";
                }
            }
            catch (Exception ex)
            {
                result = "Error during accrued interest test: " + ex.Message;
            }
            return result;
        }
Example #6
0
 protected SecurityOrder(IAccountTypeInternal account, InstrumentSize value, ITradeableInstrument tradedInstrument, bool doNotChargeCommission)
     : base(account, value)
 {
     if (tradedInstrument == null)
     {
         throw new ApplicationException("TradedInstrument is mandatory on an order.");
     }
     this.tradedInstrument = tradedInstrument;
     this.DoNotChargeCommission = doNotChargeCommission;
     if (DoNotChargeCommission)
         this.OrderInfo = "No commission charged";
 }
Example #7
0
 public TransactionNTM(IAccountTypeInternal acctA, IAccount acctB,
 InstrumentSize valueSize,
 Price price, decimal exRate, DateTime transactionDate, DateTime transactionDateTime,
 Decimal ServiceChargePercentage, Side txSide,
 ITradingJournalEntry tradingJournalEntry,
 IGLLookupRecords lookups, ListOfTransactionComponents[] components, string description)
     : base(acctA, acctB, valueSize, price, exRate, transactionDate,
             transactionDateTime, ServiceChargePercentage, txSide,
             tradingJournalEntry, lookups, components)
 {
     this.Description = description;
 }
Example #8
0
        public CommClient(ITransactionOrder transaction, InstrumentSize newValue)
        {
            if (transaction == null)
                throw new ApplicationException("It is not possible to calculate the commission when the transaction is null.");

            if (newValue == null)
                throw new ApplicationException("It is not possible to calculate the commission when the transaction value is null.");

            this.transaction = transaction;
            this.orderValue = newValue;
            this.amount = newValue.GetMoney();
            type = CommClientType.Transaction;
        }
 public BondCouponPaymentDailyCalculation(
     IBondCouponPayment parent, DateTime calcDate, DateTime settlementDate, 
     InstrumentSize positionSize, Money calculatedAccruedInterestUpToDate,
     IList<IBondCouponPaymentDailyCalculation> oldCalculations)
 {
     this.Parent = parent;
     this.Position = this.Parent.Position;
     this.CalcDate = calcDate;
     this.SettlementDate = settlementDate;
     this.PositionSize = positionSize;
     this.CalculatedAccruedInterestUpToDate = calculatedAccruedInterestUpToDate;
     this.OldCalculations = oldCalculations;
     CalculateDailyInterest();
 }
Example #10
0
 public BonusDistribution(IAccountTypeInternal acctA, IAccount acctB,
 InstrumentSize valueSize,
 Price price, decimal exRate, DateTime transactionDate, DateTime transactionDateTime,
 Decimal ServiceChargePercentage, Side txSide,
 ICorporateActionBonusDistribution bonusDistributionDetails, ITradingJournalEntry tradingJournalEntry,
 IGLLookupRecords lookups, ListOfTransactionComponents[] components)
     : base(acctA, acctB, valueSize,
          price, exRate, transactionDate, transactionDateTime,
          ServiceChargePercentage, txSide,
          tradingJournalEntry,
          lookups, components)
 {
     this.CorporateActionType = CorporateActionTypes.BonusDistribution;
     this.CorporateActionDetails = bonusDistributionDetails;
 }
Example #11
0
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="dividendDetails">The details of the cash dividend (date, price)</param>
        /// <param name="units">The total number of units over which dividend is paid</param>
        public CashDividend(IAccountTypeCustomer account, IMemorialBooking journalEntry, string description, decimal taxPercentage, IDividendHistory dividendDetails, InstrumentSize units, IGLLookupRecords lookups)
            : base(account, journalEntry, description, taxPercentage)
        {
            if (dividendDetails == null)
                throw new ApplicationException("Dividend details are mandatory.");

            if (units == null || units.IsZero)
                throw new ApplicationException("The number of units is mandatory.");

            this.DividendDetails = dividendDetails;
            this.UnitsInPossession = units;
            //this.CashGeneratingInstrument = dividendDetails.Instrument;

            createComponents(lookups);
        }
Example #12
0
        internal StgSizeOrder(IStgAmtOrder childOrder, InstrumentSize value, Price price, IOrderRouteMapper routeMapper)
            : base(childOrder.Account, value, false)
        {
            // Used for TypeConversion

            // Some check
            if (childOrder.ParentOrder != null)
                throw new ApplicationException("This order has a parent order and can no longer be converted.");

            this.IsTypeConverted = true;
            setInitialValues(routeMapper);
            this.price = price;
            this.ChildOrders.Add(childOrder);
            childOrder.Approve();
            //this.CommissionDetails = childOrder.CommissionDetails;
            this.exRate = childOrder.ExRate;
            Validate();
        }
        public static void UpdateExtPosition(DateTime date, decimal Size, int custodianID, int original_Key)
        {
            IDalSession session = NHSessionFactory.CreateSession();

            ITradeableInstrument instrument = (ITradeableInstrument)InstrumentMapper.GetInstrument(session, original_Key);
            ExtCustodian custodian = ExtCustodianMapper.GetExtCustodian(session, custodianID);
            ExtPosition position = ExtCustodianMapper.GetExtCustodianPosition(session, custodian, instrument, date);

            InstrumentSize size = new InstrumentSize(Size, instrument);

            if (position == null)
                position = new ExtPosition(custodian, size, date);
            else
                position.Size = size;

            ExtCustodianMapper.InsertOrUpdate(session, position);

            session.Close();
        }
Example #14
0
        public InstrumentConversion(IAccountTypeInternal acctA, IAccount acctB,
                InstrumentSize valueSize, InstrumentSize convertedInstrumentSize, Money additionalCash,
                decimal exRate, IInstrumentHistory instrumentTransformation,
                ITradingJournalEntry tradingJournalEntry, IGLLookupRecords lookups)
            : base(acctA, acctB, valueSize, valueSize.GetPrice(0M), exRate,
                instrumentTransformation.ChangeDate, instrumentTransformation.ChangeDate, 0M,
                (valueSize.Sign ? Side.XI : Side.XO), tradingJournalEntry, lookups, null)
        {
            if (instrumentTransformation == null)
                throw new ApplicationException("Corporate action information is missing");

            if (!(valueSize != null && valueSize.IsNotZero && convertedInstrumentSize != null && convertedInstrumentSize.IsNotZero))
                throw new ApplicationException("Not all instrument information for this corporate action is available, both instruments have to be supplied");

            if (valueSize.Underlying.Equals(convertedInstrumentSize.Underlying))
                throw new ApplicationException("Both instruments can not be the same in a corporate action");

            if (valueSize.Sign.Equals(convertedInstrumentSize.Sign))
                throw new ApplicationException("Both instruments can not have the same side in a corporate action");

            IInstrumentsHistoryConversion conversion = (IInstrumentsHistoryConversion)instrumentTransformation;
            if (!(conversion.Instrument.Equals(valueSize.Underlying) && conversion.NewInstrument.Equals(convertedInstrumentSize.Underlying)))
                throw new ApplicationException("Corporate action does not equal the instrument history data");

            decimal diff = (convertedInstrumentSize.Abs().Quantity / valueSize.Abs().Quantity) - conversion.ConversionRate;
            if (diff != 0)
                throw new ApplicationException("Sizes do not correspond with conversion rate of the Corporate action");

            if (additionalCash != null && additionalCash.IsNotZero)
            {
                ListOfTransactionComponents[] components = new ListOfTransactionComponents[1];
                components[0] = new ListOfTransactionComponents() { ComponentType = BookingComponentTypes.Conversion, ComponentValue = additionalCash };
                createComponents(lookups, components);

            }

            this.CorporateActionType = CorporateActionTypes.Conversion;

            ConvertedInstrumentSize = convertedInstrumentSize;
            CorporateActionType = instrumentTransformation.CorporateActionType;
            InstrumentTransformation = instrumentTransformation;
        }
Example #15
0
 internal AggregatedCashValuation(ValuationCollection cashValuations, bool aggregateToBase)
 {
     bool hasInitialized = false;
     if (aggregateToBase)
     {
         foreach (IValuation valuation in cashValuations)
         {
             if (valuation.Instrument.IsCash)
             {
                 if (this.account == null)
                 {
                     this.account = valuation.Account;
                     this.date = valuation.Date;
                     this.key = valuation.Key;
                     this.marketRate = 1M;
                     this.avgOpenExRate = 1M;
                     baseCurrency = ((ICurrency)valuation.Instrument).BaseCurrency;
                     price = new Price(1M, baseCurrency, baseCurrency);
                     this.bookPrice = price;
                     this.costPrice = price;
                     this.marketPrice = price;
                     this.displayInstrumentsCategory = valuation.DisplayInstrumentsCategory;
                     this.AssetClass = valuation.ValuationMutation.AssetClass;
                     this.ValuationMutation = valuation.ValuationMutation;
                 }
                 this.size += valuation.BaseMarketValue;
                 this.bookValue += valuation.BookValue;
                 this.bookChange += valuation.BookChange;
                 this.deposit += valuation.Deposit;
                 this.withDrawal += valuation.WithDrawal;
                 if (!valuation.ValuationMutation.IsSecurityValuationMutation)
                 {
                     this.depositToDate += ((IMonetaryValuationMutation)valuation.ValuationMutation).DepositToDate;
                     this.withDrawalToDate += ((IMonetaryValuationMutation)valuation.ValuationMutation).WithDrawalToDate;
                 }
                 hasInitialized = true;
             }
         }
     }
     if (!hasInitialized)
         throw new ApplicationException("Class AggregatedCashValuation could not be initialized");
 }
Example #16
0
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="account">User account</param>
        /// <param name="value">Instrument size</param>
        /// <param name="isClosure">Is this order closing a position.</param>
        /// <param name="feeFactory">The set of rules to use for calculating transaction costs.</param>
        /// <param name="doNotChargeCommission">parameter that decides whether commission should be charged</param>
        /// <param name="actionType">The action type that created this order.</param>
        public OrderSizeBased(IAccountTypeInternal account, InstrumentSize value, bool isClosure, IFeeFactory feeFactory, bool doNotChargeCommission, OrderActionTypes actionType)
            : base(account, value, (ITradeableInstrument)value.Underlying, doNotChargeCommission)
        {
            this.ActionType = actionType;
            this.isClosure = isClosure;
            setCommission(feeFactory);

            // Accrued Interest for Client Orders
            if (account.IsAccountTypeCustomer && TradedInstrument.SecCategory.Key == SecCategories.Bond)
            {
                IBond bond = (IBond)TradedInstrument;
                if (bond.DoesPayInterest)
                {
                    IExchange exchange = bond.DefaultExchange ?? bond.HomeExchange;
                    AccruedInterestDetails calc = bond.AccruedInterest(value, bond.GetSettlementDate(DateTime.Today, exchange), exchange);
                    if (calc.IsRelevant)
                        this.AccruedInterest = calc.AccruedInterest.Abs() * (decimal)this.Side * -1M;
                }
            }
        }
        public CorporateActionStockDividend(IAccountTypeInternal acctA, IAccount acctB,
        InstrumentSize valueSize, Price price, decimal exRate, DateTime transactionDate,
        IDividendHistory dividendDetails, InstrumentSize previousSize,
        ITradingJournalEntry tradingJournalEntry)
            : base(acctA, acctB, valueSize,
                 price, exRate, transactionDate, transactionDate,
                 0M, valueSize.Sign ? Side.XI : Side.XO,
                 tradingJournalEntry, null, null)
        {
            if (dividendDetails == null)
                throw new ApplicationException("Dividend details are mandatory when creating a stock dividend corporate action");

            if (previousSize == null)
                throw new ApplicationException("The units in possession are mandatory when creating a stock dividend corporate action");
            else if (previousSize.IsZero)
                throw new ApplicationException("The units can not be zero when creating a stock dividend corporate action");

            this.CorporateActionType = CorporateActionTypes.StockDividend;
            this.CorporateActionDetails = dividendDetails;
            this.PreviousSize = previousSize;
        }
Example #18
0
        public static void CheckMaximalRoundOffError(bool isSizeBased, InstrumentSize size, Money amount, Price price, Money accruedInterest, Side side)
        {
            if (!isSizeBased)
            {
                InstrumentSize calcAmt = size.CalculateAmount(price) * (decimal)side * -1M;
                //if (accruedInterest != null && accruedInterest.IsNotZero)
                //{
                //    accruedInterest = accruedInterest.Abs() * (decimal)side * -1M;
                //    calcAmt += accruedInterest;
                //}

                InstrumentSize diff = (calcAmt.Abs() - amount.Abs());
                if (diff.IsNotZero && !diff.IsWithinTolerance(0.02m))
                {
                    decimal percLeft = diff.Abs().Quantity / amount.Abs().Quantity;
                    if (percLeft >= 0.05m)
                        throw new ApplicationException(string.Format(
                            "Price times Size ({0}) differs by {1}% from the provided Amount ({2}). Order cannot be filled.",
                            calcAmt.DisplayString, Math.Round(percLeft * 100m, 1), amount.DisplayString));
                }
            }
        }
Example #19
0
 public static decimal CalculateAccruedInterestAmount(int orderId, decimal size, DateTime settlementDate)
 {
     using (IDalSession session = NHSessionFactory.CreateSession())
     {
         decimal accruedInterest = 0;
         IStgOrder order = (IStgOrder)OrderMapper.GetOrder(session, orderId);
         if (order != null && order.RequestedInstrument.SecCategory.Key == SecCategories.Bond)
         {
             IBond bond = (IBond)order.RequestedInstrument;
             if (bond.DoesPayInterest)
             {
                 if (order.IsSizeBased)
                 {
                     InstrumentSize volume = new InstrumentSize(size, bond);
                     AccruedInterestDetails calc = bond.AccruedInterest(volume, settlementDate, null);
                     if (calc.IsRelevant)
                         accruedInterest = calc.AccruedInterest.Quantity;
                 }
             }
         }
         return accruedInterest;
     }
 }
Example #20
0
        public IOrderExecution Fill(InstrumentSize size, Price price, Money amount, decimal exRate,
            IAccount counterParty, DateTime transactionDate, DateTime transactionDateTime, IExchange exchange,
            bool isCompleteFill, Money serviceCharge, decimal serviceChargePercentage, Money accruedInterest,
            ITradingJournalEntry tradingJournalEntry, IGLLookupRecords lookups)
        {
            IOrderExecution returnValue = null;

            if (size == null || price == null || amount == null)
                throw new Exception("Size, Price and Amount are mandatory when filling the order.");

            if (IsFillable != OrderFillability.True)
                throw new ApplicationException("This Order is not fillable.");

            setSignServiceCharge(ref serviceCharge, ref serviceChargePercentage);
            if (accruedInterest != null && accruedInterest.IsNotZero)
                accruedInterest = accruedInterest.Abs() * (decimal)this.Side * -1M;
            CheckMaximalRoundOffError(IsSizeBased, size, amount, price, accruedInterest, this.Side);

            if (isCompleteFill)
            {
                // Check whether the order has not been filled before
                if (Transactions.Count > 0)
                    throw new ApplicationException("The order has already been filled and so it can not be a complete fill.");

                if (this.OpenValue.IsZero)
                    throw new ApplicationException("The open value of this order is zero.");

                InstrumentSize diff = getTradeDifferenceOpenValue(size, amount, serviceCharge, accruedInterest);
                if (diff.IsNotZero)
                {
                    const decimal maxAllowed = 0.05m;
                    // TickSize && NominalValue
                    decimal tickSize = 0M;
                    if (this.OrderType == OrderTypes.SizeBased)
                    {
                        IInstrumentExchange ie = getInstrumentExchange(exchange);
                        if (ie != null)
                            tickSize = ie.TickSize;
                    }
                    if (this.RequestedInstrument.SecCategory.Key == SecCategories.Bond)
                        tickSize = ((IBond)this.RequestedInstrument).NominalValue.Quantity;

                    if (!(tickSize > 0M && Math.Abs(diff.Quantity / tickSize) < 1M))
                    {
                        decimal fillRatio = diff.Abs().Quantity / this.OpenValue.Abs().Quantity;
                        if (fillRatio > maxAllowed)
                            throw new ApplicationException(
                                string.Format("The size of this transaction is different from the order size by more than {0:0.##}%.", maxAllowed * 100));
                    }
                }
                amount.XRate = exRate;
            }
            else
            {
                orderInitialCheck(ref amount, size, exRate, serviceCharge, accruedInterest);
            }

            this.IsCompleteFilled = isCompleteFill;
            orderCheckSide(this.Side, ref amount, ref size);
            checkServiceChargePercentage(serviceCharge, serviceChargePercentage, amount);

            ListOfTransactionComponents[] components = packageComponents(amount, serviceCharge, accruedInterest);

            returnValue = new OrderExecution(this, counterParty, size, price, exRate, transactionDate, transactionDateTime, serviceChargePercentage, tradingJournalEntry, lookups, components);
            fillOrder(returnValue, size, price, amount, serviceCharge, accruedInterest);
            return returnValue;
        }
Example #21
0
 private InstrumentSize getTradeDifferenceOpenValue(InstrumentSize size, Money amount, Money serviceCharge, Money accruedInterest)
 {
     InstrumentSize diff;
     if (IsSizeBased)
         diff = (this.OpenValue.Abs() - size.Abs());
     else
         diff = (this.OpenValue.Abs() - amount.Abs() + serviceCharge + accruedInterest);
     return diff;
 }
Example #22
0
 protected bool orderCheckSide(Side side, ref Money amount, ref InstrumentSize size)
 {
     if (side == Side.Buy)
     {
         size = size.Abs();
         amount = amount.Abs() * -1;
     }
     else
     {
         size = size.Abs() * -1;
         amount = amount.Abs();
     }
     return true;
 }
Example #23
0
        protected void orderInitialCheck(ref Money amount, InstrumentSize size, decimal exRate, Money serviceCharge, Money accruedInterest)
        {
            InstrumentSize diff = getTradeDifferenceOpenValue(size, amount, serviceCharge, accruedInterest);
            if (!diff.Sign)
            {
                if (diff < diff.Clone(-0.02m))
                    throw new ApplicationException("This size of the trade is larger than the order size.");
            }

            if (IsMonetary) // can not be partfilled
            {
                if (FilledValue != null)
                    throw new ApplicationException("Monetary orders can only be filled once.");
                if (!diff.IsWithinTolerance(0.02m))
                    throw new ApplicationException("Monetary orders can only be filled completely.");
            }
            else if (!(IsSizeBased)) // applies only to amount based orders
            {
                // If first fill -> check if size should not be equal to Order size
                if (FilledValue == null)
                {
                    if (diff.IsWithinTolerance(0.02m) && this.Amount != null)
                    {
                        amount = this.Amount;
                        // reduce it with servicecharge
                        amount = MoneyMath.AdjustAmountForServiceCharge(amount, serviceCharge, Side, MathOperator.Subtract);
                        // reduce it with accruedInterest
                        amount = MoneyMath.AdjustAmountForServiceCharge(amount, accruedInterest, Side, MathOperator.Subtract);
                    }
                }
            }

            amount.XRate = exRate;

            //bool approved = (route != null) ? route.ApproveTransactions : false;
            if (IsFillable != OrderFillability.True)
            {
                throw new ApplicationException("This Order is not fillable.");
            }
        }
Example #24
0
 /// <summary>
 /// Initializes a new instance of the <see cref="T:B4F.TotalGiro.Instruments.PredictedSize">PredictedSize</see> class.
 /// </summary>
 /// <param name="size">The predicted size</param>
 /// <param name="rateDate">The date of the used rate to predict the size</param>
 public PredictedSize(InstrumentSize size, DateTime rateDate)
 {
     this.size = size;
     this.rateDate = rateDate;
 }
Example #25
0
        /// <summary>
        /// Fills an order by setting the agreed size and price, exchange rate, counter party and transaction date.
        /// </summary>
        /// <param name="trade">The order to be filled</param>
        /// <param name="size">Size of the instrument</param>
        /// <param name="price">Agreed price of the instrument</param>
        /// <param name="amount">Amount of the order (=size * price)</param>
        /// <returns>True if it succeeded</returns>
        protected bool fillOrder(ITransactionOrder trade, InstrumentSize size, Price price, Money amount, Money serviceCharge, Money accruedInterest)
        {
            decimal ratio = 1m;
            Transactions.AddTransactionOrder(trade);
            FilledValue += fillOrderValue(size, amount, serviceCharge, accruedInterest);
            if (this.IsSecurity)
            {
                ((ISecurityOrder)this).ServiceCharge += serviceCharge;
                if (this.IsAmountBased)
                    ((ISecurityOrder)this).AccruedInterest += accruedInterest;
            }

            // If OrderExecution -> set FillRatio
            if (trade.TransactionType == TransactionTypes.Execution)
            {
                if (IsCompleteFilled)
                    // if order is already partly filled -> subtract rest
                    ratio = 1M - Transactions.TotalFillRatio();
                else
                {
                    InstrumentSize diff = PlacedValue.Abs() - fillOrderValue(size, amount, serviceCharge, accruedInterest).Abs();
                    if (diff.IsZero || diff.IsWithinTolerance(0.02M))
                        ratio = 1M;
                    else
                    {
                        ratio = fillOrderValue(size, amount, serviceCharge, accruedInterest).Abs().Quantity / PlacedValue.Abs().Quantity;
                        // If this trade filled the order (OpenSize = 0) -> take the remainder ratio
                        if (OpenValue.IsZero)
                        {
                            decimal var = ratio - (1M - getFillatioTransactions());
                            if (Math.Abs(var) < 0.0001M)
                                ratio = 1M - getFillatioTransactions();
                        }
                    }
                }
            }
            trade.FillRatio = ratio;
            OrderStateMachine.SetNewStatus(this, OrderStateEvents.Fill);

            //// If MoneyOrder on order -> set ExRate
            //if (IsMonetary)
            //{
            //    // Use the size as the amount -> because it is a conversion
            //    processMoneyFill(price, trade);
            //}

            return true;
        }
Example #26
0
 /// <summary>
 /// The value added with the ServiceCharge
 /// The following calculation has been used:
 /// side  servCh value  fillOrderValue
 /// ----  ---    -----  -----------
 /// buy    -5   -100     -105
 /// sell   -5    100      105
 /// </summary>
 internal override InstrumentSize fillOrderValue(InstrumentSize size, Money value, Money serviceCharge, Money accruedInterest)
 {
     Money orderValue = MoneyMath.AdjustAmountForServiceCharge(value * -1, serviceCharge, Side, MathOperator.Add);
     orderValue += (accruedInterest * -1);
     return (InstrumentSize)orderValue;
 }
Example #27
0
        protected virtual TransactionFillDetails getTransactionFillDetailsAmountBasedOrderByGoalSeek(
            Money grossAmount, Side side, bool isCommissionRelevant, bool isValueInclComm,
            DateTime settlementDate, Price price, IExchange exchange,
            ICommRule rule, ICommClient client, decimal servChargePerc, int precision)
        {
            decimal realAmount;
            decimal guess = grossAmount.Abs().CalculateSize(price).Quantity;
            FinancialMath.MaxCycles = 200;

            // Check -> use Commission
            bool useComm = true;
            bool useAddComm = false;
            if (!isCommissionRelevant || rule == null)
                useComm = false;

            if (useComm)
                useAddComm = (rule.AdditionalCalculation != null);

            realAmount = FinancialMath.GoalSeek(x =>
                new InstrumentSize(x, this).CalculateAmount(price).Quantity +
                (useComm ? rule.CommCalculation.Calculate(client.GetNewInstance(new InstrumentSize(x, this), price, (useAddComm ? rule.AdditionalCalculation.Calculate(client.GetNewInstance(new InstrumentSize(x, this), price)) : null))).Quantity : 0M) +
                (useAddComm ? rule.AdditionalCalculation.Calculate(client.GetNewInstance(new InstrumentSize(x, this), price)).Quantity : 0M) +
                (new InstrumentSize(x, this).CalculateAmount(price).Abs().Quantity * servChargePerc),
                grossAmount.Abs().Quantity, guess, precision);

            InstrumentSize size = new InstrumentSize(realAmount, this);
            Money amount = size.CalculateAmount(price);
            InstrumentSize cleanSize = amount.CalculateSize(price);

            Money servCh = (amount.Abs() * servChargePerc);
            Money comm = amount.ZeroedAmount();
            Money addComm = amount.ZeroedAmount();
            if (useComm)
            {
                if (rule.AdditionalCalculation != null)
                    addComm = rule.AdditionalCalculation.Calculate(client.GetNewInstance(cleanSize, price));
                comm = rule.CommCalculation.Calculate(client.GetNewInstance(cleanSize, price, addComm));

                // if sell -> comm is already in the amount
                if (side == Side.Sell && (comm + addComm) != null && (comm + addComm).IsNotZero)
                {
                    amount += (comm + addComm);
                    cleanSize = amount.CalculateSize(price);
                    if (!isValueInclComm)
                    {
                        if (rule.AdditionalCalculation != null)
                            addComm = rule.AdditionalCalculation.Calculate(client.GetNewInstance(cleanSize, price));
                        comm = rule.CommCalculation.Calculate(client.GetNewInstance(cleanSize, price, addComm));
                    }
                }
            }
            return new TransactionFillDetails(cleanSize, amount, null, servCh, servChargePerc, comm + addComm, grossAmount.Abs(), side);
        }
Example #28
0
 // Orphan instruments
 public PortfolioComponentView(InstrumentSize size)
     : this(size.Underlying, 0m, null)
 {
 }
        public static bool InitialiseConversion(int instrumentConversionId)
        {
            using (IDalSession session = NHSessionFactory.CreateSession())
            {
                bool success = false;
                int successCount = 0;
                IInstrumentsHistoryConversion conversion = InstrumentHistoryMapper.GetInstrumentConversion(session, instrumentConversionId);
                if (!conversion.IsInitialised)
                {
                    if (conversion.ChangeDate > DateTime.Today)
                        throw new ApplicationException("The change date is in the future.");

                    int journalId = int.Parse((string)(System.Configuration.ConfigurationManager.AppSettings.Get(@"DefaultTransactiesEUR")));
                    IJournal journal = JournalMapper.GetJournal(session, journalId);
                    IList<IHistoricalPosition> accountsWithPositionByDate = B4F.TotalGiro.MIS.StoredPositions.StoredPositionTransactionMapper.GetAccountsWithPositionByDate(session, conversion.ChangeDate, conversion.Instrument.Key);

                    if (accountsWithPositionByDate != null && accountsWithPositionByDate.Count > 0)
                    {
                        DateTime transactionDate = conversion.ChangeDate;
                        decimal exRate = ((ITradeableInstrument)conversion.Instrument).CurrencyNominal.ExchangeRate.Rate;

                        foreach (IHistoricalPosition hp in accountsWithPositionByDate)
                        {
                            if (!conversion.Conversions.Any(x => x.AccountA.Key == hp.Account.Key))
                            {
                                IDalSession session2 = NHSessionFactory.CreateSession();
                                IAccountTypeCustomer account = (IAccountTypeCustomer)AccountMapper.GetAccount(session2, hp.Account.Key);
                                InstrumentSize size = hp.ValueSize * -1M;
                                InstrumentSize newSize = new InstrumentSize(hp.ValueSize.Quantity * conversion.ConversionRate, conversion.NewInstrument);

                                if (size.IsNotZero)
                                {
                                    ITradingJournalEntry tradingJournalEntry = getNewBooking(session2, journal, transactionDate);
                                    IInstrumentConversion instConv = new InstrumentConversion(
                                        account, account.DefaultAccountforTransfer,
                                        size, newSize, exRate, conversion, tradingJournalEntry);
                                    if (session2.Insert(instConv))
                                        successCount++;
                                }
                                else
                                    successCount++;
                            }
                            else
                                successCount++;
                        }
                    }
                    if (accountsWithPositionByDate.Count == successCount)
                    {
                        conversion.IsInitialised = true;
                        session.InsertOrUpdate(conversion);
                        success = true;
                    }
                }
                return success;
            }
        }
Example #30
0
        /// <summary>
        /// Used by method <b>Calculate</b> on derived classes to perform the common part of the commission calculation.
        /// </summary>
        /// <param name="size">The size for which to calculate commission.</param>
        /// <param name="client">The order for which to calculate commission.</param>
        /// <returns>The value of the commission.</returns>
        protected Money calculateNormal(InstrumentSize size, ICommClient client)
        {
            Money result = new Money(0m, CommCurrency);
            InstrumentSize comSize = size.Abs();

            foreach (CommCalcLineSizeBased line in CommLines)
            {
                if (line.Envelops(comSize))
                {
                    result = line.Calculate(comSize);
                    SetCommissionInfoOnOrder(client, string.Format("Flat -> Size ({0}) {1} -> use {2}.", comSize.DisplayString, line.DisplayRange, line.LineDistinctives));
                    break;
                }
            }
            return addFixMinMax(result, client);
        }