private void SessionOnOrderFilled(OEC.API.Order order, OEC.API.Fill fill)
        {
            if (!fill.Active)
            {
                return;
            }

            SendOutMessage(new ExecutionMessage
            {
                SecurityId = new SecurityId
                {
                    SecurityCode = order.Contract.Symbol,
                    BoardCode    = order.Route == null ? order.Contract.Exchange.Name : order.Route.Name,
                },
                ExecutionType         = ExecutionTypes.Transaction,
                OriginalTransactionId = _orderTransactions.TryGetValue2(order) ?? 0,
                OrderId       = order.ID,
                TradeId       = fill.ID,
                TradePrice    = order.Contract.Cast(fill.Price),
                ServerTime    = fill.Timestamp.ApplyTimeZone(TimeHelper.Est),
                TradeVolume   = fill.Quantity,
                SystemComment = fill.Comments,
                Commission    = fill.Commission.ToDecimal(),
                HasTradeInfo  = true,
            });
        }
Esempio n. 2
0
        private void SessionOnOrderStateChanged(OEC.API.Order order, OrderState oldState)
        {
            var trId = _orderTransactions.TryGetValue2(order);

            // TODO
            if (trId == null)
            {
                return;
            }

            ProcessOrder(order, trId.Value);
        }
Esempio n. 3
0
        private void SessionOnOrderConfirmed(OEC.API.Order order, int oldOrderId)
        {
            //if (oldOrderId > 0)
            //{
            //	SendOutMessage(new ExecutionMessage
            //	{
            //		ExecutionType = ExecutionTypes.Order,
            //		OrderId = oldOrderId,
            //		OrderState = OrderStates.Done,
            //	});
            //}

            //SendOutMessage(new ExecutionMessage
            //{
            //	ExecutionType = ExecutionTypes.Order,
            //	OrderId = order.ID,
            //	OrderStatus = OrderStatus.ReceiveByServer,
            //});
        }
Esempio n. 4
0
        private void SessionOnOrderFilled(OEC.API.Order order, OEC.API.Fill fill)
        {
            if (!fill.Active)
            {
                return;
            }

            SendOutMessage(new ExecutionMessage
            {
                ExecutionType         = ExecutionTypes.Trade,
                OriginalTransactionId = _orderTransactions.TryGetValue2(order) ?? 0,
                OrderId       = order.ID,
                TradeId       = fill.ID,
                TradePrice    = order.Contract.Cast(fill.Price),
                ServerTime    = fill.Timestamp.ApplyTimeZone(TimeHelper.Est),
                Volume        = fill.Quantity,
                SystemComment = fill.Comments,
                Commission    = fill.Commission.ToDecimal(),
            });
        }
Esempio n. 5
0
        private void SessionOnCommandUpdated(OEC.API.Order order, Command command)
        {
            //var msg = "Команда обновилась: #{0}, {1}-{2}, order #{3}".Put(command.ID, command.Type, command.State, oecOrder.OrderString());
            //this.AddInfoLog(msg);

            ////ProcessEvents(() =>
            ////{
            //var currentOrder = _orderMap.GetLocalOrder(oecOrder);

            //if (currentOrder == null)
            //	throw new OECException("CommandUpdated: Локальная заявка для OEC заявки '{0}' не найдена.".Put(oecOrder.OrderString()));

            //if (!(command.Type == CommandType.Modify || command.State == CommandState.Failed))
            //{
            //	// при необходимости будет обработано при получении OrderStateChanged
            //	currentOrder.Messages.Add(msg);
            //	return;
            //}

            //switch (command.State)
            //{
            //	case CommandState.Sent:
            //	{
            //		// Type == Modify
            //		var newOrder = _orderMap.GetLocalOrder(command.Version);
            //		if (newOrder == null)
            //			throw new OECException("CommandUpdated2: Локальная заявка для версии '{0}' не найдена.".Put(command.Version));

            //		if (command.ID > 0 && newOrder.Id <= 0)
            //		{
            //			var updatemsg = "OecCbOnCommandUpdated: Команда на модификацию (oldId={0}) принята сервером. newId={1}".Put(newOrder.Id, command.ID);
            //			this.AddInfoLog(updatemsg);

            //			GetOrder(newOrder.Security, newOrder.Type, command.ID, id => newOrder, order =>
            //			{
            //				_orderMap.BindOrderToOecOrderVersion(order, command.Version);
            //				order.Messages.Add(updatemsg);
            //				order.Status = OrderStatus.ReceiveByServer;

            //				return true;
            //			});
            //		}
            //		break;
            //	}
            //	case CommandState.Executed:
            //	{
            //		// Type == Modify
            //		var prevOecOrderVersion = oecOrder.Versions.Current.GetPreviousExecutedVersion();
            //		if (prevOecOrderVersion == null)
            //		{
            //			var errmsg = "Предыдущая версия заявки '{0}' не найдена.".Put(oecOrder.OrderString());
            //			this.AddErrorLog(errmsg);
            //			throw new OECException(errmsg);
            //		}

            //		var oldOrder = _orderMap.GetLocalOrder(prevOecOrderVersion);
            //		if (oldOrder == null)
            //			throw new OECException("CommandUpdated3: Локальная заявка для версии '{0}' не найдена.".Put(prevOecOrderVersion));

            //		OnModifyCommandExecuted(oldOrder, currentOrder, oecOrder);
            //		break;
            //	}
            //	case CommandState.Failed:
            //	{
            //		switch (command.Type)
            //		{
            //			case CommandType.Create:
            //				// will be handled in OnOrderChanged
            //				this.AddWarningLog("Команда Create вернула ошибку: {0}", command.ResultComments);
            //				break;
            //			case CommandType.Modify:
            //				var newOrder = _orderMap.GetLocalOrder(command.Version);
            //				if (newOrder == null)
            //					throw new OECException("CommandUpdated4: Локальная заявка для версии '{0}' не найдена.".Put(command.Version));

            //				newOrder.Id = 0;
            //				newOrder.State = OrderStates.Done;
            //				newOrder.Status = OrderStatus.NotValidated;
            //				newOrder.LastChangeTime = command.ResultTimestamp;

            //				RaiseOrderFailed(newOrder, new OECException("Команда Modify завершилась неудачно, комментарий='{0}'".Put(command.ResultComments)));
            //				break;
            //			case CommandType.Cancel:
            //				RaiseOrderFailed(currentOrder, new OECException("Команда Cancel завершилась неудачно, комментарий='{0}'".Put(command.ResultComments)));
            //				break;
            //		}
            //		break;
            //	}
            //}
            //});
        }
Esempio n. 6
0
        private void ProcessOrder(OEC.API.Order order, long trasactionId)
        {
            if (order == null)
            {
                throw new ArgumentNullException(nameof(order));
            }

            if (trasactionId == 0)
            {
                throw new ArgumentOutOfRangeException(nameof(trasactionId));
            }

            var execMsg = new ExecutionMessage
            {
                OriginalTransactionId = trasactionId,
                OrderId       = order.ID,
                Side          = order.Side.ToStockSharp(),
                ExecutionType = ExecutionTypes.Order,
                ServerTime    = order.States.Current.Timestamp.ApplyTimeZone(TimeHelper.Est),
                OrderType     = order.Type.ToStockSharp(),
                Volume        = order.Quantity,
                PortfolioName = order.Account.Name,
                SecurityId    = new SecurityId
                {
                    SecurityCode = order.Contract.Symbol,
                    BoardCode    = order.Route == null ? order.Contract.Exchange.Name : order.Route.Name,
                },
                Comment    = order.Comments,
                OrderPrice = order.Contract.Cast(order.Price) ?? 0,
            };

            var currVersion = order.Versions.Current;

            switch (currVersion.Flags)
            {
            case OrderFlags.FOK:
                execMsg.TimeInForce = TimeInForce.MatchOrCancel;
                break;

            case OrderFlags.IOC:
                execMsg.TimeInForce = TimeInForce.CancelBalance;
                break;

            case OrderFlags.GTC:
                execMsg.TimeInForce = TimeInForce.PutInQueue;
                //execMsg.ExpiryDate = DateTimeOffset.MaxValue;
                break;
            }

            if (currVersion.End != OEC.API.Version.MaximumEnd)
            {
                execMsg.ExpiryDate = currVersion.End.ApplyTimeZone(TimeHelper.Est);
            }

            if (execMsg.OrderType == OrderTypes.Conditional)
            {
                var condition = new OpenECryOrderCondition();
                execMsg.Condition = condition;

                switch (order.Type)
                {
                case OrderType.StopLimit:
                    condition.StopType  = OpenECryStopType.StopLimit;
                    condition.StopPrice = order.Contract.Cast(order.Price);
                    execMsg.OrderPrice  = order.Contract.Cast(order.Price2) ?? 0;
                    break;

                case OrderType.Stop:
                    condition.StopType  = OpenECryStopType.StopMarket;
                    condition.StopPrice = order.Contract.Cast(order.Price);
                    //execMsg.Price = 0;
                    break;

                case OrderType.TrailingStopLoss:
                case OrderType.TrailingStopLimit:
                    //execMsg.Price = 0;
                    var stopType = order.Type == OrderType.TrailingStopLimit ? OpenECryStopType.TrailingStopLimit : OpenECryStopType.TrailingStopMarket;

                    var eqtsData = currVersion.ExtData as EquityTrailingStopData;
                    if (eqtsData != null)
                    {
                        condition.StopType       = stopType;
                        condition.Delta          = eqtsData.Amount.ToDecimal();
                        condition.IsPercentDelta = eqtsData.IsPercentAmount;
                        condition.TriggerType    = eqtsData.TriggerType.ToStockSharp();
                        condition.StopPrice      = order.Contract.Cast(order.Price);
                    }
                    else
                    {
                        var tsData = currVersion.ExtData as OEC.API.TrailingStopData;

                        if (tsData != null)
                        {
                            condition.StopType       = stopType;
                            condition.Delta          = tsData.Delta.ToDecimal();
                            condition.ReferencePrice = tsData.ReferencePrice.ToDecimal();
                            condition.StopPrice      = order.Contract.Cast(order.Price);
                        }
                    }

                    break;

                default:
                    throw new ArgumentOutOfRangeException(LocalizedStrings.Str1849Params.Put(order.Type));
                }
            }

            switch (order.CurrentState)
            {
            case OrderState.Accepted:
            {
                execMsg.OrderState  = OrderStates.Pending;
                execMsg.OrderStatus = OrderStatus.Accepted;
                break;
            }

            case OrderState.Held:
            {
                execMsg.OrderState  = OrderStates.Pending;
                execMsg.OrderStatus = OrderStatus.ReceiveByServer;
                break;
            }

            case OrderState.Sent:
            {
                execMsg.OrderState  = OrderStates.Pending;
                execMsg.OrderStatus = OrderStatus.SentToServer;
                break;
            }

            case OrderState.Suspended:
            {
                break;
            }

            case OrderState.Rejected:
            {
                execMsg.OrderState  = OrderStates.Failed;
                execMsg.OrderStatus = OrderStatus.RejectedBySystem;
                execMsg.Error       = new InvalidOperationException(order.States.Current.Comments);

                break;
            }

            case OrderState.Working:
            {
                //execMsg.ExtensionInfo[_keyExchangeOrderId] = order.Versions.Current.Command.ExchangeOrderID;

                execMsg.OrderState  = OrderStates.Active;
                execMsg.OrderStatus = OrderStatus.Accepted;

                execMsg.Balance = order.Quantity - order.Fills.TotalQuantity;

                break;
            }

            case OrderState.Completed:
            {
                execMsg.OrderState = OrderStates.Done;

                if (order.IsFilled)
                {
                    execMsg.Balance = 0;
                }
                else
                {
                    execMsg.Balance = order.Quantity - order.Fills.TotalQuantity;
                }

                break;
            }

            case OrderState.Cancelled:
            {
                execMsg.OrderState = OrderStates.Done;
                execMsg.Balance    = order.Quantity - order.Fills.TotalQuantity;

                break;
            }

            case OrderState.None:
            {
                break;
            }

            case OrderState.Unknown:
            {
                break;
            }

            default:
                throw new OpenECryException(LocalizedStrings.Str2557Params.Put(order.CurrentState));
            }

            SendOutMessage(execMsg);
        }
Esempio n. 7
0
 private void SessionOnPostAllocation(OEC.API.Order order, OEC.API.Contract contract, OEC.API.PostAllocationBlock allocation, PostAllocationCheckResult result)
 {
 }
 public BusinessEntities.Order GetLocalOrder(OEC.API.Order oecOrder, bool create = true)
 {
     return(GetLocalOrder(oecOrder.Versions.Current, create));
 }