Esempio n. 1
0
        public static IDictionary<string, object> ApplyFilter(IFilterDescriptor filter)
        {
            IDictionary<string, object> parameters = new Dictionary<string, object>();
            string filerMessage = string.Empty;
            List<string> convertValue = new List<string>();
            string filerOperators = string.Empty;
            if (filter is CompositeFilterDescriptor)
            {
                foreach (IFilterDescriptor childFilter in ((CompositeFilterDescriptor)filter).FilterDescriptors)
                {
                    parameters.SafeAdd(ApplyFilter(childFilter));
                }
            }
            else
            {
                FilterDescriptor filterDescriptor = (FilterDescriptor)filter;
                filerMessage = filterDescriptor.Member;
                convertValue.Add(filterDescriptor.Value.ToSafeString());
                switch (filterDescriptor.Operator)
                {
                    case FilterOperator.IsEqualTo:
                        parameters.SafeAdd(filerMessage, filterDescriptor.Value);
                        break;
                    case FilterOperator.IsNotEqualTo:
                        parameters.SafeAdd(IdGenerator.NewComb().ToSafeString(), new Condition(string.Format("{0}<>'{1}'", filerMessage, filterDescriptor.Value)));
                        break;
                    case FilterOperator.StartsWith:
                        parameters.SafeAdd(IdGenerator.NewComb().ToSafeString(), new Condition(string.Format("{0} like '{1}%'", filerMessage, filterDescriptor.Value)));
                        break;
                    case FilterOperator.Contains:
                        parameters.SafeAdd(IdGenerator.NewComb().ToSafeString(), new Condition(string.Format("{0} like '%{1}%'", filerMessage, filterDescriptor.Value)));
                        break;
                    case FilterOperator.EndsWith:
                        parameters.SafeAdd(IdGenerator.NewComb().ToSafeString(), new Condition(string.Format("{0} like '%{1}'", filerMessage, filterDescriptor.Value)));
                        break;
                    case FilterOperator.IsLessThanOrEqualTo:
                        parameters.SafeAdd(IdGenerator.NewComb().ToSafeString(), new Condition(string.Format("{0} <='{1}'", filerMessage, filterDescriptor.Value)));
                        break;
                    case FilterOperator.IsLessThan:
                        parameters.SafeAdd(IdGenerator.NewComb().ToSafeString(), new Condition(string.Format("{0}<'{1}'", filerMessage, filterDescriptor.Value)));
                        break;
                    case FilterOperator.IsGreaterThanOrEqualTo:
                        parameters.SafeAdd(IdGenerator.NewComb().ToSafeString(), new Condition(string.Format("{0}>='{1}'", filerMessage, filterDescriptor.Value)));
                        break;
                    case FilterOperator.IsGreaterThan:
                        parameters.SafeAdd(IdGenerator.NewComb().ToSafeString(), new Condition(string.Format("{0}>'{1}'", filerMessage, filterDescriptor.Value)));
                        break;
                }
            }

            return parameters;
        }
Esempio n. 2
0
        public void Delete(string id)
        {
            string errorMsg = string.Empty;
            DoResult actionResult = DoResult.Failed;
            string actionMessage = string.Empty;

            try
            {
                string processDefID = Request.Form["ProcessDefID"];
                string activityID = id;
                ProcessDefine processDefine = wfEngine.GetProcessDefine(ProcessDefID);
                Activity activity = processDefine.Activities.FirstOrDefault(a => a.ID == activityID);
                processDefine.Activities.Remove(activity);

                foreach (var transition in processDefine.Transitions.Where(t => t.DestActivity == activityID || t.SrcActivity == activityID).ToList())
                {
                    processDefine.Transitions.Remove(transition);
                }

                // ProcessDefService processDefService = new ProcessDefService();
                IDictionary<string, object> parameters = new Dictionary<string, object>();
                parameters.SafeAdd("Name", processDefine.ID);
                parameters.SafeAdd("Version", processDefine.Version);
                ProcessDef processDef = repository.FindOne<ProcessDef>(parameters);
                processDef.Content = processDefine.ToXml();

                repository.SaveOrUpdate(processDef);

                wfEngine.ClearProcessCache();

                actionResult = DoResult.Success;
                //获取提示信息
                actionMessage = RemarkAttribute.GetEnumRemark(actionResult);

                //显示提示信息
                WebUtil.PromptMsg(actionMessage);

                //刷新页面
                Refresh();

            }
            catch (Exception ex)
            {
                //获取提示信息
                actionMessage = RemarkAttribute.GetEnumRemark(actionResult);
                log.Error(ex);
            }
        }
Esempio n. 3
0
        private Dictionary<string, List<int>> FindSameStrings(string text, int length, Dictionary<string, List<int>> indexes)
        {
            for (int startIndex = 0; startIndex < text.Length - length; startIndex++)
            {
                string cutString = text.Substring(startIndex, length);
                indexes.SafeAdd(cutString, startIndex);
            }

            indexes = indexes.Where(x => x.Value.Count > 1).ToDictionary(x => x.Key, x => x.Value);
            return indexes;
        }
Esempio n. 4
0
        /// <summary>
        /// 删除节点
        /// </summary>
        /// <param name="argument"></param>
        public string DeleteTreeNode(string argument)
        {
            AjaxResult ajaxResult = new AjaxResult();
            DoResult doResult = DoResult.Failed;
            string actionMessage = string.Empty;
            try
            {
                Organization org = repository.GetDomain<Organization>(argument);
                if (org != null)
                {
                    IDictionary<string, object> parameters = new Dictionary<string, object>();
                    parameters.SafeAdd("OrgID", org.ID);
                    IList<EmployeeOrg> employeeOrgList = repository.FindAll<EmployeeOrg>(parameters);
                    if (employeeOrgList.Count == 0)
                    {
                        repository.Delete<Organization>(org.ID);
                        doResult = DoResult.Success;
                    }
                    else
                    {
                        doResult = DoResult.Failed;
                        actionMessage = "请先删除该部门下面的操作员!";
                    }
                }
                else
                {
                    doResult = DoResult.Failed;
                }

                //获取提示信息
                actionMessage = string.Format("删除组织{0}", org.Name);

                //记录操作日志
                AddActionLog(org, doResult, actionMessage);

                ajaxResult.Result = doResult;
                ajaxResult.RetValue = org.ParentID;
                ajaxResult.PromptMsg = actionMessage;
            }
            catch (Exception ex)
            {
                log.Error(actionMessage, ex);
                AddActionLog<Organization>(actionMessage, DoResult.Failed);
            }

            return JsonConvert.SerializeObject(ajaxResult);
        }
        public Dictionary<Dictionary<char, char>, List<Dictionary<char, char>>> GetMatchSubs(Dictionary<char, char>[] substitutions)
        {
            Dictionary<Dictionary<char, char>, List<Dictionary<char, char>>> matchSubs = new Dictionary<Dictionary<char, char>, List<Dictionary<char, char>>>();

            foreach (var subs1 in substitutions)
            {
                foreach (var subs2 in substitutions)
                {
                    if (TextAnalysis.AreSubstMatch(subs1, subs2))
                    {
                        matchSubs.SafeAdd(subs1, subs2);
                    }
                }
            }

            return matchSubs;
        }
Esempio n. 6
0
        public string Delete(string argument)
        {
            AjaxResult ajaxResult = new AjaxResult();

            string errorMsg = string.Empty;
            DoResult doResult = DoResult.Failed;
            string actionMessage = string.Empty;
            try
            {
                if (!string.IsNullOrWhiteSpace(argument))
                {
                    string roleID = argument;

                    IRepository<string> repository = new Repository<string>();
                    IDictionary<string, object> parameters = new Dictionary<string, object>();
                    parameters.SafeAdd("RoleID", roleID);
                    IList<ObjectRole> objectRoleList = repository.FindAll<ObjectRole>(parameters);
                    if (objectRoleList.Count == 0)
                    {
                        repository.Delete<Role>(roleID);
                        repository.ExecuteSql<RolePrivilege>(string.Format("Delete from AC_RolePrivilege where RoleID='{0}'", roleID));
                        doResult = DoResult.Success;
                        actionMessage = RemarkAttribute.GetEnumRemark(doResult);
                    }
                    else
                    {
                        doResult = DoResult.Failed;
                        actionMessage = "请先解除该角色与操作员的关联!";
                    }

                    ajaxResult.RetValue = CurrentId;
                    ajaxResult.PromptMsg = actionMessage;
                }

                ajaxResult.Result = doResult;
            }
            catch (Exception ex)
            {
                actionMessage = RemarkAttribute.GetEnumRemark(doResult);
                log.Error(actionMessage, ex);
            }

            return JsonConvert.SerializeObject(ajaxResult);
        }
        /// <summary>
        /// 获取某个活动实例的所有工作项
        /// </summary>
        /// <param name="activityInstID">活动实例ID</param>
        /// <returns></returns>
        public IList<WorkItem> GetWorkItems(string activityInstID)
        {
            IDictionary<string, object> parameters = new Dictionary<string, object>();
            parameters.SafeAdd("ActivityInstID", activityInstID);

            return repository.FindAll<WorkItem>(parameters);
        }
Esempio n. 8
0
        /// <summary>
        /// 保存资源
        /// </summary>
        /// <param name="entity">资源实体</param>
        public void SaveResource(Resource entity)
        {
            using (ITransaction trans = UnitOfWork.BeginTransaction(typeof(Resource)))
            {
                repository.Clear<Resource>();
                repository.SaveOrUpdate(entity);

                IDictionary<string, object> parameters = new Dictionary<string, object>();
                parameters.Add("ResourceID", entity.ID);
                parameters.Add("OperateID", string.Empty);
                Privilege privilege = repository.FindOne<Privilege>(parameters);
                if (privilege == null)
                {
                    repository.SaveOrUpdate(new Privilege()
                    {
                        ID = IdGenerator.NewComb().ToString(),
                        MetaDataID = string.Empty,
                        Name = entity.Text,
                        OperateID = string.Empty,
                        //AppID = entity.AppID,
                        //OwnerOrg = entity.OwnerOrg,
                        //ModuleID = entity.ModuleID,
                        //Description = entity.Description,
                        ResourceID = entity.ID,
                        SortOrder = entity.SortOrder,

                        Type = entity.Type,
                        CreateTime = DateTime.Now,
                        Creator = entity.Creator,
                    });
                }

                if (entity.Operates != null)
                {
                    string idList = "";
                    foreach (var operate in entity.Operates)
                    {
                        idList += string.Format(" '{0}',", operate.ID);
                    }
                    string sWhere = string.IsNullOrEmpty(idList.TrimEnd(',')) ? "" : string.Format(" and OperateID not in ({0}) ", idList.TrimEnd(','));
                    repository.ExecuteSql<Resource>(string.Format("delete from AC_Operate where id in (select OperateID from AC_Privilege where ResourceID='{0}' and (OperateID is not null and OperateID<>'') {1})", entity.ID, sWhere));
                    repository.ExecuteSql<Resource>(string.Format("delete from AC_Privilege where ResourceID='{0}' and (OperateID is not null and OperateID<>'') {1}", entity.ID, sWhere));

                    foreach (var operate in entity.Operates)
                    {
                        repository.SaveOrUpdate(operate);
                        parameters.Clear();
                        parameters.SafeAdd("ResourceID", entity.ID);
                        parameters.SafeAdd("OperateID", operate.ID);
                        IList<Privilege> privilegeList = repository.FindAll<Privilege>(parameters);
                        if (privilegeList.Count == 0)
                        {
                            repository.SaveOrUpdate(new Privilege()
                            {
                                ID = IdGenerator.NewComb().ToString(),
                                //AppID = entity.AppID,
                                MetaDataID = string.Empty,
                                Name = operate.OperateName,
                                OperateID = operate.ID,
                                //ModuleID = entity.ModuleID,
                                //OwnerOrg = entity.OwnerOrg,
                                //Description = entity.Description,
                                ResourceID = entity.ID,
                                SortOrder = operate.SortOrder,
                                Type = 3,
                                CreateTime = DateTime.Now,
                                Creator = entity.Creator,
                            });
                        }
                    }
                }

                trans.Commit();
            }

            repository.ClearCache<Resource>();
            repository.ClearCache<Privilege>();
            repository.ClearCache<Operate>();
        }
Esempio n. 9
0
        /// <summary>
        /// 获取当前流程实例待执行工作项及参与者字典
        /// </summary>
        /// <param name="processInstID">流程实例ID</param>
        /// <returns></returns>
        public IDictionary<WorkItem, IList<Operator>> GetActiveWorkItems(string processInstID)
        {
            IDictionary<WorkItem, IList<Operator>> result = new Dictionary<WorkItem, IList<Operator>>();

            var activeWorkItems = repository.Query<WorkItem>().Where(o => o.ProcessInstID == processInstID && o.CurrentState == (short)WorkItemStatus.WaitExecute);
            foreach (var item in activeWorkItems)
            {
                IDictionary<string, object> parameters = new Dictionary<string, object>();
                parameters.Add("WorkItemID", item.ID);
                var participants = repository.ExecuteDataTable<WorkItem>(@"select * from AC_Operator where ID in (select ParticipantID from WF_Participant where WorkItemID=$WorkItemID and ParticipantType=1)
            union
            select * from AC_Operator where ID in (select ObjectID from OM_ObjectRole where RoleID in (select ParticipantID from WF_Participant where WorkItemID=$WorkItemID and ParticipantType=2))
            union
            select * from AC_Operator where ID in (select EmployeeID from OM_EmployeeOrg where OrgID in( select ParticipantID from WF_Participant where WorkItemID=$WorkItemID and ParticipantType=3))
            ", parameters).ToList<Operator>();

                result.SafeAdd(item, participants);
            }
            return result;
        }
Esempio n. 10
0
 private PositionInfo GetPosition(SecurityId securityId)
 => _positions.SafeAdd(securityId, k => new PositionInfo(k, _getMarginPrice));
Esempio n. 11
0
        /// <summary>
        /// 获取组织下的所有员工
        /// </summary>
        /// <param name="orgID">组织ID</param>
        /// <returns></returns>
        public IList<Employee> GetEmployees(string orgID)
        {
            IDictionary<string, object> parameters = new Dictionary<string, object>();
            parameters.SafeAdd("ID", new Condition(string.Format("ID in (select b.EmployeeID from OM_EmployeeOrg b where b.OrgID='{0}')", orgID)));

            return repository.FindAll<Employee>(parameters);
        }
Esempio n. 12
0
            public override void SendOutMessage(Message message)
            {
                switch (message.Type)
                {
                case MessageTypes.Portfolio:
                {
                    var pfMsg = (PortfolioMessage)message;
                    SessionHolder.ReplaceBoardCode(pfMsg.BoardCode, board => pfMsg.BoardCode = board);
                    break;
                }

                case MessageTypes.PortfolioChange:
                {
                    var pfMsg = (PortfolioChangeMessage)message;

                    SessionHolder.ReplaceBoardCode(pfMsg.BoardCode, board => pfMsg.BoardCode = board);

                    var depoName = (string)pfMsg.Changes.TryGetValue(PositionChangeTypes.DepoName);
                    if (!depoName.IsEmpty())
                    {
                        _depoNames[pfMsg.PortfolioName] = depoName;
                    }

                    break;
                }

                case MessageTypes.Position:
                {
                    var pfMsg = (PositionMessage)message;
                    SessionHolder.ReplaceSecurityId(pfMsg.SecurityId, id => pfMsg.SecurityId = id);
                    break;
                }

                case MessageTypes.PositionChange:
                {
                    var pfMsg = (PositionChangeMessage)message;
                    SessionHolder.ReplaceSecurityId(pfMsg.SecurityId, id => pfMsg.SecurityId = id);
                    break;
                }

                case MessageTypes.Execution:
                {
                    var execMsg = (ExecutionMessage)message;

                    switch (execMsg.ExecutionType)
                    {
                    case ExecutionTypes.Order:
                    {
                        if (execMsg.OrderId != null && execMsg.OriginalTransactionId != 0)
                        {
                            _transactionsByOrderId.SafeAdd(execMsg.OrderId.Value, i => execMsg.OriginalTransactionId);

                            var trades = _tradesByOrderId.TryGetValue(execMsg.OrderId.Value);

                            if (trades != null)
                            {
                                trades.ForEach(SendOutMessage);
                                _tradesByOrderId.Remove(execMsg.OrderId.Value);
                            }
                        }

                        break;
                    }

                    case ExecutionTypes.Trade:
                    {
                        if (execMsg.OriginalTransactionId != 0)
                        {
                            break;
                        }

                        var orderId = execMsg.OrderId;

                        if (orderId != null)
                        {
                            var origTransactionId = _transactionsByOrderId.TryGetValue2(orderId.Value);

                            if (origTransactionId == null)
                            {
                                _tradesByOrderId.SafeAdd(orderId.Value).Add(execMsg);
                                return;
                            }

                            execMsg.OriginalTransactionId = origTransactionId.Value;
                        }

                        break;
                    }
                    }

                    SessionHolder.ReplaceSecurityId(execMsg.SecurityId, id => execMsg.SecurityId = id);

                    // запоминаем номер исходной транзакции, который будет исопльзоваться в FixServer
                    execMsg.UserOrderId = execMsg.OriginalTransactionId.To <string>();

                    var transaction = _transactions.TryGetValue(execMsg.OriginalTransactionId);

                    if (transaction != null && execMsg.Error != null)
                    {
                        switch (transaction.TransactionType)
                        {
                        case TransactionTypes.ReRegister:
                        {
                            var replaceMsg = (OrderReplaceMessage)transaction.Message;

                            // дополнительно отправляем сообщение ошибки снятия заявки
                            var cancelErrMsg = (ExecutionMessage)execMsg.Clone();
                            cancelErrMsg.OrderId     = replaceMsg.OldOrderId;
                            cancelErrMsg.IsCancelled = true;
                            base.SendOutMessage(cancelErrMsg);

                            break;
                        }

                        case TransactionTypes.Cancel:
                        {
                            var cancelMsg = (OrderCancelMessage)transaction.Message;

                            // заполняем номер заявки
                            execMsg.OrderId     = cancelMsg.OrderId;
                            execMsg.IsCancelled = true;
                            break;
                        }
                        }
                    }

                    break;
                }
                }

                base.SendOutMessage(message);
            }
Esempio n. 13
0
		static NamespaceDom[] MergeNamespaces(IEnumerable<NamespaceDom> namespaces)
		{
			var nsDict = new Dictionary<string, NamespaceDom>();
			
			foreach (var ns in namespaces)
			{
				var curNs = nsDict.SafeAdd(ns.Name, name => new NamespaceDom(name));
				curNs.Types.AddMany(ns.Types);
			}

			return nsDict.Values.OrderBy(_ => _.Name).ToArray();
		}
Esempio n. 14
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                string workItemID = Request.QueryString["workItemID"];
                WorkItem workItem = engine.Persistence.Repository.GetDomain<WorkItem>(workItemID);
                ActivityInst activityInst = engine.Persistence.GetActivityInst(workItem.ActivityInstID);
                ManualActivity manualActivity = engine.Persistence.GetActivity(workItem.ProcessID, activityInst.ActivityDefID) as ManualActivity;

                AgileEAP.EForm.FormView formView = new AgileEAP.EForm.FormView();
                formView.Form = manualActivity.Form;
                hidDataSource.Value = manualActivity.Form.DataSource;

                IDictionary<string, object> parameters = new Dictionary<string, object>();
                parameters.SafeAdd("processInstID", Request.QueryString["processInstID"]);
                ProcessForm processForm = engine.Persistence.Repository.FindOne<ProcessForm>(parameters);
                if (processForm != null)
                {
                    parameters.Clear();
                    parameters.Add("ID", processForm.BizID);
                    DataTable dt = engine.Persistence.Repository.ExecuteDataTable<ProcessForm>(string.Format("select * from {0}", processForm.BizTable), parameters);

                    if (dt != null && dt.Rows.Count > 0)
                    {
                        IDictionary<string, object> values = new Dictionary<string, object>();

                        foreach (DataRow row in dt.Rows)
                        {
                            foreach (DataColumn column in dt.Columns)
                            {
                                values.SafeAdd(column.ColumnName, row[column.ColumnName]);
                            }
                        }

                        formView.Values = values;
                    }
                }

                eForm.Controls.Add(formView);
            }
        }
Esempio n. 15
0
        public string Delete(string operatorID)
        {
            AjaxResult ajaxResult = new AjaxResult();

            string errorMsg = string.Empty;
            DoResult doResult = DoResult.Failed;
            string actionMessage = string.Empty;
            try
            {
                if (!string.IsNullOrWhiteSpace(operatorID))
                {
                    IRepository<string> repository = new Repository<string>();

                    UnitOfWork.ExecuteWithTrans<Operator>(() =>
                        {
                            repository.Delete<Operator>(operatorID);

                            IDictionary<string, object> parameters = new Dictionary<string, object>();
                            parameters.SafeAdd("OperatorID", operatorID);
                            Employee employee = repository.FindOne<Employee>(parameters);
                            repository.Delete<Employee>(parameters);

                            parameters.Clear();
                            parameters.SafeAdd("EmployeeID", employee.ID);
                            repository.Delete<EmployeeOrg>(parameters);

                            parameters.Clear();
                            parameters.SafeAdd("ObjectID", operatorID);
                            repository.Delete<ObjectRole>(parameters);
                        });


                    doResult = DoResult.Success;

                    //获取提示信息
                    actionMessage = RemarkAttribute.GetEnumRemark(doResult);

                    ajaxResult.RetValue = CurrentId;
                    ajaxResult.PromptMsg = actionMessage;
                }

                ajaxResult.Result = doResult;
            }
            catch (Exception ex)
            {
                actionMessage = RemarkAttribute.GetEnumRemark(doResult);
                log.Error(actionMessage, ex);
            }

            return JsonConvert.SerializeObject(ajaxResult);
        }
        private void ProcessMessage <TMessage>(SecurityId securityId, TMessage message, long originTransId, bool throwIfSecIdEmpty, Func <TMessage, TMessage, TMessage> processSuspend)
            where TMessage : Message
        {
            bool skip;

            lock (_syncRoot)
                skip = _skipTransactions.Contains(originTransId);

            if (skip)
            {
                base.OnInnerAdapterNewOutMessage(message);
                return;
            }

            var native = securityId.Native;

            if (native != null)
            {
                SecurityId?fullSecurityId;

                lock (_syncRoot)
                    fullSecurityId = _securityIds.TryGetValue2(native);

                if (fullSecurityId == null)
                {
                    lock (_syncRoot)
                    {
                        var tuple = _suspendedOutMessages.SafeAdd(securityId, key => RefTuple.Create((List <Message>)null, (Dictionary <MessageTypes, Message>)null));

                        var clone = message.Clone();

                        if (processSuspend == null)
                        {
                            if (tuple.First == null)
                            {
                                tuple.First = new List <Message>();
                            }

                            tuple.First.Add(clone);
                        }
                        else
                        {
                            if (tuple.Second == null)
                            {
                                tuple.Second = new Dictionary <MessageTypes, Message>();
                            }

                            var prev = tuple.Second.TryGetValue(clone.Type);

                            tuple.Second[clone.Type] = prev == null
                                                                ? clone
                                                                : processSuspend((TMessage)prev, (TMessage)clone);
                        }
                    }

                    return;
                }

                message.ReplaceSecurityId(fullSecurityId.Value);
            }
            else
            {
                var securityCode = securityId.SecurityCode;
                var boardCode    = securityId.BoardCode;

                var isSecCodeEmpty = securityCode.IsEmpty();

                if (isSecCodeEmpty && throwIfSecIdEmpty)
                {
                    throw new InvalidOperationException();
                }

                if (!isSecCodeEmpty && boardCode.IsEmpty())
                {
                    SecurityId?foundId = null;

                    lock (_syncRoot)
                    {
                        foreach (var id in _securityIds.Values)
                        {
                            if (!id.SecurityCode.CompareIgnoreCase(securityCode))
                            {
                                continue;
                            }

                            //if (securityId.SecurityType != null && securityId.SecurityType != id.SecurityType)
                            //	continue;

                            foundId = id;
                        }

                        if (foundId == null)
                        {
                            var tuple = _suspendedOutMessages.SafeAdd(securityId, key => RefTuple.Create(new List <Message>(), (Dictionary <MessageTypes, Message>)null));
                            tuple.First.Add(message.Clone());
                            return;
                        }
                    }

                    message.ReplaceSecurityId(foundId.Value);

                    //// если указан код и тип инструмента, то пытаемся найти инструмент по ним
                    //if (securityId.SecurityType != null)
                    //{

                    //}
                    //else
                    //	throw new ArgumentException(nameof(securityId), LocalizedStrings.Str682Params.Put(securityCode, securityId.SecurityType));
                }
            }

            base.OnInnerAdapterNewOutMessage(message);
        }
Esempio n. 17
0
        /// <summary>
        /// Vrátí slova, která mají stejný vzor
        /// </summary>
        /// <param name="testWords"></param>
        /// <param name="templates"></param>
        /// <returns></returns>
        private Dictionary<string, List<string>> GetWordsWithSamePatterns(Dictionary<string, string> testWordsHashes, Dictionary<string, string> templatesHashes)
        {
            Dictionary<string, List<string>> samePattern = new Dictionary<string, List<string>>();

            foreach (var testWordHash in testWordsHashes)
            {
                foreach (var templateHash in templatesHashes)
                {
                    if (testWordHash.Value == templateHash.Value)
                    {
                        samePattern.SafeAdd(testWordHash.Key, templateHash.Key);
                    }
                }
            }

            return samePattern;
        }
        private void OnProcessPositions(long transactionId, string[] data)
        {
            var f = Wrapper.FieldsPositions;
            var portfChangeMessages = new Dictionary <string, PortfolioChangeMessage>();

            foreach (var str in data)
            {
                var cols = str.ToColumns();

                var portfolioName = GetPortfolioName(f.AccCode.GetValue(cols), this.GetBoardCode(f.PlaceCode.GetValue(cols)));
                var secCode       = f.PaperCode.GetValue(cols);

                if (secCode == "money")
                {
                    var changesMsg = portfChangeMessages.SafeAdd(portfolioName, this.CreatePortfolioChangeMessage);

                    changesMsg.Add(PositionChangeTypes.RealizedPnL, f.PnL.GetValue(cols));
                    changesMsg.Add(PositionChangeTypes.UnrealizedPnL, f.ProfitVol.GetValue(cols));
                    changesMsg.Add(PositionChangeTypes.CurrentPrice, f.RealVol.GetValue(cols));
                    changesMsg.Add(PositionChangeTypes.BeginValue, f.IncomeRest.GetValue(cols));
                    changesMsg.Add(PositionChangeTypes.CurrentValue, f.RealRest.GetValue(cols));
                }
                else
                {
                    var secId = new SecurityId {
                        Native = f.PaperNo.GetValue(cols)
                    };

                    SendOutMessage(new PositionMessage
                    {
                        PortfolioName = portfolioName,
                        SecurityId    = secId
                    });

                    var changesMsg = this.CreatePositionChangeMessage(portfolioName, secId);

                    changesMsg.Add(PositionChangeTypes.RealizedPnL, f.PnL.GetValue(cols));
                    changesMsg.Add(PositionChangeTypes.UnrealizedPnL, f.ProfitVol.GetValue(cols));
                    changesMsg.Add(PositionChangeTypes.CurrentPrice, f.RealVol.GetValue(cols));
                    changesMsg.Add(PositionChangeTypes.CurrentValue, f.ForwordRest.GetValue(cols));
                    changesMsg.Add(PositionChangeTypes.AveragePrice, f.BalancePrice.GetValue(cols));

                    var varMargin = f.VarMargin.GetValue(cols);
                    changesMsg.Add(PositionChangeTypes.VariationMargin, varMargin);

                    if (varMargin != 0)
                    {
                        var portfChangesMsg = portfChangeMessages.SafeAdd(portfolioName, this.CreatePortfolioChangeMessage);
                        var oldVm           = portfChangesMsg.Changes.TryGetValue(PositionChangeTypes.VariationMargin);

                        if (oldVm == null)
                        {
                            portfChangesMsg.Changes[PositionChangeTypes.VariationMargin] = varMargin;
                        }
                        else
                        {
                            portfChangesMsg.Changes[PositionChangeTypes.VariationMargin] = (decimal)oldVm + varMargin;
                        }
                    }

                    SendOutMessage(changesMsg);
                }
            }

            portfChangeMessages.Values.ForEach(SendOutMessage);

            if (transactionId > 0)
            {
                SendOutMessage(new PortfolioLookupResultMessage
                {
                    OriginalTransactionId = transactionId,
                });
            }
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="StorageMessageAdapter"/>.
        /// </summary>
        /// <param name="innerAdapter">The adapter, to which messages will be directed.</param>
        /// <param name="storageRegistry">The storage of market data.</param>
        /// <param name="snapshotRegistry">Snapshot storage registry.</param>
        /// <param name="candleBuilderProvider">Candle builders provider.</param>
        public StorageMessageAdapter(IMessageAdapter innerAdapter, IStorageRegistry storageRegistry, SnapshotRegistry snapshotRegistry, CandleBuilderProvider candleBuilderProvider)
            : base(innerAdapter)
        {
            _storageRegistry       = storageRegistry ?? throw new ArgumentNullException(nameof(storageRegistry));
            _snapshotRegistry      = snapshotRegistry ?? throw new ArgumentNullException(nameof(snapshotRegistry));
            _candleBuilderProvider = candleBuilderProvider ?? throw new ArgumentNullException(nameof(candleBuilderProvider));

            var isProcessing = false;
            var sync         = new SyncObject();

            var unkByOrderId       = new Dictionary <long, List <ExecutionMessage> >();
            var unkByOrderStringId = new Dictionary <string, List <ExecutionMessage> >(StringComparer.InvariantCultureIgnoreCase);

            ThreadingHelper.Timer(() =>
            {
                lock (sync)
                {
                    if (isProcessing)
                    {
                        return;
                    }

                    isProcessing = true;
                }

                try
                {
                    foreach (var pair in GetTicks())
                    {
                        GetStorage <ExecutionMessage>(pair.Key, ExecutionTypes.Tick).Save(pair.Value);
                    }

                    foreach (var pair in GetOrderLog())
                    {
                        GetStorage <ExecutionMessage>(pair.Key, ExecutionTypes.OrderLog).Save(pair.Value);
                    }

                    foreach (var pair in GetTransactions())
                    {
                        var secId = pair.Key;

                        if (Mode.Contains(StorageModes.Incremental))
                        {
                            GetStorage <ExecutionMessage>(secId, ExecutionTypes.Transaction).Save(pair.Value);
                        }

                        if (Mode.Contains(StorageModes.Snapshot))
                        {
                            var snapshotStorage = GetSnapshotStorage(typeof(ExecutionMessage), ExecutionTypes.Transaction);

                            foreach (var message in pair.Value)
                            {
                                var originTransId = message.OriginalTransactionId;

                                if (message.TransactionId == 0 && originTransId == 0)
                                {
                                    if (!message.HasTradeInfo)
                                    {
                                        continue;
                                    }

                                    long transId;

                                    if (message.OrderId != null)
                                    {
                                        if (!_orderIds.TryGetValue(message.OrderId.Value, out transId))
                                        {
                                            unkByOrderId.SafeAdd(message.OrderId.Value).Add(message);
                                            continue;
                                        }
                                    }
                                    else if (!message.OrderStringId.IsEmpty())
                                    {
                                        if (!_orderStringIds.TryGetValue(message.OrderStringId, out transId))
                                        {
                                            unkByOrderStringId.SafeAdd(message.OrderStringId).Add(message);
                                            continue;
                                        }
                                    }
                                    else
                                    {
                                        continue;
                                    }

                                    originTransId = transId;
                                }
                                else
                                {
                                    // do not store cancellation commands into snapshot
                                    if (message.IsCancellation && message.TransactionId != 0)
                                    {
                                        continue;
                                    }

                                    if (originTransId != 0)
                                    {
                                        if (/*message.TransactionId == 0 && */ _cancellationTransactions.TryGetValue(originTransId, out var temp))
                                        {
                                            // do not store cancellation errors
                                            if (message.Error != null)
                                            {
                                                continue;
                                            }

                                            // override cancel trans id by original order's registration trans id
                                            originTransId = temp;
                                        }

                                        if (_orderStatusIds.Contains(originTransId))
                                        {
                                            // override status request trans id by original order's registration trans id
                                            originTransId = message.TransactionId;
                                        }
                                    }

                                    if (originTransId != 0)
                                    {
                                        if (message.OrderId != null)
                                        {
                                            _orderIds.TryAdd(message.OrderId.Value, originTransId);
                                        }
                                        else if (message.OrderStringId != null)
                                        {
                                            _orderStringIds.TryAdd(message.OrderStringId, originTransId);
                                        }
                                    }
                                }

                                message.SecurityId = secId;

                                if (message.TransactionId == 0)
                                {
                                    message.TransactionId = originTransId;
                                }

                                message.OriginalTransactionId = 0;

                                SaveTransaction(snapshotStorage, message);

                                if (message.OrderId != null)
                                {
                                    if (unkByOrderId.TryGetValue(message.OrderId.Value, out var suspended))
                                    {
                                        unkByOrderId.Remove(message.OrderId.Value);

                                        foreach (var trade in suspended)
                                        {
                                            trade.TransactionId = message.TransactionId;
                                            SaveTransaction(snapshotStorage, trade);
                                        }
                                    }
                                }
                                else if (!message.OrderStringId.IsEmpty())
                                {
                                    if (unkByOrderStringId.TryGetValue(message.OrderStringId, out var suspended))
                                    {
                                        unkByOrderStringId.Remove(message.OrderStringId);

                                        foreach (var trade in suspended)
                                        {
                                            trade.TransactionId = message.TransactionId;
                                            SaveTransaction(snapshotStorage, trade);
                                        }
                                    }
                                }
                            }
                        }
                    }

                    foreach (var pair in GetOrderBooks())
                    {
                        if (Mode.Contains(StorageModes.Incremental))
                        {
                            GetStorage <QuoteChangeMessage>(pair.Key, null).Save(pair.Value);
                        }

                        if (Mode.Contains(StorageModes.Snapshot))
                        {
                            var snapshotStorage = GetSnapshotStorage(typeof(QuoteChangeMessage), null);

                            foreach (var message in pair.Value)
                            {
                                snapshotStorage.Update(message);
                            }
                        }
                    }

                    foreach (var pair in GetLevel1())
                    {
                        var messages = pair.Value.Where(m => m.Changes.Count > 0).ToArray();

                        var dt = DateTime.Today;

                        var historical = messages.Where(m => m.ServerTime < dt).ToArray();
                        var today      = messages.Where(m => m.ServerTime >= dt).ToArray();

                        GetStorage <Level1ChangeMessage>(pair.Key, null).Save(historical);

                        if (Mode.Contains(StorageModes.Incremental))
                        {
                            GetStorage <Level1ChangeMessage>(pair.Key, null).Save(today);
                        }

                        if (Mode.Contains(StorageModes.Snapshot))
                        {
                            var snapshotStorage = GetSnapshotStorage(typeof(Level1ChangeMessage), null);

                            foreach (var message in today)
                            {
                                snapshotStorage.Update(message);
                            }
                        }
                    }

                    foreach (var pair in GetCandles())
                    {
                        GetStorage(pair.Key.Item1, pair.Key.Item2, pair.Key.Item3).Save(pair.Value);
                    }

                    foreach (var pair in GetPositionChanges())
                    {
                        var messages = pair.Value.Where(m => m.Changes.Count > 0).ToArray();

                        if (Mode.Contains(StorageModes.Incremental))
                        {
                            GetStorage <PositionChangeMessage>(pair.Key, null).Save(messages);
                        }

                        if (Mode.Contains(StorageModes.Snapshot))
                        {
                            var snapshotStorage = GetSnapshotStorage(typeof(PositionChangeMessage), null);

                            foreach (var message in messages)
                            {
                                snapshotStorage.Update(message);
                            }
                        }
                    }

                    var news = GetNews().ToArray();

                    if (news.Length > 0)
                    {
                        _storageRegistry.GetNewsMessageStorage(Drive, Format).Save(news);
                    }
                }
                catch (Exception excp)
                {
                    excp.LogError();
                }
                finally
                {
                    lock (sync)
                        isProcessing = false;
                }
            }).Interval(TimeSpan.FromSeconds(10));
        }
Esempio n. 20
0
        private void Download_OnClick(object sender, RoutedEventArgs e)
        {
            var settings = new Settings
            {
                Year      = SelectedYear.Year,
                Trader    = Trader.Text,
                From      = From.Value,
                To        = To.Value,
                Security1 = Security1.Text,
                Security2 = Security2.Text,
                Security3 = Security3.Text,
                Security4 = Security4.Text,
                TimeFrame = SelectedTimeFrame,
                Apart     = Apart.IsChecked == true,
            };

            CultureInfo.InvariantCulture.DoInCulture(() => new XmlSerializer <SettingsStorage>().Serialize(settings.Save(), _settingsFile));

            var year   = SelectedYear;
            var from   = From.Value ?? year.Days.First();
            var to     = (To.Value ?? year.Days.Last()).EndOfDay();
            var trader = SelectedTrader;
            var tf     = SelectedTimeFrame;
            var apart  = Apart.IsChecked == true;

            var seriesSet = _securityCtrls
                            .Where(pair => pair.Key.SelectedSecurity != null)
                            .Select(pair => Tuple.Create(new CandleSeries(typeof(TimeFrameCandle), pair.Key.SelectedSecurity, tf), pair.Value))
                            .ToArray();

            BusyIndicator.BusyContent = "Подготовка данных...";
            BusyIndicator.IsBusy      = true;

            _candles.Clear();

            var trades = new Dictionary <Security, Dictionary <DateTimeOffset, Tuple <MyTrade[], MyTrade> > >();

            var worker = new BackgroundWorker {
                WorkerReportsProgress = true
            };

            worker.DoWork += (o, ea) =>
            {
                foreach (var series in seriesSet)
                {
                    var security      = series.Item1.Security;
                    var candleStorage = _dataRegistry.GetCandleStorage(series.Item1, format: StorageFormats.Csv);
                    var secCandles    = _candles.SafeAdd(security);

                    secCandles.Clear();
                    secCandles.AddRange(candleStorage.Load(from, to));

                    var candlesDatesCache = _candlesDates.SafeAdd(Tuple.Create(security, tf), k => new DatesCache(Path.Combine(((LocalMarketDataDrive)candleStorage.Drive.Drive).GetSecurityPath(security.ToSecurityId()), "{0}min_date.bin".Put((int)tf.TotalMinutes))));

                    var minCandleDate = candlesDatesCache.MinValue;
                    var maxCandleDate = candlesDatesCache.MaxValue;

                    if (from >= minCandleDate && to <= maxCandleDate)
                    {
                        continue;
                    }

                    var finamFrom = from;
                    var finamTo   = to;

                    if (maxCandleDate != null && finamFrom >= minCandleDate && finamFrom <= maxCandleDate)
                    {
                        finamFrom = maxCandleDate.Value + TimeSpan.FromDays(1);
                    }

                    if (minCandleDate != null && finamTo >= minCandleDate && finamTo <= maxCandleDate)
                    {
                        finamTo = minCandleDate.Value - TimeSpan.FromDays(1);
                    }

                    if (finamTo <= finamFrom)
                    {
                        continue;
                    }

                    TimeFrameCandle[] newCandles;

                    if (tf.Ticks == 1)
                    {
                        newCandles = finamFrom.Range(finamTo, TimeSpan.FromDays(1)).SelectMany(day =>
                        {
                            worker.ReportProgress(1, Tuple.Create(security, day));

                            var candles = _finamHistorySource.GetTrades(security, day, day).ToEx().ToCandles <TimeFrameCandle>(tf).ToArray();
                            candleStorage.Save(candles);
                            candlesDatesCache.Add(day);
                            return(candles);
                        }).ToArray();
                    }
                    else
                    {
                        worker.ReportProgress(1, Tuple.Create(security, finamFrom, finamTo));
                        newCandles = _finamHistorySource.GetCandles(security, tf, finamFrom, finamTo).ToArray();

                        candleStorage.Save(newCandles);
                        candlesDatesCache.Add(newCandles.Select(c => c.OpenTime.Date).Distinct().ToArray());
                    }

                    // TODO
                    secCandles.AddRange(newCandles);
                }

                var traderDrive   = new LocalMarketDataDrive(Path.Combine(_settingsDir, trader));
                var traderStorage = _traderStorages.SafeAdd(trader, key => new StorageRegistry {
                    DefaultDrive = traderDrive
                });

                foreach (var series in seriesSet)
                {
                    var security = series.Item1.Security;

                    var olStorage       = traderStorage.GetOrderLogStorage(security, format: StorageFormats.Csv);
                    var tradeDatesCache = _tradesDates.SafeAdd(trader, k => new DatesCache(Path.Combine(traderDrive.Path, "dates.xml")));

                    var secTrades = from
                                    .Range(to, TimeSpan.FromDays(1))
                                    .Intersect(year.Days)
                                    .SelectMany(date =>
                    {
                        if (olStorage.Dates.Contains(date))
                        {
                            return(olStorage.Load(date));
                        }

                        if (tradeDatesCache.Contains(date))
                        {
                            return(Enumerable.Empty <OrderLogItem>());
                        }

                        worker.ReportProgress(2, date);

                        var loadedTrades = year.GetTrades(_securityStorage, trader, date);

                        var dateTrades = Enumerable.Empty <OrderLogItem>();

                        foreach (var group in loadedTrades.GroupBy(t => t.Order.Security))
                        {
                            var sec = group.Key;

                            traderStorage
                            .GetOrderLogStorage(sec, format: StorageFormats.Csv)
                            .Save(group.OrderBy(i => i.Order.Time));

                            if (group.Key == security)
                            {
                                dateTrades = group;
                            }
                        }

                        tradeDatesCache.Add(date);

                        return(dateTrades);
                    })
                                    .GroupBy(ol =>
                    {
                        var time = ol.Order.Time;

                        var period = security.Board.WorkingTime.GetPeriod(time.ToLocalTime(security.Board.Exchange.TimeZoneInfo));
                        if (period != null && period.Times.Length > 0)
                        {
                            var last = period.Times.Last().Max;

                            if (time.TimeOfDay >= last)
                            {
                                time = time.AddTicks(-1);
                            }
                        }

                        if (tf == TimeSpan.FromDays(1) && period != null && period.Times.Length > 0)
                        {
                            return(new DateTimeOffset(time.Date + period.Times[0].Min, time.Offset));
                        }

                        return(time.Truncate(tf));
                    })
                                    .ToDictionary(g => g.Key, g =>
                    {
                        var candleTrades = g.Select(ol => new MyTrade
                        {
                            Order = ol.Order,
                            Trade = ol.Trade
                        })
                                           .ToArray();

                        if (candleTrades.Length == 0)
                        {
                            return(null);
                        }

                        var order  = candleTrades[0].Order;
                        var volume = candleTrades.Sum(t1 => t1.Trade.Volume * (t1.Order.Direction == Sides.Buy ? 1 : -1));

                        if (volume == 0)
                        {
                            return(Tuple.Create(candleTrades, (MyTrade)null));
                        }

                        var side = volume > 0 ? Sides.Buy : Sides.Sell;

                        volume = volume.Abs();

                        var availableVolume = volume;
                        var avgPrice        = 0m;

                        foreach (var trade in candleTrades.Where(t1 => t1.Order.Direction == side))
                        {
                            var tradeVol = trade.Trade.Volume.Min(availableVolume);
                            avgPrice    += trade.Trade.Price * tradeVol;

                            availableVolume -= tradeVol;

                            if (availableVolume <= 0)
                            {
                                break;
                            }
                        }

                        avgPrice = avgPrice / volume;

                        return(Tuple.Create(candleTrades, new MyTrade
                        {
                            Order = new Order
                            {
                                Security = order.Security,
                                Direction = side,
                                Time = g.Key,
                                Portfolio = order.Portfolio,
                                Price = avgPrice,
                                Volume = volume,
                            },
                            Trade = new Trade
                            {
                                Security = order.Security,
                                Time = g.Key,
                                Volume = volume,
                                Price = avgPrice
                            }
                        }));
                    });

                    trades.Add(security, secTrades);
                }
            };

            worker.ProgressChanged += (o, ea) =>
            {
                switch (ea.ProgressPercentage)
                {
                case 1:
                {
                    if (ea.UserState is Tuple <Security, DateTime> )
                    {
                        BusyIndicator.BusyContent = "Скачивание {Item1.Id} тиков за {Item2:yyyy-MM-dd}...".PutEx(ea.UserState);
                    }
                    else
                    {
                        BusyIndicator.BusyContent = "Скачивание {Item1.Id} свечей с {Item2:yyyy-MM-dd} по {Item3:yyyy-MM-dd}...".PutEx(ea.UserState);
                    }

                    break;
                }

                default:
                    BusyIndicator.BusyContent = "Скачивание сделок за {0:yyyy-MM-dd}...".Put(ea.UserState);
                    break;
                }
            };

            worker.RunWorkerCompleted += (o, ea) =>
            {
                BusyIndicator.IsBusy = false;

                if (ea.Error == null)
                {
                    Chart.ClearAreas();

                    _statisticManager.Reset();

                    var equityInd = new SimpleMovingAverage {
                        Length = 1
                    };
                    ChartIndicatorElement equityElem;
                    var candlesAreas = new Dictionary <CandleSeries, ChartArea>();

                    if (apart)
                    {
                        foreach (var series in seriesSet)
                        {
                            var area = new ChartArea {
                                Title = series.Item1.Security.Id
                            };
                            Chart.AddArea(area);
                            area.YAxises.Clear();
                            candlesAreas.Add(series.Item1, area);
                        }

                        var equityArea = new ChartArea {
                            Title = LocalizedStrings.PnL
                        };
                        Chart.AddArea(equityArea);

                        equityElem = new ChartIndicatorElement
                        {
                            FullTitle        = LocalizedStrings.PnL,
                            IndicatorPainter = new PnlPainter()
                        };
                        Chart.AddElement(equityArea, equityElem);
                    }
                    else
                    {
                        var candlesArea = new ChartArea();
                        Chart.AddArea(candlesArea);

                        foreach (var tuple in seriesSet)
                        {
                            candlesAreas.Add(tuple.Item1, candlesArea);
                        }

                        const string equityYAxis = "Equity";

                        candlesArea.YAxises.Clear();
                        candlesArea.YAxises.Add(new ChartAxis
                        {
                            Id            = equityYAxis,
                            AutoRange     = true,
                            AxisType      = ChartAxisType.Numeric,
                            AxisAlignment = ChartAxisAlignment.Left,
                        });
                        equityElem = new ChartIndicatorElement
                        {
                            YAxisId          = equityYAxis,
                            FullTitle        = LocalizedStrings.PnL,
                            IndicatorPainter = new PnlPainter()
                        };
                        Chart.AddElement(candlesArea, equityElem);
                    }

                    var positionArea = new ChartArea {
                        Height = 100
                    };
                    Chart.AddArea(positionArea);
                    positionArea.YAxises.Clear();

                    var chartValues = new SortedDictionary <DateTimeOffset, IDictionary <IChartElement, object> >();
                    var pnlValues   = new Dictionary <DateTimeOffset, decimal>();

                    foreach (var series in seriesSet)
                    {
                        var security = series.Item1.Security;

                        var candleYAxis = "Candles_Y_" + security.Id;

                        var candlesArea = candlesAreas[series.Item1];

                        candlesArea.YAxises.Add(new ChartAxis
                        {
                            Id            = candleYAxis,
                            AutoRange     = true,
                            AxisType      = ChartAxisType.Numeric,
                            AxisAlignment = ChartAxisAlignment.Right,
                        });

                        var candlesElem = new ChartCandleElement
                        {
                            ShowAxisMarker = false,
                            YAxisId        = candleYAxis,
                        };
                        Chart.AddElement(candlesArea, candlesElem, series.Item1);

                        var tradesElem = new ChartTradeElement
                        {
                            BuyStrokeColor  = Colors.Black,
                            SellStrokeColor = Colors.Black,
                            BuyColor        = series.Item2.Buy,
                            SellColor       = series.Item2.Sell,
                            FullTitle       = LocalizedStrings.Str985 + " " + security.Id,
                            YAxisId         = candleYAxis,
                        };
                        Chart.AddElement(candlesArea, tradesElem);

                        var posYAxis = "Pos_Y_" + security.Id;
                        positionArea.YAxises.Add(new ChartAxis
                        {
                            Id            = posYAxis,
                            AutoRange     = true,
                            AxisType      = ChartAxisType.Numeric,
                            AxisAlignment = ChartAxisAlignment.Right,
                        });
                        var positionElem = new ChartIndicatorElement
                        {
                            FullTitle = LocalizedStrings.Str862 + " " + security.Id,
                            YAxisId   = posYAxis,
                            Color     = series.Item2.Position
                        };
                        var positionInd = new SimpleMovingAverage {
                            Length = 1
                        };
                        Chart.AddElement(positionArea, positionElem);

                        var pnlQueue = new PnLQueue(security.ToSecurityId());
                        //var level1Info = new Level1ChangeMessage
                        //{
                        //	SecurityId = pnlQueue.SecurityId,
                        //}
                        //.TryAdd(Level1Fields.PriceStep, security.PriceStep)
                        //.TryAdd(Level1Fields.StepPrice, security.StepPrice);

                        //pnlQueue.ProcessLevel1(level1Info);

                        var pos = 0m;

                        var secTrades = trades[security];

                        var secValues = _candles[security]
                                        .Select(c =>
                        {
                            if (c.State != CandleStates.Finished)
                            {
                                c.State = CandleStates.Finished;
                            }

                            pnlQueue.ProcessLevel1(new Level1ChangeMessage
                            {
                                SecurityId = security.ToSecurityId(),
                            }.TryAdd(Level1Fields.LastTradePrice, c.ClosePrice));

                            var values = new Dictionary <IChartElement, object>
                            {
                                { candlesElem, c },
                            };

                            var candleTrade = secTrades.TryGetValue(c.OpenTime);

                            if (candleTrade != null)
                            {
                                if (candleTrade.Item2 != null)
                                {
                                    values.Add(tradesElem, candleTrade.Item2);
                                }

                                foreach (var myTrade in candleTrade.Item1)
                                {
                                    pos    += myTrade.Order.Direction == Sides.Buy ? myTrade.Trade.Volume : -myTrade.Trade.Volume;
                                    var pnl = pnlQueue.Process(myTrade.ToMessage());

                                    _statisticManager.AddMyTrade(pnl);
                                }

                                _statisticManager.AddPosition(c.OpenTime, pos);
                                _statisticManager.AddPnL(c.OpenTime, pnlQueue.RealizedPnL + pnlQueue.UnrealizedPnL);
                            }

                            pnlValues[c.OpenTime] = pnlValues.TryGetValue(c.OpenTime) + (pnlQueue.RealizedPnL + pnlQueue.UnrealizedPnL);
                            values.Add(positionElem, positionInd.Process(pos));

                            return(new RefPair <DateTimeOffset, IDictionary <IChartElement, object> >
                            {
                                First = c.OpenTime,
                                Second = values
                            });
                        })
                                        .ToArray();

                        foreach (var pair in secValues)
                        {
                            var dict = chartValues.SafeAdd(pair.First, key => new Dictionary <IChartElement, object>());

                            foreach (var pair2 in pair.Second)
                            {
                                dict[pair2.Key] = pair2.Value;
                            }
                        }
                    }

                    foreach (var pair in pnlValues)
                    {
                        chartValues[pair.Key].Add(equityElem, equityInd.Process(pair.Value));
                    }

                    Chart.IsAutoRange = true;

                    try
                    {
                        Chart.Draw(chartValues.Select(p => RefTuple.Create(p.Key, p.Value)));
                    }
                    finally
                    {
                        Chart.IsAutoRange = false;
                    }
                }
                else
                {
                    new MessageBoxBuilder()
                    .Error()
                    .Owner(this)
                    .Text(ea.Error.ToString())
                    .Show();
                }
            };

            worker.RunWorkerAsync();
        }
Esempio n. 21
0
 /// <summary>
 /// 显示列表信息
 /// </summary>
 /// <param name="gvList">GridView对象</param>
 /// <param name="pageInfo">分页信息</param>
 public void ShowList(PagedGridView gvList, PageInfo pageInfo)
 {
     IDictionary<string, object> parameters = new Dictionary<string, object>();
     parameters.SafeAdd("CatalogID", CurrentId);
     parameters.SafeAdd("dataFilter", new Condition(GetFilterString()));
     IPageOfList<UploadFile> result = uploadFileService.FindAll(parameters, "Order By FileName", pageInfo);
     gvList.ItemCount = result.PageInfo.ItemCount;
     gvList.DataSource = result;
     gvList.DataBind();
 }
Esempio n. 22
0
        public string Save(string argument)
        {
            AjaxResult ajaxResult = new AjaxResult();

            string errorMsg = string.Empty;
            DoResult doResult = DoResult.Failed;
            string actionMessage = string.Empty;
            string parentID = string.Empty;
            try
            {
                Organization org = JsonConvert.DeserializeObject<Organization>(argument);
                string actionType = Request.Form["ActionType"];
                if (actionType.Equals("Add"))
                //if (PageContext.Action == ActionType.Add)
                {
                    IDictionary<string, object> parameter = new Dictionary<string, object>();
                    parameter.SafeAdd("Name", org.Name);
                    parameter.SafeAdd("Code", org.Code);
                    IList<Organization> listOrganization =repository.FindAll<Organization>(parameter);
                    if (listOrganization.Count == 0)
                    {
                        org.ID = string.IsNullOrWhiteSpace(CurrentId) ? IdGenerator.NewComb().ToString() : CurrentId;
                        org.ParentID = ParentID;
                        parentID = ParentID;
                        org.Creator = User.ID;
                        //org.Modifier = org.Creator;
                        //org.ModifyTime = org.CreateTime;
                    }
                    else
                    {
                        doResult = DoResult.Failed;
                        //获取提示信息
                        actionMessage = "部门名称已存在";

                        //记录操作日志
                        log.Error(string.Format("新增部门:{0}", actionMessage));
                        ajaxResult.Result = doResult;
                        ajaxResult.PromptMsg = actionMessage;
                        return JsonConvert.SerializeObject(ajaxResult);
                    }
                }
                else if (actionType.Equals("Update"))
                //else if (PageContext.Action == ActionType.Update)
                {
                    Organization orgDetail =repository.GetDomain<Organization>(CurrentId);
                    org.ParentID = orgDetail.ParentID;
                    parentID = org.ParentID;
                    org.ID = orgDetail.ID;
                }

                string areaCode = Configure.Get("AreaCode", "GDProvince");
                if (parentID == areaCode)
                {
                    org.OwnerOrg = string.Format("{0}/{1}/{2}", areaCode, org.Area, org.Code);
                }
                else if (parentID == "-1")
                {
                    org.OwnerOrg = areaCode;
                }
                else
                {
                    Organization parentOrg =repository.GetDomain<Organization>(parentID);
                    org.OwnerOrg = string.Format("{0}/{1}", parentOrg.OwnerOrg, org.Code);
                }

                repository.SaveOrUpdate(org);

                doResult = DoResult.Success;
                //获取提示信息
                actionMessage = RemarkAttribute.GetEnumRemark(doResult);

                //记录操作日志
                AddActionLog(org, doResult, actionMessage);

                ajaxResult.Result = doResult;
                ajaxResult.RetValue = org.ID;
                ajaxResult.PromptMsg = actionMessage;

            }
            catch (Exception ex)
            {
                actionMessage = RemarkAttribute.GetEnumRemark(doResult);
                log.Error(actionMessage, ex);
            }

            return JsonConvert.SerializeObject(ajaxResult);
        }
		private void OnProcessPositions(long transactionId, string[] data)
		{
			var f = Wrapper.FieldsPositions;
			var portfChangeMessages = new Dictionary<string, PortfolioChangeMessage>();

			foreach (var str in data)
			{
				var cols = str.ToColumns();

				var portfolioName = GetPortfolioName(f.AccCode.GetValue(cols), this.GetBoardCode(f.PlaceCode.GetValue(cols)));
				var secCode = f.PaperCode.GetValue(cols);

				if (secCode == "money")
				{
					var changesMsg = portfChangeMessages.SafeAdd(portfolioName, this.CreatePortfolioChangeMessage);

					changesMsg.Add(PositionChangeTypes.RealizedPnL, f.PnL.GetValue(cols));
					changesMsg.Add(PositionChangeTypes.UnrealizedPnL, f.ProfitVol.GetValue(cols));
					changesMsg.Add(PositionChangeTypes.CurrentPrice, f.RealVol.GetValue(cols));
					changesMsg.Add(PositionChangeTypes.BeginValue, f.IncomeRest.GetValue(cols));
					changesMsg.Add(PositionChangeTypes.CurrentValue, f.RealRest.GetValue(cols));
				}
				else
				{
					var secId = new SecurityId { Native = f.PaperNo.GetValue(cols) };

					SendOutMessage(new PositionMessage
					{
						PortfolioName = portfolioName,
						SecurityId = secId
					});

					var changesMsg = this.CreatePositionChangeMessage(portfolioName, secId);

					changesMsg.Add(PositionChangeTypes.RealizedPnL, f.PnL.GetValue(cols));
					changesMsg.Add(PositionChangeTypes.UnrealizedPnL, f.ProfitVol.GetValue(cols));
					changesMsg.Add(PositionChangeTypes.CurrentPrice, f.RealVol.GetValue(cols));
					changesMsg.Add(PositionChangeTypes.CurrentValue, f.ForwordRest.GetValue(cols));
					changesMsg.Add(PositionChangeTypes.AveragePrice, f.BalancePrice.GetValue(cols));

					var varMargin = f.VarMargin.GetValue(cols);
					changesMsg.Add(PositionChangeTypes.VariationMargin, varMargin);

					if (varMargin != 0)
					{
						var portfChangesMsg = portfChangeMessages.SafeAdd(portfolioName, this.CreatePortfolioChangeMessage);
						var oldVm = portfChangesMsg.Changes.TryGetValue(PositionChangeTypes.VariationMargin);

						if(oldVm == null)
							portfChangesMsg.Changes[PositionChangeTypes.VariationMargin] = varMargin;
						else
							portfChangesMsg.Changes[PositionChangeTypes.VariationMargin] = (decimal)oldVm + varMargin;
					}

					SendOutMessage(changesMsg);
				}	
			}

			portfChangeMessages.Values.ForEach(SendOutMessage);

			if (transactionId > 0)
			{
				SendOutMessage(new PortfolioLookupResultMessage
				{
					OriginalTransactionId = transactionId,
				});	
			}
		}
        /// <inheritdoc />
        protected override void OnInnerAdapterNewOutMessage(Message message)
        {
            Message TryApplyState(IOriginalTransactionIdMessage msg, SubscriptionStates state)
            {
                void TryCheckOnline(FilteredMarketDepthInfo info)
                {
                    if (state != SubscriptionStates.Online)
                    {
                        return;
                    }

                    var book   = info.BookSubscription;
                    var orders = info.OrdersSubscription;

                    if (info.BookSubscription.State == SubscriptionStates.Online && orders.State == SubscriptionStates.Online)
                    {
                        var online = _online.SafeAdd(book.SecurityId.Value);

                        online.Subscribers.Add(info.SubscribeId);
                        online.BookSubscribers.Add(book.TransactionId);
                        online.OrdersSubscribers.Add(orders.TransactionId);

                        info.Online = online;
                    }
                }

                var id = msg.OriginalTransactionId;

                lock (_sync)
                {
                    if (_byBookId.TryGetValue(id, out var info))
                    {
                        var book = info.BookSubscription;

                        book.State = book.State.ChangeSubscriptionState(state, id, this);

                        var subscribeId = info.SubscribeId;

                        if (!state.IsActive())
                        {
                            if (info.Online != null)
                            {
                                info.Online.BookSubscribers.Remove(id);
                                info.Online.OrdersSubscribers.Remove(info.OrdersSubscription.TransactionId);

                                info.Online.Subscribers.Remove(subscribeId);
                                info.Online = null;
                            }
                        }
                        else
                        {
                            TryCheckOnline(info);
                        }

                        switch (book.State)
                        {
                        case SubscriptionStates.Stopped:
                        case SubscriptionStates.Active:
                        case SubscriptionStates.Error:
                            return(new SubscriptionResponseMessage {
                                OriginalTransactionId = subscribeId, Error = (msg as IErrorMessage)?.Error
                            });

                        case SubscriptionStates.Finished:
                            return(new SubscriptionFinishedMessage {
                                OriginalTransactionId = subscribeId
                            });

                        case SubscriptionStates.Online:
                            return(new SubscriptionOnlineMessage {
                                OriginalTransactionId = subscribeId
                            });

                        default:
                            throw new ArgumentOutOfRangeException(book.State.ToString());
                        }
                    }
                    else if (_byOrderStatusId.TryGetValue(id, out info))
                    {
                        info.OrdersSubscription.State = info.OrdersSubscription.State.ChangeSubscriptionState(state, id, this);

                        if (!state.IsActive())
                        {
                            info.Online?.OrdersSubscribers.Remove(id);
                        }
                        else
                        {
                            TryCheckOnline(info);
                        }

                        return(null);
                    }
                    else if (_unsubscribeRequests.TryGetAndRemove(id, out var tuple))
                    {
                        info = tuple.Item1;

                        if (tuple.Item2)
                        {
                            var book = info.BookSubscription;
                            book.State = book.State.ChangeSubscriptionState(SubscriptionStates.Stopped, book.TransactionId, this);

                            return(new SubscriptionResponseMessage
                            {
                                OriginalTransactionId = info.UnSubscribeId,
                                Error = (msg as IErrorMessage)?.Error,
                            });
                        }
                        else
                        {
                            var orders = info.OrdersSubscription;
                            orders.State = orders.State.ChangeSubscriptionState(SubscriptionStates.Stopped, orders.TransactionId, this);
                            return(null);
                        }
                    }
                    else
                    {
                        return((Message)msg);
                    }
                }
            }

            List <QuoteChangeMessage> filtered = null;

            switch (message.Type)
            {
            case MessageTypes.SubscriptionResponse:
            {
                var responseMsg = (SubscriptionResponseMessage)message;
                message = TryApplyState(responseMsg, responseMsg.IsOk() ? SubscriptionStates.Active : SubscriptionStates.Error);
                break;
            }

            case MessageTypes.SubscriptionFinished:
            {
                message = TryApplyState((SubscriptionFinishedMessage)message, SubscriptionStates.Finished);
                break;
            }

            case MessageTypes.SubscriptionOnline:
            {
                message = TryApplyState((SubscriptionOnlineMessage)message, SubscriptionStates.Online);
                break;
            }

            case MessageTypes.QuoteChange:
            {
                var quoteMsg = (QuoteChangeMessage)message;

                if (quoteMsg.State != null)
                {
                    break;
                }

                HashSet <long> leftIds = null;

                lock (_sync)
                {
                    if (_byBookId.Count == 0)
                    {
                        break;
                    }

                    var            ids       = quoteMsg.GetSubscriptionIds();
                    HashSet <long> processed = null;

                    foreach (var id in ids)
                    {
                        if (processed != null && processed.Contains(id))
                        {
                            continue;
                        }

                        if (!_byBookId.TryGetValue(id, out var info))
                        {
                            continue;
                        }

                        var book = info.Process(quoteMsg);

                        if (leftIds is null)
                        {
                            leftIds = new HashSet <long>(ids);
                        }

                        if (info.Online is null)
                        {
                            leftIds.Remove(id);
                        }
                        else
                        {
                            if (processed is null)
                            {
                                processed = new HashSet <long>();
                            }

                            processed.AddRange(info.Online.BookSubscribers.Cache);
                            leftIds.RemoveRange(info.Online.BookSubscribers.Cache);
                        }

                        if (filtered == null)
                        {
                            filtered = new List <QuoteChangeMessage>();
                        }

                        filtered.Add(book);
                    }
                }

                if (leftIds is null)
                {
                    break;
                }
                else if (leftIds.Count == 0)
                {
                    message = null;
                }
                else
                {
                    quoteMsg.SetSubscriptionIds(leftIds.ToArray());
                }

                break;
            }

            case MessageTypes.Execution:
            {
                var execMsg = (ExecutionMessage)message;

                if (execMsg.IsMarketData())
                {
                    break;
                }

                HashSet <long> leftIds = null;

                lock (_sync)
                {
                    if (_byOrderStatusId.Count == 0)
                    {
                        break;
                    }

                    var            ids       = execMsg.GetSubscriptionIds();
                    HashSet <long> processed = null;

                    foreach (var id in ids)
                    {
                        if (processed != null && processed.Contains(id))
                        {
                            continue;
                        }

                        if (!_byOrderStatusId.TryGetValue(id, out var info))
                        {
                            continue;
                        }

                        if (leftIds is null)
                        {
                            leftIds = new HashSet <long>(ids);
                        }

                        if (info.Online is null)
                        {
                            leftIds.Remove(id);
                        }
                        else
                        {
                            if (processed is null)
                            {
                                processed = new HashSet <long>();
                            }

                            processed.AddRange(info.Online.OrdersSubscribers.Cache);
                            leftIds.RemoveRange(info.Online.OrdersSubscribers.Cache);
                        }

                        if (filtered is null)
                        {
                            filtered = new List <QuoteChangeMessage>();
                        }

                        var book = info.Process(execMsg);

                        if (book is object)
                        {
                            filtered.Add(book);
                        }
                    }
                }

                if (leftIds is null)
                {
                    break;
                }
                else if (leftIds.Count == 0)
                {
                    message = null;
                }
                else
                {
                    execMsg.SetSubscriptionIds(leftIds.ToArray());
                }

                break;
            }
            }

            if (message != null)
            {
                base.OnInnerAdapterNewOutMessage(message);
            }

            if (filtered != null)
            {
                foreach (var book in filtered)
                {
                    base.OnInnerAdapterNewOutMessage(book);
                }
            }
        }
Esempio n. 25
0
        /// <summary>
        /// Start storage auto-save thread.
        /// </summary>
        private void StartStorageTimer()
        {
            if (_timer != null || !Buffer.Enabled || Buffer.DisableStorageTimer)
            {
                return;
            }

            var isProcessing = false;
            var sync         = new SyncObject();

            var unkByOrderId       = new Dictionary <long, List <ExecutionMessage> >();
            var unkByOrderStringId = new Dictionary <string, List <ExecutionMessage> >(StringComparer.InvariantCultureIgnoreCase);

            _timer = ThreadingHelper.Timer(() =>
            {
                lock (sync)
                {
                    if (isProcessing)
                    {
                        return;
                    }

                    isProcessing = true;
                }

                try
                {
                    var incremental = Settings.IsMode(StorageModes.Incremental);
                    var snapshot    = Settings.IsMode(StorageModes.Snapshot);

                    foreach (var pair in Buffer.GetTicks())
                    {
                        if (incremental)
                        {
                            Settings.GetStorage <ExecutionMessage>(pair.Key, ExecutionTypes.Tick).Save(pair.Value);
                        }
                    }

                    foreach (var pair in Buffer.GetOrderLog())
                    {
                        if (incremental)
                        {
                            Settings.GetStorage <ExecutionMessage>(pair.Key, ExecutionTypes.OrderLog).Save(pair.Value);
                        }
                    }

                    foreach (var pair in Buffer.GetTransactions())
                    {
                        var secId = pair.Key;

                        if (incremental)
                        {
                            Settings.GetStorage <ExecutionMessage>(secId, ExecutionTypes.Transaction).Save(pair.Value);
                        }

                        if (snapshot)
                        {
                            var snapshotStorage = GetSnapshotStorage(DataType.Transactions);

                            foreach (var message in pair.Value)
                            {
                                // do not store cancellation commands into snapshot
                                if (message.IsCancellation /* && message.TransactionId != 0*/)
                                {
                                    continue;
                                }

                                var originTransId = message.OriginalTransactionId;

                                if (message.TransactionId == 0 && originTransId == 0)
                                {
                                    if (!message.HasTradeInfo)
                                    {
                                        continue;
                                    }

                                    long transId;

                                    if (message.OrderId != null)
                                    {
                                        if (!_orderIds.TryGetValue(message.OrderId.Value, out transId))
                                        {
                                            unkByOrderId.SafeAdd(message.OrderId.Value).Add(message);
                                            continue;
                                        }
                                    }
                                    else if (!message.OrderStringId.IsEmpty())
                                    {
                                        if (!_orderStringIds.TryGetValue(message.OrderStringId, out transId))
                                        {
                                            unkByOrderStringId.SafeAdd(message.OrderStringId).Add(message);
                                            continue;
                                        }
                                    }
                                    else
                                    {
                                        continue;
                                    }

                                    originTransId = transId;
                                }
                                else
                                {
                                    if (originTransId != 0)
                                    {
                                        if (/*message.TransactionId == 0 && */ _cancellationTransactions.TryGetValue(originTransId, out var temp))
                                        {
                                            // do not store cancellation errors
                                            if (message.Error != null)
                                            {
                                                continue;
                                            }

                                            // override cancel trans id by original order's registration trans id
                                            originTransId = temp;
                                        }

                                        if (_orderStatusIds.Contains(originTransId))
                                        {
                                            // override status request trans id by original order's registration trans id
                                            originTransId = message.TransactionId;
                                        }
                                    }

                                    if (originTransId != 0)
                                    {
                                        if (message.OrderId != null)
                                        {
                                            _orderIds.TryAdd(message.OrderId.Value, originTransId);
                                        }
                                        else if (message.OrderStringId != null)
                                        {
                                            _orderStringIds.TryAdd(message.OrderStringId, originTransId);
                                        }
                                    }
                                }

                                message.SecurityId = secId;

                                if (message.TransactionId == 0)
                                {
                                    message.TransactionId = originTransId;
                                }

                                message.OriginalTransactionId = 0;

                                SaveTransaction(snapshotStorage, message);

                                if (message.OrderId != null)
                                {
                                    if (unkByOrderId.TryGetValue(message.OrderId.Value, out var suspended))
                                    {
                                        unkByOrderId.Remove(message.OrderId.Value);

                                        foreach (var trade in suspended)
                                        {
                                            trade.TransactionId = message.TransactionId;
                                            SaveTransaction(snapshotStorage, trade);
                                        }
                                    }
                                }
                                else if (!message.OrderStringId.IsEmpty())
                                {
                                    if (unkByOrderStringId.TryGetValue(message.OrderStringId, out var suspended))
                                    {
                                        unkByOrderStringId.Remove(message.OrderStringId);

                                        foreach (var trade in suspended)
                                        {
                                            trade.TransactionId = message.TransactionId;
                                            SaveTransaction(snapshotStorage, trade);
                                        }
                                    }
                                }
                            }
                        }
                    }

                    foreach (var pair in Buffer.GetOrderBooks())
                    {
                        if (incremental)
                        {
                            Settings.GetStorage <QuoteChangeMessage>(pair.Key, null).Save(pair.Value);
                        }

                        if (snapshot)
                        {
                            var snapshotStorage = GetSnapshotStorage(DataType.MarketDepth);

                            foreach (var message in pair.Value)
                            {
                                snapshotStorage.Update(message);
                            }
                        }
                    }

                    foreach (var pair in Buffer.GetLevel1())
                    {
                        var messages = pair.Value.Where(m => m.Changes.Count > 0).ToArray();

                        if (incremental)
                        {
                            Settings.GetStorage <Level1ChangeMessage>(pair.Key, null).Save(messages);
                        }

                        if (Settings.IsMode(StorageModes.Snapshot))
                        {
                            var snapshotStorage = GetSnapshotStorage(DataType.Level1);

                            foreach (var message in messages)
                            {
                                snapshotStorage.Update(message);
                            }
                        }
                    }

                    foreach (var pair in Buffer.GetCandles())
                    {
                        Settings.GetStorage(pair.Key.Item1, pair.Key.Item2, pair.Key.Item3).Save(pair.Value);
                    }

                    foreach (var pair in Buffer.GetPositionChanges())
                    {
                        var messages = pair.Value.Where(m => m.Changes.Count > 0).ToArray();

                        if (incremental)
                        {
                            Settings.GetStorage <PositionChangeMessage>(pair.Key, null).Save(messages);
                        }

                        if (snapshot)
                        {
                            var snapshotStorage = GetSnapshotStorage(DataType.PositionChanges);

                            foreach (var message in messages)
                            {
                                snapshotStorage.Update(message);
                            }
                        }
                    }

                    var news = Buffer.GetNews().ToArray();

                    if (news.Length > 0)
                    {
                        Settings.GetStorage <NewsMessage>(default, null).Save(news);
Esempio n. 26
0
        /*qlj 2013.1.8改  将表单独立于流程之外*/
        public ActionResult Index()
        {
            //IWorkflowEngine engine = new WorkflowEngine();
            try
            {
                string processDefID = Request.QueryString["processDefID"];
                string entry = Request.QueryString["Entry"];
                string eFormID = Request.QueryString["eFormID"];
                ManualActivity manualActivity = null;
                eForm formInfo = null;
                if (string.IsNullOrEmpty(processDefID) && !string.IsNullOrEmpty(eFormID))
                {
                    formInfo = repository.GetDomain<eForm>(eFormID);
                }
                else
                {
                    if (!string.IsNullOrEmpty(processDefID) && entry.EqualIgnoreCase("StartProcess"))
                    {
                        Activity startActivity = workflowEngine.Persistence.GetStartActivity(processDefID);
                        manualActivity = workflowEngine.Persistence.GetOutActivities(processDefID, startActivity.ID)[0] as ManualActivity;
                    }
                    else
                    {
                        string workItemID = Request.QueryString["workItemID"];
                        WorkItem workItem = repository.GetDomain<WorkItem>(workItemID);
                        ActivityInst activityInst = workflowEngine.Persistence.GetActivityInst(workItem.ActivityInstID);
                        manualActivity = workflowEngine.Persistence.GetActivity(workItem.ProcessID, activityInst.ActivityDefID) as ManualActivity;
                    }
                }
                if (manualActivity != null && manualActivity.eForm != null)
                {
                    formInfo = repository.GetDomain<eForm>(manualActivity.eForm);
                }
                   if (formInfo != null&&!string.IsNullOrEmpty(formInfo.Content))
                   {
                     Form  form=JsonConvert.DeserializeObject<Form>(formInfo.Content);
                       string processInstID = Request.QueryString["processInstID"];
                       ProcessForm processForm = null;
                       IDictionary<string, object> values = new Dictionary<string, object>();
                       if (!string.IsNullOrEmpty(processInstID))
                       {
                           IDictionary<string, object> parameters = new Dictionary<string, object>();
                           parameters.SafeAdd("processInstID", processInstID);
                           processForm = repository.FindOne<ProcessForm>(parameters);
                           if (processForm != null)
                           {
                               parameters.Clear();
                               parameters.Add("ID", processForm.BizID);
                               DataTable dt = repository.ExecuteDataTable<ProcessForm>(string.Format("select * from {0}", processForm.BizTable), parameters);
                               if (dt != null && dt.Rows.Count > 0)
                               {

                                   foreach (DataRow row in dt.Rows)
                                   {
                                       foreach (var field in form.Fields)//manualActivity.Form.Fields)
                                       {

                                           if (field.ControlType == ControlType.SysVariable || field.ControlType == ControlType.HiddenInput)
                                           {
                                               switch (field.DefaultValue.ToInt())
                                               {
                                                   case (short)SystemControlType.OrgID:
                                                       Organization org = repository.Query<Organization>().FirstOrDefault(o => o.Code == workContext.User.OrgID);
                                                       values.SafeAdd(field.Name, org.Name);
                                                       if (!string.IsNullOrEmpty(field.ExtendData))
                                                       {
                                                           values.SafeAdd(field.ExtendData, workContext.User.OrgID);
                                                       }
                                                       break;
                                                   case (short)SystemControlType.UserID:
                                                       values.SafeAdd(field.Name, workContext.User.Name);
                                                       if (!string.IsNullOrEmpty(field.ExtendData))
                                                       {
                                                           values.SafeAdd(field.ExtendData, workContext.User.ID);
                                                       }
                                                       break;
                                                   case (short)SystemControlType.CurrentDate:
                                                       values.SafeAdd(field.Name, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                                                       break;
                                               }

                                           }
                                           else if (dt.Columns.Contains(field.Name))
                                           {
                                               if (!string.IsNullOrEmpty(row[field.Name].ToSafeString()))
                                               {
                                                   values.SafeAdd(field.Name, row[field.Name]);
                                               }
                                               else
                                               {
                                                   if (!string.IsNullOrEmpty(field.DefaultValue))
                                                       values.SafeAdd(field.Name, field.DefaultValue);
                                               }
                                           }

                                       }
                                   }
                               }
                           }
                       }
                       if (processForm == null)
                       {
                           foreach (var field in form.Fields)//manualActivity.Form.Fields)
                           {
                               if (field.ControlType == ControlType.SysVariable||field.ControlType==ControlType.HiddenInput)
                               {
                                   switch (field.DefaultValue.ToInt())
                                   {
                                       case (short)SystemControlType.OrgID:
                                           Organization org = repository.Query<Organization>().FirstOrDefault(o => o.Code == workContext.User.OrgID);
                                           values.SafeAdd(field.Name, org.Name);
                                           if (!string.IsNullOrEmpty(field.ExtendData))
                                           {
                                               values.SafeAdd(field.ExtendData, workContext.User.OrgID);
                                           }
                                           break;
                                       case (short)SystemControlType.UserID:
                                           values.SafeAdd(field.Name, workContext.User.Name);
                                           if (!string.IsNullOrEmpty(field.ExtendData))
                                           {
                                               values.SafeAdd(field.ExtendData, workContext.User.ID);
                                           }
                                           break;
                                       case (short)SystemControlType.CurrentDate:
                                           values.SafeAdd(field.Name, DateTime.Now.ToSafeDateTime());
                                           break;
                                   }
                               }
                               else if (field.ControlType != ControlType.SysVariable && field.ControlType != ControlType.HiddenInput)
                               {
                                   if (!string.IsNullOrEmpty(field.DefaultValue))
                                       values.SafeAdd(field.Name, field.DefaultValue);
                               }
                               else
                               {
                                   // values.SafeAdd(field.Name, workContext.);
                               }
                           }
                       }
                       ViewData["Values"] = values;
                       ViewData["Form"] = form;//manualActivity.Form;
                   }
                //}
            }
            catch (Exception ex)
            {
                log.Error("初始化表单失败" + ex);
            }
            return View();
        }
Esempio n. 27
0
        public static GridFilter GetFilter(this DataSourceRequest command)
        {
            if (command.PageSize == 0)
            {
                command.PageSize = Configure.Get<int>("PageSize", 15);
            }

            IDictionary<string, object> parameters = new Dictionary<string, object>();
            string sortcommand = null;
            if (command.Sorts != null && command.Sorts.Count > 0)
            {
                string sortDirection = ListSortDirection.Ascending == command.Sorts[0].SortDirection ? "asc" : "desc";
                sortcommand = string.Format("order by {0} {1}", command.Sorts[0].Member, sortDirection);
            }

            if (command.Filters != null)
            {
                foreach (IFilterDescriptor filterDescriptor in command.Filters)
                {
                    parameters.SafeAdd(ApplyFilter(filterDescriptor));
                }
            }

            return new GridFilter()
            {

                PageInfo = new PageInfo() { PageIndex = command.Page, PageSize = command.PageSize },
                Parameters = parameters,
                SortCommand = sortcommand
            };
        }
Esempio n. 28
0
 public static void Assign <TConvention>(string entityName)
     where TConvention : class, ISqlConvention, new()
 {
     _Conventions.SafeAdd(entityName, new TConvention());
 }
Esempio n. 29
0
        /// <summary>
        /// 返回查询条件
        /// </summary>
        /// <param name="filterValues"></param>
        public override KeyValuePair<string, IDictionary<string, object>> GetFilterCondition(IDictionary<string, object> filterValues)
        {
            string paramValue = GetFilterValue<string>(filterValues, Field.Name + "data").Trim(',').Trim();
            string inputValue = GetFilterValue<string>(filterValues, Field.Name).Trim(',').Trim();

            if (inputValue == "批量值" && !string.IsNullOrEmpty(paramValue))
            {
                IDictionary<string, object> parameters = new Dictionary<string, object>();
                parameters.Add(new KeyValuePair<string, object>(ParamChar + Field.Name, paramValue));

                return new KeyValuePair<string, IDictionary<string, object>>(string.Format(" And {0} in (select value from DD_BatchValue where BatchDataID={1}{0}) ", Field.Name, ParamChar), parameters);
            }

            if (Field.DataType == DataType.String)
            {
                Dictionary<string, object> parameters = new Dictionary<string, object>();

                if (HasValue(filterValues))
                {
                    KeyValuePair<string, object> parameter = NewParameter(Field.Name, filterValues);
                    parameters.SafeAdd(parameter.Key, parameter.Value);
                }

                return new KeyValuePair<string, IDictionary<string, object>>(string.Format(" And {0}={1}{0}", Field.Name, ParamChar), parameters);
                //  return new KeyValuePair<string, IDictionary<string, object>>(string.Format(" And {0} like '%'{2}{1}{0}{2}'%' ", Field.Name, ParamChar, ParamChar == "@" ? "+" : "||"), parameters);
            }

            return base.GetFilterCondition(filterValues);
        }
Esempio n. 30
0
            public void Process(ExecutionMessage message)
            {
                if (!message.HasOrderInfo())
                {
                    throw new ArgumentException(nameof(message));
                }

                // ignore market orders
                if (message.OrderPrice == 0)
                {
                    return;
                }

                // ignore unknown orders
                if (message.OriginalTransactionId == 0)
                {
                    return;
                }

                var key = Tuple.Create(message.Side, message.OrderPrice);

                switch (message.OrderState)
                {
                case OrderStates.Done:
                case OrderStates.Failed:
                {
                    var pair = _executions.TryGetValue(key);

                    if (pair == null)
                    {
                        break;
                    }

                    var balance = pair.First.TryGetAndRemove(message.OriginalTransactionId);

                    if (pair.First.Count == 0)
                    {
                        _executions.Remove(key);
                    }
                    else
                    {
                        pair.Second -= balance;
                    }

                    break;
                }

                case OrderStates.Active:
                {
                    var balance = message.Balance;

                    if (balance != null)
                    {
                        var pair = _executions.SafeAdd(key, k => RefTuple.Create(new Dictionary <long, decimal>(), 0M));

                        var prev = pair.First.TryGetValue(message.OriginalTransactionId);

                        pair.First[message.OriginalTransactionId] = balance.Value;
                        pair.Second += balance.Value - prev;
                    }

                    break;
                }
                }
            }
Esempio n. 31
0
        public ActionResult Form()
        {
            try
            {
                string processDefID = Request.QueryString["processDefID"];
                string eFormID = Request.QueryString["eFormID"];
                string entry = Request.QueryString["Entry"];
                eForm formInfo = null;
                if (string.IsNullOrEmpty(processDefID) && !string.IsNullOrEmpty(eFormID))
                {
                    formInfo = repository.GetDomain<eForm>(eFormID);
                }
                if (formInfo != null && !string.IsNullOrEmpty(formInfo.Content))
                {
                    Form form = JsonConvert.DeserializeObject<Form>(formInfo.Content);
                    string processInstID = Request.QueryString["processInstID"];
                    //ProcessForm processForm = null;
                    IDictionary<string, object> values = new Dictionary<string, object>();
                    //if (!string.IsNullOrEmpty(processInstID))
                    //{
                    //    IDictionary<string, object> parameters = new Dictionary<string, object>();
                    //    parameters.SafeAdd("processInstID", processInstID);
                    //    processForm = repository.FindOne<ProcessForm>(parameters);
                    //    if (processForm != null)
                    //    {
                    //        parameters.Clear();
                    //        parameters.Add("ID", processForm.BizID);
                    //        DataTable dt = repository.ExecuteDataTable<ProcessForm>(string.Format("select * from {0}", processForm.BizTable), parameters);
                    //        if (dt != null && dt.Rows.Count > 0)
                    //        {

                    //            foreach (DataRow row in dt.Rows)
                    //            {
                    //                foreach (var field in form.Fields)//manualActivity.Form.Fields)
                    //                {

                    //                    if (field.ControlType == ControlType.SysVariable)
                    //                    {
                    //                        switch (field.DefaultValue.ToInt())
                    //                        {
                    //                            case (short)SystemControlType.OrgID:
                    //                                Organization org = repository.Query<Organization>().FirstOrDefault(o => o.Code == workContext.User.OrgID);
                    //                                values.SafeAdd(field.Name, org.Name);
                    //                                if (!string.IsNullOrEmpty(field.ExtendData))
                    //                                {
                    //                                    values.SafeAdd(field.ExtendData, workContext.User.OrgID);
                    //                                }
                    //                                break;
                    //                            case (short)SystemControlType.UserID:
                    //                                values.SafeAdd(field.Name, workContext.User.Name);
                    //                                if (!string.IsNullOrEmpty(field.ExtendData))
                    //                                {
                    //                                    values.SafeAdd(field.ExtendData, workContext.User.ID);
                    //                                }
                    //                                break;
                    //                            case (short)SystemControlType.CurrentDate:
                    //                                values.SafeAdd(field.Name, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                    //                                break;
                    //                        }

                    //                    }
                    //                    else if (dt.Columns.Contains(field.Name))
                    //                    {
                    //                        if (!string.IsNullOrEmpty(row[field.Name].ToSafeString()))
                    //                        {
                    //                            values.SafeAdd(field.Name, row[field.Name]);
                    //                        }
                    //                        else
                    //                        {
                    //                            if (!string.IsNullOrEmpty(field.DefaultValue))
                    //                                values.SafeAdd(field.Name, field.DefaultValue);
                    //                        }
                    //                    }

                    //                }
                    //            }
                    //        }
                    //    }
                    //}
                    //if (processForm == null)
                    //{
                        foreach (var field in form.Fields)//manualActivity.Form.Fields)
                        {
                            if (field.ControlType == ControlType.SysVariable)
                            {
                                switch (field.DefaultValue.ToInt())
                                {
                                    case (short)SystemControlType.OrgID:
                                        Organization org = repository.Query<Organization>().FirstOrDefault(o => o.Code == workContext.User.OrgID);
                                        values.SafeAdd(field.Name, org.Name);
                                        if (!string.IsNullOrEmpty(field.ExtendData))
                                        {
                                            values.SafeAdd(field.ExtendData, workContext.User.OrgID);
                                        }
                                        break;
                                    case (short)SystemControlType.UserID:
                                        values.SafeAdd(field.Name, workContext.User.Name);
                                        if (!string.IsNullOrEmpty(field.ExtendData))
                                        {
                                            values.SafeAdd(field.ExtendData, workContext.User.ID);
                                        }
                                        break;
                                    case (short)SystemControlType.CurrentDate:
                                        values.SafeAdd(field.Name, DateTime.Now.ToSafeDateTime());
                                        break;
                                }
                            }
                            else if (field.ControlType != ControlType.SysVariable && field.ControlType != ControlType.HiddenInput)
                            {
                                if (!string.IsNullOrEmpty(field.DefaultValue))
                                    values.SafeAdd(field.Name, field.DefaultValue);
                            }
                            else
                            {
                                // values.SafeAdd(field.Name, workContext.);
                            }
                        }
                    //}
                    //ViewData["Values"] = values;
                    //ViewData["Form"] = form;//manualActivity.Form;
                        FormModel formModel = new FormModel()
                        {
                            Form = form,
                            Values = values
                        };

                }
            }
            catch (Exception ex)
            {
                log.Error("初始化表单失败" + ex);
            }
            return View();
        }
        /// <inheritdoc />
        public override void Generate()
        {
            var hasTemplate = !Template.IsEmpty();

            if (hasTemplate)
            {
                File.Copy(Template, FileName);
            }

            using (var stream = File.OpenWrite(FileName))
                using (var worker = hasTemplate ? _provider.OpenExist(stream) : _provider.CreateNew(stream))
                {
                    foreach (var strategy in Strategies)
                    {
                        if (Template.IsEmpty())
                        {
                            worker.RenameSheet(strategy.Name);
                        }
                        else
                        {
                            if (!worker.ContainsSheet(strategy.Name))
                            {
                                worker.AddSheet().RenameSheet(strategy.Name);
                            }
                        }

                        worker
                        .SetCell(0, 0, LocalizedStrings.Str1331)

                        .SetCell(0, 1, LocalizedStrings.Security + ":")
                        .SetCell(1, 1, strategy.Security != null ? strategy.Security.Id : string.Empty)

                        .SetCell(0, 2, LocalizedStrings.Portfolio + ":")
                        .SetCell(1, 2, strategy.Portfolio != null ? strategy.Portfolio.Name : string.Empty)

                        .SetCell(0, 3, LocalizedStrings.Str1334)
                        .SetCell(1, 3, Format(strategy.TotalWorkingTime))

                        .SetCell(0, 4, LocalizedStrings.Str1335)
                        //.SetCell(1, 4, FormatTime(base.Strategy.TotalCPUTime))

                        .SetCell(0, 5, LocalizedStrings.Str862 + ":")
                        .SetCell(1, 5, strategy.Position)

                        .SetCell(0, 6, LocalizedStrings.PnL + ":")
                        .SetCell(1, 6, strategy.PnL)

                        .SetCell(0, 7, LocalizedStrings.Str159 + ":")
                        .SetCell(1, 7, strategy.Commission)

                        .SetCell(0, 8, LocalizedStrings.Str163 + ":")
                        .SetCell(1, 8, strategy.Slippage)

                        .SetCell(0, 9, LocalizedStrings.Str161 + ":")
                        .SetCell(1, 9, Format(strategy.Latency));

                        var rowIndex = 11;

                        foreach (var parameter in strategy.StatisticManager.Parameters.SyncGet(c => c.ToArray()))
                        {
                            var value = parameter.Value;

                            if (value is TimeSpan ts)
                            {
                                value = Format(ts);
                            }
                            else if (value is decimal dec)
                            {
                                value = dec.Round(Decimals);
                            }

                            worker
                            .SetCell(0, rowIndex, parameter.Name)
                            .SetCell(1, rowIndex, value);

                            rowIndex++;
                        }

                        rowIndex += 2;
                        worker.SetCell(0, rowIndex, LocalizedStrings.Str1340);
                        rowIndex++;

                        foreach (var strategyParam in strategy.Parameters.CachedValues)
                        {
                            var value = strategyParam.Value;

                            if (value is TimeSpan span)
                            {
                                value = Format(span);
                            }
                            else if (value is decimal dec)
                            {
                                value = dec.Round(Decimals);
                            }

                            worker
                            .SetCell(0, rowIndex, strategyParam.Name)
                            .SetCell(1, rowIndex, value);

                            rowIndex++;
                        }

                        var columnShift = 3;

                        worker
                        .SetCell(columnShift + 0, 0, LocalizedStrings.Str985)

                        .SetCell(columnShift + 0, 1, LocalizedStrings.Str1192).SetStyle(columnShift + 0, typeof(long))
                        .SetCell(columnShift + 1, 1, LocalizedStrings.Transaction).SetStyle(columnShift + 1, typeof(long))
                        .SetCell(columnShift + 2, 1, LocalizedStrings.Time).SetStyle(columnShift + 2, "HH:mm:ss.fff")
                        .SetCell(columnShift + 3, 1, LocalizedStrings.Price).SetStyle(columnShift + 3, typeof(decimal))
                        .SetCell(columnShift + 4, 1, LocalizedStrings.Str1341).SetStyle(columnShift + 4, typeof(decimal))
                        .SetCell(columnShift + 5, 1, LocalizedStrings.Volume).SetStyle(columnShift + 5, typeof(decimal))
                        .SetCell(columnShift + 6, 1, LocalizedStrings.Str128)
                        .SetCell(columnShift + 7, 1, LocalizedStrings.Str1190).SetStyle(columnShift + 7, typeof(long))
                        .SetCell(columnShift + 8, 1, LocalizedStrings.Str163).SetStyle(columnShift + 8, typeof(decimal))
                        .SetCell(columnShift + 9, 1, LocalizedStrings.Str135)
                        .SetCell(columnShift + 10, 1, LocalizedStrings.Str1342).SetStyle(columnShift + 11, typeof(decimal))
                        .SetCell(columnShift + 11, 1, LocalizedStrings.Str1343).SetStyle(columnShift + 12, typeof(decimal))
                        .SetCell(columnShift + 12, 1, LocalizedStrings.Str1344).SetStyle(columnShift + 13, typeof(decimal))
                        .SetCell(columnShift + 13, 1, LocalizedStrings.Str1345).SetStyle(columnShift + 14, typeof(decimal))
                        .SetCell(columnShift + 14, 1, LocalizedStrings.Str862).SetStyle(columnShift + 15, typeof(decimal));

                        //worker
                        //	.SetConditionalFormatting(columnShift + 10, ComparisonOperator.Less, "0", null, Colors.Red)
                        //	.SetConditionalFormatting(columnShift + 11, ComparisonOperator.Less, "0", null, Colors.Red)
                        //	.SetConditionalFormatting(columnShift + 12, ComparisonOperator.Less, "0", null, Colors.Red)
                        //	.SetConditionalFormatting(columnShift + 13, ComparisonOperator.Less, "0", null, Colors.Red);

                        var totalPnL = 0m;
                        var position = 0m;

                        var queues = new Dictionary <Security, PnLQueue>();

                        rowIndex = 2;
                        foreach (var trade in strategy.MyTrades.ToArray())
                        {
                            var tradePnL = strategy.PnLManager.ProcessMessage(trade.ToMessage())?.PnL ?? 0;

                            totalPnL += tradePnL;
                            position += trade.GetPosition() ?? 0;

                            var queue = queues.SafeAdd(trade.Trade.Security, key => new PnLQueue(key.ToSecurityId()));

                            var localInfo = queue.Process(trade.ToMessage());

                            worker
                            .SetCell(columnShift + 0, rowIndex, trade.Trade.Id)
                            .SetCell(columnShift + 1, rowIndex, trade.Order.TransactionId)
                            .SetCell(columnShift + 2, rowIndex, Format(trade.Trade.Time))
                            .SetCell(columnShift + 3, rowIndex, trade.Trade.Price)
                            .SetCell(columnShift + 4, rowIndex, trade.Order.Price)
                            .SetCell(columnShift + 5, rowIndex, trade.Trade.Volume)
                            .SetCell(columnShift + 6, rowIndex, Format(trade.Order.Direction))
                            .SetCell(columnShift + 7, rowIndex, trade.Order.Id)
                            .SetCell(columnShift + 8, rowIndex, trade.Slippage)
                            .SetCell(columnShift + 9, rowIndex, trade.Order.Comment)
                            .SetCell(columnShift + 10, rowIndex, tradePnL.Round(Decimals))
                            .SetCell(columnShift + 11, rowIndex, localInfo.PnL.Round(Decimals))
                            .SetCell(columnShift + 12, rowIndex, totalPnL.Round(Decimals))
                            .SetCell(columnShift + 13, rowIndex, queue.RealizedPnL.Round(Decimals))
                            .SetCell(columnShift + 14, rowIndex, position);

                            rowIndex++;
                        }

                        if (IncludeOrders)
                        {
                            columnShift += 17;

                            worker
                            .SetCell(columnShift + 0, 0, LocalizedStrings.Orders)

                            .SetCell(columnShift + 0, 1, LocalizedStrings.Str1190).SetStyle(columnShift + 0, typeof(long))
                            .SetCell(columnShift + 1, 1, LocalizedStrings.Transaction).SetStyle(columnShift + 1, typeof(long))
                            .SetCell(columnShift + 2, 1, LocalizedStrings.Str128)
                            .SetCell(columnShift + 3, 1, LocalizedStrings.Str1346).SetStyle(columnShift + 3, "HH:mm:ss.fff")
                            .SetCell(columnShift + 4, 1, LocalizedStrings.Str1347).SetStyle(columnShift + 4, "HH:mm:ss.fff")
                            .SetCell(columnShift + 5, 1, LocalizedStrings.Str1348)
                            .SetCell(columnShift + 6, 1, LocalizedStrings.Price).SetStyle(columnShift + 6, typeof(decimal))
                            .SetCell(columnShift + 7, 1, LocalizedStrings.Str1324)
                            .SetCell(columnShift + 8, 1, LocalizedStrings.State)
                            .SetCell(columnShift + 9, 1, LocalizedStrings.Str1325).SetStyle(columnShift + 10, typeof(decimal))
                            .SetCell(columnShift + 10, 1, LocalizedStrings.Volume).SetStyle(columnShift + 11, typeof(decimal))
                            .SetCell(columnShift + 11, 1, LocalizedStrings.Type)
                            .SetCell(columnShift + 12, 1, LocalizedStrings.Str1326)
                            .SetCell(columnShift + 13, 1, LocalizedStrings.Str1327)
                            .SetCell(columnShift + 14, 1, LocalizedStrings.Str135);

                            //worker
                            //	.SetConditionalFormatting(columnShift + 8, ComparisonOperator.Equal, "\"{0}\"".Put(LocalizedStrings.Str1329), null, Colors.Green)
                            //	.SetConditionalFormatting(columnShift + 8, ComparisonOperator.Equal, "\"{0}\"".Put(LocalizedStrings.Str238), null, Colors.Red);

                            rowIndex = 2;
                            foreach (var order in strategy.Orders.ToArray())
                            {
                                worker
                                .SetCell(columnShift + 0, rowIndex, order.Id)
                                .SetCell(columnShift + 1, rowIndex, order.TransactionId)
                                .SetCell(columnShift + 2, rowIndex, Format(order.Direction))
                                .SetCell(columnShift + 3, rowIndex, Format(order.Time))
                                .SetCell(columnShift + 4, rowIndex, Format(order.LastChangeTime))
                                .SetCell(columnShift + 5, rowIndex, Format(order.LastChangeTime - order.Time))
                                .SetCell(columnShift + 6, rowIndex, order.Price)
                                .SetCell(columnShift + 7, rowIndex, Format(order.State))
                                .SetCell(columnShift + 8, rowIndex, order.IsMatched() ? LocalizedStrings.Str1328 : (order.IsCanceled() ? LocalizedStrings.Str1329 : LocalizedStrings.Str238))
                                .SetCell(columnShift + 9, rowIndex, order.Balance)
                                .SetCell(columnShift + 10, rowIndex, order.Volume)
                                .SetCell(columnShift + 11, rowIndex, Format(order.Type))
                                .SetCell(columnShift + 12, rowIndex, Format(order.LatencyRegistration))
                                .SetCell(columnShift + 13, rowIndex, Format(order.LatencyCancellation))
                                .SetCell(columnShift + 14, rowIndex, order.Comment);

                                if (order.Condition != null)
                                {
                                    var stopParams = order.Condition.Parameters.Keys.ToArray();

                                    for (var i = 0; i < stopParams.Length; i++)
                                    {
                                        worker.SetCell(columnShift + 11 + i, rowIndex, stopParams[i]);
                                    }
                                }

                                rowIndex++;
                            }
                        }
                    }
                }
        }
 public void AddRename(string key, string value)
 {
     Renames.SafeAdd <string, string>(key, value);
 }
Esempio n. 34
0
 OrderInfo EnsureGetInfo <TMessage>(TMessage msg, Sides side, decimal volume, decimal balance)
     where TMessage : Message, ITransactionIdMessage, ISecurityIdMessage, IPortfolioNameMessage
 {
     this.AddDebugLog("{0} bal_new {1}/{2}.", msg.TransactionId, balance, volume);
     return(_ordersInfo.SafeAdd(msg.TransactionId, key => new OrderInfo(key, msg.SecurityId, msg.PortfolioName, side, volume, balance)));
 }
Esempio n. 35
0
        /// <summary>
        /// 获取员工所在部门名称
        /// </summary>
        /// <param name="orgID">组织ID</param>
        /// <returns></returns>
        public IList<Organization> GetOrgNameByUserID(string userID)
        {
            IDictionary<string, object> parameters = new Dictionary<string, object>();
            parameters.SafeAdd("ID", new Condition(string.Format("ID in (select b.OrgID from OM_EmployeeOrg b where b.EmployeeID='{0}')", userID)));

            return repository.FindAll<Organization>(parameters);
        }
Esempio n. 36
0
        /// <summary>
        /// 初始化对象            
        /// </summary>
        /// <param name="xElem"></param>
        public override void Initilize(XElement xElem)
        {
            Attibutes = new Dictionary<string, object>();
            Properties = new Dictionary<string, object>();

            XElement basic = xElem.Element("basic");
            xElem.Attributes()
                  .ForEach(e => { if (!string.IsNullOrEmpty(e.Name.LocalName) && !string.IsNullOrEmpty(e.Value))Attibutes.SafeAdd(e.Name.LocalName, e.Value.Trim()); });

            basic.Elements()
                 .Where(e => e.Elements().Count() == 0)
                 .ForEach(e => { if (!string.IsNullOrEmpty(e.Name.LocalName) && !string.IsNullOrEmpty(e.Value)) Properties.SafeAdd(e.Name.LocalName, e.Value.Trim()); });

            TimeLimit = new TimeLimit(this, basic.Element("timeLimit"));
            var xInitiator = basic.Element("initiator");
            StarterType = xInitiator.Element("starterType").Value;
            Initiators = xInitiator.Elements("participantor").Select(o => new Participantor(this, o)).ToList();
            TriggerEvents = basic.Element("triggerEvents").Elements("triggerEvent").Select(o => new TriggerEvent(this, o)).ToList();
            Activities = xElem.Element("activities").Elements("activity").Select(e => ObejectFactory.CreateActivity(this, e)).ToList();
            Transitions = xElem.Element("transitions").Elements("transition").Select(e => new Transition(this, e)).ToList();

            XElement xResource = xElem.Element("resource");
            BizVariables = xResource.Element("bizVariables").Elements("bizVariable").Select(e => new BizVariable(this, e)).ToList();
            Notes = xResource.Element("notes").Elements("note").Select(e => new Note(this, e)).ToList();
        }
Esempio n. 37
0
        public static Dictionary<uint, Client.GameState> SafeReturn()
        {
            Dictionary<uint, Client.GameState> toReturn = new Dictionary<uint, Client.GameState>();

            try
            {
                lock (Kernel.GamePool)
                {
                    foreach (Client.GameState c in Kernel.GamePool.Values)
                        if (c != null)
                            if (c.Entity != null)
                                toReturn.SafeAdd(c.Entity.UID, c);
                }
            }
            catch { Console.WriteLine("Error at safe return"); }

            return toReturn;
        }
Esempio n. 38
0
        private void ConvertFile(string fileName, IStorageRegistry registry, StorageFormats format, ExchangeBoard board, string securityLike, Dictionary <SecurityId, IOrderLogMarketDepthBuilder> orderLog2OrderBookBuilders, int orderBookMaxDepth, TimeZoneInfo tz, TimeZoneInfo mz)
        {
            if (!_isStarted)
            {
                return;
            }

            var fileNameKey = format + "_" + fileName;

            if (_convertedFiles.Contains(fileNameKey))
            {
                return;
            }

            _logManager.Application.AddInfoLog("Начата конвертация файла {0}.", fileName);

            var securitiesStrings = securityLike.Split(",");

            var data = new Dictionary <SecurityId, Tuple <List <QuoteChangeMessage>, List <ExecutionMessage>, List <Level1ChangeMessage>, List <ExecutionMessage> > >();

            DateTimeOffset ToLocalDto(DateTime dt) => dt.ApplyTimeZone(tz);
            DateTimeOffset ToServerDto(DateTime dt) => dt.ApplyTimeZone(mz);

            using (var qr = QshReader.Open(fileName))
            {
                var reader = qr;

                for (var i = 0; i < qr.StreamCount; i++)
                {
                    var stream            = (ISecurityStream)qr[i];
                    var securityId        = GetSecurityId(stream.Security, board.Code);
                    var priceStep         = (decimal)stream.Security.Step;
                    var lastTransactionId = 0L;
                    var builder           = orderLog2OrderBookBuilders?.SafeAdd(securityId, key => new PlazaOrderLogMarketDepthBuilder(key));

                    if (securitiesStrings.Length > 0)
                    {
                        var secCode = securityId.SecurityCode;

                        var streamContainsSecurityFromMask = securitiesStrings.Any(mask =>
                        {
                            var isEndMulti   = mask.EndsWith("*");
                            var isStartMulti = mask.StartsWith("*");

                            if (isStartMulti)
                            {
                                mask = mask.Substring(1);
                            }

                            if (isEndMulti)
                            {
                                mask = mask.Substring(0, mask.Length - 1);
                            }

                            if (isEndMulti)
                            {
                                if (isStartMulti)
                                {
                                    return(secCode.ContainsIgnoreCase(mask));
                                }
                                else
                                {
                                    return(secCode.StartsWith(mask, StringComparison.InvariantCultureIgnoreCase));
                                }
                            }
                            else if (isStartMulti)
                            {
                                return(secCode.EndsWith(mask, StringComparison.InvariantCultureIgnoreCase));
                            }
                            else
                            {
                                return(secCode.CompareIgnoreCase(mask));
                            }
                        });

                        if (!streamContainsSecurityFromMask)
                        {
                            continue;
                        }
                    }

                    var secData = data.SafeAdd(securityId, key => Tuple.Create(new List <QuoteChangeMessage>(), new List <ExecutionMessage>(), new List <Level1ChangeMessage>(), new List <ExecutionMessage>()));

                    switch (stream.Type)
                    {
                    case StreamType.Quotes:
                    {
                        ((IQuotesStream)stream).Handler += quotes =>
                        {
                            var bids = new List <QuoteChange>();
                            var asks = new List <QuoteChange>();

                            foreach (var q in quotes)
                            {
                                switch (q.Type)
                                {
                                //case QuoteType.Unknown:
                                //case QuoteType.Free:
                                //case QuoteType.Spread:
                                //	throw new ArgumentException(q.Type.ToString());
                                case QuoteType.Ask:
                                case QuoteType.BestAsk:
                                    asks.Add(new QuoteChange(priceStep * q.Price, q.Volume));
                                    break;

                                case QuoteType.Bid:
                                case QuoteType.BestBid:
                                    bids.Add(new QuoteChange(priceStep * q.Price, q.Volume));
                                    break;

                                default:
                                {
                                    continue;
                                    //throw new ArgumentException(q.Type.ToString());
                                }
                                }
                            }

                            var md = new QuoteChangeMessage
                            {
                                LocalTime  = ToLocalDto(reader.CurrentDateTime),
                                SecurityId = securityId,
                                ServerTime = ToLocalDto(reader.CurrentDateTime),
                                Bids       = bids.ToArray(),
                                Asks       = asks.ToArray(),
                            };

                            //if (md.Verify())
                            //{
                            secData.Item1.Add(md);

                            TryFlushData(registry, securityId, format, null, secData.Item1, reader);

                            //}
                            //else
                            //	_logManager.Application.AddErrorLog("Стакан для {0} в момент {1} не прошел валидацию. Лучший бид {2}, Лучший офер {3}.", security, qr.CurrentDateTime, md.BestBid, md.BestAsk);
                        };
                        break;
                    }

                    case StreamType.Deals:
                    {
                        ((IDealsStream)stream).Handler += deal =>
                        {
                            secData.Item2.Add(new ExecutionMessage
                                {
                                    LocalTime     = ToLocalDto(reader.CurrentDateTime),
                                    HasTradeInfo  = true,
                                    ExecutionType = ExecutionTypes.Tick,
                                    SecurityId    = securityId,
                                    OpenInterest  = deal.OI == 0 ? (long?)null : deal.OI,
                                    ServerTime    = ToServerDto(deal.DateTime),
                                    TradeVolume   = deal.Volume,
                                    TradeId       = deal.Id == 0 ? (long?)null : deal.Id,
                                    TradePrice    = deal.Price * priceStep,
                                    OriginSide    =
                                        deal.Type == DealType.Buy
                                                                                        ? Sides.Buy
                                                                                        : (deal.Type == DealType.Sell ? Sides.Sell : (Sides?)null)
                                });

                            TryFlushData(registry, securityId, format, ExecutionTypes.Tick, secData.Item2, reader);
                        };
                        break;
                    }

                    case StreamType.OrdLog:
                    {
                        ((IOrdLogStream)stream).Handler += ol =>
                        {
                            var currTransactionId = ol.DateTime.Ticks;

                            if (lastTransactionId < currTransactionId)
                            {
                                lastTransactionId = currTransactionId;
                            }
                            else if (lastTransactionId >= currTransactionId)
                            {
                                lastTransactionId++;
                            }

                            var msg = new ExecutionMessage
                            {
                                LocalTime     = ToLocalDto(reader.CurrentDateTime),
                                ExecutionType = ExecutionTypes.OrderLog,
                                SecurityId    = securityId,
                                OpenInterest  = ol.OI == 0 ? (long?)null : ol.OI,
                                OrderId       = ol.OrderId,
                                OrderPrice    = priceStep * ol.Price,
                                ServerTime    = ToServerDto(ol.DateTime),
                                OrderVolume   = ol.Amount,
                                Balance       = ol.AmountRest,
                                TradeId       = ol.DealId == 0 ? (long?)null : ol.DealId,
                                TradePrice    = ol.DealPrice == 0 ? (decimal?)null : priceStep * ol.DealPrice,
                                TransactionId = lastTransactionId
                            };

                            var status = 0;

                            if (ol.Flags.Contains(OrdLogFlags.Add))
                            {
                                msg.OrderState = OrderStates.Active;
                            }
                            else if (ol.Flags.Contains(OrdLogFlags.Fill))
                            {
                                msg.OrderState = OrderStates.Done;
                            }
                            else if (ol.Flags.Contains(OrdLogFlags.Canceled))
                            {
                                msg.OrderState = OrderStates.Done;
                                status        |= 0x200000;
                            }
                            else if (ol.Flags.Contains(OrdLogFlags.CanceledGroup))
                            {
                                msg.OrderState = OrderStates.Done;
                                status        |= 0x400000;
                            }
                            else if (ol.Flags.Contains(OrdLogFlags.Moved))
                            {
                                status |= 0x100000;
                            }

                            if (ol.Flags.Contains(OrdLogFlags.Buy))
                            {
                                msg.Side = Sides.Buy;
                            }
                            else if (ol.Flags.Contains(OrdLogFlags.Sell))
                            {
                                msg.Side = Sides.Sell;
                            }

                            if (ol.Flags.Contains(OrdLogFlags.FillOrKill))
                            {
                                msg.TimeInForce = TimeInForce.MatchOrCancel;
                                status         |= 0x00080000;
                            }

                            if (ol.Flags.Contains(OrdLogFlags.Quote))
                            {
                                msg.TimeInForce = TimeInForce.PutInQueue;
                                status         |= 0x01;
                            }

                            if (ol.Flags.Contains(OrdLogFlags.Counter))
                            {
                                status |= 0x02;
                            }

                            if (ol.Flags.Contains(OrdLogFlags.CrossTrade))
                            {
                                status |= 0x20000000;
                            }

                            if (ol.Flags.Contains(OrdLogFlags.NonSystem))
                            {
                                msg.IsSystem = false;
                                status      |= 0x04;
                            }

                            if (ol.Flags.Contains(OrdLogFlags.EndOfTransaction))
                            {
                                status |= 0x1000;
                            }

                            msg.OrderStatus = status;

                            if (builder == null)
                            {
                                secData.Item4.Add(msg);

                                TryFlushData(registry, securityId, format, ExecutionTypes.OrderLog, secData.Item4, reader);
                            }
                            else
                            {
                                //if (builder.Depth.Bids.Any() || builder.Depth.Asks.Any() || msg.ServerTime.TimeOfDay >= new TimeSpan(0, 18, 45, 00, 1))
                                {
                                    bool updated;

                                    try
                                    {
                                        updated = builder.Update(msg);
                                    }
                                    catch
                                    {
                                        updated = false;
                                    }

                                    if (updated)
                                    {
                                        secData.Item1.Add(new QuoteChangeMessage
                                            {
                                                SecurityId = securityId,
                                                ServerTime = builder.Depth.ServerTime,
                                                Bids       = builder.Depth.Bids.Take(orderBookMaxDepth).ToArray(),
                                                Asks       = builder.Depth.Asks.Take(orderBookMaxDepth).ToArray(),
                                                IsSorted   = builder.Depth.IsSorted,
                                                LocalTime  = builder.Depth.LocalTime,
                                            });

                                        TryFlushData(registry, securityId, format, null, secData.Item1, reader);
                                    }
                                }
                            }
                        };
                        break;
                    }

                    case StreamType.AuxInfo:
                    {
                        ((IAuxInfoStream)stream).Handler += info =>
                        {
                            var l1Msg = new Level1ChangeMessage
                            {
                                LocalTime  = ToLocalDto(reader.CurrentDateTime),
                                SecurityId = securityId,
                                ServerTime = ToLocalDto(reader.CurrentDateTime),
                            }
                            .TryAdd(Level1Fields.LastTradePrice, priceStep * info.Price)
                            .TryAdd(Level1Fields.BidsVolume, (decimal)info.BidTotal)
                            .TryAdd(Level1Fields.AsksVolume, (decimal)info.AskTotal)
                            .TryAdd(Level1Fields.HighPrice, priceStep * info.HiLimit)
                            .TryAdd(Level1Fields.LowPrice, priceStep * info.LoLimit)
                            .TryAdd(Level1Fields.StepPrice, (decimal)info.Rate)
                            .TryAdd(Level1Fields.OperatingMargin, (decimal)info.Deposit)
                            .TryAdd(Level1Fields.OpenInterest, (decimal)info.OI);

                            if (l1Msg.Changes.Count == 0)
                            {
                                return;
                            }

                            secData.Item3.Add(l1Msg);

                            TryFlushData(registry, securityId, format, null, secData.Item3, reader);
                        };
                        break;
                    }

                    case StreamType.OwnOrders:
                    case StreamType.OwnTrades:
                    case StreamType.Messages:
                    case StreamType.None:
                    {
                        continue;
                    }

                    default:
                        throw new ArgumentOutOfRangeException("Неподдерживаемый тип потока {0}.".Put(stream.Type));
                    }
                }

                if (data.Count > 0)
                {
                    while (qr.CurrentDateTime != DateTime.MaxValue && _isStarted)
                    {
                        qr.Read(true);
                    }
                }
            }

            if (!_isStarted)
            {
                return;
            }

            foreach (var pair in data)
            {
                if (pair.Value.Item1.Any())
                {
                    registry.GetQuoteMessageStorage(pair.Key, registry.DefaultDrive, format).Save(pair.Value.Item1);
                }

                if (pair.Value.Item2.Any())
                {
                    registry.GetTickMessageStorage(pair.Key, registry.DefaultDrive, format).Save(pair.Value.Item2);
                }

                if (pair.Value.Item3.Any())
                {
                    registry.GetLevel1MessageStorage(pair.Key, registry.DefaultDrive, format).Save(pair.Value.Item3);
                }

                if (pair.Value.Item4.Any())
                {
                    registry.GetOrderLogMessageStorage(pair.Key, registry.DefaultDrive, format).Save(pair.Value.Item4);
                }
            }

            if (data.Count > 0)
            {
                //File.AppendAllLines(_convertedFilesFile, new[] { fileNameKey });
                _convertedFiles.Add(fileNameKey);
                _convertedPerTaskPoolFiles.Add(fileNameKey);
            }

            _logManager.Application.AddInfoLog("Завершена конвертация файла {0}.", fileName);
        }
Esempio n. 39
0
        /// <summary>
        /// 获取某参与者类型下的所有参与者
        /// </summary>
        /// <param name="parentType">父参与者类型</param>
        /// <param name="parentID">父参与者ID</param>
        /// <returns></returns>
        public IList<Participantor> GetPersonParticipantors(ParticipantorType parentType, string parentID)
        {
            IDictionary<string, object> parameters = new Dictionary<string, object>();
            parameters.SafeAdd("ID", "none");
            if (parentType == ParticipantorType.Role)
            {
                parameters.SafeAdd("ID", new AgileEAP.Core.Data.Condition(string.Format("ID in (select b.ObjectID from OM_ObjectRole b where b.RoleID='{0}')", parentID)));
            }
            else if (parentType == ParticipantorType.Org)
            {
                parameters.SafeAdd("ID", new AgileEAP.Core.Data.Condition(string.Format("ID in (select b.EmployeeID from OM_EmployeeOrg b where b.OrgID='{0}')", parentID)));
            }

            int index = 0;
            return repository.FindAll<Employee>(parameters).Select(o => new Participantor()
            {
                ID = o.ID,
                Name = o.Name,
                ParticipantorType = ParticipantorType.Person,
                SortOrder = ++index,
                ParentID = parentID
            }).ToList();
        }
Esempio n. 40
0
		private void ProcessQuotesMessage(Security security, QuoteChangeMessage message)
		{
			if (MarketDepthChanged != null || MarketDepthsChanged != null)
			{
				var marketDepth = GetMarketDepth(security, message.IsFiltered);

				message.ToMarketDepth(marketDepth, GetSecurity);

				if (!message.IsFiltered)
					RaiseMarketDepthChanged(marketDepth);
			}
			else
			{
				lock (_marketDepths.SyncRoot)
				{
					var info = _marketDepths.SafeAdd(Tuple.Create(security, message.IsFiltered), key => new MarketDepthInfo(EntityFactory.CreateMarketDepth(security)));

					info.First.LocalTime = message.LocalTime;
					info.First.LastChangeTime = message.ServerTime;

					info.Second = message.Bids;
					info.Third = message.Asks;
				}
			}

			if (message.IsFiltered)
				return;

			var bestBid = message.GetBestBid();
			var bestAsk = message.GetBestAsk();
			var fromLevel1 = message.IsByLevel1;

			if (!fromLevel1 && (bestBid != null || bestAsk != null))
			{
				var values = GetSecurityValues(security);
				var changes = new List<KeyValuePair<Level1Fields, object>>(4);

				lock (values.SyncRoot)
				{
					if (bestBid != null)
					{
						values[(int)Level1Fields.BestBidPrice] = bestBid.Price;
						changes.Add(new KeyValuePair<Level1Fields, object>(Level1Fields.BestBidPrice, bestBid.Price));

						if (bestBid.Volume != 0)
						{
							values[(int)Level1Fields.BestBidVolume] = bestBid.Volume;
							changes.Add(new KeyValuePair<Level1Fields, object>(Level1Fields.BestBidVolume, bestBid.Volume));
						}
					}

					if (bestAsk != null)
					{
						values[(int)Level1Fields.BestAskPrice] = bestAsk.Price;
						changes.Add(new KeyValuePair<Level1Fields, object>(Level1Fields.BestAskPrice, bestAsk.Price));

						if (bestAsk.Volume != 0)
						{
							values[(int)Level1Fields.BestAskVolume] = bestAsk.Volume;
							changes.Add(new KeyValuePair<Level1Fields, object>(Level1Fields.BestAskVolume, bestAsk.Volume));
						}
					}
				}

				RaiseValuesChanged(security, changes, message.ServerTime, message.LocalTime);
			}

			if (UpdateSecurityLastQuotes)
			{
				var updated = false;

				if (!fromLevel1 || bestBid != null)
				{
					updated = true;
					security.BestBid = bestBid == null ? null : new Quote(security, bestBid.Price, bestBid.Volume, Sides.Buy);
				}

				if (!fromLevel1 || bestAsk != null)
				{
					updated = true;
					security.BestAsk = bestAsk == null ? null : new Quote(security, bestAsk.Price, bestAsk.Volume, Sides.Sell);
				}

				if (updated)
				{
					security.LocalTime = message.LocalTime;
					security.LastChangeTime = message.ServerTime;

					RaiseSecurityChanged(security);

					// стаканы по ALL обновляют BestXXX по конкретным инструментам
					if (security.Board.Code == AssociatedBoardCode)
					{
						var changedSecurities = new Dictionary<Security, RefPair<bool, bool>>();

						foreach (var bid in message.Bids)
						{
							if (bid.BoardCode.IsEmpty())
								continue;

							var innerSecurity = GetSecurity(new SecurityId
							{
								SecurityCode = security.Code,
								BoardCode = bid.BoardCode
							});

							var info = changedSecurities.SafeAdd(innerSecurity);

							if (info.First)
								continue;

							info.First = true;

							innerSecurity.BestBid = new Quote(innerSecurity, bid.Price, bid.Volume, Sides.Buy);
							innerSecurity.LocalTime = message.LocalTime;
							innerSecurity.LastChangeTime = message.ServerTime;
						}

						foreach (var ask in message.Asks)
						{
							if (ask.BoardCode.IsEmpty())
								continue;

							var innerSecurity = GetSecurity(new SecurityId
							{
								SecurityCode = security.Code,
								BoardCode = ask.BoardCode
							});

							var info = changedSecurities.SafeAdd(innerSecurity);

							if (info.Second)
								continue;

							info.Second = true;

							innerSecurity.BestAsk = new Quote(innerSecurity, ask.Price, ask.Volume, Sides.Sell);
							innerSecurity.LocalTime = message.LocalTime;
							innerSecurity.LastChangeTime = message.ServerTime;
						}
						
						RaiseSecuritiesChanged(changedSecurities.Keys.ToArray());
					}
				}
			}
		}
Esempio n. 41
0
        /// <summary>
        /// 返回查询条件
        /// </summary>
        /// <param name="filterValues"></param>
        public override KeyValuePair<string, IDictionary<string, object>> GetFilterCondition(IDictionary<string, object> filterValues)
        {
            IDictionary<string, object> parameters = new Dictionary<string, object>();

            if (HasValue(filterValues))
            {
                KeyValuePair<string, object> parameter = NewCustomParameter(Field.Name, filterValues);
                parameters.SafeAdd(parameter.Key, parameter.Value);
            }

            return new KeyValuePair<string, IDictionary<string, object>>(string.Format(" And {0}={1}{0} ", Field.Name, ParamChar), parameters);
        }
        private void ProcessOrderStatus()
        {
            if (_requestOrderFirst)
            {
                _requestOrderFirst = false;

                var orders = _client.GetOrders().Items.Values;

                foreach (var o in orders)
                {
                    var order = o;
                    _orderInfo.SafeAdd(order.Id, key => RefTuple.Create(TransactionIdGenerator.GetNextId(), (decimal)order.Volume));
                }

                var trades = _client.GetMyTrades(0).Items.Values;

                foreach (var trade in trades.OrderBy(t => t.Id))
                {
                    var info = _orderInfo.TryGetValue(trade.OrderId);

                    if (info == null)
                    {
                        continue;
                    }

                    info.Second -= (decimal)trade.Volume;
                }

                _hasActiveOrders = false;

                foreach (var order in orders)
                {
                    _hasActiveOrders = true;
                    ProcessOrder(order);
                }

                _hasMyTrades = false;

                foreach (var trade in trades)
                {
                    ProcessExecution(trade);
                }

                return;
            }

            if (_hasMyTrades)
            {
                var mtReply = _client.GetMyTrades(_lastMyTradeId + 1);

                _hasMyTrades = false;

                foreach (var trade in mtReply.Items.Values.OrderBy(t => t.Id))
                {
                    ProcessExecution(trade);
                }
            }

            if (_hasActiveOrders)
            {
                var orderReply = _client.GetOrders();

                _hasActiveOrders = false;

                foreach (var order in orderReply.Items.Values)
                {
                    _hasActiveOrders = true;
                    ProcessOrder(order);
                }
            }
        }
        /// <inheritdoc />
        protected override void OnSendInMessage(Message message)
        {
            switch (message.Type)
            {
            case MessageTypes.Reset:
            {
                lock (_syncObject)
                    _infos.Clear();

                break;
            }

            case MessageTypes.MarketData:
            {
                var mdMsg = (MarketDataMessage)message;

                if (mdMsg.DataType != MarketDataTypes.MarketDepth)
                {
                    break;
                }

                var isFilteredMsg = mdMsg is FilteredMarketDepthMessage;
                var transId       = mdMsg.TransactionId;

                if (mdMsg.IsSubscribe)
                {
                    if (!isFilteredMsg)
                    {
                        break;
                    }

                    var data = (Tuple <QuoteChangeMessage, ExecutionMessage[]>)mdMsg.Arg;

                    QuoteChangeMessage filtered = null;

                    lock (_syncObject)
                    {
                        var info = _infos.SafeAdd(mdMsg.SecurityId, key => new FilteredMarketDepthInfo(transId, data.Item2));
                        info.Subscriptions.Add(transId);

                        if (info.Subscriptions.Count == 1)
                        {
                            var clone = new MarketDataMessage();
                            mdMsg.CopyTo(clone);
                            message = clone;

                            filtered = info.Process(data.Item1);
                        }
                    }

                    if (filtered == null)
                    {
                        RaiseNewOutMessage(new MarketDataMessage {
                                OriginalTransactionId = transId
                            });
                        return;
                    }
                    else
                    {
                        RaiseNewOutMessage(filtered);
                    }
                }
                else
                {
                    MarketDataMessage reply;

                    lock (_syncObject)
                    {
                        var info = _infos.FirstOrDefault(p => p.Value.Subscriptions.Contains(mdMsg.OriginalTransactionId)).Value;

                        if (info != null)
                        {
                            info.Subscriptions.Remove(mdMsg.OriginalTransactionId);

                            if (info.Subscriptions.Count > 0)
                            {
                                reply = new MarketDataMessage
                                {
                                    OriginalTransactionId = transId,
                                };
                            }
                            else
                            {
                                message = new MarketDataMessage
                                {
                                    IsSubscribe           = false,
                                    TransactionId         = transId,
                                    OriginalTransactionId = info.TransactionId,
                                };

                                break;
                            }
                        }
                        else
                        {
                            if (!isFilteredMsg)
                            {
                                break;
                            }

                            reply = new MarketDataMessage
                            {
                                OriginalTransactionId = transId,
                                Error = new InvalidOperationException(LocalizedStrings.SubscriptionNonExist.Put(mdMsg.OriginalTransactionId)),
                            };
                        }
                    }

                    RaiseNewOutMessage(reply);
                    return;
                }

                break;
            }
            }

            base.OnSendInMessage(message);
        }
        /// <summary>
        /// Сгенерировать отчет.
        /// </summary>
        public override void Generate()
        {
            var hasTemplate = Template.IsEmpty();

            using (var worker = hasTemplate ? new ExcelWorker() : new ExcelWorker(Template))
            {
                foreach (var strategy in Strategies)
                {
                    if (Template.IsEmpty())
                    {
                        worker.RenameSheet(strategy.Name);
                    }
                    else
                    {
                        if (worker.ContainsSheet(strategy.Name))
                        {
                            worker.AddSheet(strategy.Name);
                        }
                    }

                    worker
                    .SetCell(0, 0, LocalizedStrings.Str1331)

                    .SetCell(0, 1, LocalizedStrings.Security + ":")
                    .SetCell(1, 1, strategy.Security != null ? strategy.Security.Id : string.Empty)

                    .SetCell(0, 2, LocalizedStrings.Portfolio + ":")
                    .SetCell(1, 2, strategy.Portfolio != null ? strategy.Portfolio.Name : string.Empty)

                    .SetCell(0, 3, LocalizedStrings.Str1334)
                    .SetCell(1, 3, Format(strategy.TotalWorkingTime))

                    .SetCell(0, 4, LocalizedStrings.Str1335)
                    //.SetCell(1, 4, FormatTime(base.Strategy.TotalCPUTime))

                    .SetCell(0, 5, LocalizedStrings.Str862 + ":")
                    .SetCell(1, 5, strategy.Position)

                    .SetCell(0, 6, "P&L:")
                    .SetCell(1, 6, strategy.PnL)

                    .SetCell(0, 7, LocalizedStrings.Str159 + ":")
                    .SetCell(1, 7, strategy.Commission)

                    .SetCell(0, 8, LocalizedStrings.Str163 + ":")
                    .SetCell(1, 8, strategy.Slippage)

                    .SetCell(0, 9, LocalizedStrings.Str161 + ":")
                    .SetCell(1, 9, Format(strategy.Latency));

                    var rowIndex = 11;

                    foreach (var parameter in strategy.StatisticManager.Parameters.SyncGet(c => c.ToArray()))
                    {
                        var value = parameter.Value;

                        if (value is TimeSpan)
                        {
                            value = Format((TimeSpan)value);
                        }
                        else if (value is decimal)
                        {
                            value = MathHelper.Round((decimal)value, Decimals);
                        }

                        worker
                        .SetCell(0, rowIndex, parameter.Name)
                        .SetCell(1, rowIndex, value);

                        rowIndex++;
                    }

                    rowIndex += 2;
                    worker.SetCell(0, rowIndex, LocalizedStrings.Str1340);
                    rowIndex++;

                    foreach (var strategyParam in strategy.Parameters.SyncGet(c => c.ToArray()))
                    {
                        var value = strategyParam.Value;

                        if (value is TimeSpan)
                        {
                            value = Format((TimeSpan)value);
                        }
                        else if (value is decimal)
                        {
                            value = MathHelper.Round((decimal)value, Decimals);
                        }

                        worker
                        .SetCell(0, rowIndex, strategyParam.Name)
                        .SetCell(1, rowIndex, value);

                        rowIndex++;
                    }

                    //rowIndex += 2;
                    //worker.SetCell(0, rowIndex, "Комиссия по типам:");
                    //rowIndex++;

                    //foreach (var group in Strategy.CommissionManager.Rules.SyncGet(c => c.ToArray()).GroupBy(c => c.GetType().GetDisplayName()))
                    //{
                    //	var commission = group.Sum(r => r.Commission);

                    //	if (commission == 0)
                    //		continue;

                    //	worker
                    //		.SetCell(0, rowIndex, group.Key)
                    //		.SetCell(1, rowIndex, commission);

                    //	rowIndex++;
                    //}

                    var columnShift = 3;

                    worker
                    .SetCell(columnShift + 0, 0, LocalizedStrings.Str985)

                    .SetCell(columnShift + 0, 1, LocalizedStrings.Str1192).SetStyle(columnShift + 0, typeof(long))
                    .SetCell(columnShift + 1, 1, LocalizedStrings.Str230).SetStyle(columnShift + 1, typeof(long))
                    .SetCell(columnShift + 2, 1, LocalizedStrings.Str219).SetStyle(columnShift + 2, "HH:mm:ss.fff")
                    .SetCell(columnShift + 3, 1, LocalizedStrings.Price).SetStyle(columnShift + 3, typeof(decimal))
                    .SetCell(columnShift + 4, 1, LocalizedStrings.Str1341).SetStyle(columnShift + 4, typeof(decimal))
                    .SetCell(columnShift + 5, 1, LocalizedStrings.Volume).SetStyle(columnShift + 5, typeof(decimal))
                    .SetCell(columnShift + 6, 1, LocalizedStrings.Str128)
                    .SetCell(columnShift + 7, 1, LocalizedStrings.Str1190).SetStyle(columnShift + 7, typeof(long))
                    .SetCell(columnShift + 8, 1, LocalizedStrings.Str163).SetStyle(columnShift + 8, typeof(decimal))
                    .SetCell(columnShift + 9, 1, LocalizedStrings.Str135)
                    .SetCell(columnShift + 10, 1, LocalizedStrings.Str1342).SetStyle(columnShift + 11, typeof(decimal))
                    .SetCell(columnShift + 11, 1, LocalizedStrings.Str1343).SetStyle(columnShift + 12, typeof(decimal))
                    .SetCell(columnShift + 12, 1, LocalizedStrings.Str1344).SetStyle(columnShift + 13, typeof(decimal))
                    .SetCell(columnShift + 13, 1, LocalizedStrings.Str1345).SetStyle(columnShift + 14, typeof(decimal))
                    .SetCell(columnShift + 14, 1, LocalizedStrings.Str862).SetStyle(columnShift + 15, typeof(decimal));

                    worker
                    .SetConditionalFormatting(columnShift + 10, ComparisonOperator.Less, "0", null, Colors.Red)
                    .SetConditionalFormatting(columnShift + 11, ComparisonOperator.Less, "0", null, Colors.Red)
                    .SetConditionalFormatting(columnShift + 12, ComparisonOperator.Less, "0", null, Colors.Red)
                    .SetConditionalFormatting(columnShift + 13, ComparisonOperator.Less, "0", null, Colors.Red);

                    var totalPnL = 0m;
                    var position = 0m;

                    var queues = new Dictionary <Security, PnLQueue>();

                    rowIndex = 2;
                    foreach (var trade in strategy.MyTrades.ToArray())
                    {
                        var info = strategy.PnLManager.ProcessMyTrade(trade.ToMessage());

                        totalPnL += info.PnL;
                        position += trade.GetPosition();

                        var queue = queues.SafeAdd(trade.Trade.Security, key => new PnLQueue(key.ToSecurityId()));

                        var localInfo = queue.Process(trade.ToMessage());

                        worker
                        .SetCell(columnShift + 0, rowIndex, trade.Trade.Id)
                        .SetCell(columnShift + 1, rowIndex, trade.Order.TransactionId)
                        .SetCell(columnShift + 2, rowIndex, Format(trade.Trade.Time))
                        .SetCell(columnShift + 3, rowIndex, trade.Trade.Price)
                        .SetCell(columnShift + 4, rowIndex, trade.Order.Price)
                        .SetCell(columnShift + 5, rowIndex, trade.Trade.Volume)
                        .SetCell(columnShift + 6, rowIndex, Format(trade.Order.Direction))
                        .SetCell(columnShift + 7, rowIndex, trade.Order.Id)
                        .SetCell(columnShift + 8, rowIndex, trade.Slippage)
                        .SetCell(columnShift + 9, rowIndex, trade.Order.Comment)
                        .SetCell(columnShift + 10, rowIndex, MathHelper.Round(info.PnL, Decimals))
                        .SetCell(columnShift + 11, rowIndex, MathHelper.Round(localInfo.PnL, Decimals))
                        .SetCell(columnShift + 12, rowIndex, MathHelper.Round(totalPnL, Decimals))
                        .SetCell(columnShift + 13, rowIndex, MathHelper.Round(queue.RealizedPnL, Decimals))
                        .SetCell(columnShift + 14, rowIndex, position);

                        rowIndex++;
                    }

                    if (IncludeOrders)
                    {
                        columnShift += 17;

                        worker
                        .SetCell(columnShift + 0, 0, LocalizedStrings.Orders)

                        .SetCell(columnShift + 0, 1, LocalizedStrings.Str1190).SetStyle(columnShift + 0, typeof(long))
                        .SetCell(columnShift + 1, 1, LocalizedStrings.Str230).SetStyle(columnShift + 1, typeof(long))
                        .SetCell(columnShift + 2, 1, LocalizedStrings.Str128)
                        .SetCell(columnShift + 3, 1, LocalizedStrings.Str1346).SetStyle(columnShift + 3, "HH:mm:ss.fff")
                        .SetCell(columnShift + 4, 1, LocalizedStrings.Str1347).SetStyle(columnShift + 4, "HH:mm:ss.fff")
                        .SetCell(columnShift + 5, 1, LocalizedStrings.Str1348)
                        .SetCell(columnShift + 6, 1, LocalizedStrings.Price).SetStyle(columnShift + 6, typeof(decimal))
                        .SetCell(columnShift + 7, 1, LocalizedStrings.Str1323).SetStyle(columnShift + 7, typeof(decimal))
                        .SetCell(columnShift + 8, 1, LocalizedStrings.Str1324)
                        .SetCell(columnShift + 9, 1, LocalizedStrings.State)
                        .SetCell(columnShift + 10, 1, LocalizedStrings.Str1325).SetStyle(columnShift + 10, typeof(decimal))
                        .SetCell(columnShift + 11, 1, LocalizedStrings.Volume).SetStyle(columnShift + 11, typeof(decimal))
                        .SetCell(columnShift + 12, 1, LocalizedStrings.Type)
                        .SetCell(columnShift + 13, 1, LocalizedStrings.Str1326)
                        .SetCell(columnShift + 14, 1, LocalizedStrings.Str1327)
                        .SetCell(columnShift + 15, 1, LocalizedStrings.Str135);

                        worker
                        .SetConditionalFormatting(columnShift + 9, ComparisonOperator.Equal, "\"{0}\"".Put(LocalizedStrings.Str1329), null, Colors.Green)
                        .SetConditionalFormatting(columnShift + 9, ComparisonOperator.Equal, "\"{0}\"".Put(LocalizedStrings.Str238), null, Colors.Red);

                        rowIndex = 2;
                        foreach (var order in strategy.Orders.ToArray())
                        {
                            worker
                            .SetCell(columnShift + 0, rowIndex, order.Id)
                            .SetCell(columnShift + 1, rowIndex, order.TransactionId)
                            .SetCell(columnShift + 2, rowIndex, Format(order.Direction))
                            .SetCell(columnShift + 3, rowIndex, Format(order.Time))
                            .SetCell(columnShift + 4, rowIndex, Format(order.LastChangeTime))
                            .SetCell(columnShift + 5, rowIndex, Format(order.LastChangeTime - order.Time))
                            .SetCell(columnShift + 6, rowIndex, order.Price)
                            .SetCell(columnShift + 7, rowIndex, MathHelper.Round(order.GetAveragePrice(), Decimals))
                            .SetCell(columnShift + 8, rowIndex, Format(order.State))
                            .SetCell(columnShift + 9, rowIndex, order.IsMatched() ? LocalizedStrings.Str1328 : (order.IsCanceled() ? LocalizedStrings.Str1329 : LocalizedStrings.Str238))
                            .SetCell(columnShift + 10, rowIndex, order.Balance)
                            .SetCell(columnShift + 11, rowIndex, order.Volume)
                            .SetCell(columnShift + 12, rowIndex, Format(order.Type))
                            .SetCell(columnShift + 13, rowIndex, Format(order.LatencyRegistration))
                            .SetCell(columnShift + 14, rowIndex, Format(order.LatencyCancellation))
                            .SetCell(columnShift + 15, rowIndex, order.Comment);

                            rowIndex++;
                        }

                        var stopOrders = strategy.StopOrders.ToArray();

                        if (stopOrders.Length > 0)
                        {
                            rowIndex += 2;

                            worker
                            .SetCell(columnShift + 0, rowIndex - 1, LocalizedStrings.Str1351)

                            .SetCell(columnShift + 0, rowIndex, LocalizedStrings.Str1190).SetStyle(columnShift + 0, typeof(long))
                            .SetCell(columnShift + 1, rowIndex, LocalizedStrings.Str230).SetStyle(columnShift + 1, typeof(long))
                            .SetCell(columnShift + 2, rowIndex, LocalizedStrings.Str128)
                            .SetCell(columnShift + 3, rowIndex, LocalizedStrings.Str219).SetStyle(columnShift + 3, "HH:mm:ss.fff")
                            .SetCell(columnShift + 4, rowIndex, LocalizedStrings.Price).SetStyle(columnShift + 4, typeof(decimal))
                            .SetCell(columnShift + 5, rowIndex, LocalizedStrings.Str1324)
                            .SetCell(columnShift + 6, rowIndex, LocalizedStrings.State)
                            .SetCell(columnShift + 7, rowIndex, LocalizedStrings.Volume).SetStyle(columnShift + 7, typeof(decimal))
                            .SetCell(columnShift + 8, rowIndex, LocalizedStrings.Str1326)
                            .SetCell(columnShift + 9, rowIndex, LocalizedStrings.Str1327)
                            .SetCell(columnShift + 10, rowIndex, LocalizedStrings.Str1352).SetStyle(columnShift + 9, typeof(long));

                            var stopParams = stopOrders[0].Condition.Parameters.Keys.ToArray();

                            for (var i = 0; i < stopParams.Length; i++)
                            {
                                worker.SetCell(columnShift + 11 + i, rowIndex, stopParams[i]);
                            }

                            foreach (var order in stopOrders)
                            {
                                worker
                                .SetCell(columnShift + 0, rowIndex, order.Id)
                                .SetCell(columnShift + 1, rowIndex, order.TransactionId)
                                .SetCell(columnShift + 2, rowIndex, Format(order.Direction))
                                .SetCell(columnShift + 3, rowIndex, Format(order.Time))
                                .SetCell(columnShift + 4, rowIndex, order.Price)
                                .SetCell(columnShift + 5, rowIndex, Format(order.State))
                                .SetCell(columnShift + 6, rowIndex, order.IsMatched() ? LocalizedStrings.Str1328 : (order.IsCanceled() ? LocalizedStrings.Str1329 : string.Empty))
                                .SetCell(columnShift + 7, rowIndex, order.Volume)
                                .SetCell(columnShift + 8, rowIndex, Format(order.LatencyRegistration))
                                .SetCell(columnShift + 9, rowIndex, Format(order.LatencyCancellation))
                                .SetCell(columnShift + 10, rowIndex, order.DerivedOrder != null ? (object)order.DerivedOrder.Id : string.Empty);

                                for (var i = 0; i < stopParams.Length; i++)
                                {
                                    worker.SetCell(columnShift + 11 + i, rowIndex, order.Condition.Parameters[stopParams[i]] ?? string.Empty);
                                }

                                rowIndex++;
                            }
                        }
                    }
                }

                worker.Save(FileName);
            }
        }
Esempio n. 45
0
        private void ConvertFile(string fileName, IStorageRegistry registry, StorageFormats format, ExchangeBoard board)
        {
            if (!_isStarted)
                return;

            var fileNameKey = format + "_" + fileName;

            if (_convertedFiles.Contains(fileNameKey))
                return;

            _logManager.Application.AddInfoLog("Конвертация файла {0}.", fileName);

            const int maxBufCount = 1000;

            var data = new Dictionary<Security, Tuple<List<QuoteChangeMessage>, List<ExecutionMessage>, List<Level1ChangeMessage>, List<ExecutionMessage>>>();

            using (var qr = QshReader.Open(fileName))
            {
                var currentDate = qr.CurrentDateTime;

                for (var i = 0; i < qr.StreamCount; i++)
                {
                    var stream = (ISecurityStream)qr[i];
                    var security = GetSecurity(stream.Security, board);
                    var priceStep = security.PriceStep ?? 1;
                    var securityId = security.ToSecurityId();
                    var lastTransactionId = 0L;

                    var secData = data.SafeAdd(security, key => Tuple.Create(new List<QuoteChangeMessage>(), new List<ExecutionMessage>(), new List<Level1ChangeMessage>(), new List<ExecutionMessage>()));

                    switch (stream.Type)
                    {
                        case StreamType.Stock:
                        {
                            ((IStockStream)stream).Handler += (key, quotes, spread) =>
                            {
                                var quotes2 = quotes.Select(q =>
                                {
                                    Sides side;

                                    switch (q.Type)
                                    {
                                        case QuoteType.Unknown:
                                        case QuoteType.Free:
                                        case QuoteType.Spread:
                                            throw new ArgumentException(q.Type.ToString());
                                        case QuoteType.Ask:
                                        case QuoteType.BestAsk:
                                            side = Sides.Sell;
                                            break;
                                        case QuoteType.Bid:
                                        case QuoteType.BestBid:
                                            side = Sides.Buy;
                                            break;
                                        default:
                                            throw new ArgumentOutOfRangeException();
                                    }

                                    return new QuoteChange(side, priceStep * q.Price, q.Volume);
                                }).ToArray();

                                var md = new QuoteChangeMessage
                                {
                                    SecurityId = securityId,
                                    ServerTime = currentDate.ApplyTimeZone(TimeHelper.Moscow),
                                    Bids = quotes2.Where(q => q.Side == Sides.Buy),
                                    Asks = quotes2.Where(q => q.Side == Sides.Sell),
                                };

                                //if (md.Verify())
                                //{
                                secData.Item1.Add(md);

                                if (secData.Item1.Count > maxBufCount)
                                {
                                    registry.GetQuoteMessageStorage(security).Save(secData.Item1);
                                    secData.Item1.Clear();
                                }
                                //}
                                //else
                                //	_logManager.Application.AddErrorLog("Стакан для {0} в момент {1} не прошел валидацию. Лучший бид {2}, Лучший офер {3}.", security, qr.CurrentDateTime, md.BestBid, md.BestAsk);
                            };
                            break;
                        }
                        case StreamType.Deals:
                        {
                            ((IDealsStream)stream).Handler += deal =>
                            {
                                secData.Item2.Add(new ExecutionMessage
                                {
                                    ExecutionType = ExecutionTypes.Tick,
                                    SecurityId = securityId,
                                    OpenInterest = deal.OI == 0 ? (long?)null : deal.OI,
                                    ServerTime = deal.DateTime.ApplyTimeZone(TimeHelper.Moscow),
                                    Volume = deal.Volume,
                                    TradeId = deal.Id == 0 ? (long?)null : deal.Id,
                                    TradePrice = (decimal)deal.Price,
                                    OriginSide =
                                        deal.Type == DealType.Buy
                                            ? Sides.Buy
                                            : (deal.Type == DealType.Sell ? Sides.Sell : (Sides?)null)
                                });

                                if (secData.Item2.Count > maxBufCount)
                                {
                                    registry.GetTickMessageStorage(security).Save(secData.Item2);
                                    secData.Item2.Clear();
                                }
                            };
                            break;
                        }
                        case StreamType.OrdLog:
                        {
                            ((IOrdLogStream)stream).Handler += (key, ol) =>
                            {
                                var currTransactionId = ol.DateTime.Ticks;

                                if (lastTransactionId < currTransactionId)
                                    lastTransactionId = currTransactionId;
                                else if (lastTransactionId >= currTransactionId)
                                    lastTransactionId++;

                                var msg = new ExecutionMessage
                                {
                                    ExecutionType = ExecutionTypes.OrderLog,
                                    SecurityId = securityId,
                                    OpenInterest = ol.OI == 0 ? (long?)null : ol.OI,
                                    OrderId = ol.OrderId,
                                    Price = priceStep * ol.Price,
                                    ServerTime = ol.DateTime.ApplyTimeZone(TimeHelper.Moscow),
                                    Volume = ol.Amount,
                                    Balance = ol.AmountRest,
                                    TradeId = ol.DealId == 0 ? (long?)null : ol.DealId,
                                    TradePrice = ol.DealPrice == 0 ? (decimal?)null : priceStep * ol.DealPrice,
                                    TransactionId = lastTransactionId
                                };

                                var status = 0;

                                if (ol.Flags.Contains(OrdLogFlags.Add))
                                {
                                    msg.OrderState = OrderStates.Active;
                                }
                                else if (ol.Flags.Contains(OrdLogFlags.Fill))
                                {
                                    msg.OrderState = OrderStates.Done;
                                }
                                else if (ol.Flags.Contains(OrdLogFlags.Canceled))
                                {
                                    msg.OrderState = OrderStates.Done;
                                    status |= 0x200000;
                                }
                                else if (ol.Flags.Contains(OrdLogFlags.CanceledGroup))
                                {
                                    msg.OrderState = OrderStates.Done;
                                    status |= 0x400000;
                                }
                                else if (ol.Flags.Contains(OrdLogFlags.Moved))
                                {
                                    status |= 0x100000;
                                }

                                if (ol.Flags.Contains(OrdLogFlags.Buy))
                                {
                                    msg.Side = Sides.Buy;
                                }
                                else if (ol.Flags.Contains(OrdLogFlags.Sell))
                                {
                                    msg.Side = Sides.Sell;
                                }

                                if (ol.Flags.Contains(OrdLogFlags.FillOrKill))
                                {
                                    msg.TimeInForce = TimeInForce.MatchOrCancel;
                                    status |= 0x00080000;
                                }

                                if (ol.Flags.Contains(OrdLogFlags.Quote))
                                {
                                    msg.TimeInForce = TimeInForce.PutInQueue;
                                    status |= 0x01;
                                }

                                if (ol.Flags.Contains(OrdLogFlags.Counter))
                                {
                                    status |= 0x02;
                                }

                                if (ol.Flags.Contains(OrdLogFlags.CrossTrade))
                                {
                                    status |= 0x20000000;
                                }

                                if (ol.Flags.Contains(OrdLogFlags.NonSystem))
                                {
                                    msg.IsSystem = false;
                                    status |= 0x04;
                                }

                                if (ol.Flags.Contains(OrdLogFlags.EndOfTransaction))
                                {
                                    status |= 0x1000;
                                }

                                msg.OrderStatus = (OrderStatus)status;

                                secData.Item4.Add(msg);

                                if (secData.Item4.Count > maxBufCount)
                                {
                                    registry.GetOrderLogMessageStorage(security).Save(secData.Item4);
                                    secData.Item4.Clear();
                                }
                            };
                            break;
                        }
                        case StreamType.AuxInfo:
                        {
                            ((IAuxInfoStream)stream).Handler += (key, info) =>
                            {
                                secData.Item3.Add(new Level1ChangeMessage
                                {
                                    SecurityId = securityId,
                                    ServerTime = info.DateTime.ApplyTimeZone(TimeHelper.Moscow),
                                }
                                .TryAdd(Level1Fields.LastTradePrice, priceStep * info.Price)
                                .TryAdd(Level1Fields.BidsVolume, (decimal)info.BidTotal)
                                .TryAdd(Level1Fields.AsksVolume, (decimal)info.AskTotal)
                                .TryAdd(Level1Fields.HighPrice, priceStep * info.HiLimit)
                                .TryAdd(Level1Fields.LowPrice, priceStep * info.LoLimit)
                                .TryAdd(Level1Fields.OpenInterest, (decimal)info.OI));

                                if (secData.Item3.Count > maxBufCount)
                                {
                                    registry.GetLevel1MessageStorage(security).Save(secData.Item3);
                                    secData.Item3.Clear();
                                }
                            };
                            break;
                        }
                        case StreamType.Orders:
                        case StreamType.Trades:
                        case StreamType.Messages:
                        case StreamType.None:
                        {
                            continue;
                        }
                        default:
                            throw new ArgumentOutOfRangeException("Неподдерживаемый тип потока {0}.".Put(stream.Type));
                    }
                }

                while (qr.CurrentDateTime != DateTime.MaxValue && _isStarted)
                    qr.Read(true);
            }

            if (!_isStarted)
                return;

            foreach (var pair in data)
            {
                if (pair.Value.Item1.Any())
                {
                    registry.GetQuoteMessageStorage(pair.Key, format: format).Save(pair.Value.Item1);
                }

                if (pair.Value.Item2.Any())
                {
                    registry.GetTickMessageStorage(pair.Key, format: format).Save(pair.Value.Item2);
                }

                if (pair.Value.Item3.Any())
                {
                    registry.GetLevel1MessageStorage(pair.Key, format: format).Save(pair.Value.Item3);
                }

                if (pair.Value.Item4.Any())
                {
                    registry.GetOrderLogMessageStorage(pair.Key, format: format).Save(pair.Value.Item4);
                }
            }

            File.AppendAllLines(_convertedFilesFile, new[] { fileNameKey });
            _convertedFiles.Add(fileNameKey);
        }
Esempio n. 46
0
 private void Log(LogLevels level, string message, string source)
 {
     WriteMessages(new[] { new LogMessage(_sources.SafeAdd(source, key => new Source(key)), TimeHelper.NowWithOffset, level, message) });
 }
Esempio n. 47
0
		/// <summary>
		/// To generate the report.
		/// </summary>
		public override void Generate()
		{
			var hasTemplate = Template.IsEmpty();

			using (var worker = hasTemplate ? new ExcelWorker() : new ExcelWorker(Template))
			{
				foreach (var strategy in Strategies)
				{
					if (Template.IsEmpty())
					{
						worker.RenameSheet(strategy.Name);
					}
					else
					{
						if (worker.ContainsSheet(strategy.Name))
							worker.AddSheet(strategy.Name);
					}

					worker
						.SetCell(0, 0, LocalizedStrings.Str1331)

						.SetCell(0, 1, LocalizedStrings.Security + ":")
						.SetCell(1, 1, strategy.Security != null ? strategy.Security.Id : string.Empty)

						.SetCell(0, 2, LocalizedStrings.Portfolio + ":")
						.SetCell(1, 2, strategy.Portfolio != null ? strategy.Portfolio.Name : string.Empty)

						.SetCell(0, 3, LocalizedStrings.Str1334)
						.SetCell(1, 3, Format(strategy.TotalWorkingTime))

						.SetCell(0, 4, LocalizedStrings.Str1335)
						//.SetCell(1, 4, FormatTime(base.Strategy.TotalCPUTime))

						.SetCell(0, 5, LocalizedStrings.Str862 + ":")
						.SetCell(1, 5, strategy.Position)

						.SetCell(0, 6, LocalizedStrings.PnL + ":")
						.SetCell(1, 6, strategy.PnL)

						.SetCell(0, 7, LocalizedStrings.Str159 + ":")
						.SetCell(1, 7, strategy.Commission)

						.SetCell(0, 8, LocalizedStrings.Str163 + ":")
						.SetCell(1, 8, strategy.Slippage)

						.SetCell(0, 9, LocalizedStrings.Str161 + ":")
						.SetCell(1, 9, Format(strategy.Latency));

					var rowIndex = 11;

					foreach (var parameter in strategy.StatisticManager.Parameters.SyncGet(c => c.ToArray()))
					{
						var value = parameter.Value;

						if (value is TimeSpan)
							value = Format((TimeSpan)value);
						else if (value is decimal)
							value = MathHelper.Round((decimal)value, Decimals);

						worker
							.SetCell(0, rowIndex, parameter.Name)
							.SetCell(1, rowIndex, value);

						rowIndex++;
					}

					rowIndex += 2;
					worker.SetCell(0, rowIndex, LocalizedStrings.Str1340);
					rowIndex++;

					foreach (var strategyParam in strategy.Parameters.SyncGet(c => c.ToArray()))
					{
						var value = strategyParam.Value;

						if (value is TimeSpan)
							value = Format((TimeSpan)value);
						else if (value is decimal)
							value = MathHelper.Round((decimal)value, Decimals);

						worker
							.SetCell(0, rowIndex, strategyParam.Name)
							.SetCell(1, rowIndex, value);

						rowIndex++;
					}

					//rowIndex += 2;
					//worker.SetCell(0, rowIndex, "Комиссия по типам:");
					//rowIndex++;

					//foreach (var group in Strategy.CommissionManager.Rules.SyncGet(c => c.ToArray()).GroupBy(c => c.GetType().GetDisplayName()))
					//{
					//	var commission = group.Sum(r => r.Commission);

					//	if (commission == 0)
					//		continue;

					//	worker
					//		.SetCell(0, rowIndex, group.Key)
					//		.SetCell(1, rowIndex, commission);

					//	rowIndex++;
					//}

					var columnShift = 3;

					worker
						.SetCell(columnShift + 0, 0, LocalizedStrings.Str985)

						.SetCell(columnShift + 0, 1, LocalizedStrings.Str1192).SetStyle(columnShift + 0, typeof(long))
						.SetCell(columnShift + 1, 1, LocalizedStrings.Transaction).SetStyle(columnShift + 1, typeof(long))
						.SetCell(columnShift + 2, 1, LocalizedStrings.Time).SetStyle(columnShift + 2, "HH:mm:ss.fff")
						.SetCell(columnShift + 3, 1, LocalizedStrings.Price).SetStyle(columnShift + 3, typeof(decimal))
						.SetCell(columnShift + 4, 1, LocalizedStrings.Str1341).SetStyle(columnShift + 4, typeof(decimal))
						.SetCell(columnShift + 5, 1, LocalizedStrings.Volume).SetStyle(columnShift + 5, typeof(decimal))
						.SetCell(columnShift + 6, 1, LocalizedStrings.Str128)
						.SetCell(columnShift + 7, 1, LocalizedStrings.Str1190).SetStyle(columnShift + 7, typeof(long))
						.SetCell(columnShift + 8, 1, LocalizedStrings.Str163).SetStyle(columnShift + 8, typeof(decimal))
						.SetCell(columnShift + 9, 1, LocalizedStrings.Str135)
						.SetCell(columnShift + 10, 1, LocalizedStrings.Str1342).SetStyle(columnShift + 11, typeof(decimal))
						.SetCell(columnShift + 11, 1, LocalizedStrings.Str1343).SetStyle(columnShift + 12, typeof(decimal))
						.SetCell(columnShift + 12, 1, LocalizedStrings.Str1344).SetStyle(columnShift + 13, typeof(decimal))
						.SetCell(columnShift + 13, 1, LocalizedStrings.Str1345).SetStyle(columnShift + 14, typeof(decimal))
						.SetCell(columnShift + 14, 1, LocalizedStrings.Str862).SetStyle(columnShift + 15, typeof(decimal));

					worker
						.SetConditionalFormatting(columnShift + 10, ComparisonOperator.Less, "0", null, Colors.Red)
						.SetConditionalFormatting(columnShift + 11, ComparisonOperator.Less, "0", null, Colors.Red)
						.SetConditionalFormatting(columnShift + 12, ComparisonOperator.Less, "0", null, Colors.Red)
						.SetConditionalFormatting(columnShift + 13, ComparisonOperator.Less, "0", null, Colors.Red);

					var totalPnL = 0m;
					var position = 0m;

					var queues = new Dictionary<Security, PnLQueue>();

					rowIndex = 2;
					foreach (var trade in strategy.MyTrades.ToArray())
					{
						var info = strategy.PnLManager.ProcessMessage(trade.ToMessage());

						totalPnL += info.PnL;
						position += trade.GetPosition();

						var queue = queues.SafeAdd(trade.Trade.Security, key => new PnLQueue(key.ToSecurityId()));

						var localInfo = queue.Process(trade.ToMessage());

						worker
							.SetCell(columnShift + 0, rowIndex, trade.Trade.Id)
							.SetCell(columnShift + 1, rowIndex, trade.Order.TransactionId)
							.SetCell(columnShift + 2, rowIndex, Format(trade.Trade.Time))
							.SetCell(columnShift + 3, rowIndex, trade.Trade.Price)
							.SetCell(columnShift + 4, rowIndex, trade.Order.Price)
							.SetCell(columnShift + 5, rowIndex, trade.Trade.Volume)
							.SetCell(columnShift + 6, rowIndex, Format(trade.Order.Direction))
							.SetCell(columnShift + 7, rowIndex, trade.Order.Id)
							.SetCell(columnShift + 8, rowIndex, trade.Slippage)
							.SetCell(columnShift + 9, rowIndex, trade.Order.Comment)
							.SetCell(columnShift + 10, rowIndex, MathHelper.Round(info.PnL, Decimals))
							.SetCell(columnShift + 11, rowIndex, MathHelper.Round(localInfo.PnL, Decimals))
							.SetCell(columnShift + 12, rowIndex, MathHelper.Round(totalPnL, Decimals))
							.SetCell(columnShift + 13, rowIndex, MathHelper.Round(queue.RealizedPnL, Decimals))
							.SetCell(columnShift + 14, rowIndex, position);

						rowIndex++;
					}

					if (IncludeOrders)
					{
						columnShift += 17;

						worker
							.SetCell(columnShift + 0, 0, LocalizedStrings.Orders)

							.SetCell(columnShift + 0, 1, LocalizedStrings.Str1190).SetStyle(columnShift + 0, typeof(long))
							.SetCell(columnShift + 1, 1, LocalizedStrings.Transaction).SetStyle(columnShift + 1, typeof(long))
							.SetCell(columnShift + 2, 1, LocalizedStrings.Str128)
							.SetCell(columnShift + 3, 1, LocalizedStrings.Str1346).SetStyle(columnShift + 3, "HH:mm:ss.fff")
							.SetCell(columnShift + 4, 1, LocalizedStrings.Str1347).SetStyle(columnShift + 4, "HH:mm:ss.fff")
							.SetCell(columnShift + 5, 1, LocalizedStrings.Str1348)
							.SetCell(columnShift + 6, 1, LocalizedStrings.Price).SetStyle(columnShift + 6, typeof(decimal))
							.SetCell(columnShift + 7, 1, LocalizedStrings.Str1323).SetStyle(columnShift + 7, typeof(decimal))
							.SetCell(columnShift + 8, 1, LocalizedStrings.Str1324)
							.SetCell(columnShift + 9, 1, LocalizedStrings.State)
							.SetCell(columnShift + 10, 1, LocalizedStrings.Str1325).SetStyle(columnShift + 10, typeof(decimal))
							.SetCell(columnShift + 11, 1, LocalizedStrings.Volume).SetStyle(columnShift + 11, typeof(decimal))
							.SetCell(columnShift + 12, 1, LocalizedStrings.Type)
							.SetCell(columnShift + 13, 1, LocalizedStrings.Str1326)
							.SetCell(columnShift + 14, 1, LocalizedStrings.Str1327)
							.SetCell(columnShift + 15, 1, LocalizedStrings.Str135);

						worker
							.SetConditionalFormatting(columnShift + 9, ComparisonOperator.Equal, "\"{0}\"".Put(LocalizedStrings.Str1329), null, Colors.Green)
							.SetConditionalFormatting(columnShift + 9, ComparisonOperator.Equal, "\"{0}\"".Put(LocalizedStrings.Str238), null, Colors.Red);

						rowIndex = 2;
						foreach (var order in strategy.Orders.ToArray())
						{
							worker
								.SetCell(columnShift + 0, rowIndex, order.Id)
								.SetCell(columnShift + 1, rowIndex, order.TransactionId)
								.SetCell(columnShift + 2, rowIndex, Format(order.Direction))
								.SetCell(columnShift + 3, rowIndex, Format(order.Time))
								.SetCell(columnShift + 4, rowIndex, Format(order.LastChangeTime))
								.SetCell(columnShift + 5, rowIndex, Format(order.LastChangeTime - order.Time))
								.SetCell(columnShift + 6, rowIndex, order.Price)
								.SetCell(columnShift + 7, rowIndex, MathHelper.Round(order.GetAveragePrice(strategy.Connector), Decimals))
								.SetCell(columnShift + 8, rowIndex, Format(order.State))
								.SetCell(columnShift + 9, rowIndex, order.IsMatched() ? LocalizedStrings.Str1328 : (order.IsCanceled() ? LocalizedStrings.Str1329 : LocalizedStrings.Str238))
								.SetCell(columnShift + 10, rowIndex, order.Balance)
								.SetCell(columnShift + 11, rowIndex, order.Volume)
								.SetCell(columnShift + 12, rowIndex, Format(order.Type))
								.SetCell(columnShift + 13, rowIndex, Format(order.LatencyRegistration))
								.SetCell(columnShift + 14, rowIndex, Format(order.LatencyCancellation))
								.SetCell(columnShift + 15, rowIndex, order.Comment);

							rowIndex++;
						}

						var stopOrders = strategy.StopOrders.ToArray();

						if (stopOrders.Length > 0)
						{
							rowIndex += 2;

							worker
								.SetCell(columnShift + 0, rowIndex - 1, LocalizedStrings.Str1351)

								.SetCell(columnShift + 0, rowIndex, LocalizedStrings.Str1190).SetStyle(columnShift + 0, typeof(long))
								.SetCell(columnShift + 1, rowIndex, LocalizedStrings.Transaction).SetStyle(columnShift + 1, typeof(long))
								.SetCell(columnShift + 2, rowIndex, LocalizedStrings.Str128)
								.SetCell(columnShift + 3, rowIndex, LocalizedStrings.Time).SetStyle(columnShift + 3, "HH:mm:ss.fff")
								.SetCell(columnShift + 4, rowIndex, LocalizedStrings.Price).SetStyle(columnShift + 4, typeof(decimal))
								.SetCell(columnShift + 5, rowIndex, LocalizedStrings.Str1324)
								.SetCell(columnShift + 6, rowIndex, LocalizedStrings.State)
								.SetCell(columnShift + 7, rowIndex, LocalizedStrings.Volume).SetStyle(columnShift + 7, typeof(decimal))
								.SetCell(columnShift + 8, rowIndex, LocalizedStrings.Str1326)
								.SetCell(columnShift + 9, rowIndex, LocalizedStrings.Str1327)
								.SetCell(columnShift + 10, rowIndex, LocalizedStrings.Str1352).SetStyle(columnShift + 9, typeof(long));

							var stopParams = stopOrders[0].Condition.Parameters.Keys.ToArray();

							for (var i = 0; i < stopParams.Length; i++)
								worker.SetCell(columnShift + 11 + i, rowIndex, stopParams[i]);

							foreach (var order in stopOrders)
							{
								worker
									.SetCell(columnShift + 0, rowIndex, order.Id)
									.SetCell(columnShift + 1, rowIndex, order.TransactionId)
									.SetCell(columnShift + 2, rowIndex, Format(order.Direction))
									.SetCell(columnShift + 3, rowIndex, Format(order.Time))
									.SetCell(columnShift + 4, rowIndex, order.Price)
									.SetCell(columnShift + 5, rowIndex, Format(order.State))
									.SetCell(columnShift + 6, rowIndex, order.IsMatched() ? LocalizedStrings.Str1328 : (order.IsCanceled() ? LocalizedStrings.Str1329 : string.Empty))
									.SetCell(columnShift + 7, rowIndex, order.Volume)
									.SetCell(columnShift + 8, rowIndex, Format(order.LatencyRegistration))
									.SetCell(columnShift + 9, rowIndex, Format(order.LatencyCancellation))
									.SetCell(columnShift + 10, rowIndex, order.DerivedOrder != null ? (object)order.DerivedOrder.Id : string.Empty);

								for (var i = 0; i < stopParams.Length; i++)
									worker.SetCell(columnShift + 11 + i, rowIndex, order.Condition.Parameters[stopParams[i]] ?? string.Empty);

								rowIndex++;
							}
						}
					}
				}

				worker.Save(FileName, true);
			}
		}
Esempio n. 48
0
        public string IsExist(string argument)
        {
            AjaxResult ajaxResult = new AjaxResult();

            try
            {
                string dataID = Request.Form["DataID"].Trim();
                IDictionary<string, object> para = new Dictionary<string, object>();
                para.SafeAdd("ID", dataID);
                Operator operatorInfo =repository.FindOne<Operator>(para);
                if (operatorInfo != null)
                {
                    ajaxResult.PromptMsg = "该用户已经存在!";
                }

                ajaxResult.RetValue = string.Empty;
                ajaxResult.Result = DoResult.Success;


            }
            catch (Exception ex)
            {
                ajaxResult.Result = DoResult.Failed;
                ajaxResult.PromptMsg = "获取信息出错,请联系管理员!";
                log.Error(ex);
            }

            return JsonConvert.SerializeObject(ajaxResult);
        }
Esempio n. 49
0
        public string Save(string argument)
        {
            AjaxResult ajaxResult = new AjaxResult();
            string errorMsg = string.Empty;
            DoResult actionResult = DoResult.Failed;
            string actionMessage = string.Empty;
            string processInstID = Request.QueryString["processInstID"];
            ProcessForm processForm;
            try
            {
                Dictionary<string, object> formValues = JsonConvert.DeserializeObject<Dictionary<string, object>>(argument);

                string table = Request.Form["DataSource"];
                StringBuilder sbFields = new StringBuilder();
                StringBuilder sbValues = new StringBuilder();
                string cmdText = string.Empty;
                StringBuilder sbUpdateValues = new StringBuilder();

                IDictionary<string, object> parameters = new Dictionary<string, object>();
                parameters.SafeAdd("ProcessInstID", processInstID);
                processForm = engine.Persistence.Repository.FindOne<ProcessForm>(parameters);
                if (processForm != null)
                {
                    foreach (var item in formValues)
                    {
                        if (sbUpdateValues.Length > 0)
                            sbUpdateValues.Append(",");
                        sbUpdateValues.AppendFormat("{0} = :{0}", item.Key);
                    }
                    cmdText = string.Format("update {0} set {1} where ID ='{2}'", table, sbUpdateValues.ToString(), processForm.BizID);
                }
                else
                {
                    string bizID = IdGenerator.NewComb().ToString();
                    formValues.SafeAdd("ID", bizID);
                    foreach (var item in formValues)
                    {
                        sbFields.Append(item.Key).Append(",");
                        sbValues.Append(":").Append(item.Key).Append(",");
                    }

                    processForm = new ProcessForm()
                    {
                        ID = IdGenerator.NewComb().ToString(),
                        BizID = bizID,
                        BizTable = table,
                        CreateTime = DateTime.Now,
                        Creator = User.ID,
                        ProcessInstID = processInstID,
                        KeyWord = sbValues.ToString()
                    };
                    cmdText = string.Format("insert into {0}({1}) values({2})", table, sbFields.ToString().TrimEnd(','), sbValues.ToString().TrimEnd(','));
                }

                string workItemID = Request.QueryString["workItemID"];
                UnitOfWork.ExecuteWithTrans<WorkItem>(() =>
                {
                    engine.Persistence.Repository.ExecuteSql<WorkItem>(cmdText, formValues);
                    engine.Persistence.Repository.SaveOrUpdate(processForm);
                    engine.CompleteWorkItem(workItemID, formValues);
                });

                actionResult = DoResult.Success;
                //获取提示信息
                actionMessage = string.Format("启动工作流实例{0}工作项{1}", processForm.ProcessInstID, workItemID);

                //记录操作日志
                AddActionLog(processForm, actionResult, actionMessage);

                ajaxResult.Result = actionResult;
                ajaxResult.RetValue = processForm.BizID;
                ajaxResult.PromptMsg = actionMessage;
            }
            catch (Exception ex)
            {
                actionMessage = RemarkAttribute.GetEnumRemark(actionResult);
                log.Error(actionMessage, ex);
            }

            return JsonConvert.SerializeObject(ajaxResult);
        }
        /// <summary>
        /// Download securities info.
        /// </summary>
        /// <param name="securities">Securities.</param>
        public static void DownloadInfo(this IDictionary <Tuple <string, SecurityTypes>, SecurityMessage> securities)
        {
            if (securities.Count == 0)
            {
                return;
            }

            void MostAppropriated(IEnumerable <SecurityMessage> messages, Tuple <string, SecurityTypes> key, SecurityMessage destination)
            {
                SecurityMessage found = null;

                if (messages != null)
                {
                    messages = messages.Where(s =>
                    {
                        var name = key.Item1;

                        return(s.SecurityId.SecurityCode.CompareIgnoreCase(name) || s.ShortName.CompareIgnoreCase(name) || s.Name.CompareIgnoreCase(name));
                    });

                    switch (key.Item2)
                    {
                    case SecurityTypes.Future:
                        found = messages.OrderByDescending(m => m.ExpiryDate).FirstOrDefault();
                        break;

                    case SecurityTypes.Stock:
                        found = messages.OrderBy(m => m.SecurityId.BoardCode.StartsWithIgnoreCase("TQ") ? 0 : 1).FirstOrDefault();
                        break;
                    }
                }

                if (found == null)
                {
                    System.Diagnostics.Debug.WriteLine("{0}={1}", key.Item1, key.Item2);
                }
                else
                {
                    var native = destination.SecurityId.Native;
                    found.CopyTo(destination, false);
                    destination.SetNativeId(native);
                }
            }

            var client = new InstrumentProviderClient();

            if (securities.Count <= 10)
            {
                foreach (var pair in securities)
                {
                    var name = pair.Key.Item1;
                    var type = pair.Key.Item2;

                    var found = client.LookupSecurities(new SecurityLookupMessage
                    {
                        SecurityId = new SecurityId {
                            SecurityCode = name
                        },
                        SecurityType = type,
                    });

                    if (found.Count == 0)
                    {
                        found = client.LookupSecurities(new SecurityLookupMessage
                        {
                            SecurityType = type,
                            ShortName    = name
                        });

                        if (found.Count == 0)
                        {
                            found = client.LookupSecurities(new SecurityLookupMessage
                            {
                                SecurityType = type,
                                Name         = name
                            });
                        }
                    }

                    MostAppropriated(found, pair.Key, pair.Value);
                }
            }
            else
            {
                var byCode      = new Dictionary <Tuple <string, SecurityTypes?>, List <SecurityMessage> >();
                var byShortName = new Dictionary <Tuple <string, SecurityTypes?>, List <SecurityMessage> >();
                var byName      = new Dictionary <Tuple <string, SecurityTypes?>, List <SecurityMessage> >();

                foreach (var message in client.LookupSecurities(Extensions.LookupAllCriteriaMessage))
                {
                    var secType = message.SecurityType;

                    byCode.SafeAdd(Tuple.Create(message.SecurityId.SecurityCode.ToUpperInvariant(), secType)).Add(message);

                    if (!message.ShortName.IsEmpty())
                    {
                        byShortName.SafeAdd(Tuple.Create(message.ShortName.ToUpperInvariant(), secType)).Add(message);
                    }

                    if (!message.Name.IsEmpty())
                    {
                        byName.SafeAdd(Tuple.Create(message.Name.ToUpperInvariant(), secType)).Add(message);
                    }
                }