private static byte[] GetDataIn4BitFormat(TraderState state, QuotationCommand command, int?beginSequence = null, int?endSequence = null)
        {
            var    stringBuilder = new StringBuilder(CAPACITY);
            string seqenceStr    = string.Format("{0}{1}{2}", (beginSequence ?? command.Sequence), _SequenceSeparator, (endSequence ?? command.Sequence));

            stringBuilder.Append(seqenceStr);
            stringBuilder.Append(_StartSeparator);
            OverridedQuotation[] overridedQuotations = command.OverridedQs;
            if (overridedQuotations != null && overridedQuotations.Length > 0)
            {
                for (int i = 0; i < overridedQuotations.Length; i++)
                {
                    OverridedQuotation overridedQuotation = overridedQuotations[i];
                    if (!state.InstrumentsView.ContainsKey(overridedQuotation.InstrumentID))
                    {
                        continue;
                    }
                    if (overridedQuotation.QuotePolicyID != state.InstrumentsView[overridedQuotation.InstrumentID])
                    {
                        continue;
                    }
                    if (i != 0)
                    {
                        stringBuilder.Append(_OutterSeparator);
                    }
                    AppendQuotationParts(stringBuilder, overridedQuotation);
                }
            }
            stringBuilder.Append(_StartSeparator);
            return(Quotation4BitEncoder.Encode(stringBuilder.ToString()));
        }
Example #2
0
        public void Initialize(TraderState traderState)
        {
            Market   = traderState.Market;
            Strategy = new HoldUntilPriceDropsStrategy();

            _cryptoApi.TickerUpdated
            .Where(t => t.Market == traderState.Market)
            .Select(ticker => Observable.FromAsync(token => UpdatePrice(ticker)))
            .Concat()
            .Subscribe(unit => { }, OnCompleted);

            _cryptoApi.OrderUpdated
            .Where(o => o.Market == traderState.Market)
            .Select(order => Observable.FromAsync(token => UpdateOrder(order)))
            .Concat()
            .Subscribe();

            TraderState = traderState;

            Strategy.Settings = traderState.Settings ?? TraderSettings.Default;
            if (TraderState.Trades.Count == 0)
            {
                TraderState.Trades.Add(new Trade {
                    Status = TradeStatus.Empty
                });
            }
        }
        public byte[] GetPriceInBytes(Token token, TraderState state)
        {
            byte[] price;
            ConcurrentDictionary <long, byte[]> dict;

            if (!this._PriceCache.TryGetValue(token.AppType, out dict))
            {
                dict = new ConcurrentDictionary <long, byte[]>();
                this._PriceCache.TryAdd(token.AppType, dict);
            }
            if (dict.TryGetValue(state.SignMapping, out price))
            {
                return(price);
            }
            if (token.AppType == AppType.TradingConsole)
            {
                price = GetDataIn4BitFormat(state, this._QuotationCommand);
            }
            else
            {
                price = GetDataInGeneralFormat(token, state, this._QuotationCommand);
            }
            dict.TryAdd(state.SignMapping, price);
            return(price);
        }
        //Change Password
        public static XElement  UpdatePassword(Session session, string loginID, string oldPassword, string newPassword)
        {
            string message   = "";
            bool   isSucceed = false;

            try
            {
                string[][] recoverPasswordDatas = new string[][] { };
                isSucceed = UpdatePassword3(session, loginID, oldPassword, newPassword, recoverPasswordDatas, out message);
                if (isSucceed)
                {
                    Token       token      = SessionManager.Default.GetToken(session);
                    TraderState state      = SessionManager.Default.GetTradingConsoleState(session);
                    bool        isEmployee = state != null && state.IsEmployee;
                    Application.Default.TradingConsoleServer.SaveChangePasswordLog(token, isEmployee, "");
                }
                var dict = new Dictionary <string, string>()
                {
                    { "message", message }, { "isSucceed", isSucceed.ToPlainBitString() }
                };
                return(XmlResultHelper.NewResult(dict));
            }
            catch (System.Exception exception)
            {
                _Logger.Error(exception);
                return(XmlResultHelper.NewErrorResult());
            }
        }
 public static byte[] GetPriceInBytes(Token token, TraderState state, QuotationCommand command, int beginSequence, int endSequence)
 {
     if (token.AppType == AppType.TradingConsole)
     {
         return(GetDataIn4BitFormat(state, command, beginSequence, endSequence));
     }
     return(GetDataInGeneralFormat(token, state, command, beginSequence, endSequence));
 }
Example #6
0
 public static byte[] GetDataForCommand(Token token, TraderState state, Command command)
 {
     if (string.IsNullOrEmpty(state.QuotationFilterSign))
     {
         return(null);
     }
     return(GetDataBytesInUtf8Format(token, state, command));
 }
Example #7
0
        private PacketContent UpdateQuotePolicyDetailAction(SerializedInfo request, Token token)
        {
            var         args  = ArgumentsParser.Parse(request.Content);
            TraderState state = SessionManager.Default.GetTradingConsoleState(request.ClientInfo.Session);

            return(Application.Default.TradingConsoleServer.UpdateQuotePolicyDetail(args[0].ToGuid(), args[1].ToGuid(), state)
                   .ToPacketContent());
        }
Example #8
0
        private static byte[] GetDataBytesInUtf8Format(Token token, TraderState state, Command command)
        {
            var node = ConvertCommand(token, state, command);

            if (node == null)
            {
                return(null);
            }
            string xml = node.OuterXml;

            return(string.IsNullOrEmpty(xml) ? null : PacketConstants.ContentEncoding.GetBytes(xml));
        }
Example #9
0
 public void SaveLogForWeb(Session session, string logCode, string action, string transactionId)
 {
     try
     {
         Token       token      = SessionManager.Default.GetToken(session);
         TraderState state      = SessionManager.Default.GetTradingConsoleState(session);
         bool        isEmployee = state != null && state.IsEmployee;
         Application.Default.TradingConsoleServer.SaveLog(token, isEmployee, GetLocalIP(), logCode, DateTime.Now, action, new Guid(transactionId));
     }
     catch (System.Exception exception)
     {
         _Logger.Error(exception);
     }
 }
Example #10
0
 public XElement GetNewsContents(Session session, string newsID)
 {
     try
     {
         TraderState state = SessionManager.Default.GetTradingConsoleState(session);
         var         ds    = Application.Default.TradingConsoleServer.GetNewsContents(newsID, state.Language);
         return(XmlResultHelper.NewResult(ds.ToXml()));
     }
     catch (Exception exception)
     {
         _Logger.Error(exception);
         return(XmlResultHelper.NewErrorResult());
     }
 }
        public static DataSet Init(Session session, DataSet initData)
        {
            TraderState       state = SessionManager.Default.GetTradingConsoleState(session);
            DataRowCollection rows  = initData.Tables["Instrument"].Rows;
            List <Guid>       instrumentsFromBursa = new List <Guid>();

            foreach (DataRow instrumentRow in rows)
            {
                state.AddInstrumentIDToQuotePolicyMapping((Guid)instrumentRow["ID"], (Guid)instrumentRow["QuotePolicyID"]);
                if (IsFromBursa(instrumentRow))
                {
                    instrumentsFromBursa.Add((Guid)instrumentRow["ID"]);
                }
            }
            //Account
            rows = initData.Tables["Account"].Rows;
            Guid[] accountIDs = new Guid[rows.Count];
            int    i          = 0;

            foreach (DataRow accountRow in rows)
            {
                if (!state.Accounts.ContainsKey(accountRow["ID"]))
                {
                    state.Accounts.Add(accountRow["ID"], null);
                    state.AccountGroups[accountRow["GroupID"]] = null;
                }
                accountIDs[i++] = (Guid)accountRow["ID"];
            }
            SessionManager.Default.AddTradingConsoleState(session, state);
            int commandSequence = CommandManager.Default.LastSequence;

            SessionManager.Default.AddNextSequence(session, commandSequence);
            DataTable customerTable = initData.Tables["Customer"];

            state.IsEmployee = (bool)customerTable.Rows[0]["IsEmployee"];
            Token   token        = SessionManager.Default.GetToken(session);
            DataSet ds           = Merge(token, initData, accountIDs);
            bool    supportBursa = Convert.ToBoolean(ConfigurationManager.AppSettings["SupportBursa"]);

            if (supportBursa)
            {
                DateTime tradeDay = DateTime.Now.Date;
                AddDefaultTimeTableForBursa(ds, tradeDay);
            }
            AddBestLimitsForBursa(ds, instrumentsFromBursa);
            ds.SetInstrumentGuidMapping();
            ds.SetCommandSequence(commandSequence);
            state.CaculateQuotationFilterSign();
            return(ds);
        }
Example #12
0
 public DataSet GetInstruments(Session session, List <Guid> instrumentIDs)
 {
     try
     {
         TraderState state   = SessionManager.Default.GetTradingConsoleState(session);
         Token       token   = SessionManager.Default.GetToken(session);
         DataSet     dataSet = Application.Default.TradingConsoleServer.GetInstruments(token, instrumentIDs, state);
         return(dataSet);
     }
     catch (System.Exception exception)
     {
         _Logger.Error(exception);
         return(null);
     }
 }
Example #13
0
 public static XElement SaveLog(Session session, string logCode, DateTime timestamp, string action, Guid transactionId)
 {
     try
     {
         Token       token      = SessionManager.Default.GetToken(session);
         TraderState state      = SessionManager.Default.GetTradingConsoleState(session);
         bool        isEmployee = state == null ? false : state.IsEmployee;
         Application.Default.TradingConsoleServer.SaveLog(token, isEmployee, "", logCode, timestamp, action, transactionId);
         return(XmlResultHelper.NewResult(""));
     }
     catch (System.Exception exception)
     {
         AppDebug.LogEvent("TradingConsole.SaveLog:", exception.ToString(), System.Diagnostics.EventLogEntryType.Error);
         return(XmlResultHelper.NewErrorResult());
     }
 }
Example #14
0
 public XElement Quote2(Session session, string instrumentID, double buyQuoteLot, double sellQuoteLot, int tick)
 {
     try
     {
         Token       token      = SessionManager.Default.GetToken(session);
         TraderState state      = SessionManager.Default.GetTradingConsoleState(session);
         bool        isEmployee = state != null && state.IsEmployee;
         Application.Default.TradingConsoleServer.Quote2(token, isEmployee, Application.Default.StateServer, GetLocalIP(), instrumentID, buyQuoteLot, sellQuoteLot, tick);
         return(XmlResultHelper.NewResult(StringConstants.OkResult));
     }
     catch (System.Exception exception)
     {
         _Logger.Error(exception);
         return(XmlResultHelper.NewErrorResult());
     }
 }
Example #15
0
        private DataSet InternalGetQuotePolicyDetailsAndRefreshInstrumentsState(Session session, Guid customerID)
        {
            DataSet     dataSet = Application.Default.TradingConsoleServer.GetQuotePolicyDetails(customerID);
            TraderState state   = SessionManager.Default.GetTradingConsoleState(session);

            Application.Default.TradingConsoleServer.RefreshInstrumentsState2(dataSet, ref state, session.ToString());
            if (state == null)
            {
                return(dataSet);
            }
            TraderState traderState = new TraderState(state);

            traderState.CaculateQuotationFilterSign();
            SessionManager.Default.AddTradingConsoleState(session, traderState);
            return(dataSet);
        }
Example #16
0
        public static XElement GetTickByTickHistoryData(Session session, Guid instrumentId, DateTime from, DateTime to)
        {
            TraderState state  = SessionManager.Default.GetTradingConsoleState(session);
            XElement    result = null;

            if (state.InstrumentsView.ContainsKey(instrumentId))
            {
                Guid    quotePolicyId = state.InstrumentsView[instrumentId];
                DataSet ds            = Application.Default.TradingConsoleServer.GetTickByTickHistoryDatas2(instrumentId, quotePolicyId, from, to);
                result = XmlResultHelper.NewResult(ds.ToXml());
            }
            else
            {
                result = XmlResultHelper.NewResult(string.Empty);
            }
            return(result);
        }
 public static PacketContent Logout(Session session)
 {
     try
     {
         Token token = SessionManager.Default.GetToken(session);
         if (token != null)
         {
             TraderState state = SessionManager.Default.GetTradingConsoleState(session);
             Application.Default.TradingConsoleServer.SaveLogoutLog(token, "", state != null && state.IsEmployee);
             Application.Default.StateServer.Logout(token);
             Application.Default.SessionMonitor.Remove(session);
         }
     }
     catch (Exception ex)
     {
         _Logger.Error(ex);
     }
     return(XmlResultHelper.NewResult("").ToPacketContent());
 }
        private static byte[] GetDataInGeneralFormat(Token token, TraderState state, QuotationCommand command, int?beginSequence = null, int?endSequence = null)
        {
            XmlDocument xmlDoc   = new XmlDocument();
            XmlElement  commands = xmlDoc.CreateElement("Commands");

            xmlDoc.AppendChild(commands);
            XmlNode commandNode = command.ToXmlNode(token, state);

            if (commandNode == null)
            {
                return(null);
            }
            XmlNode commandNode2 = commands.OwnerDocument.ImportNode(commandNode, true);

            commands.AppendChild(commandNode2);
            commands.SetAttribute("FirstSequence", (beginSequence ?? command.Sequence).ToString());
            commands.SetAttribute("LastSequence", (endSequence ?? command.Sequence).ToString());
            return(PacketConstants.ContentEncoding.GetBytes(commands.OuterXml));
        }
Example #19
0
        private void WriteForCommand()
        {
            Token       token;
            TraderState state = SessionManager.Default.GetTokenAndState(this._Id, out token);

            if (state == null || token == null)
            {
                Write();
                return;
            }
            byte[] data = CommandTranslator.GetDataForCommand(token, state, this._CurrentCommand.Command);
            if (data == null)
            {
                Write();
                return;
            }
            this._CurrentPacket = SerializeManager.Default.SerializeCommand(data);
            this.BeginWrite(this._CurrentPacket, 0, this._CurrentPacket.Length);
        }
Example #20
0
 //Use in TickByTick Chart
 public DataSet GetTickByTickHistoryDatas(Session session, Guid instrumentId)
 {
     try
     {
         TraderState state = SessionManager.Default.GetTradingConsoleState(session);
         if (state.InstrumentsView.ContainsKey(instrumentId))
         {
             Guid    quotePolicyId = state.InstrumentsView[instrumentId];
             DataSet dataSet       = Application.Default.TradingConsoleServer.GetTickByTickHistoryDatas(instrumentId, quotePolicyId);
             return(dataSet);
         }
         _Logger.Warn(string.Format("Instrument {0} doesn't exists in TradingConsoleState", instrumentId));
         return(null);
     }
     catch (Exception e)
     {
         _Logger.Error(e);
         return(null);
     }
 }
Example #21
0
        private void WriteForQuotation()
        {
            Token       token;
            TraderState state = SessionManager.Default.GetTokenAndState(this._Id, out token);

            if (state == null || token == null)
            {
                Write();
                return;
            }
            this._QuotationQueue.Clear();
            this._QuotationQueue.Add(this._CurrentCommand.Quotation.QuotationCommand);
            while (this._Queue.Count > 0)
            {
                CommandForClient item = this._Queue.Peek();
                if (item.CommandType != DataType.Quotation)
                {
                    break;
                }
                item = this._Queue.Dequeue();
                this._QuotationQueue.Add(item.Quotation.QuotationCommand);
            }
            byte[] content;
            if (this._QuotationQueue.Count == 1)
            {
                content = this._CurrentCommand.Quotation.GetPriceInBytes(token, state);
            }
            else
            {
                QuotationCommand command = new QuotationCommand();
                command.Merge(this._QuotationQueue);
                content = QuotationTranslator.GetPriceInBytes(token, state, command, this._QuotationQueue[0].Sequence, this._QuotationQueue[this._QuotationQueue.Count - 1].Sequence);
            }
            if (content == null)
            {
                Write();
                return;
            }
            this._CurrentPacket = SerializeManager.Default.SerializePrice(content);
            this.BeginWrite(this._CurrentPacket, 0, this._CurrentPacket.Length);
        }
 //Activate
 public static bool UpdatePassword2(Session session, string loginID, string oldPassword, string newPassword, string[][] recoverPasswordDatas, out string message)
 {
     message = "";
     try
     {
         bool isSucceed = UpdatePassword3(session, loginID, oldPassword, newPassword, recoverPasswordDatas, out message);
         if (isSucceed)
         {
             Token       token      = SessionManager.Default.GetToken(session);
             TraderState state      = SessionManager.Default.GetTradingConsoleState(session);
             bool        isEmployee = state != null && state.IsEmployee;
             Application.Default.TradingConsoleServer.SaveActivateLog(token, isEmployee, "");
         }
         return(isSucceed);
     }
     catch (System.Exception exception)
     {
         _Logger.Error(exception);
         message = exception.ToString();
         return(false);
     }
 }
Example #23
0
        protected void Reset()
        {
            Market = "BTC-ETC";
            var pushManagerMock = new Mock <IPushManager>();

            Strategy.SetupGet(strategy => strategy.Settings).Returns(new TraderSettings {
                TradingBudget = 1000
            });
            CoinTrader = new CoinTrader(CryptoApiMock.Object)
            {
                Strategy     = Strategy.Object,
                IsInTestMode = true
            };
            var tickerSubject = new Subject <Ticker>();
            var orderSubject  = new Subject <CryptoOrder>();

            CryptoApiMock.SetupGet(c => c.TickerUpdated).Returns(tickerSubject);
            CryptoApiMock.SetupGet(c => c.OrderUpdated).Returns(orderSubject);
            TraderGrainMock.Setup(t => t.IsInitialized()).ReturnsAsync(true);
            HubNotifierMock.Setup(h => h.UpdateTrader(It.IsAny <TraderState>())).Returns(Task.CompletedTask);
            HubNotifierMock.Setup(h => h.UpdateTicker(It.IsAny <Ticker>())).Returns(Task.CompletedTask);
            TraderGrainMock.Setup(t => t.UpdateTrades(It.IsAny <List <Trade> >())).Returns(Task.CompletedTask);
            pushManagerMock.Setup(p => p.TriggerPush(It.IsAny <PushMessage>())).Returns(Task.CompletedTask);
            var traderState = new TraderState
            {
                Trades   = new List <Trade>(),
                Budget   = new Budget(),
                Settings = new TraderSettings {
                    TradingBudget = 1000
                }
            };

            CoinTrader.TraderState = traderState;
            TraderGrainMock.Setup(c => c.GetTraderData()).ReturnsAsync(traderState);
            OrleansClientMock.Setup(c => c.GetGrain <ITraderGrain>(It.IsAny <string>(), It.IsAny <string>()))
            .Returns(TraderGrainMock.Object);
        }
Example #24
0
        //no use
        public XmlNode GetParameterForJava(Session session, string companyCode, string version)
        {
            //Get xml
            try
            {
                string physicalPath = SettingManager.Default.PhysicPath + "\\" + companyCode + "\\" + version + "\\";
                string xmlPath      = physicalPath + "Setting\\Parameter.xml";
                var    doc          = new System.Xml.XmlDocument();
                doc.Load(xmlPath);
                xmlPath = physicalPath + "Setting\\Login.xml";
                var doc2 = new System.Xml.XmlDocument();
                doc2.Load(xmlPath);
                var node2 = doc2.GetElementsByTagName("Login")[0];

                var parameterXmlNode = doc.GetElementsByTagName("Parameter")[0];

                string      newsLanguage = node2.SelectNodes("NewsLanguage").Item(0).InnerXml;
                TraderState state        = SessionManager.Default.GetTradingConsoleState(session);
                if (state == null)
                {
                    state = new TraderState(session.ToString());
                }
                state.Language = newsLanguage.ToLower();
                SessionManager.Default.AddTradingConsoleState(session, state);
                XmlElement newChild = doc.CreateElement("NewsLanguage");
                newChild.InnerText = newsLanguage;
                parameterXmlNode.AppendChild(newChild);
                var node = doc.GetElementsByTagName("Parameters")[0];
                return(node);
            }
            catch (System.Exception ex)
            {
                _Logger.Error(ex);
                return(null);
            }
        }
        private InitializeData Parse(DataSet initData)
        {
            DataRowCollection rows        = initData.Tables["Instrument"].Rows;
            TraderState       traderState = SessionManager.Default.GetTradingConsoleState(_Request.ClientInfo.Session);

            Debug.Assert(traderState != null);
            traderState.Instruments.Clear();
            foreach (DataRow instrumentRow in rows)
            {
                traderState.AddInstrumentIDToQuotePolicyMapping((Guid)instrumentRow["ID"], (Guid)instrumentRow["QuotePolicyID"]);
            }
            traderState.CaculateQuotationFilterSign();

            rows = initData.Tables["Account"].Rows;
            Guid[] accountIds = new Guid[rows.Count];
            int    i          = 0;

            traderState.Accounts.Clear();
            foreach (DataRow accountRow in rows)
            {
                Guid accountId      = (Guid)accountRow["ID"];
                Guid accountGroupId = (Guid)accountRow["GroupID"];
                traderState.Accounts.Add(accountId, null);
                if (!traderState.AccountGroups.Contains(accountGroupId))
                {
                    traderState.AccountGroups.Add(accountGroupId, null);
                }
                accountIds[i++] = accountId;
            }
            InitializeData initializeData = new InitializeData();

            if (initData.Tables["OrganizationName"].Rows.Count > 0)
            {
                initializeData.OrganizationName = initData.Tables["OrganizationName"].Rows[0]["Name"] == DBNull.Value ? "" : (string)initData.Tables["OrganizationName"].Rows[0]["Name"];
            }
            else
            {
                initializeData.OrganizationName = "";
            }
            initializeData.LastSequence = CommandManager.Default.LastSequence;
            initializeData.SettingSet   = new SettingSet();
            initializeData.SettingSet.Initialize(initData);
            initializeData.TradingSet = new TradingSet();
            initializeData.TradingSet.Initialize(initData);
            if (initializeData.TradingSet.HasMessage)
            {
                DataSet dataSet = Trader.Server.CppTrader.DataMapping.Util.DataAccess.GetMessages(_Token);
                initializeData.TradingSet.InitializeMessages(dataSet);
            }

            AccountBalance[]  accountBalances   = null;
            AccountCurrency[] accountCurrencies = null;
            Contract[]        contracts         = null;

            XmlNode   accountsData = Application.Default.StateServer.GetAccountsForInit(accountIds);
            DataTable orderTable   = initData.Tables["Order"];

            orderTable.PrimaryKey = new DataColumn[] { orderTable.Columns["ID"] };

            Dictionary <Guid, Transaction> exectuedTransactions = new Dictionary <Guid, Transaction>();

            foreach (Transaction transaction in initializeData.TradingSet.Transactions)
            {
                if (transaction.Phase == Phase.Executed)
                {
                    exectuedTransactions.Add(transaction.Id, transaction);
                }
            }

            this.ParseAccountData(accountsData, orderTable.Rows, exectuedTransactions, out accountBalances, out accountCurrencies, out contracts);

            initializeData.TradingSet.AccountBalances   = accountBalances;
            initializeData.TradingSet.AccountCurrencies = accountCurrencies;
            initializeData.TradingSet.Contracts         = contracts;

            return(initializeData);
        }
Example #26
0
        private XmlNode GetParameterForJava(Session session, string companyCode, string version)
        {
            SessionManager.Default.AddVersion(session, version);
            string physicalPath = Path.Combine(LoginHelper.GetOrginazationDir(companyCode), version);

            //Get xml
            try
            {
                string xmlPath = Path.Combine(physicalPath, SettingManager.Default.GetJavaTraderSettings("parameter"));

                var parameterDocument = new XmlDocument();
                parameterDocument.Load(xmlPath);
                XmlNode parameterXmlNode = parameterDocument.GetElementsByTagName("Parameter")[0];

                xmlPath = Path.Combine(physicalPath, SettingManager.Default.GetJavaTraderSettings("login"));
                var loginDocument = new System.Xml.XmlDocument();
                loginDocument.Load(xmlPath);
                XmlNode     loginXmlNode = loginDocument.GetElementsByTagName("Login")[0];
                string      newsLanguage = loginXmlNode.SelectNodes("NewsLanguage").Item(0).InnerXml;
                TraderState state        = SessionManager.Default.GetTradingConsoleState(session) ??
                                           new TraderState(session.ToString());
                state.Language = newsLanguage.ToLower();
                SessionManager.Default.AddTradingConsoleState(session, state);
                XmlElement newChild = parameterDocument.CreateElement("NewsLanguage");
                newChild.InnerText = loginXmlNode.SelectNodes("NewsLanguage").Item(0).InnerXml;
                parameterXmlNode.AppendChild(newChild);
                string agreementContent      = "";
                string agreementFileFullPath = Path.Combine(physicalPath, SettingManager.Default.GetJavaTraderSettings("agreement"));
                if (File.Exists(agreementFileFullPath))
                {
                    var agreementDocument = new System.Xml.XmlDocument();
                    agreementDocument.Load(agreementFileFullPath);
                    var agreementXmlNode = agreementDocument.GetElementsByTagName("Agreement")[0];

                    string showAgreement = agreementXmlNode.SelectNodes("ShowAgreement").Item(0).InnerXml.Trim().ToLower();
                    if (showAgreement == "true")
                    {
                        agreementContent = agreementXmlNode.SelectNodes("Content").Item(0).InnerXml;
                    }
                }

                XmlElement agreementXmlNode2 = parameterDocument.CreateElement("Agreement");
                agreementXmlNode2.InnerText = agreementContent;
                parameterXmlNode.AppendChild(agreementXmlNode2);

                string columnSettings = Path.Combine(LoginHelper.GetOrginazationDir(companyCode), SettingManager.Default.GetJavaTraderSettings("column_setting"));
                if (File.Exists(columnSettings))
                {
                    var columnSettingsDocument = new XmlDocument();
                    columnSettingsDocument.Load(columnSettings);
                    XmlNode columnSettingsXmlNode = columnSettingsDocument.GetElementsByTagName("ColumnSettings")[0];
                    columnSettingsXmlNode = parameterDocument.ImportNode(columnSettingsXmlNode, true);
                    parameterXmlNode.AppendChild(columnSettingsXmlNode);
                }
                string integralitySettings = Path.Combine(LoginHelper.GetOrginazationDir(companyCode), SettingManager.Default.GetJavaTraderSettings("integrality_settings"));
                if (File.Exists(columnSettings))
                {
                    var integralitySettingsDocument = new XmlDocument();
                    integralitySettingsDocument.Load(integralitySettings);
                    var integralitySettingsXmlNode = integralitySettingsDocument.GetElementsByTagName("IntegralitySettings")[0];
                    integralitySettingsXmlNode = parameterDocument.ImportNode(integralitySettingsXmlNode, true);
                    parameterXmlNode.AppendChild(integralitySettingsXmlNode);
                }

                var node = parameterDocument.GetElementsByTagName("Parameters")[0];
                return(node);
            }
            catch (Exception ex)
            {
                _Logger.Error(ex);
                return(null);
            }
        }
Example #27
0
 public async Task UpdateTrader(TraderState trader)
 {
     await _hub.Clients.All.SendAsync("traderUpdate:" + trader.Market, trader);
 }
Example #28
0
        public XmlNode VerifyRefrence(Session session, State state, XmlNode xmlCommands, out bool changed)
        {
            changed = false;
            if (!(state is TraderState))
            {
                return(xmlCommands);
            }

            TraderState tradingConsoleState = (TraderState)state;

            List <Guid> instrumentIDs = new List <Guid>();

            try
            {
                foreach (XmlElement xmlElement in xmlCommands.ChildNodes)
                {
                    XmlElement tran         = null;
                    Guid       instrumentID = Guid.Empty;
                    switch (xmlElement.Name)
                    {
                    case "Execute2":
                        tran         = (XmlElement)xmlElement.GetElementsByTagName("Transaction")[0];
                        instrumentID = XmlConvert.ToGuid(tran.Attributes["InstrumentID"].Value);
                        if (!tradingConsoleState.InstrumentsView.ContainsKey(instrumentID))
                        {
                            instrumentIDs.Add(instrumentID);
                            changed = true;
                        }
                        break;

                    case "Place":
                        tran         = (XmlElement)xmlElement.GetElementsByTagName("Transaction")[0];
                        instrumentID = XmlConvert.ToGuid(tran.Attributes["InstrumentID"].Value);
                        if (!tradingConsoleState.Instruments.ContainsKey(instrumentID))
                        {
                            instrumentIDs.Add(instrumentID);
                            changed = true;
                        }
                        break;
                    }
                }

                if (instrumentIDs.Count > 0)
                {
                    DataSet     dataSet     = this.GetInstruments(session, instrumentIDs);
                    XmlDocument xmlDocument = xmlCommands.OwnerDocument;
                    XmlElement  parameters  = xmlDocument.CreateElement("Parameters");

                    System.Text.StringBuilder stringBuilder       = new System.Text.StringBuilder();
                    System.IO.StringWriter    instrumentWriter    = new System.IO.StringWriter(stringBuilder);
                    System.Xml.XmlWriter      instrumentXmlWriter = new XmlTextWriter(instrumentWriter);

                    System.Xml.Serialization.XmlSerializer xmlSerializer = new System.Xml.Serialization.XmlSerializer(typeof(DataSet));
                    xmlSerializer.Serialize(instrumentXmlWriter, dataSet);

                    parameters.SetAttribute("DataSet", stringBuilder.ToString());
                    xmlCommands.InsertBefore(parameters, xmlCommands.FirstChild);
                    changed = true;
                }
            }
            catch (System.Exception ex)
            {
                _Logger.Error(ex);
            }

            return(xmlCommands);
        }