Exemplo n.º 1
0
        public static Sides?ToSide(this SmartOrderAction action)
        {
            switch (action)
            {
            case SmartOrderAction.Buy:
                return(Sides.Buy);

            case SmartOrderAction.Sell:
                return(Sides.Sell);

            case SmartOrderAction.Short:
                return(Sides.Sell);

            case SmartOrderAction.Cover:
                return(Sides.Buy);

            case 0:
                return(null);

            default:
                throw new ArgumentOutOfRangeException(nameof(action), action, LocalizedStrings.Str1882);
            }
        }
Exemplo n.º 2
0
 internal void OnUpdateOrder(string portfolio, string securityId, SmartOrderState state, SmartOrderAction action, SmartOrderType type,
                             SmartOrderValidity validity, double price, double volume, double stop, double balance, DateTime time, string smartOrderId,
                             string orderIdStr, int status, int transactionId)
 {
     // http://www.itinvest.ru/forum/index.php?showtopic=63063&st=0&p=242023&#entry242023
     OrderChanged.SafeInvoke(portfolio, securityId, state,
                             action, type, validity == SmartOrderValidity.Day, price.ToDecimal(), (int)volume,
                             stop.ToDecimal(), (int)balance, time, smartOrderId, orderIdStr.To <long>(), status, transactionId);
 }
Exemplo n.º 3
0
 internal void OnAddTradeHistory(int row, int rowCount, string securityId, DateTime time, double price, double volume, string tradeno, SmartOrderAction action)
 {
     NewHistoryTrade.SafeInvoke(row, rowCount, securityId, time, price.ToDecimal(), volume.ToDecimal(), tradeno.To <long>(), action);
 }
Exemplo n.º 4
0
 internal void OnAddTrade(string securityId, DateTime time, double price, double volume, string tradeNo, SmartOrderAction action)
 {
     NewTrade.SafeInvoke(securityId, time, price.ToDecimal(), volume.ToDecimal(), tradeNo.To <long>(), action);
 }
Exemplo n.º 5
0
 /// <summary>
 /// Зарегистрировать заявку.
 /// </summary>
 /// <param name="portfolioName">Номер портфеля.</param>
 /// <param name="securityId">Идентификатор инструмента.</param>
 /// <param name="action">Направление действия.</param>
 /// <param name="type">Тип заявки.</param>
 /// <param name="validity">Время действия.</param>
 /// <param name="price">Цена.</param>
 /// <param name="volume">Объем.</param>
 /// <param name="stopPrice">Стоп цена (если регистрируется стоп-заявка).</param>
 /// <param name="transactionId">Идентификатор транзакции.</param>
 public abstract void RegisterOrder(string portfolioName, string securityId, SmartOrderAction action, SmartOrderType type, SmartOrderValidity validity, double price, int volume, double stopPrice, int transactionId);
 private void OnNewTrade(string smartId, DateTime time, decimal?price, decimal?volume, long tradeId, SmartOrderAction action)
 {
     SendOutMessage(CreateTrade(smartId, time, price, volume, tradeId, action));
 }
        private void OnNewHistoryTrade(int row, int rowCount, string smartId, DateTime time, decimal?price, decimal?volume, long tradeId, SmartOrderAction action)
        {
            this.AddDebugLog("OnNewHistoryTrade row = {0} rowCount = {1} securityId = {2} time = {3} price = {4} volume = {5} id = {6} action = {7}",
                             row, rowCount, smartId, time, price, volume, tradeId, action);

            var msg = CreateTrade(smartId, time, price, volume, tradeId, action);

            //msg.IsFinished = row == (rowCount - 1);
            SendOutMessage(msg);
        }
 private static ExecutionMessage CreateTrade(string smartId, DateTime time, decimal?price, decimal?volume, long tradeId, SmartOrderAction action)
 {
     return(new ExecutionMessage
     {
         SecurityId = new SecurityId {
             Native = smartId
         },
         TradeId = tradeId,
         TradePrice = price,
         TradeVolume = volume,
         OriginSide = action.ToSide(),
         ServerTime = time.ApplyTimeZone(TimeHelper.Moscow),
         ExecutionType = ExecutionTypes.Tick,
     });
 }
Exemplo n.º 9
0
        /// <summary>
        /// Зарегистрировать заявку.
        /// </summary>
        /// <param name="portfolioName">Номер портфеля.</param>
        /// <param name="securityId">Идентификатор инструмента.</param>
        /// <param name="action">Направление действия.</param>
        /// <param name="type">Тип заявки.</param>
        /// <param name="validity">Время действия.</param>
        /// <param name="price">Цена.</param>
        /// <param name="volume">Объем.</param>
        /// <param name="stopPrice">Стоп цена (если регистрируется стоп-заявка).</param>
        /// <param name="transactionId">Идентификатор транзакции.</param>
        public override void RegisterOrder(string portfolioName, string securityId, SmartOrderAction action, SmartOrderType type, SmartOrderValidity validity, double price, int volume, double stopPrice, int transactionId)
        {
            StOrder_Action smartAction;

            switch (action)
            {
            case SmartOrderAction.Buy:
                smartAction = StOrder_Action.StOrder_Action_Buy;
                break;

            case SmartOrderAction.Sell:
                smartAction = StOrder_Action.StOrder_Action_Sell;
                break;

            case SmartOrderAction.Short:
                smartAction = StOrder_Action.StOrder_Action_Short;
                break;

            case SmartOrderAction.Cover:
                smartAction = StOrder_Action.StOrder_Action_Cover;
                break;

            default:
                throw new ArgumentOutOfRangeException("action");
            }

            StOrder_Type smartType;

            switch (type)
            {
            case SmartOrderType.Stop:
                smartType = StOrder_Type.StOrder_Type_Stop;
                break;

            case SmartOrderType.StopLimit:
                smartType = StOrder_Type.StOrder_Type_StopLimit;
                break;

            case SmartOrderType.Limit:
                smartType = StOrder_Type.StOrder_Type_Limit;
                break;

            case SmartOrderType.Market:
                smartType = StOrder_Type.StOrder_Type_Market;
                break;

            default:
                throw new ArgumentOutOfRangeException("type");
            }

            StOrder_Validity smartValidity;

            switch (validity)
            {
            case SmartOrderValidity.Day:
                smartValidity = StOrder_Validity.StOrder_Validity_Day;
                break;

            case SmartOrderValidity.Gtc:
                smartValidity = StOrder_Validity.StOrder_Validity_Gtc;
                break;

            default:
                throw new ArgumentOutOfRangeException("validity");
            }

            SafeGetServer().PlaceOrder(portfolioName, securityId, smartAction, smartType, smartValidity, price, volume, stopPrice, transactionId);
        }
Exemplo n.º 10
0
        private void OnOrderChanged(string portfolioName, string secSmartId, SmartOrderState state, SmartOrderAction action, SmartOrderType smartType, bool isOneDay,
                                    decimal?price, int volume, decimal?stop, int balance, DateTime time, string smartOrderId, long orderId, int status, int transactionId)
        {
            this.AddInfoLog(() => "SmartTrader.UpdateOrder: id {0} smartId {1} type {2} direction {3} price {4} volume {5} balance {6} time {7} security {8} state {9}"
                            .Put(orderId, smartOrderId, smartType, action, price, volume, balance, time, secSmartId, state));

            var side = action.ToSide();

            if (side == null)
            {
                throw new InvalidOperationException(LocalizedStrings.Str1872Params.Put(action, orderId, transactionId));
            }

            // http://stocksharp.com/forum/yaf_postsm28324_Oshibka-pri-vystavlienii-ili-sniatii-zaiavki.aspx#post28324
            if (transactionId == 0)
            {
                return;
            }

            if (state.IsReject())
            {
                // заявка была ранее зарегистрирована через SmartTrader
                //if (_smartIdOrders.ContainsKey(smartOrderId))
                //{
                // замечены SystemCancel приходящие в процессе Move после которых приходит Active
                if (state != SmartOrderState.SystemCancel)
                {
                    //var trId = GetTransactionBySmartId(smartOrderId);

                    SendOutMessage(new ExecutionMessage
                    {
                        ExecutionType         = ExecutionTypes.Transaction,
                        OriginalTransactionId = transactionId,
                        OrderStringId         = smartOrderId,
                        ServerTime            = time.ApplyTimeZone(TimeHelper.Moscow),
                        OrderState            = OrderStates.Failed,
                        Error        = new InvalidOperationException(LocalizedStrings.Str1873Params.Put(transactionId)),
                        HasOrderInfo = true,
                    });
                }
                //}

                return;
            }

            var orderType = smartType.ToOrderType();

            var orderState  = OrderStates.Active;
            var orderStatus = OrderStatus.Accepted;

            switch (state)
            {
            case SmartOrderState.ContragentReject:
                orderStatus = OrderStatus.NotAcceptedByManager;
                orderState  = OrderStates.Failed;
                break;

            // Принята ТС
            case SmartOrderState.Submited:
                orderStatus = OrderStatus.SentToServer;
                break;

            // Зарегистрирована в ТС
            case SmartOrderState.Pending:
                orderStatus = OrderStatus.ReceiveByServer;

                if (orderType == OrderTypes.Conditional)
                {
                    orderState = OrderStates.Active;
                }

                break;

            // Выведена на рынок
            case SmartOrderState.Open:
                orderStatus = OrderStatus.Accepted;

                if (orderType == OrderTypes.Conditional && orderId != 0)
                {
                    orderState = OrderStates.Done;
                }
                else
                {
                    orderState = OrderStates.Active;
                }
                break;

            // Снята по окончанию торгового дня
            case SmartOrderState.Expired:
                orderState = OrderStates.Done;
                break;

            // Отменёна
            case SmartOrderState.Cancel:
                orderState = OrderStates.Done;
                break;

            // Исполнена
            case SmartOrderState.Filled:
                orderState = OrderStates.Done;
                break;

            // Частично исполнена
            case SmartOrderState.Partial:
                if (orderState == OrderStates.None)
                {
                    orderState = OrderStates.Active;
                }
                break;

            // Отклонена биржей
            case SmartOrderState.ContragentCancel:
                orderStatus = OrderStatus.CanceledByManager;
                orderState  = OrderStates.Failed;
                break;

            // Отклонена биржей
            case SmartOrderState.SystemReject:
                orderStatus = OrderStatus.NotDone;
                orderState  = OrderStates.Failed;
                break;

            // Отклонена биржей
            case SmartOrderState.SystemCancel:
                orderStatus = OrderStatus.GateError;
                orderState  = OrderStates.Failed;
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }

            SendOutMessage(new ExecutionMessage
            {
                SecurityId = new SecurityId {
                    Native = secSmartId
                },
                PortfolioName         = portfolioName,
                Side                  = (Sides)side,
                OrderPrice            = price ?? 0,
                OrderVolume           = volume,
                ServerTime            = time.ApplyTimeZone(TimeHelper.Moscow),
                Balance               = balance,
                OrderId               = orderId == 0 ? (long?)null : orderId,
                OrderType             = orderType,
                OrderState            = orderState,
                OrderStatus           = orderStatus,
                OriginalTransactionId = transactionId,
                OrderStringId         = smartOrderId,
                ExpiryDate            = isOneDay ? DateTimeOffset.Now.Date.ApplyTimeZone(TimeHelper.Moscow) : (DateTimeOffset?)null,
                Condition             = orderType == OrderTypes.Conditional ? new SmartComOrderCondition {
                    StopPrice = stop
                } : null,
                ExecutionType = ExecutionTypes.Transaction,
                HasOrderInfo  = true,
            });
        }
		private void OnNewTrade(string smartId, DateTime time, decimal price, decimal volume, long tradeId, SmartOrderAction action)
		{
			SendOutMessage(CreateTrade(smartId, time, price, volume, tradeId, action));
		}
		private void OnNewHistoryTrade(int row, int rowCount, string smartId, DateTime time, decimal price, decimal volume, long tradeId, SmartOrderAction action)
		{
			this.AddDebugLog("OnNewHistoryTrade row = {0} rowCount = {1} securityId = {2} time = {3} price = {4} volume = {5} id = {6} action = {7}",
				row, rowCount, smartId, time, price, volume, tradeId, action);

			var msg = CreateTrade(smartId, time, price, volume, tradeId, action);
			//msg.IsFinished = row == (rowCount - 1);
			SendOutMessage(msg);
		}
		private static ExecutionMessage CreateTrade(string smartId, DateTime time, decimal price, decimal volume, long tradeId, SmartOrderAction action)
		{
			return new ExecutionMessage
			{
				SecurityId = new SecurityId { Native = smartId },
				TradeId = tradeId,
				TradePrice = price,
				Volume = volume,
				OriginSide = action.ToSide(),
				ServerTime = time.ApplyTimeZone(TimeHelper.Moscow),
				ExecutionType = ExecutionTypes.Tick,
			};
		}
		private void OnOrderChanged(string portfolioName, string secSmartId, SmartOrderState state, SmartOrderAction action, SmartOrderType smartType, bool isOneDay,
			decimal? price, int volume, decimal? stop, int balance, DateTime time, string smartOrderId, long orderId, int status, int transactionId)
		{
			this.AddInfoLog(() => "SmartTrader.UpdateOrder: id {0} smartId {1} type {2} direction {3} price {4} volume {5} balance {6} time {7} security {8} state {9}"
				.Put(orderId, smartOrderId, smartType, action, price, volume, balance, time, secSmartId, state));

			var side = action.ToSide();

			if (side == null)
				throw new InvalidOperationException(LocalizedStrings.Str1872Params.Put(action, orderId, transactionId));

			// http://stocksharp.com/forum/yaf_postsm28324_Oshibka-pri-vystavlienii-ili-sniatii-zaiavki.aspx#post28324
			if (transactionId == 0)
				return;

			if (state.IsReject())
			{
				// заявка была ранее зарегистрирована через SmartTrader
				//if (_smartIdOrders.ContainsKey(smartOrderId))
				//{
				// замечены SystemCancel приходящие в процессе Move после которых приходит Active
				if (state != SmartOrderState.SystemCancel)
				{
					//var trId = GetTransactionBySmartId(smartOrderId);

					SendOutMessage(new ExecutionMessage
					{
						ExecutionType = ExecutionTypes.Order,
						OriginalTransactionId = transactionId,
						OrderStringId = smartOrderId,
						ServerTime = time.ApplyTimeZone(TimeHelper.Moscow),
						OrderState = OrderStates.Failed,
						Error = new InvalidOperationException(LocalizedStrings.Str1873Params.Put(transactionId)),
					});
				}
				//}

				return;
			}

			var orderType = smartType.ToOrderType();

			var orderState = OrderStates.Active;
			var orderStatus = OrderStatus.Accepted;

			switch (state)
			{
				case SmartOrderState.ContragentReject:
					orderStatus = OrderStatus.NotAcceptedByManager;
					orderState = OrderStates.Failed;
					break;
				// Принята ТС
				case SmartOrderState.Submited:
					orderStatus = OrderStatus.SentToServer;
					break;
				// Зарегистрирована в ТС
				case SmartOrderState.Pending:
					orderStatus = OrderStatus.ReceiveByServer;

					if (orderType == OrderTypes.Conditional)
						orderState = OrderStates.Active;

					break;
				// Выведена на рынок
				case SmartOrderState.Open:
					orderStatus = OrderStatus.Accepted;

					if (orderType == OrderTypes.Conditional && orderId != 0)
						orderState = OrderStates.Done;
					else
						orderState = OrderStates.Active;
					break;
				// Снята по окончанию торгового дня
				case SmartOrderState.Expired:
					orderState = OrderStates.Done;
					break;
				// Отменёна
				case SmartOrderState.Cancel:
					orderState = OrderStates.Done;
					break;
				// Исполнена
				case SmartOrderState.Filled:
					orderState = OrderStates.Done;
					break;
				// Частично исполнена
				case SmartOrderState.Partial:
					if (orderState == OrderStates.None)
						orderState = OrderStates.Active;
					break;
				// Отклонена биржей
				case SmartOrderState.ContragentCancel:
					orderStatus = OrderStatus.CanceledByManager;
					orderState = OrderStates.Failed;
					break;
				// Отклонена биржей
				case SmartOrderState.SystemReject:
					orderStatus = OrderStatus.NotDone;
					orderState = OrderStates.Failed;
					break;
				// Отклонена биржей
				case SmartOrderState.SystemCancel:
					orderStatus = OrderStatus.GateError;
					orderState = OrderStates.Failed;
					break;
				default:
					throw new ArgumentOutOfRangeException();
			}

			SendOutMessage(new ExecutionMessage
			{
				SecurityId = new SecurityId { Native = secSmartId },
				PortfolioName = portfolioName,
				Side = (Sides)side,
				OrderPrice = price ?? 0,
				Volume = volume,
				ServerTime = time.ApplyTimeZone(TimeHelper.Moscow),
				Balance = balance,
				OrderId = orderId == 0 ? (long?)null : orderId,
				OrderType = orderType,
				OrderState = orderState,
				OrderStatus = orderStatus,
				OriginalTransactionId = transactionId,
				OrderStringId = smartOrderId,
				ExpiryDate = isOneDay ? DateTimeOffset.Now.Date.ApplyTimeZone(TimeHelper.Moscow) : (DateTimeOffset?)null,
				Condition = orderType == OrderTypes.Conditional ? new SmartComOrderCondition { StopPrice = stop } : null,
				ExecutionType = ExecutionTypes.Order,
			});
		}