コード例 #1
0
        /// <summary>
        /// Places and tries to execute a market order synchronously. Since it might be a modification of an
        /// existing active order, no specific order Id is returned - instead a bool indicating operation result.
        /// </summary>
        /// <param name="manipulateExistingOrders">[where applicable] Is the operation allowed to close a matching existing order, or should we always open a new one. This is suitable for Active orders brokers, that dissallow hedged orders at the same time.</param>
        public string ExecuteMarket(OrderTypeEnum orderType, int volume, decimal?price, decimal?slippage,
                                    decimal?takeProfit, decimal?stopLoss, TimeSpan timeOut, out PositionExecutionInfo executionInfo,
                                    out string operationResultMessage)
        {
            //TracerHelper.TraceEntry();

            operationResultMessage = string.Empty;
            executionInfo          = PositionExecutionInfo.Empty;

            ISourceOrderExecution provider = _provider;

            if (provider == null || provider.DefaultAccount == null)
            {
                operationResultMessage = "Position not properly initialized.";
                return(string.Empty);
            }

            _isProcessing = true;

            string result = OnExecuteMarket(provider, orderType, volume, price, slippage, takeProfit, stopLoss, timeOut,
                                            out executionInfo, out operationResultMessage);

            SystemMonitor.CheckError(result == executionInfo.ExecutionId, operationResultMessage);

            _isProcessing = false;

            return(result);
        }
コード例 #2
0
ファイル: Order.cs プロジェクト: nice5torm/TDIN_proj
 public Order(OrderTypeEnum orderType, List <Item> items)
 {
     Id          = IdCounter++;
     OrderStatus = OrderStatusEnum.Pending;
     OrderType   = orderType;
     Items       = items;
 }
コード例 #3
0
        //void UpdateResult()
        //{
        //}

        /// <summary>
        /// Will create the corresponding order, based to the passed in order information.
        /// Used to create corresponding orders to ones already existing in the platform.
        /// </summary>
        public virtual bool AdoptExistingOrderInformation(OrderInformation information)
        {
            _id.ExecutionPlatformId = information.OrderPlatformId;
            _type = information.OrderType;

            _currentResult = information.CurrentProfit / _session.SessionInfo.LotSize;

            if (information.IsOpen == false)
            {
                _totalResult = _currentResult;
            }

            _currentVolume = information.Volume;
            _initialVolume = 1;

            _isOpen    = information.IsOpen;
            _openPrice = information.OpenPrice;

            _orderMaximumResultAchieved = _currentResult;

            _sourceOpenTime  = information.SourceOpenTime;
            _sourceCloseTime = information.SourceCloseTime;

            _sourceStopLoss   = information.OrderStopLoss;
            _sourceTakeProfit = information.OrderTakeProfit;

            _localOpenTime = DateTime.Now;

            return(true);
        }
コード例 #4
0
        /// <summary>
        ///
        /// </summary>
        public OrderInformation(string orderPlatformId, string orderSymbol, int orderType, double volume, double openPrice, double closePrice,
                                double orderStopLoss, double orderTakeProfit, double currentProfit, double orderSwap, int orderPlatformOpenTime, int orderPlatformCloseTime,
                                int orderExpiration, double orderCommission, string orderComment, int orderMagicNumber)
        {
            _orderPlatformId = orderPlatformId;
            _orderSymbol     = orderSymbol;
            _orderType       = (OrderTypeEnum)orderType;
            _volume          = volume;
            _openPrice       = openPrice;
            _closePrice      = closePrice;
            _orderStopLoss   = orderStopLoss;
            _orderTakeProfit = orderTakeProfit;
            _currentProfit   = currentProfit;
            _orderSwap       = orderSwap;
            _sourceOpenTime  = GeneralHelper.GenerateDateTimeSecondsFrom1970(orderPlatformOpenTime);

            //According to documentataion this is the way to establish if order is closed, see here : http://docs.mql4.com/trading/OrderSelect
            _isOpen = orderPlatformCloseTime == 0;

            _sourceCloseTime  = GeneralHelper.GenerateDateTimeSecondsFrom1970(orderPlatformCloseTime);
            _orderExpiration  = GeneralHelper.GenerateDateTimeSecondsFrom1970(orderExpiration);
            _orderCommission  = orderCommission;
            _orderComment     = orderComment;
            _orderMagicNumber = orderMagicNumber;
        }
コード例 #5
0
        /// <summary>
        /// Places and tries to execute a market order synchronously. Since it might be a modification of an
        /// existing active order, no specific order Id is returned - instead a bool indicating operation result.
        /// </summary>
        /// <param name="manipulateExistingOrders">[where applicable] Is the operation allowed to close a matching existing order, or should we always open a new one. This is suitable for Active orders brokers, that dissallow hedged orders at the same time.</param>
        public string ExecuteMarket(OrderTypeEnum orderType, int volume, decimal?price, decimal?slippage,
                                    decimal?takeProfit, decimal?stopLoss, TimeSpan timeOut, out PositionExecutionInfo executionInfo,
                                    out string operationResultMessage)
        {
            operationResultMessage = string.Empty;
            executionInfo          = PositionExecutionInfo.Empty;

            ISourceOrderExecution provider = _orderProvider;

            if (provider == null || provider.DefaultAccount == null)
            {
                operationResultMessage = "Position not properly initialized.";
                return(string.Empty);
            }

            // Trace pre-execution info.
            string traceMessage = string.Format("Submit Type[{0}] Volume [{1}] Price [{2}] Slippage [{3}] TP [{4}] SL [{5}] TimeOut [{6}]", orderType.ToString(),
                                                volume.ToString(), GeneralHelper.ToString(price), GeneralHelper.ToString(slippage), GeneralHelper.ToString(takeProfit),
                                                GeneralHelper.ToString(stopLoss), timeOut.ToString());

            traceMessage += GenerateConditionsInfo();

            TracerHelper.Trace(_tracer, traceMessage, TracerItem.PriorityEnum.High);

            _isProcessing = true;

            string result = OnExecuteMarket(provider, orderType, volume, price, slippage, takeProfit, stopLoss, timeOut,
                                            out executionInfo, out operationResultMessage);

            SystemMonitor.CheckError(result == executionInfo.ExecutionId, operationResultMessage);

            _isProcessing = false;

            return(result);
        }
コード例 #6
0
        /// <summary>
        /// 
        /// </summary>
        protected override string OnExecuteMarket(ISourceOrderExecution provider, OrderTypeEnum orderType, int volume, 
            decimal? price, decimal? slippage, decimal? takeProfit, decimal? stopLoss, TimeSpan timeOut,
            out PositionExecutionInfo executionInfo, out string operationResultMessage)
        {
            SystemMonitor.CheckError(provider.SupportsActiveOrderManagement, "Wrong position type for this provider.");

            executionInfo = PositionExecutionInfo.Empty;

            IQuoteProvider quoteProvider = _manager.ObtainQuoteProvider(_dataDelivery.SourceId, Symbol);
            if (quoteProvider == null)
            {
                operationResultMessage = "Failed to establish quote provider for [" + _dataDelivery.SourceId.Name + ", " + Symbol.Name + "].";
                SystemMonitor.Error(operationResultMessage);
                return string.Empty;
            }

            price = ProcessPrice(quoteProvider, orderType, price);

            // New order shall be created.
            ActiveOrder order = new ActiveOrder(_manager, provider, quoteProvider, _dataDelivery.SourceId, Symbol, true);

            OrderInfo? infoReference;

            // Using the extended operationTimeOut to 40 seconds.
            bool result = provider.SynchronousExecute(provider.DefaultAccount.Info, order, _info.Symbol,
                orderType, volume, slippage, price, takeProfit, stopLoss, string.Empty, TimeSpan.FromSeconds(40), out infoReference, out operationResultMessage);

            if (result && infoReference.HasValue)
            {
                OrderInfo infoAssign = infoReference.Value;
                if (infoAssign.Type == OrderTypeEnum.UNKNOWN)
                {
                    infoAssign.Type = orderType;
                }

                if (infoAssign.Volume == int.MinValue
                    || infoAssign.Volume == int.MaxValue)
                {// Volume was not retrieved by integration.
                    infoAssign.Volume = volume;
                }

                if (infoAssign.OpenPrice.HasValue)
                {
                    executionInfo = new PositionExecutionInfo(infoReference.Value.Id, _dataDelivery.SourceId, provider.SourceId, Symbol,
                        infoAssign.Type, infoAssign.OpenPrice.Value, volume, volume,
                        infoAssign.OpenTime, PositionExecutionInfo.ExecutionResultEnum.Success);
                }
                else
                {
                    SystemMonitor.Error("Received execution result, but price not assigned.");
                }

                order.AdoptInfo(infoAssign);

                provider.TradeEntities.AddOrder(order);
                return infoReference.Value.Id;
            }

            return string.Empty;
        }
コード例 #7
0
        /// <summary>
        ///
        /// </summary>
        ActiveOrder ObtainManipulationOrder(ISourceOrderExecution provider, OrderTypeEnum orderType, int minVolume,
                                            out bool suitableOrdersAvailable)
        {
            suitableOrdersAvailable = false;

            lock (provider.TradeEntities)
            {
                foreach (ActiveOrder activeOrder in provider.TradeEntities.GetOrdersByStateUnsafe(OrderStateEnum.Executed))
                {
                    if (activeOrder.Symbol == Symbol &&
                        minVolume <= activeOrder.CurrentVolume &&
                        (activeOrder.Type == orderType))
                    {// Found a opposing order, close it.
                        suitableOrdersAvailable = true;

                        lock (_activeSelectedOrders)
                        {
                            if (_activeSelectedOrders.Contains(activeOrder) == false)
                            {// Only if this order is not currently processed, take it for processing.
                                _activeSelectedOrders.Add(activeOrder);
                                return(activeOrder);
                            }
                        }
                    }
                }
            }

            return(null);
        }
コード例 #8
0
        /// <summary>
        ///
        /// </summary>
        public virtual bool Submit(OrderTypeEnum orderType, int volume, decimal?allowedSlippage,
                                   decimal?desiredPrice, string comment)
        {
            string message;

            return(Submit(orderType, volume, allowedSlippage, desiredPrice, 0, 0, comment, out message));
        }
コード例 #9
0
        /// <summary>
        /// Full submit of orders with a full set of parameters.
        /// </summary>
        /// <returns>The Id of the placement operation, allowing to trace its further execution or Empty if placement fails.</returns>
        public string Submit(OrderTypeEnum orderType, int volume, decimal?price, decimal?slippage,
                             decimal?takeProfit, decimal?stopLoss, out string operationResultMessage)
        {
            ISourceOrderExecution provider = OrderExecutionProvider;

            if (provider == null || provider.DefaultAccount == null)
            {
                operationResultMessage = "Position not properly initialized.";
                return(string.Empty);
            }

            if (price.HasValue == false)
            {
                price = _price;
            }

            // Trace pre-execution info.
            string traceMessage = string.Format("Submit Type[{0}] Volume [{1}] Price [{2}] Slippage [{3}] TP [{4}] SL [{5}]", orderType.ToString(),
                                                volume.ToString(), GeneralHelper.ToString(price), GeneralHelper.ToString(slippage), GeneralHelper.ToString(takeProfit), GeneralHelper.ToString(stopLoss));

            traceMessage += GenerateConditionsInfo();

            TracerHelper.Trace(_tracer, traceMessage, TracerItem.PriorityEnum.High);

            return(OnSubmit(provider, orderType, volume, price, slippage, takeProfit, stopLoss, out operationResultMessage));
        }
コード例 #10
0
        /// <summary>
        ///
        /// </summary>
        protected override string OnSubmit(ISourceOrderExecution provider, OrderTypeEnum orderType, int volume, decimal?price,
                                           decimal?slippage, decimal?takeProfit, decimal?stopLoss, out string operationResultMessage)
        {
            SystemMonitor.CheckError(provider.SupportsActiveOrderManagement, "Wrong position type for this provider.");

            IQuoteProvider quotes = _manager.ObtainQuoteProvider(_dataDelivery.SourceId, Symbol);

            ActiveOrder order = new ActiveOrder(_manager, provider, quotes,
                                                _dataDelivery.SourceId, Symbol, true);

            price = ProcessPrice(quotes, orderType, price);

            string id = provider.SubmitOrder(provider.DefaultAccount.Info, order, _info.Symbol,
                                             orderType, volume, slippage, price, takeProfit, stopLoss, string.Empty, out operationResultMessage);

            if (string.IsNullOrEmpty(id))
            {
                return(string.Empty);
            }

            OrderInfo info = new OrderInfo(id, Symbol, orderType, OrderStateEnum.Submitted, volume,
                                           price, null, null, null, null, null, null, null, null, null, null, string.Empty, null);

            order.AdoptInfo(info);
            provider.TradeEntities.AddOrder(order);

            return(id);
        }
コード例 #11
0
        /// <summary>
        /// Преобразовывает i-ые значения в объект класса Order
        /// </summary>
        /// <param name="i"></param>
        /// <returns></returns>
        private Order ToOrder(int i, bool isBuy)
        {
            Order order;

            if (isBuy)
            {
                if (i < 0 || i >= BuyOrdersIds.Count)
                {
                    return(null);
                }
                double        stopPrice = BuyStopPrices[i];
                OrderTypeEnum type      = (Math.Abs(stopPrice) <= 0.0001 ? OrderTypeEnum.LIMIT : OrderTypeEnum.STOP);
                order = new Order(Symbol, 0, BuyOrdersIds[i], (int)BuyVolumes[i], (int)BuyFilledVolumes[i], BuyPrices[i], stopPrice, ActionEnum.BUY, type);
            }
            else
            {
                if (i < 0 || i >= SellOrdersIds.Count)
                {
                    return(null);
                }
                double        stopPrice = SellStopPrices[i];
                OrderTypeEnum type      = (Math.Abs(stopPrice) <= 0.0001 ? OrderTypeEnum.LIMIT : OrderTypeEnum.STOP);
                order = new Order(Symbol, 0, SellOrdersIds[i], (int)SellVolumes[i], (int)SellFilledVolumes[i], SellPrices[i], stopPrice, ActionEnum.SELL, type);
            }
            return(order);
        }
コード例 #12
0
        /// <summary>
        /// 
        /// </summary>
        public OrderInformation(string orderPlatformId, string orderSymbol, int orderType, double volume, double openPrice, double closePrice,
            double orderStopLoss, double orderTakeProfit, double currentProfit, double orderSwap, int orderPlatformOpenTime, int orderPlatformCloseTime,
            int orderExpiration, double orderCommission, string orderComment, int orderMagicNumber)
        {
            _orderPlatformId = orderPlatformId;
            _orderSymbol = orderSymbol;
            _orderType = (OrderTypeEnum)orderType;
            _volume = volume;
            _openPrice = openPrice;
            _closePrice = closePrice;
            _orderStopLoss = orderStopLoss;
            _orderTakeProfit = orderTakeProfit;
            _currentProfit = currentProfit;
            _orderSwap = orderSwap;
            _sourceOpenTime = GeneralHelper.GenerateDateTimeSecondsFrom1970(orderPlatformOpenTime);

            //According to documentataion this is the way to establish if order is closed, see here : http://docs.mql4.com/trading/OrderSelect
            _isOpen = orderPlatformCloseTime == 0;

            _sourceCloseTime = GeneralHelper.GenerateDateTimeSecondsFrom1970(orderPlatformCloseTime);
            _orderExpiration = GeneralHelper.GenerateDateTimeSecondsFrom1970(orderExpiration);
            _orderCommission = orderCommission;
            _orderComment = orderComment;
            _orderMagicNumber = orderMagicNumber;
        }
コード例 #13
0
        /// <summary>
        /// Constructor.
        /// </summary>
        public OrderInfo(string orderId, Symbol symbol, OrderTypeEnum orderType, OrderStateEnum state, int volume, Decimal?openPrice, Decimal?closePrice,
                         Decimal?orderStopLoss, Decimal?orderTakeProfit, Decimal?currentProfit, Decimal?orderSwap, DateTime?orderPlatformOpenTime, DateTime?orderPlatformCloseTime,
                         DateTime?orderPlatformPlaceTime, DateTime?orderExpiration, Decimal?orderCommission, string orderComment, string tag)
        {
            _id            = orderId;
            _symbol        = symbol;
            _type          = orderType;
            _volume        = volume;
            _openPrice     = openPrice;
            _closePrice    = closePrice;
            _stopLoss      = orderStopLoss;
            _takeProfit    = orderTakeProfit;
            _currentProfit = currentProfit;
            _swap          = orderSwap;
            _openTime      = orderPlatformOpenTime;
            _placeTime     = orderPlatformPlaceTime;

            _state = state;

            _closeTime  = orderPlatformCloseTime;
            _expiration = orderExpiration;
            _commission = orderCommission;
            _comment    = orderComment;
            _tag        = tag;
        }
コード例 #14
0
 public static string GenerateId(OrderTypeEnum orderType, string code3)
 {
     lock (locker)
     {
         return("GA_" + code3 + "_" + orderType.ToString() + DateTime.Now.ToString("yyyyMMddHHmmssfff") + new Random().Next(1000, 9999));
     }
 }
コード例 #15
0
 public List <Order> GetLastDec(string symbol)
 {
     try
     {
         List <Order> lastDecision = new List <Order>();
         if (string.IsNullOrEmpty(symbol))
         {
             return(lastDecision);
         }
         MySqlCommand selectCommand = DatabaseConnection.CreateCommand();
         string       query         = GetDisicionByDecQuery.Replace("?dSymbol", symbol);
         selectCommand.CommandText = query;
         //selectCommand.Parameters.AddWithValue("?dSymbol", symbol);
         using (MySqlDataReader reader = selectCommand.ExecuteReader())
         {
             while (reader.Read())
             {
                 int           volume       = reader.GetInt32("volume");
                 double        price        = reader.GetDouble("price");
                 double        stopprice    = reader.GetDouble("stopprice");
                 string        actionString = reader.GetString("buysell");
                 ActionEnum    action       = actionString == "BUY" ? ActionEnum.BUY : ActionEnum.SELL;
                 OrderTypeEnum type         = Math.Abs(stopprice) <= 0.0001 ? OrderTypeEnum.LIMIT : OrderTypeEnum.STOP;
                 lastDecision.Add(new Order(symbol, 0, "", volume, 0, price, stopprice, action, type));
             }
             reader.Close();
         }
         return(lastDecision);
     } catch (Exception e)
     {
         throw new SmartException(e);
     }
 }
コード例 #16
0
        string OrderExecutionSourceStub.IImplementation.SubmitOrder(AccountInfo accountInfo, Symbol symbol,
                                                                    OrderTypeEnum orderType, int volume, decimal?allowedSlippage, decimal?desiredPrice, decimal?takeProfit,
                                                                    decimal?stopLoss, string comment, out string operationResultMessage)
        {
            operationResultMessage = string.Empty;
            string operationResultMessageCopy = string.Empty;

            PlaceOrderOperation operation = null;

            GeneralHelper.GenericReturnDelegate <string> operationDelegate = delegate()
            {
                string submitResult = DoSubmitOrder(accountInfo, symbol, orderType, volume, allowedSlippage, desiredPrice,
                                                    takeProfit, stopLoss, comment, out operation, out operationResultMessageCopy);

                return(submitResult);
            };

            object result;

            if (_messageLoopOperator.Invoke(operationDelegate, TimeSpan.FromSeconds(8), out result) == false)
            {// Timed out.
                operationResultMessage = "Timeout submiting order.";
                return(null);
            }

            if (string.IsNullOrEmpty((string)result))
            {// Operation error.
                operationResultMessage = operationResultMessageCopy;
                return(null);
            }

            // Return the ID of the submitted order.
            return((string)result);
        }
コード例 #17
0
        /// <summary>
        ///
        /// </summary>
        public virtual bool Open(OrderTypeEnum orderType, double volume, double allowedSlippage,
                                 double desiredPrice, string comment)
        {
            string message;

            return(Open(orderType, volume, allowedSlippage, desiredPrice, 0, 0, comment, out message));
        }
コード例 #18
0
        public OrderView GetOrder(int targetId, OrderTypeEnum orderType)
        {
            var orderTypeStrategy = OrderTypeFactory.GetOrderTypeStrategy(orderType);
            var order             = orderTypeStrategy.GetOrderReview(targetId);

            order.Total = order.OrderDetails.Sum(x => x.Product.Price * x.Quantity);
            return(order);
        }
コード例 #19
0
 /// <summary>
 /// 转换成枚举
 /// </summary>
 public static int OrderTypeToValue(OrderTypeEnum enumOption)
 {
     try{
         return((int)enumOption);
     }catch (Exception ex) {
         throw new ArgumentException("enumOption", ex);
     }
 }
コード例 #20
0
        /// <summary>
        /// Creates instance of <see cref="OrderExpressionInfo{T}" />.
        /// </summary>
        /// <param name="keySelector">A function to extract a key from an element.</param>
        /// <param name="orderType">Whether to (subsequently) sort ascending or descending.</param>
        /// <exception cref="ArgumentNullException">If <paramref name="keySelector"/> is null.</exception>
        public OrderExpressionInfo(Expression <Func <T, object?> > keySelector, OrderTypeEnum orderType)
        {
            _ = keySelector ?? throw new ArgumentNullException(nameof(keySelector));

            this.KeySelector = keySelector;
            this.OrderType   = orderType;

            this.keySelectorFunc = new Lazy <Func <T, object?> >(this.KeySelector.Compile);
        }
        /// <summary>
        /// Creates instance of <see cref="OrderExpressionInfo{TItem}" />.
        /// </summary>
        /// <param name="keySelector">A function to extract a key from an element.</param>
        /// <param name="orderType">Whether to (subsequently) sort ascending or descending.</param>
        /// <exception cref="ArgumentNullException">If <paramref name="keySelector"/> is null.</exception>
        public OrderExpressionInfo(Expression <Func <TItem, object> > keySelector, OrderTypeEnum orderType)
        {
            _ = keySelector ?? throw new ArgumentNullException(nameof(keySelector));

            KeySelector = keySelector;
            OrderType   = orderType;

            _keySelectorFunc = new Lazy <Func <TItem, object> >(KeySelector.Compile);
        }
コード例 #22
0
ファイル: Order.cs プロジェクト: eddiyur/FinalProject
 public Order(PersonClass person, OrderTypeEnum orderType, string orderID, DateTime orderDate, DateTime orderDeliveryDate, List <PriceTable> productsList)
 {
     Person            = person;
     OrderType         = orderType;
     OrderID           = orderID;
     OrderDate         = orderDate;
     OrderDeliveryDate = orderDeliveryDate;
     OrderProductsList = productsList;
 }
コード例 #23
0
        protected void CreateOrder(bool isBuy)
        {
            OrderTypeEnum orderType = isBuy ? OrderTypeEnum.BUY_MARKET : OrderTypeEnum.SELL_MARKET;

            if (checkBoxPendingOrder.Checked)
            {
                if (radioButtonLimit.Checked)
                {
                    if (isBuy)
                    {
                        orderType = OrderTypeEnum.BUY_LIMIT_MARKET;
                    }
                    else
                    {
                        orderType = OrderTypeEnum.SELL_LIMIT_MARKET;
                    }
                }
                else if (radioButtonStop.Checked)
                {
                    if (isBuy)
                    {
                        orderType = OrderTypeEnum.BUY_STOP_MARKET;
                    }
                    else
                    {
                        orderType = OrderTypeEnum.SELL_STOP_MARKET;
                    }
                }
            }

            decimal?slippage = null;

            if (this.checkBoxSlippage.Checked)
            {
                slippage = this.numericUpDownSlippage.Value;
            }

            decimal?desiredPrice = isBuy ? DataProvider.Ask : DataProvider.Bid;
            string  operationResultMessage;

            if (checkBoxPendingOrder.Checked)
            {
                desiredPrice = numericUpDownPendingPrice.Value;
            }

            string comment = textBoxComment.Text;

            if (CreatePlaceOrderEvent(orderType, checkBoxSynchronous.Checked, GetVolume(), slippage,
                                      desiredPrice, TakeProfit, StopLoss, checkBoxBalancedPositionMode.Checked, comment, out operationResultMessage) == false)
            {// Show error requestMessage.
                MessageBox.Show(operationResultMessage, "Order Operation Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else
            {
                this.Hide();
            }
        }
コード例 #24
0
        /// <summary>
        ///
        /// </summary>
        bool ConvertToMBTOrderType(OrderTypeEnum orderType, decimal?desiredPrice, decimal?allowedSlippage, out int type, out int buySell, out int lTimeInForce)
        {
            type    = 0;
            buySell = 0;

            // By default set it up for Market/Limit type.
            type         = (int)MBTOrderTypeEnum.VALUE_MARKET;
            lTimeInForce = (int)TifEnum.VALUE_GTC;

            if (desiredPrice.HasValue && allowedSlippage.HasValue)
            {                                          // In order to place Market order with slippage, we use Limit order (same thing).
                lTimeInForce = (int)TifEnum.VALUE_IOC; // Immediate or cancel.
                type         = (int)MBTOrderTypeEnum.VALUE_LIMIT;
            }

            switch (orderType)
            {
            case OrderTypeEnum.BUY_MARKET:
                // Limit orders allow to assign limit execution price (aka slippage).
                //type = (int)MBTOrderTypeEnum.VALUE_LIMIT;
                buySell = 10000;
                break;

            case OrderTypeEnum.SELL_MARKET:
                // Limit orders allow to assign limit execution price (aka slippage).
                //type = (int)MBTOrderTypeEnum.VALUE_LIMIT;
                buySell = 10001;
                break;

            case OrderTypeEnum.BUY_LIMIT_MARKET:
                type    = (int)MBTOrderTypeEnum.VALUE_STOP_MARKET;
                buySell = 10000;
                break;

            case OrderTypeEnum.SELL_LIMIT_MARKET:
                type    = (int)MBTOrderTypeEnum.VALUE_STOP_MARKET;
                buySell = 10001;
                break;

            case OrderTypeEnum.BUY_STOP_MARKET:
                type    = (int)MBTOrderTypeEnum.VALUE_STOP_MARKET;
                buySell = 10000;
                break;

            case OrderTypeEnum.SELL_STOP_MARKET:
                type    = (int)MBTOrderTypeEnum.VALUE_STOP_MARKET;
                buySell = 10001;
                break;

            case OrderTypeEnum.UNKNOWN:
            default:
                SystemMonitor.NotImplementedWarning();
                return(false);
            }

            return(true);
        }
コード例 #25
0
ファイル: Order.cs プロジェクト: yyl-20020115/OpenForexNew
        /// <summary>
        /// Statis helper, allows the calculation of order results.
        /// </summary>
        public static Decimal?GetRawResult(decimal?open, decimal volume, OrderStateEnum state,
                                           OrderTypeEnum type, decimal?ask, decimal?bid, decimal?close, bool considerVolume)
        {
            if (state != OrderStateEnum.Closed && state != OrderStateEnum.Executed)
            {
                if (state == OrderStateEnum.Failed || state == OrderStateEnum.Initialized ||
                    state == OrderStateEnum.UnInitialized || state == OrderStateEnum.Unknown)
                {
                    return(null);
                }

                // Canceled, Submitted
                return(0);
            }

            if (open.HasValue == false ||
                (state == OrderStateEnum.Executed && (ask.HasValue == false || bid.HasValue == false)) ||
                (state == OrderStateEnum.Closed && close.HasValue == false))
            {
                return(null);
            }

            decimal currentValue = 0;

            if (state == OrderStateEnum.Executed)
            {
                currentValue = OrderInfo.TypeIsBuy(type) ? bid.Value : ask.Value;
            }
            else if (state == OrderStateEnum.Closed)
            {
                currentValue = close.Value;
            }
            else
            {
                return(null);
            }

            Decimal difference = 0;

            if (OrderInfo.TypeIsBuy(type))
            {
                difference = currentValue - open.Value;
            }
            else
            {
                difference = open.Value - currentValue;
            }

            if (considerVolume)
            {
                return(volume * difference);
            }
            else
            {
                return(difference);
            }
        }
コード例 #26
0
ファイル: OrdersController.cs プロジェクト: ivdmi/aspirantura
        // получить список аспирантов с отметками принадлежности приказу
        private ICollection <AssignedAspirantData> PopulateAspirantDataAsync(OrderTypeEnum orderType, int orderId = -1)
        {
            IQueryable <Aspirant> aspirants = from a in _context.Aspirants.
                                              Include(s => s.StatusType).
                                              Include(o => o.AsppirantOrders).
                                              ThenInclude(o => o.Order).
                                              AsNoTracking().
                                              OrderBy(k => k.InputDate).
                                              OrderBy(s => s.Name)
                                              select a;

            var assignedAspirants = new List <AssignedAspirantData>();

            if (orderType == OrderTypeEnum.Зарахування)
            {
                aspirants = aspirants.Where(s => s.StatustypeId == (int)StatusTypeEnum.новий);

                foreach (var item in aspirants)
                {
                    assignedAspirants.Add(new AssignedAspirantData
                    {
                        Id             = item.Id,
                        Name           = item.Name,
                        Surename       = item.Surename,
                        Patronymic     = item.Patronymic,
                        SpecialityId   = item.SpecialityId,
                        Budget         = true,
                        DayForm        = true,
                        StationaryForm = true
                    });
                }
            }

            /*
             *
             * assignedAspirants.Add(new AssignedAspirantData
             *      {
             *          Id = item.Id,
             *          Name = item.Name,
             *          Surename = item.Surename,
             *          Patronymic = item.Patronymic,
             *          Course = item.Course,
             *          StatusName = item.StatusType.Name,
             *          InputDate = item.InputDate,
             *          Protection = item.Protection,
             *          ProtectionDate = item.ProtectionDate,
             *          Assigned = _context.AspirantOrders.Any(k => (k.AspirantId == item.Id && k.OrderId == orderId))
             *      });
             *
             */



            return(assignedAspirants.ToList());
        }
コード例 #27
0
        /// <summary>
        /// Will use current platform prices for the operation.
        /// </summary>
        public virtual bool Open(OrderTypeEnum orderType, double volume)
        {
            double price = DataProvider.Ask; // Buy

            if (orderType == OrderTypeEnum.OP_SELL || orderType == OrderTypeEnum.OP_SELLLIMIT || orderType == OrderTypeEnum.OP_SELLSTOP)
            {// Sell.
                price = DataProvider.Bid;
            }

            return(Open(orderType, volume, this.DefaultExecutionSlippage, price, DefaultComment));
        }
コード例 #28
0
        public ClientOrderLookupPage(OrderTypeEnum ExpectedOrderType)
        {
            this.m_ExpectedOrderType = ExpectedOrderType;
            this.m_BarcodeScanPort   = YellowstonePathology.Business.BarcodeScanning.BarcodeScanPort.Instance;

            InitializeComponent();

            DataContext = this;
            Loaded     += new RoutedEventHandler(ClientOrderLookupPage_Loaded);
            Unloaded   += new RoutedEventHandler(ClientOrderLookupPage_Unloaded);
        }
コード例 #29
0
        public ClientOrderLookupPage(OrderTypeEnum ExpectedOrderType)
        {
            this.m_ExpectedOrderType = ExpectedOrderType;
            this.m_BarcodeScanPort = YellowstonePathology.Business.BarcodeScanning.BarcodeScanPort.Instance;

            InitializeComponent();

            DataContext = this;
            Loaded += new RoutedEventHandler(ClientOrderLookupPage_Loaded);
            Unloaded +=new RoutedEventHandler(ClientOrderLookupPage_Unloaded);
        }
コード例 #30
0
        public string GenerateOrderNo(int courseId, int userId, OrderTypeEnum orderType)
        {
            DynamicParameters parameter = new DynamicParameters();

            parameter.Add("@CouserId", courseId, DbType.Int32, ParameterDirection.Input);
            parameter.Add("@UserId", userId, DbType.Int32, ParameterDirection.Input);
            parameter.Add("@OrderType", (int)orderType, DbType.Int32, direction: ParameterDirection.Input);
            parameter.Add("@OrderNo", "", DbType.String, direction: ParameterDirection.Output);
            ExecuteProc("P_CreateOrderNo", parameter);
            return(parameter.Get <string>("@OrderNo"));
        }
コード例 #31
0
 public void PlaceOrder(string symbol, ActionEnum action, OrderTypeEnum type, double price, double volume, double stopPrice, int cookie)
 {
     if (IsConnected)
     {
         WriteToLog("Place order. Symbol: {0}; Action: {1}; Price: {2}; Volume: {3}",
                    symbol, action, price, volume);
         SmartComServer.PlaceOrder(Portfolio, symbol, action == ActionEnum.BUY ? StOrder_Action.StOrder_Action_Buy : StOrder_Action.StOrder_Action_Sell
                                   , type == OrderTypeEnum.LIMIT ? StOrder_Type.StOrder_Type_Limit : StOrder_Type.StOrder_Type_StopLimit, StOrder_Validity.StOrder_Validity_Day
                                   , price, volume, stopPrice, cookie);
     }
 }
コード例 #32
0
ファイル: AdminController.cs プロジェクト: BlueFisher/LOK
        public async Task <ActionResult> OrdersTable(OrderTableViewModel model)
        {
            if (!Request.IsAjaxRequest())
            {
                return(RedirectToAction("Index"));
            }
            ViewBag.hasFunctionBtn = model.HasFunction;

            Expression <Func <Order, bool> > exp;

            OrderTypeEnum orderType = model.Type == "Getting" ? OrderTypeEnum.Get : OrderTypeEnum.Send;

            ViewBag.OrderTableType = orderType;
            exp = (p => p.OrderType == orderType);

            switch (model.Status)
            {
            case "Full":
                break;

            case "OnGoing":
                exp = exp.And(p => p.OrderStatus == OrderStatusEnum.OnGoing);
                break;

            case "Closed":
                exp = exp.And(p => p.OrderStatus == OrderStatusEnum.Closed);
                break;

            case "Completed":
                exp = exp.And(p => p.OrderStatus == OrderStatusEnum.Completed);
                break;

            case "Confirming":
                exp = exp.And(p => p.OrderStatus == OrderStatusEnum.Confirming);
                break;

            case "Failed":
                exp = exp.And(p => p.OrderStatus == OrderStatusEnum.Failed);
                break;

            case "Active":
            default:
                exp = exp.And(p => (p.OrderStatus == OrderStatusEnum.Confirming || p.OrderStatus == OrderStatusEnum.OnGoing));
                break;
            }

            if (model.UserId != null)
            {
                exp = exp.And(p => p.UserId == model.UserId);
            }

            return(View("Ajax/OrdersTable", await OrderManager.GetOrdersAsync(exp)));
        }
コード例 #33
0
 public Order(string symbol, int cookie, string orderId, double volume, double filledVolume, double price, double stopPrice, StOrder_Action action, StOrder_Type type)
 {
     Symbol       = symbol;
     Cookie       = cookie;
     OrderId      = orderId;
     Volume       = (int)volume;
     FilledVolume = (int)filledVolume;
     Price        = price;
     StopPrice    = stopPrice;
     Action       = Server.ActionCast(action);
     Type         = Server.OrderTypeCast(type);
 }
コード例 #34
0
        /// <summary>
        /// 
        /// </summary>
        protected override string OnExecuteMarket(ISourceOrderExecution provider, OrderTypeEnum orderType, int volume, 
            decimal? price, decimal? slippage, decimal? takeProfit, decimal? stopLoss, TimeSpan timeOut, 
            out PositionExecutionInfo executionInfo, out string operationResultMessage)
        {
            SystemMonitor.CheckError(provider.SupportsActiveOrderManagement == false, "Wrong position type for this provider.");

            executionInfo = PositionExecutionInfo.Empty;
            PassiveOrder order;
            lock (this)
            {
                order = new PassiveOrder(_manager, _dataDelivery.SourceId, provider.SourceId);
            }

            OrderInfo? infoReference;

            bool result = provider.SynchronousExecute(provider.DefaultAccount.Info, order, _info.Symbol,
                orderType, volume, slippage, price, takeProfit, stopLoss, string.Empty, out infoReference, out operationResultMessage);

            if (result && infoReference.HasValue)
            {
                OrderInfo infoAssign = infoReference.Value;
                if (infoAssign.Type == OrderTypeEnum.UNKNOWN)
                {
                    infoAssign.Type = orderType;
                }

                if (infoAssign.Volume == int.MinValue
                    || infoAssign.Volume == int.MaxValue)
                {// Volume was not retrieved by integration.
                    infoAssign.Volume = volume;
                }

                if (infoAssign.OpenPrice.HasValue)
                {
                    executionInfo = new PositionExecutionInfo(infoReference.Value.Id, _dataDelivery.SourceId, provider.SourceId, Symbol,
                        infoAssign.Type, infoAssign.OpenPrice.Value, volume, volume,
                        infoAssign.OpenTime, PositionExecutionInfo.ExecutionResultEnum.Success);
                }
                else
                {
                    SystemMonitor.Error("Received execution result, but price not assigned.");
                }

                order.AdoptInfo(infoAssign);

                provider.TradeEntities.AddOrder(order);

                return infoReference.Value.Id;
            }

            return string.Empty;
        }
コード例 #35
0
 /// <summary>
 /// 
 /// </summary>
 public OrderMessage(AccountInfo accountInfo, Symbol symbol, OrderTypeEnum orderType, int volume, decimal? price, decimal? slippage, 
     decimal? takeProfit, decimal? stopLoss, string comment)
     : base(accountInfo)
 {
     _symbol = symbol;
     _orderType = orderType;
     _volume = volume;
     _desiredPrice = price;
     _slippage = slippage;
     _takeProfit = takeProfit;
     _stopLoss = stopLoss;
     _comment = comment;
 }
コード例 #36
0
 /// <summary>
 /// 
 /// </summary>
 public PositionExecutionInfo(string executionId, ComponentId dataSourceId, ComponentId executionSourceId,
     Symbol symbol, OrderTypeEnum orderType, decimal? price, int volumeRequest, int volumeExecuted, DateTime? time, ExecutionResultEnum result)
 {
     _executionId = executionId;
     _orderType = orderType;
     _dataSourceId = dataSourceId;
     _executionSourceId = executionSourceId;
     _symbol = symbol;
     _result = result;
     _executedPrice = price;
     _volumeRequested = volumeRequest;
     _volumeExecuted = volumeExecuted;
     _executionTime = time;
 }
コード例 #37
0
        public bool ExecuteMarketOrder(AccountInfo accountInfo, Symbol symbol, OrderTypeEnum orderType, int volume, decimal? allowedSlippage, decimal? desiredPrice, decimal? takeProfit, decimal? stopLoss, string comment, out OrderInfo? orderPlaced, out string operationResultMessage)
        {
            operationResultMessage = string.Empty;
            string operationResultMessageCopy = string.Empty;
            object orderId, psd;

            bool isBuy = OrderInfo.TypeIsBuy(orderType);

            OrderInfo? order = null;
            GeneralHelper.GenericReturnDelegate<bool> operationDelegate = delegate()
            {
                _manager.Desk.OpenTrade(accountInfo.Id, symbol.Name, isBuy, _adapter.DefaultLotSize, (double)desiredPrice.Value, (string)_adapter.GetInstrumentData(symbol.Name, "QuoteID"), 0, (double)stopLoss.Value, (double)takeProfit.Value, 0, out orderId, out psd);

                order = new OrderInfo();
                OrderInfo tempOrder = order.Value;
                tempOrder.Id = orderId.ToString();

                TableAut accountsTable = (FXCore.TableAut)_manager.Desk.FindMainTable("trades");

                RowAut item = (RowAut)accountsTable.FindRow("OrderID", orderId, 0);

                return true;
            };

            orderPlaced = order;

            object result;
            if (_messageLoopOperator.Invoke(operationDelegate, TimeSpan.FromSeconds(8), out result) == false)
            {// Timed out.
                operationResultMessage = "Timeout submiting order.";
                return false;
            }

            if (string.IsNullOrEmpty((string)result))
            {// Operation error.
                operationResultMessage = operationResultMessageCopy;
                return false;
            }

            return true;
        }
コード例 #38
0
ファイル: OrderType.cs プロジェクト: superliujian/Sxta
 /// <summary> 
 /// Private constructor.
 /// </summary>
 /// <param name="pValue">the enum value corresponding to this order type
 /// </param>
 private OrderType(OrderTypeEnum pValue)
 {
     val = pValue;
 }
コード例 #39
0
        /// <summary>
        /// Will use current platform prices for the operation.
        /// </summary>
        public virtual bool Submit(OrderTypeEnum orderType, int volume)
        {
            decimal? price = null;

            if (QuoteProvider != null)
            {
                if (orderType == OrderTypeEnum.SELL_MARKET || orderType == OrderTypeEnum.SELL_LIMIT_MARKET || orderType == OrderTypeEnum.SELL_STOP_MARKET)
                {// Sell.
                    price = QuoteProvider.Bid;
                }
                else
                {
                    price = QuoteProvider.Ask; // Buy
                }
            }

            return Submit(orderType, volume, this.DefaultExecutionSlippage, price, DefaultComment);
        }
コード例 #40
0
ファイル: OrderHelper.cs プロジェクト: borealwinter/simpl
        public string PlaceDropshipOrder(
            OrderTypeEnum orderType,
            List<OrderLineItem> orderLineItems,
            int fulfillmentLocation,
            int entityId,
            ShipAddress shipAddress,
            string commentText,
            string userId,
            int equipmentCatalog,
            int receivingId = 0,
            string wtn = null)
        {
            var failureString = string.Empty;
            var masterOrder = GenerateMasterOrder(orderType, commentText, entityId, receivingId);

            // establish entity objects
            var primaryOrder = GenerateOrder(orderType, shipAddress, orderLineItems, fulfillmentLocation);
            masterOrder.Orders.Add(primaryOrder);
            ApplyBusinessRulesToOrder(masterOrder, fulfillmentLocation);

            // Add required objects to the database
            using (var db = DBContextFactory.CreateContext())
            {
                db.MasterOrders.AddObject(masterOrder);

                try
                {
                    db.SaveChanges(); // save order to the db
                }
                catch (SqlException)
                {
                    throw new Exception("Error creating new order: database");
                }
                catch (Exception ex)
                {
                    throw new Exception("Error creating new order.", ex);
                }

                var exceptionMessage = "Error when trying to save the DropShip order, please see inner exception for more details";
                try
                {
                    foreach (var order in masterOrder.Orders)
                    {
                        // if order is a dropship get this data to our shipping vendor du jour
                        if (orderType == OrderTypeEnum.Dropship)
                        {

                            // if we are using live Complemar interface, uncomment the code block you wish to use for submitting code to Complemar:

                            // Asynchronous code ******************************************
                            /**/
                            var uniqueId = userId;

                            //BackgroundWorker worker = new BackgroundWorker();
                            //worker.DoWork += new DoWorkEventHandler((sender, e) =>
                            //{
                            //    SIMPL.BLL.Dropship.ComplemarOrderHelper complemarHelper = new BLL.Dropship.ComplemarOrderHelper(primaryOrder, masterOrder, orderLineItems, shipAddress);
                            //    complemarHelper.SubmitOrder(uniqueId);
                            //});
                            //worker.RunWorkerAsync();

                            // Synchronous code *******************************************
                            var complemarHelper = new Dropship.ComplemarOrderHelper(order, masterOrder, shipAddress);
                            complemarHelper.SubmitOrder(uniqueId);

                            /**/

                            // save itx-formatted order to db

                            var itxHelper = new Dropship.ItxOrderHelper(order, shipAddress, equipmentCatalog, wtn);
                            itxHelper.SubmitOrder();

                            // verify all items were submitted to complemar
                            if (itxHelper.UnsentItems.Count > 1)
                            {
                                var unsentItemString = itxHelper.UnsentItems.Aggregate(string.Empty, (current, item) =>
                                                       current + string.Format("{0} was not sent.<br />",
                                                       DBCache.EquipmentTypes.First(e => e.EquipmentTypeId == item.EquipTypeId).EquipName));
                                failureString += "<br />" + unsentItemString;
                            }
                        }
                    }
                }
                catch (SqlException inner)
                {
                    if (_errorLoggingService != null)
                    {
                        var myException = new Exception(exceptionMessage, inner);
                        if (_errorLoggingService != null)
                        {
                            _errorLoggingService.LogErrorNoContext(myException);
                        }
                    }
                    failureString += "The order was placed but fell out during importing. Please check Order History page to verify order was placed.<br />";
                }
                catch (Exception inner)
                {
                    if (_errorLoggingService != null)
                    {
                        var myException = new Exception(exceptionMessage, inner);
                        if (_errorLoggingService != null)
                        {
                            _errorLoggingService.LogErrorNoContext(myException);
                        }
                    }
                    failureString += "The order was placed but fell out during importing. Please check Order History page to verify order was placed.<br />";
                }

            } // close context

            return String.IsNullOrEmpty(failureString) ? masterOrder.MasterOrderId.ToString(CultureInfo.InvariantCulture) : failureString;
        }
コード例 #41
0
ファイル: OrderType.cs プロジェクト: superliujian/Sxta
 /// <summary> 
 /// Copy constructor.
 /// </summary>
 /// <param name="otherOrderType">the order type to copy
 /// </param>
 public OrderType(OrderType otherOrderType)
 {
     val = otherOrderType.val;
 }
コード例 #42
0
        /// <summary>
        /// Submits the order over to the orders interface, make sure to call in Invocation thread.
        /// </summary>
        string DoSubmitOrder(AccountInfo accountInfo, Symbol symbol, OrderTypeEnum orderType, int volume, Decimal? allowedSlippage, Decimal? desiredPrice,
            Decimal? takeProfit, Decimal? stopLoss, string comment, out PlaceOrderOperation operation, out string operationResultMessage)
        {
            SystemMonitor.CheckError(_messageLoopOperator.InvokeRequred == false, "Invoke required.");

            operationResultMessage = "Operation not supported.";
            operation = null;

            MbtAccount pAcct = GetAccountByInfo(accountInfo);

            if (pAcct == null)
            {
                operationResultMessage = "Failed to retrieve account.";
                SystemMonitor.OperationWarning(operationResultMessage);
                return null;
            }

            if (orderType != OrderTypeEnum.SELL_MARKET && orderType != OrderTypeEnum.BUY_MARKET)
            {
                operationResultMessage = "Order type [" + orderType.ToString() + "] not supported or tested by this provider.";
                return null;
                //if (desiredPrice.HasValue)
                //{
                //    dStopPrice = (double)desiredPrice.Value;
                //}
                //else
                //{
                //    SystemMonitor.Error("Desired price not assigned, on placing order type [" + orderType.ToString() + " ], not submitted.");
                //    return null;
                //}
            }

            // ---
            int iVolume = volume;

            int iOrdType, iBuySell;

            double dPrice = desiredPrice.HasValue ? (double)desiredPrice.Value : 0;
            double dPrice2 = 0;
            int lTimeInForce = -1;

            if (ConvertToMBTOrderType(orderType, desiredPrice, allowedSlippage, out iOrdType, out iBuySell, out lTimeInForce) == false)
            {
                operationResultMessage = "Failed to convert type of order.";
                SystemMonitor.OperationWarning(operationResultMessage);
                return null;
            }

            if (allowedSlippage.HasValue && dPrice != 0)
            {// Put the slippage in as a limit price.
                // This forms the "limit" price we are willing to pay for this order.
                if (OrderInfo.TypeIsBuy(orderType))
                {
                    dPrice = dPrice + (double)allowedSlippage.Value;
                }
                else
                {
                    dPrice = dPrice - (double)allowedSlippage.Value;
                }
            }

            string message = string.Empty;

            lock (this)
            {// Make sure to keep the entire package here locked, since the order operation get placed after the submit
                // so we need to make sure we shall catch the responce in OnSubmit() too.

                //if (_orderClient.Submit(iBuySell, iVolume, symbol.Name, dPrice, dStopPrice, (int)TifEnum.VALUE_GTC, 10020, iOrdType,
                //    10042, 0, pAcct, "MBTX", string.Empty, 0, 0, DateTime.FromBinary(0), DateTime.FromBinary(0), 0, 0, 0, 0, -1, ref message) == false)
                //{// Error requestMessage.
                //    operationResultMessage = message;
                //    return null;
                //}

                // Instead of using Market Orders, we shall use Limit Orders, since they allow to set an execution limit price.
                // The VALUE_IOC instructs to execute or cancel the order, instead of GTC (Good Till Cancel)
                if (_orderClient.Submit(iBuySell, iVolume, symbol.Name, dPrice, dPrice2, lTimeInForce, 10020, iOrdType,
                    10042, 0, pAcct, "MBTX", string.Empty, 0, 0, DateTime.FromBinary(0), DateTime.FromBinary(0), 0, 0, 0, 0, -1, ref message) == false)
                {// Error requestMessage.
                    operationResultMessage = message;
                    return null;
                }

                operation = new PlaceOrderOperation() { Id = message };
                // The message, or operation Id is the order token (further stored in OrderInfo.id)
                _operationStub.RegisterOperation(operation, false);
            }

            return message;
        }
コード例 #43
0
        /// <summary>
        /// Submit an order.
        /// </summary>
        public string SubmitOrder(AccountInfo account, Symbol symbol, OrderTypeEnum orderType, int volume, 
            decimal? allowedSlippage, decimal? desiredPrice, decimal? takeProfit, decimal? stopLoss, 
            string comment, out string operationResultMessage)
        {
            operationResultMessage = string.Empty;
            string operationResultMessageCopy = string.Empty;
            object orderId, psd;
            bool isBuy = OrderInfo.TypeIsBuy(orderType);

            GeneralHelper.GenericReturnDelegate<string> operationDelegate = delegate()
            {
                _manager.Desk.OpenTrade(account.Id, symbol.Name, isBuy,
                    _adapter.DefaultLotSize, (double)desiredPrice.Value,
                    (string)_adapter.GetInstrumentData(symbol.Name, "QuoteID"),
                    0,
                    stopLoss.HasValue ? (double)stopLoss.Value : 0,
                    takeProfit.HasValue ? (double)takeProfit.Value : 0,
                    0, out orderId, out psd);

                return orderId.ToString();
            };

            object result;
            if (_messageLoopOperator.Invoke(operationDelegate, TimeSpan.FromSeconds(8), out result) == false)
            {// Timed out.
                operationResultMessage = "Timeout submiting order.";
                return null;
            }

            if (string.IsNullOrEmpty((string)result))
            {// Operation error.
                operationResultMessage = operationResultMessageCopy;
                return null;
            }

            // Return the ID of the submitted order.
            return (string)result;
        }
コード例 #44
0
 /// <summary>
 /// Redefine for the operationTimeOut, by providing the DefaultTimeOut.
 /// </summary>
 public bool SynchronousExecute(AccountInfo account, Order order, Symbol symbol, OrderTypeEnum orderType,
     int volume, decimal? allowedSlippage, decimal? desiredPrice, decimal? takeProfit, decimal? stopLoss,
     string comment, out OrderInfo? info, out string operationResultMessage)
 {
     return SynchronousExecute(account, order, symbol, orderType,
         volume, allowedSlippage, desiredPrice, takeProfit, stopLoss,
         comment, this.DefaultTimeOut, out info, out operationResultMessage);
 }
コード例 #45
0
        string OrderExecutionSourceStub.IImplementation.SubmitOrder(AccountInfo accountInfo, Symbol symbol, 
            OrderTypeEnum orderType, int volume, decimal? allowedSlippage, decimal? desiredPrice, decimal? takeProfit, 
            decimal? stopLoss, string comment, out string operationResultMessage)
        {
            operationResultMessage = string.Empty;
            string operationResultMessageCopy = string.Empty;

            PlaceOrderOperation operation = null;
            GeneralHelper.GenericReturnDelegate<string> operationDelegate = delegate()
            {
                string submitResult = DoSubmitOrder(accountInfo, symbol, orderType, volume, allowedSlippage, desiredPrice,
                    takeProfit, stopLoss, comment, out operation, out operationResultMessageCopy);

                return submitResult;
            };

            object result;
            if (_messageLoopOperator.Invoke(operationDelegate, TimeSpan.FromSeconds(8), out result) == false)
            {// Timed out.
                operationResultMessage = "Timeout submiting order.";
                return null;
            }

            if (string.IsNullOrEmpty((string)result))
            {// Operation error.
                operationResultMessage = operationResultMessageCopy;
                return null;
            }

            // Return the ID of the submitted order.
            return (string)result;
        }
コード例 #46
0
        /// <summary>
        /// Main SynchronousExecute method.
        /// </summary>
        public bool SynchronousExecute(AccountInfo account, Order order, Symbol symbol, OrderTypeEnum orderType, 
            int volume, decimal? allowedSlippage, decimal? desiredPrice, decimal? takeProfit, decimal? stopLoss, 
            string comment, TimeSpan operationTimeOut, out OrderInfo? info, out string operationResultMessage)
        {
            TracerHelper.Trace(this.Name);

            info = null;
            operationResultMessage = string.Empty;

            if (OperationalState != OperationalStateEnum.Operational)
            {
                operationResultMessage = "Attempted operations on non operational order executioner.";
                SystemMonitor.Error(operationResultMessage);
                return false;
            }

            if (account.IsEmpty
                || string.IsNullOrEmpty(account.Id)
                || string.IsNullOrEmpty(account.Name))
            {
                operationResultMessage = "Account info on order execution provider not properly assigned.";
                return false;
            }

            allowedSlippage = ProcessSlippage(allowedSlippage);

            ExecuteMarketOrderMessage request = new ExecuteMarketOrderMessage(account,
                symbol, orderType, volume, desiredPrice, allowedSlippage, takeProfit, stopLoss, comment);

            request.PerformSynchronous = true;

            ResponseMessage response = this.SendAndReceiveResponding<ResponseMessage>
                (SourceTransportInfo, request, operationTimeOut);

            if (response == null)
            {// Time out.
                operationResultMessage = "Failed receive result for order request. In this scenario inconsistency may occur!";
                SystemMonitor.Error(operationResultMessage);
                return false;
            }

            if (response.OperationResult == false)
            {
                operationResultMessage = response.OperationResultMessage;
                return false;
            }

            //if (orderType == OrderTypeEnum.BUY_MARKET
            //    || orderType == OrderTypeEnum.SELL_MARKET)
            //{// Immediate order.
            //    resultState = OrderStateEnum.Executed;
            //}
            //else
            //{// Delayed pending order.
            //    resultState = OrderStateEnum.Submitted;
            //}

            ExecuteMarketOrderResponseMessage responseMessage = (ExecuteMarketOrderResponseMessage)response;
            operationResultMessage = "Order opened.";

            info = responseMessage.Info;

            //RaiseOrderUpdateEvent(account, order.Info, ActiveOrder.UpdateTypeEnum.Submitted);

            return true;
        }
コード例 #47
0
        /// <summary>
        /// 
        /// </summary>
        ActiveOrder ObtainManipulationOrder(ISourceOrderExecution provider, OrderTypeEnum orderType, int minVolume, 
            out bool suitableOrdersAvailable)
        {
            suitableOrdersAvailable = false;

            lock (provider.TradeEntities)
            {
                foreach (ActiveOrder activeOrder in provider.TradeEntities.GetOrdersByStateUnsafe(OrderStateEnum.Executed))
                {
                    if (activeOrder.Symbol == Symbol
                        && minVolume <= activeOrder.CurrentVolume
                        && (activeOrder.Type == orderType))
                    {// Found a opposing order, close it.

                        suitableOrdersAvailable = true;

                        lock (_activeSelectedOrders)
                        {
                            if (_activeSelectedOrders.Contains(activeOrder) == false)
                            {// Only if this order is not currently processed, take it for processing.
                                _activeSelectedOrders.Add(activeOrder);
                                return activeOrder;
                            }
                        }
                    }
                }
            }

            return null;
        }
コード例 #48
0
ファイル: OrderHelper.cs プロジェクト: borealwinter/simpl
        private Order GenerateOrder(OrderTypeEnum orderType, ShipAddress shipAddress, List<OrderLineItem> items, int fulfillmentLocation)
        {
            var order = new Order();
            OrderType foundType;

            // Add collateral to order (disconnect letter / exchange letter)
            switch (orderType)
            {
                case OrderTypeEnum.Dropship:
                    items.AddRange(AddCollateral(items));
                    order.FillLocId = Dropship.DropshipHelper.GetShippingVendorId();
                    order.ShipAddress1 = shipAddress;
                    foundType = DBCache.OrderTypes.FirstOrDefault(c => c.OrderTypeName.ToLower() == "fios_drop");
                    if (foundType != null)
                    {
                        order.OrderTypeId = foundType.OrderTypeId;
                    }
                    ReturnMailerConversion(items);
                    break;

                case OrderTypeEnum.Field:
                    order.FillLocId = fulfillmentLocation;
                    foundType = DBCache.OrderTypes.FirstOrDefault(c => c.OrderTypeName.ToLower() == "fios_field");
                    if (foundType != null)
                        order.OrderTypeId = foundType.OrderTypeId;
                    break;
            }

            foreach (var item in items)
            {
                order.OrderLineItems.Add(item);
            }

            var orderStatus = DBCache.OrderStatuses.FirstOrDefault(c => c.OrderStatusName.ToLower() == "ordered");
            if (orderStatus != null)
                order.Status = orderStatus.OrderStatusId;
            return order;
        }
コード例 #49
0
ファイル: OrderHelper.cs プロジェクト: borealwinter/simpl
        private MasterOrder GenerateMasterOrder(OrderTypeEnum orderType, string commentText, int entityId, int receivingId = 0)
        {
            if (receivingId == 0)
            {
                receivingId = entityId;
            }
            // Assign order and master order properties
            var masterOrder = new MasterOrder
                {
                    CreatingEntityId = entityId,
                    CreateDateTime = DateTime.Now,
                    ReceivingEntityId = orderType == OrderTypeEnum.Dropship ? 8 : receivingId
                };

            // find a master order number that doesn't exist
            var masterOrderNumber = 0;
            using (var context = DBContextFactory.CreateContext())
            {
                while (masterOrderNumber == 0 || context.MasterOrders.FirstOrDefault(o => o.MasterOrderId == masterOrderNumber) != null)
                {
                    masterOrderNumber = _random.Next(100000000, 999999999);
                }
            }

            masterOrder.MasterOrderId = masterOrderNumber;

            if (!String.IsNullOrEmpty(commentText))
            {
                var comment = new Comment
                    {
                        CommentEntityId = entityId,
                        CommentOrderId = masterOrder.MasterOrderId,
                        CommentText = commentText,
                        CommentTime = masterOrder.CreateDateTime
                    };

                masterOrder.Comments.Add(comment);
            }
            return masterOrder;
        }
コード例 #50
0
ファイル: OrderHelper.cs プロジェクト: borealwinter/simpl
        public string PlaceFieldOrder(
            OrderTypeEnum orderType,
            List<OrderLineItem> orderLineItems,
            int fulfillmentLocation,
            int entityId,
            ShipAddress shipAddress,
            string commentText,
            string userId,
            int receivingId = 0)
        {
            var failureString = string.Empty;
            var masterOrder = GenerateMasterOrder(orderType, commentText, entityId, receivingId);
            int owningLocId;
            string userEmail;
            // establish entity objects
            var primaryOrder = GenerateOrder(orderType, shipAddress, orderLineItems, fulfillmentLocation);
            masterOrder.Orders.Add(primaryOrder);
            ApplyBusinessRulesToOrder(masterOrder, fulfillmentLocation);

            // Add required objects to the database
            using (var db = DBContextFactory.CreateContext())
            {
                var userEntity = db.Entities.First(e => e.EntityId == entityId);
                owningLocId = db.Locations.First(l => l.LocId == userEntity.LocId).OwningLocId;
                userEmail = userEntity.Email;

                db.MasterOrders.AddObject(masterOrder);

                try
                {
                    db.SaveChanges(); // save order to the db
                }
                catch (SqlException)
                {
                    throw new Exception("Error creating new order: database");
                }
                catch (Exception ex)
                {
                    throw new Exception("Error creating new order.", ex);
                }

            } // close context
            if (primaryOrder.ShipAddress == null) // order is not a dropship order
            {
                var mail = new JP.Util.MailHelper(); // create and send email to designated recipients at location
                //get the orderobject based on the orderid
                using (var db = DBContextFactory.CreateContext())
                {
                    primaryOrder = (from c in db.Orders
                             .Include("Location")
                                    where c.OrderId == primaryOrder.OrderId
                                    select c).First();
                }

                var okToSend = mail.CreateOrderNotification(primaryOrder, owningLocId, userEmail); // get recipients list order number, order items, etc, and format into email.
                if (okToSend)
                    mail.Send();
            }

            return String.IsNullOrEmpty(failureString) ? masterOrder.MasterOrderId.ToString(CultureInfo.InvariantCulture) : failureString;
        }
コード例 #51
0
        /// <summary>
        /// 
        /// </summary>
        decimal? ProcessPrice(IQuoteProvider quoteProvider, OrderTypeEnum orderType, decimal? price)
        {
            if (price.HasValue == false && quoteProvider.Ask.HasValue && quoteProvider.Bid.HasValue)
            {
                if (OrderInfo.TypeIsBuy(orderType))
                {
                    return quoteProvider.Ask;
                }
                else
                {
                    return quoteProvider.Bid;
                }
            }

            return price;
        }
コード例 #52
0
        /// <summary>
        /// This allows more specific control over the operation.
        /// </summary>
        public bool Submit(OrderTypeEnum orderType, int volume, decimal? allowedSlippage, 
            decimal? desiredPrice, decimal? takeProfit, decimal? stopLoss, string comment, out string operationResultMessage)
        {
            SystemMonitor.CheckThrow(volume > 0, "Misuse of the Order class.");

            if (State != OrderStateEnum.Initialized)
            {
                operationResultMessage = "Misuse of the Order class [Order not initialized; or Must not place trade, that has already been placed].";
                SystemMonitor.Warning(operationResultMessage);
                return false;
            }

            ISourceOrderExecution executionProvider = _executionProvider;

            operationResultMessage = "Session not assigned.";

            if (desiredPrice.HasValue == false)
            {
                desiredPrice = OrderInfo.TypeIsBuy(orderType) ? QuoteProvider.Bid : QuoteProvider.Ask;
            }

            if (executionProvider == null)
            {// Placement of order failed.
                State = OrderStateEnum.Failed;
                SystemMonitor.Report("Order was not executed [" + operationResultMessage + "].");
                return false;
            }

            string id = OrderExecutionProvider.SubmitOrder(Account.Info, this, Symbol, orderType, volume,
                    allowedSlippage, desiredPrice, takeProfit, stopLoss, comment, out operationResultMessage);

            if (string.IsNullOrEmpty(id))
            {
                State = OrderStateEnum.Failed;
                SystemMonitor.OperationError("Order was not executed [" + operationResultMessage + "].");
                return false;
            }

            lock(this)
            {
                _info.Type = orderType;
                _initialVolume = volume;
                _info.Id = id;
                _info.Volume = volume;

                _info.StopLoss = stopLoss;
                _info.TakeProfit = takeProfit;

                State = OrderStateEnum.Submitted;
                _localOpenTime = DateTime.Now;
            }

            Account.TradeEntities.AddOrder(this);

            if (State == OrderStateEnum.Executed)
            {
                RaiseOrderUpdatedEvent(UpdateTypeEnum.Executed);
            }
            else
            {
                RaiseOrderUpdatedEvent(UpdateTypeEnum.Submitted);
            }

            return true;
        }
コード例 #53
0
        bool OrderExecutionSourceStub.IImplementation.ExecuteMarketOrder(AccountInfo accountInfo, Symbol symbol, OrderTypeEnum orderType, int volume, Decimal? allowedSlippage, Decimal? desiredPrice,
            Decimal? takeProfit, Decimal? stopLoss, string comment, out OrderInfo? orderPlaced, out string operationResultMessage)
        {
            string operationResultMessageCopy = string.Empty;

            PlaceOrderOperation operation = null;
            GeneralHelper.GenericReturnDelegate<bool> operationDelegate = delegate()
            {
                string submitResult = DoSubmitOrder(accountInfo, symbol, orderType, volume, allowedSlippage, desiredPrice,
                    takeProfit, stopLoss, comment, out operation, out operationResultMessageCopy);

                return string.IsNullOrEmpty(submitResult) == false;
            };

            orderPlaced = null;

            object result;
            if (_messageLoopOperator.Invoke(operationDelegate, TimeSpan.FromSeconds(5), out result) == false)
            {// Timed out.
                operationResultMessage = "Timeout placing order.";
                return false;
            }

            if ((bool)result == false)
            {// Operation error.
                operationResultMessage = operationResultMessageCopy;
                return false;
            }

            object operationResult;
            if (operation.WaitResult<object>(TimeSpan.FromSeconds(60), out operationResult) == false)
            {
                operationResultMessage = "Order place timeout.";
                return false;
            }

            orderPlaced = (OrderInfo?)operationResult;

            if (operationResult == null || orderPlaced.HasValue == false)
            {
                operationResultMessage = "Order place failed.";
                return false;
            }

            // Operation OK.
            operationResultMessage = string.Empty;
            orderPlaced = operation.OrderResponce;

            if (orderPlaced.HasValue == false)
            {
                return false;
            }

            return true;
        }
コード例 #54
0
        bool SubmitPositionOrder(OrderTypeEnum orderType, bool synchronous, int volume, decimal? allowedSlippage, decimal? desiredPrice,
            decimal? sourceTakeProfit, decimal? sourceStopLoss, bool allowExistingOrdersManipulation, string comment, out string operationResultMessage)
        {
            SystemMonitor.CheckThrow(_selectedSession != null, "Selected session must be not null to create orders.");

            Position position = _selectedSession.OrderExecutionProvider.TradeEntities.ObtainPositionBySymbol(_selectedSession.Info.Symbol);

            if (position == null)
            {
                operationResultMessage = "Failed to find position order.";
                SystemMonitor.Error(operationResultMessage);
                return false;
            }

            string submitResult = string.Empty;
            if (synchronous == false)
            {
                submitResult = position.Submit(orderType, volume,
                    desiredPrice, allowedSlippage, sourceTakeProfit, sourceStopLoss, out operationResultMessage);
            }
            else
            {
                PositionExecutionInfo info;
                submitResult = position.ExecuteMarket(orderType, volume, desiredPrice, allowedSlippage,
                    sourceTakeProfit, sourceStopLoss, TimeSpan.FromSeconds(15), out info, out operationResultMessage);
            }

            if (string.IsNullOrEmpty(submitResult))
            {
                operationResultMessage = "Failed to initialize order [" +  operationResultMessage + "].";
                SystemMonitor.Error(operationResultMessage);
                return false;
            }

            return true;
        }
コード例 #55
0
        /// <summary>
        /// 
        /// </summary>
        bool ConvertToMBTOrderType(OrderTypeEnum orderType, decimal? desiredPrice, decimal? allowedSlippage, out int type, out int buySell, out int lTimeInForce)
        {
            type = 0;
            buySell = 0;

            // By default set it up for Market/Limit type.
            type = (int)MBTOrderTypeEnum.VALUE_MARKET;
            lTimeInForce = (int)TifEnum.VALUE_GTC;

            if (desiredPrice.HasValue && allowedSlippage.HasValue)
            {// In order to place Market order with slippage, we use Limit order (same thing).
                lTimeInForce = (int)TifEnum.VALUE_IOC; // Immediate or cancel.
                type = (int)MBTOrderTypeEnum.VALUE_LIMIT;
            }

            switch (orderType)
            {
                case OrderTypeEnum.BUY_MARKET:
                    // Limit orders allow to assign limit execution price (aka slippage).
                    //type = (int)MBTOrderTypeEnum.VALUE_LIMIT;
                    buySell = 10000;
                    break;
                case OrderTypeEnum.SELL_MARKET:
                    // Limit orders allow to assign limit execution price (aka slippage).
                    //type = (int)MBTOrderTypeEnum.VALUE_LIMIT;
                    buySell = 10001;
                    break;

                case OrderTypeEnum.BUY_LIMIT_MARKET:
                    type = (int)MBTOrderTypeEnum.VALUE_STOP_MARKET;
                    buySell = 10000;
                    break;
                case OrderTypeEnum.SELL_LIMIT_MARKET:
                    type = (int)MBTOrderTypeEnum.VALUE_STOP_MARKET;
                    buySell = 10001;
                    break;
                case OrderTypeEnum.BUY_STOP_MARKET:
                    type = (int)MBTOrderTypeEnum.VALUE_STOP_MARKET;
                    buySell = 10000;
                    break;
                case OrderTypeEnum.SELL_STOP_MARKET:
                    type = (int)MBTOrderTypeEnum.VALUE_STOP_MARKET;
                    buySell = 10001;
                    break;

                case OrderTypeEnum.UNKNOWN:
                default:
                    SystemMonitor.NotImplementedWarning();
                    return false;
            }

            return true;
        }
コード例 #56
0
 /// <summary>
 /// 
 /// </summary>
 public virtual bool Submit(OrderTypeEnum orderType, int volume, decimal? allowedSlippage,
     decimal? desiredPrice, string comment)
 {
     string message;
     return Submit(orderType, volume, allowedSlippage, desiredPrice, 0, 0, comment, out message);
 }
コード例 #57
0
 partial void OnOrderTypeChanging(OrderTypeEnum value);
コード例 #58
0
        /// <summary>
        /// 
        /// </summary>
        public string SubmitOrder(AccountInfo account, Order order, Symbol symbol, OrderTypeEnum orderType,
            int volume, decimal? allowedSlippage, decimal? desiredPrice, decimal? takeProfit, decimal? stopLoss, 
            string comment, out string operationResultMessage)
        {
            TracerHelper.Trace(this.Name);

            if (OperationalState != OperationalStateEnum.Operational)
            {
                operationResultMessage = "Attempted operations on non operational order executioner.";
                SystemMonitor.Error(operationResultMessage);
                return null;
            }

            if (account.IsEmpty
                || string.IsNullOrEmpty(account.Id)
                || string.IsNullOrEmpty(account.Name))
            {
                operationResultMessage = "Account info on order execution provider not properly assigned.";
                return null;
            }

            allowedSlippage = ProcessSlippage(allowedSlippage);

            SubmitOrderMessage request = new SubmitOrderMessage(account,
                symbol, orderType, volume, desiredPrice, allowedSlippage, takeProfit, stopLoss, comment);

            request.RequestResponse = true;
            request.PerformSynchronous = true;

            ResponseMessage response = this.SendAndReceiveResponding<ResponseMessage>
                (SourceTransportInfo, request);

            if (response == null)
            {// Time out.
                operationResultMessage = "Failed receive result for order request. In this scenario inconsistency may occur!";
                SystemMonitor.Error(operationResultMessage);
                return null;
            }

            if (response.OperationResult == false)
            {
                operationResultMessage = response.OperationResultMessage;
                return null;
            }

            SubmitOrderResponseMessage responseMessage = (SubmitOrderResponseMessage)response;
            operationResultMessage = "Order submited.";

            //RaiseOrderUpdateEvent(account, order.Info, Order.UpdateTypeEnum.Submitted);

            return responseMessage.OrderId;
        }
コード例 #59
0
        /// <summary>
        /// 
        /// </summary>
        protected override string OnSubmit(ISourceOrderExecution provider, OrderTypeEnum orderType, int volume, decimal? price,
            decimal? slippage, decimal? takeProfit, decimal? stopLoss, out string operationResultMessage)
        {
            SystemMonitor.CheckError(provider.SupportsActiveOrderManagement, "Wrong position type for this provider.");

            IQuoteProvider quotes = _manager.ObtainQuoteProvider(_dataDelivery.SourceId, Symbol);

            ActiveOrder order = new ActiveOrder(_manager, provider, quotes,
                _dataDelivery.SourceId, Symbol, true);

            price = ProcessPrice(quotes, orderType, price);

            string id = provider.SubmitOrder(provider.DefaultAccount.Info, order, _info.Symbol,
                orderType, volume, slippage, price, takeProfit, stopLoss, string.Empty, out operationResultMessage);

            if (string.IsNullOrEmpty(id))
            {
                return string.Empty;
            }

            OrderInfo info = new OrderInfo(id, Symbol, orderType, OrderStateEnum.Submitted, volume,
                price, null, null, null, null, null, null, null, null, null, null, string.Empty, null);

            order.AdoptInfo(info);
            provider.TradeEntities.AddOrder(order);

            return id;
        }
コード例 #60
0
 public void IFoundAClient(YellowstonePathology.Business.Client.Model.Client client)
 {
     this.m_Client = client;
     this.m_AClientHasBeenFound = true;
     this.m_ExpectedOrderType = (OrderTypeEnum)Enum.Parse(typeof(OrderTypeEnum), client.ClientLocationCollection.CurrentLocation.OrderType, true);
 }