예제 #1
0
        public static string[] ClosePositions(int[] positionIds, bool ignoreWarnings, bool noCharges)
        {
            IDalSession session = NHSessionFactory.CreateSession();
            ArrayList warningMessages = new ArrayList();
            string instrumentName = "";
            string accountName = "";

            try
            {
                IList<IFundPosition> positions = AccountMapper.GetFundPositions(session, positionIds);
                FeeFactory feeFactory = FeeFactory.GetInstance(session);

                ArrayList orders = new ArrayList();
                foreach (IFundPosition position in positions)
                {
                    instrumentName = string.Format("{0} ({1})", position.Instrument.Name, ((ITradeableInstrument)position.Instrument).Isin);
                    accountName = string.Format("{0} ({1})", position.Account.ShortName, position.Account.Number);

                    if (!AccountMapper.AccountStatusIsOpen(session, position.Account.Status))
                        throw new ApplicationException("Position cannot be closed for this account because the account's status is closed.");

                    Order order = new OrderSizeBased(position.Account, position.Size * (-1), true, feeFactory, noCharges);
                    OrderValidationResult validationResult = order.Validate();

                    if (validationResult.MainType == OrderValidationType.Success ||
                       (validationResult.MainType == OrderValidationType.Warning && ignoreWarnings))
                        orders.Add(order);
                    else if (validationResult.MainType == OrderValidationType.Warning)
                        warningMessages.Add(validationResult.Message);
                    else if (validationResult.MainType == OrderValidationType.Invalid)
                        throw new ApplicationException(validationResult.Message);
                }

                if (orders.Count > 0 && warningMessages.Count == 0)
                    OrderMapper.Insert(session, orders);
            }
            catch (Exception ex)
            {
                throw new ApplicationException(string.Format("{0} [Instrument: {1}, Account: {2}]", ex.Message, instrumentName, accountName));
            }
            finally
            {
                session.Close();
            }

            string[] messagesArray = new string[warningMessages.Count];
            warningMessages.CopyTo(messagesArray);
            return messagesArray;
        }
예제 #2
0
        public bool CompareForCloseOrders(out IList newOrders)
        {
            bool result = false;
            newOrders = null;

            if (parent.Setting.CompareAction == PortfolioCompareAction.CloseOrders)
            {
                foreach (PositionComparer pos in this)
                {
                    if (!pos.InModel)
                    {
                        // Check existing order and its type
                        if (pos.ExistingOrderAmount != null && pos.ExistingOrderAmount.IsNotZero)
                            throw new ApplicationException(string.Format("It is not possible to place close orders whenever there are still active amount based orders for {0}", pos.Instrument.Name));

                        if (pos.ExistingOrderSize != null && pos.ActualPositionSize != null && !pos.ExistingOrderSize.Underlying.Equals(pos.ActualPositionSize.Underlying))
                            throw new ApplicationException("Something spooky went wrong in the close orders procedure");

                        // check if there is a previous order
                        InstrumentSize prevOrderSize = null;
                        if (pos.ExistingOrderSize != null && pos.ExistingOrderSize.IsNotZero)
                        {
                            // Check if the previous Order(s) do(es) not exceed the Position Size
                            if (pos.ActualPositionSize.Sign != pos.ExistingOrderSize.Sign && pos.ActualPositionSize.Abs() < pos.ExistingOrderSize.Abs())
                                throw new ApplicationException(string.Format("Account {0} already has orders for {1}. The current order size {2} exceed the position size {3}. Please cancel these order(s) {4}.", parent.Account.DisplayNumberWithName, pos.ActualPositionSize.Underlying.DisplayName, pos.ExistingOrderSize.DisplayString, pos.ActualPositionSize.DisplayString, pos.OrderIds));

                            prevOrderSize = pos.ExistingOrderSize;
                        }
                        // Close the position
                        pos.OrderSize = (pos.ActualPositionSize * -1) - prevOrderSize;
                        pos.IsClosure = true;
                    }
                }

                try
                {
                    // Create the Orders
                    newOrders = new ArrayList();
                    IOrder order = null;

                    foreach (PositionComparer pos in this)
                    {
                        // Only add Close Orders for Tradeable instruments
                        if (!pos.Instrument.SecCategory.IsCash)
                        {
                            if (pos.IsClosure && pos.OrderSize != null && pos.OrderSize.IsNotZero)
                            {
                                InstructionTypeRebalance instruction = (InstructionTypeRebalance)parent.Setting.Instruction;
                                order = new OrderSizeBased(parent.Account, pos.OrderSize, true, parent.FeeFactory, instruction.DoNotChargeCommission, parent.Setting.ActionType);
                                order.Instruction = instruction;
                                newOrders.Add(order);
                            }
                        }
                    }
                    result = true;
                }

                catch (Exception ex)
                {
                    result = false;
                    throw new ApplicationException(string.Format("An error occured in the compare module while creating closing orders for account {0}.", parent.Account.DisplayNumberWithName), ex);
                }
            }
            return result;
        }
예제 #3
0
        public static void PlaceOrder(int accountId, int instrumentId, bool isAmountBased, bool isSell, decimal amount, decimal size)
        {
            IDalSession session = NHSessionFactory.CreateSession();

            try
            {
                IAccountTypeInternal bankAccount = (IAccountTypeInternal)AccountMapper.GetAccount(session, accountId);
                IInstrument theInstrument = InstrumentMapper.GetInstrument(session, instrumentId);
                FeeFactory fee = FeeFactory.GetInstance(session);
                Order order;

                if (isAmountBased)
                {
                    Decimal qty = (isSell ? (amount * -1) : amount);
                    Money theMoney = new Money(qty, ((ITradeableInstrument)theInstrument).CurrencyNominal);
                    order = new OrderAmountBased(bankAccount, theMoney, theInstrument, true, fee);
                }
                else
                {
                    Decimal qty = (isSell ? (size * -1) : size);
                    InstrumentSize theSize = new InstrumentSize(qty, theInstrument);
                    order = new OrderSizeBased(bankAccount, theSize, true, fee);
                }

                OrderMapper.Insert(session, order);
            }
            finally
            {
                session.Close();
            }
        }
예제 #4
0
        private bool liquidatePortfolio(IClientDepartureInstruction instruction)
        {
            bool retVal = false;
            bool sizeBasedOrdersExits = false;
            IList orders = new ArrayList();

            IList<IOrder> openOrders = instruction.Account.OpenOrdersForAccount;

            if (openOrders.Any(x => x.IsAmountBased))
                throw new ApplicationException(string.Format("The account {0} does have pending amount based orders and thus can not be liquidated.", instruction.Account.DisplayNumberWithName));

            sizeBasedOrdersExits = openOrders.Any(x => x.IsSizeBased);
            if (instruction.Account.Get(e => e.Portfolio).Get(e => e.PortfolioInstrument) != null)
            {
                foreach (IFundPosition pos in instruction.Account.Portfolio.PortfolioInstrument.ExcludeNonTradeableInstruments().Where(x => x.Size.IsNotZero))
                {
                    InstrumentSize openOrderSize = null;
                    if (sizeBasedOrdersExits)
                        openOrderSize = openOrders
                            .Where(x => x.RequestedInstrument.Key == pos.Instrument.Key)
                            .Select(x => x.OpenValue).Sum();

                    InstrumentSize orderSize = pos.Size.Negate() - openOrderSize;
                    if (orderSize.IsNotZero)
                    {
                        IOrder order = new OrderSizeBased(instruction.Account, orderSize, true, getFeeFactory(FeeFactoryInstanceTypes.Commission), instruction.DoNotChargeCommission, OrderActionTypes.Departure);
                        order.Instruction = instruction;
                        order.OrderInfo = string.Format("Portfolio liquidated on {0}", DateTime.Now.ToString());
                        orders.Add(order);
                    }
                }

                if (orders.Count > 0)
                {
                    instruction.UpdateableOrders = orders;
                    instruction.Message = string.Format("{0} orders generated to liquidate portfolio on {1}",
                        orders.Count, DateTime.Now.ToString());
                    retVal = true;
                }
            }
            return retVal;
        }
예제 #5
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;
        }
예제 #6
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;
        }