Ejemplo n.º 1
0
 private void updateLabels(OrderValidationResult validationResult)
 {
     chkBypassValidation.Visible = false;
     chkBypassValidation.Checked = false;
     switch (validationResult.MainType)
     {
         case OrderValidationType.Warning:
             lblErrorMessage.Text = "<br/>" + validationResult.Message + "<br/>Do you want to enter this order?";
             rblIgnoreWarning.Visible = true;
             rblIgnoreWarning.SelectedValue = "No";
             ViewState["IsRblIgnoreWarningVisible"] = true;
             break;
         case OrderValidationType.Invalid:
             lblErrorMessage.Text = "<br/>" + validationResult.Message;
             chkBypassValidation.Visible = true;
             break;
     }
 }
Ejemplo n.º 2
0
        public override OrderValidationResult Validate()
        {
            OrderValidationResult result = new OrderValidationResult(OrderValidationSubType.Success, "");
            short? decimals = null;
            decimal tickSize = 0M;

            IInstrumentExchange ie = getInstrumentExchange(true);
            if (ie != null)
            {
                decimals = ie.NumberOfDecimals;
                tickSize = ie.TickSize;
            }

            if (decimals == null && Route != null && Route.Exchange != null)
                decimals = Route.Exchange.DefaultNumberOfDecimals;

            if (tickSize > 0 && this.OrderType == OrderTypes.SizeBased)
                AdjustToTickSize(tickSize);
            else if (this.OrderType == OrderTypes.SizeBased && this.RequestedInstrument.SecCategory.Key == SecCategories.Bond)
                AdjustToTickSize(((IBond)this.RequestedInstrument).NominalValue.Quantity);
            else if (decimals != null)
                SetNumberOfDecimals((short)decimals);
            return result;
        }
Ejemplo n.º 3
0
        private OrderValidationResult checkInstructionExists()
        {
            string message = "";
            OrderValidationResult retVal = new OrderValidationResult(OrderValidationSubType.Success, "");

            if (Side == Side.Sell)
            {
                IInstructionCollection instructions = ((IAccountTypeCustomer)Account).ActiveRebalanceInstructions;
                if (instructions != null && instructions.Count > 0)
                {
                    foreach (IInstruction instruction in instructions)
                    {
                        if (instruction.IsActive)
                        {
                            message = string.Format("This order can not be entered since the account {0} is in a rebalance instruction (status {1}).", Account.ShortName, instruction.DisplayStatus);
                            retVal = new OrderValidationResult(OrderValidationSubType.Invalid_InstructionExists, message);
                            break;
                        }
                    }
                }
            }
            return retVal;
        }
Ejemplo n.º 4
0
        private OrderValidationResult checkSideOrders()
        {
            string message = "";
            OrderValidationResult retVal = new OrderValidationResult(OrderValidationSubType.Success, "");
            OrderSideFilter opSideFilter = (Side == Side.Buy ? OrderSideFilter.Sell : OrderSideFilter.Buy);

            if (Account.OpenOrdersForAccount != null && Account.OpenOrdersForAccount.Count > 0)
            {
                IAccountOrderCollection col = Account.OpenOrdersForAccount.Filter(RequestedInstrument, opSideFilter);
                if (col != null && col.Count > 0)
                {
                    message = string.Format("Warning: a {0} order already exists for {1}.", opSideFilter.ToString(), RequestedInstrument.Name);
                    retVal = new OrderValidationResult(OrderValidationSubType.Warning_OppositeSideOrder, message);
                }
            }
            return retVal;
        }
Ejemplo n.º 5
0
        /// <summary>
        /// if closure -> check not another buy order already exists.
        /// </summary>
        /// <returns></returns>
        private OrderValidationResult checkBuyCloseOrders()
        {
            string message = "";
            OrderValidationResult retVal = new OrderValidationResult(OrderValidationSubType.Success, "");

            if (((IOrderSizeBased)this).IsClosure && Side == Side.Buy && Account.OpenOrdersForAccount != null && Account.OpenOrdersForAccount.Count > 0)
            {
                OrderSideFilter sideFilter = OrderSideFilter.Buy;
                IAccountOrderCollection col = Account.OpenOrdersForAccount.Filter(RequestedInstrument, sideFilter);
                if (col != null && col.Count > 0)
                {
                    message = string.Format("Warning: {0} buy order(s) with a total size of {1} already exists for {2}.",
                        col.Count, col.TotalSize(RequestedInstrument), RequestedInstrument.Name);
                    retVal = new OrderValidationResult(OrderValidationSubType.Warning_BuyCloseOrderAlreadyExists, message);
                }
            }
            return retVal;
        }
Ejemplo n.º 6
0
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public virtual OrderValidationResult Validate()
        {
            // Buy  -> Check Cash (Buying Power)
            // Sell -> Check the Positions

            string message = "";
            OrderValidationResult retVal = new OrderValidationResult(OrderValidationSubType.Success, "");

            //Check if an instruction exist - Invalid_InstructionExists
            retVal = checkInstructionExists();
            if (retVal.Type != OrderValidationSubType.Success)
                return retVal;

            if (Side == Side.Buy)
            {
                if (!Account.AccountOwner.IsStichting)
                {
                    // check the Cash -> Buying Power check
                    // BP = All Cash (incl cash management fund) - Open Orders - Open Trades (Not Approved)
                    Money currentOrderAmount;
                    Money totalCashAmount;
                    string oldPriceWarning = "";

                    if (!IsMonetary && ((ISecurityOrder)this).TradedInstrument.SecCategory.Key == SecCategories.CashManagementFund)
                        totalCashAmount = Account.TotalPositionAmount(PositionAmountReturnValue.Cash);
                    else
                        totalCashAmount = Account.TotalPositionAmount(PositionAmountReturnValue.BothCash);

                    if (totalCashAmount == null || totalCashAmount.IsZero)
                    {
                        message = string.Format("This order ({0}) can not be entered since there is no cash.", Value.ToString());
                        return new OrderValidationResult(OrderValidationSubType.Invalid_NoCash, message);
                    }

                    if (IsSizeBased)
                    {
                        // if closure -> check not another buy order already exists.
                        OrderValidationResult buyCloseCheck = checkBuyCloseOrders();
                        if (buyCloseCheck.Type != OrderValidationSubType.Success)
                            return buyCloseCheck;

                        // Get the Price of the Instrument
                        IPriceDetail priceDetail = RequestedInstrument.CurrentPrice;

                        if (priceDetail == null)
                        {
                            message = string.Format("The order validation is not very accurate since no current price is available for {0}.", Value.Underlying.Name);
                            return new OrderValidationResult(OrderValidationSubType.Warning_NoCurrentPrice, message);
                        }
                        else
                        {
                            Money accruedInterest = ((ISecurityOrder)this).AccruedInterest;
                            currentOrderAmount = ((Money)(Value.CalculateAmount(priceDetail.Price) + Commission + accruedInterest)).CurrentBaseAmount;
                            if (priceDetail.IsOldDate)
                            {
                                oldPriceWarning = string.Format("The order validation is not very accurate since the last available price ({0}) is from {1}.", priceDetail.Price.ToString(), priceDetail.Date.ToShortDateString());
                            }
                        }
                    }
                    else
                    {
                        currentOrderAmount = GrossAmountBase;

                        //// Check when Foreign currency amount -> if foreign currency is available
                        if (!Value.Underlying.ToCurrency.IsBase)
                        {
                            ICashPosition posFx = Account.Portfolio.PortfolioCashGL.GetPosition(Value.Underlying.ToCurrency);
                            Money orderAmtFx = Account.OpenOrdersForAccount.TotalAmountInSpecifiedNominalCurrency((ICurrency)Value.Underlying);
                            if (posFx == null)
                            {
                                message = string.Format("This order ({0}) can not be placed since the account doesn't have a {1} position.", GrossAmount.DisplayString, Value.Underlying.Name);
                                retVal = new OrderValidationResult(OrderValidationSubType.Invalid_NoCash, message);
                            }
                            else if (!((Money)(posFx.SettledSize - orderAmtFx - GrossAmount)).Sign)
                            {
                                string messageOpenOrders = "";
                                if (orderAmtFx != null && orderAmtFx.IsNotZero)
                                    messageOpenOrders = string.Format(" minus the open order amount ({0}) in {1}", orderAmtFx.ToString(), Value.Underlying.Name);
                                message = string.Format("This order ({0}) exceeds the current {1} cash amount ({2}){3}.", GrossAmount.DisplayString, Value.Underlying.Name, posFx.SettledSize.ToString(), messageOpenOrders);
                                retVal = new OrderValidationResult(OrderValidationSubType.Invalid_NotEnoughCash, message);
                            }
                            if (retVal.Type != OrderValidationSubType.Success)
                            {
                                retVal.Message += Environment.NewLine + string.Format("Place a {0} order instead.", Account.AccountOwner.StichtingDetails.BaseCurrency.ToString());
                                return retVal;
                            }
                        }
                    }

                    // Consider both Buy & Sell orders
                    Money openOrderAmount = Account.OpenOrderAmount(OpenOrderAmountReturnValue.Gross);
                    if (!((Money)(totalCashAmount - openOrderAmount - currentOrderAmount)).Sign)
                    {
                        if (openOrderAmount != null && openOrderAmount.IsNotZero)
                            message = string.Format(" minus the open order amount ({0})", openOrderAmount.DisplayString);
                        message = string.Format("This order ({0}) exceeds the total cash amount ({1}){2}.", currentOrderAmount.DisplayString, totalCashAmount.DisplayString, message);
                        retVal = new OrderValidationResult(OrderValidationSubType.Invalid_NotEnoughCash, message);
                    }

                    retVal.Message += oldPriceWarning;
                    if (oldPriceWarning != string.Empty && retVal.Type == OrderValidationSubType.Success)
                    {
                        retVal.Type = OrderValidationSubType.Warning_OldPrice;
                    }
                }
            }
            else
            {
                // Get the current Position size
                InstrumentSize positionSize = null;
                IFundPosition position = Account.Portfolio.PortfolioInstrument.GetPosition((ITradeableInstrument) RequestedInstrument);
                if (position != null)
                    positionSize = position.Size;

                if (positionSize == null || positionSize.IsZero)
                {
                    message = string.Format("You tried to sell {0} but there are no positions found.", RequestedInstrument.Name);
                    return new OrderValidationResult(OrderValidationSubType.Invalid_NoPosition, message);
                }

                // Get the positions size of the order
                PredictedSize predSize;
                if (!IsSizeBased)
                {
                    // Amount based -> Get the Price/ExRate
                    predSize = RequestedInstrument.PredictSize(Amount);

                    // If there is no Price/ExRate found -> warning
                    if (predSize.Status == PredictedSizeReturnValue.NoRate)
                    {
                        message = string.Format("The order validation is not very accurate since no current {0} is available for {1}.", (RequestedInstrument.IsCash ? "exchangerate" : "price"), Value.Underlying.Name);
                        return new OrderValidationResult(OrderValidationSubType.Warning_NoCurrentPrice, message);
                    }
                }
                else
                {
                    predSize = new PredictedSize(Value, DateTime.Now);
                }

                // Get the open order size
                InstrumentSize openOrderSize = null;
                if (Account.OpenOrdersForAccount != null && Account.OpenOrdersForAccount.Count > 0)
                    openOrderSize = Account.OpenOrdersForAccount.TotalSize(RequestedInstrument);

                if (!((InstrumentSize)(positionSize + (predSize.Size + openOrderSize))).Sign)
                {
                    message = string.Format("You tried to sell {0} {1} but in the portfolio only {2} positions were found", predSize.Size.Abs().ToString(), RequestedInstrument.Name, positionSize.ToString());
                    if (openOrderSize != null && openOrderSize.IsNotZero)
                        message += Environment.NewLine + string.Format(" and order(s) existed for {0}.", openOrderSize.ToString());
                    else
                        message += ".";
                    retVal = new OrderValidationResult(OrderValidationSubType.Invalid_NotEnoughPosition, message);
                }

                if (predSize.Status == PredictedSizeReturnValue.OldRateDate)
                {
                    retVal.Message += (retVal.Message == string.Empty ? "" : Environment.NewLine) + string.Format("The order validation is not very accurate since the last available {0} ({1}) is from {2}.", (RequestedInstrument.IsCash ? "exchangerate" : "price"), predSize.Rate, predSize.RateDate.ToShortDateString());
                    if (retVal.Type == OrderValidationSubType.Success)
                    {
                        retVal.Type = OrderValidationSubType.Warning_OldPrice;
                    }
                }
            }

            // Check opposite orders
            OrderValidationResult sideCheck = checkSideOrders();
            if (sideCheck.Type != OrderValidationSubType.Success)
            {
                retVal.Message += (retVal.Message == string.Empty ? "" : Environment.NewLine) + sideCheck.Message;
                if (retVal.Type == OrderValidationSubType.Success)
                {
                    retVal.Type = sideCheck.Type;
                }
            }

            return retVal;
        }
Ejemplo n.º 7
0
 private void updateLabels(OrderValidationResult validationResult)
 {
     cbBypassValidation.Visible = false;
     cbBypassValidation.Checked = false;
     switch (validationResult.MainType)
     {
         case OrderValidationType.Warning:
             elbErrorMessage.Text = validationResult.Message + "<br/>Do you want to enter this order?";
             rblIgnoreWarning.Visible = true;
             rblIgnoreWarning.SelectedValue = "No";
             ViewState["IsRblIgnoreWarningVisible"] = true;
             break;
         case OrderValidationType.Invalid:
             elbErrorMessage.Text = validationResult.Message;
             cbBypassValidation.Visible = SecurityManager.IsCurrentUserInRole("Asset Manager: Manual Order Bypass Validation");
             break;
     }
 }
Ejemplo n.º 8
0
        public static OrderValidationResult PlaceOrder(
                                                int accountId, 
                                                int instrumentId, 
                                                Side side,
                                                bool isAmountBased, 
                                                decimal size,
                                                decimal amount,
                                                int currencyId,
                                                bool isValueInclComm,
                                                bool ignoreWarnings,
                                                bool bypassValidation)
        {
            OrderValidationResult validationResult = new OrderValidationResult(OrderValidationSubType.Invalid_NotValidated, "This order has not been validated.");
            IDalSession session = NHSessionFactory.CreateSession();

            try
            {
                IAccountTypeInternal account = (IAccountTypeInternal)AccountMapper.GetAccount(session, accountId);
                IInstrument instrument = InstrumentMapper.GetInstrument(session, instrumentId);
                //FeeFactory fee = FeeFactory.GetInstance(session);
                Order order;
                decimal sign = (side == Side.Sell ? -1 : 1);

                if (!isAmountBased)
                {
                    InstrumentSize value = new InstrumentSize(sign * size, instrument);
                    order = new OrderSizeBased(account, value, false, null, true);
                }
                else
                {
                    ICurrency currency = InstrumentMapper.GetCurrency(session, currencyId);
                    if (currency == null)
                        currency = ((ITradeableInstrument)instrument).CurrencyNominal;
                    Money value = new Money(sign * amount, currency);
                    order = new OrderAmountBased(account, value, instrument, isValueInclComm, null, true);
                }

                // Do Validation
                if (bypassValidation)
                    validationResult = new OrderValidationResult(OrderValidationSubType.Success, "");
                else
                    validationResult = order.Validate();

                if (validationResult.MainType == OrderValidationType.Success ||
                   (validationResult.MainType == OrderValidationType.Warning && ignoreWarnings))
                {
                    OrderMapper.Insert(session, order);
                    validationResult = new OrderValidationResult(OrderValidationSubType.Success, "");
                }
            }
            finally
            {
                session.Close();
            }

            return validationResult;
        }
Ejemplo n.º 9
0
        public static OrderValidationResult PlaceOrder(
                                                int accountId, 
                                                int instrumentId, 
                                                Side side,
                                                bool isAmountBased, 
                                                decimal size,
                                                decimal amount,
                                                int currencyId,
                                                bool isValueInclComm,
                                                bool noCharges,
                                                bool ignoreWarnings,
                                                bool bypassValidation)
        {
            OrderValidationResult validationResult = new OrderValidationResult(OrderValidationSubType.Invalid_NotValidated, "This order has not been validated.");
            IDalSession session = NHSessionFactory.CreateSession();

            try
            {
                IAccountTypeCustomer account = (IAccountTypeCustomer)AccountMapper.GetAccount(session, accountId);
                IInstrument instrument = InstrumentMapper.GetInstrument(session, instrumentId);
                FeeFactory fee = FeeFactory.GetInstance(session);
                Order order;
                decimal sign = (side == Side.Sell ? -1 : 1);

                if (!isAmountBased)
                {
                    InstrumentSize value = new InstrumentSize(sign * size, instrument);
                    order = new OrderSizeBased(account, value, false, fee, noCharges);
                }
                else
                {
                    ICurrency currency = InstrumentMapper.GetCurrency(session, currencyId);
                    if (currency == null)
                        currency = ((ITradeableInstrument)instrument).CurrencyNominal;
                    if (!getCurrencies(account, instrument).Contains(currency))
                        throw new ArgumentException(
                            string.Format("Invalid currency ({0}). Currency should be either the base currency or the instrument currency.",
                                          currency.Symbol));
                    Money value = new Money(sign * amount, currency);
                    order = new OrderAmountBased(account, value, instrument, isValueInclComm, fee, noCharges);
                }

                // Do Validation
                if (bypassValidation)
                    validationResult = new OrderValidationResult(OrderValidationSubType.Success, "");
                else
                    validationResult = order.Validate();

                if (validationResult.MainType == OrderValidationType.Success ||
                   (validationResult.MainType == OrderValidationType.Warning && ignoreWarnings))
                {
                    OrderMapper.Insert(session, order);
                    validationResult = new OrderValidationResult(OrderValidationSubType.Success, "");
                }
            }
            finally
            {
                session.Close();
            }

            return validationResult;
        }