Exemplo n.º 1
0
        /// <summary>
        /// Launches the IQ Feed Connector form and starts connection
        /// </summary>
        /// <param name="loginId">Login ID</param>
        /// <param name="password">Password</param>
        /// <param name="productId">Product ID provided by IQ for the give Login ID</param>
        /// <param name="productVersion">Prouct version of the IQ Feed Connector installed</param>
        /// <returns></returns>
        public bool Connect(string loginId, string password, string productId, string productVersion)
        {
            try
            {
                _loginId        = loginId;
                _password       = password;
                _productId      = productId;
                _productVersion = productVersion;

                if (LaunchForm())
                {
                    // Opens connections with the Form
                    CreateConnection();

                    return(true);
                }

                return(false);
            }
            catch (Exception exception)
            {
                _logger.Error(exception, _type.FullName, "LaunchForm");
                return(false);
            }
        }
Exemplo n.º 2
0
        /// <summary>
        /// Reads OEE MQ parameters from the Config file
        /// </summary>
        private void ReadOeeMqServerConfigSettings()
        {
            try
            {
                if (File.Exists(AppDomain.CurrentDomain.BaseDirectory + @"\Config\" + _oeeServerConfig))
                {
                    var doc = new XmlDocument();

                    // Read Specified configuration file
                    doc.Load(AppDomain.CurrentDomain.BaseDirectory + @"\Config\" + _oeeServerConfig);

                    // Read the specified Node values
                    XmlNodeList nodes = doc.SelectNodes(xpath: "RabbitMQ/*");
                    if (nodes != null)
                    {
                        // Clear any previous values
                        _oeeMqServerparameters.Clear();

                        foreach (XmlNode node in nodes)
                        {
                            // Add value to the dictionary
                            _oeeMqServerparameters.Add(node.Name, node.InnerText);
                        }
                    }
                    return;
                }
                _asyncClassLogger.Info("File not found: " + _oeeServerConfig, _type.FullName, "ReadMdeMqConfigSettings");
            }
            catch (Exception exception)
            {
                _asyncClassLogger.Error(exception, _type.FullName, "ReadMdeMqConfigSettings");
            }
        }
Exemplo n.º 3
0
        /// <summary>
        /// Creats market order object from incoming string message
        /// </summary>
        /// <param name="marketOrder">Market Order to add values to</param>
        /// <param name="message">Received message</param>
        /// <returns></returns>
        private bool ParseToMarketOrder(MarketOrder marketOrder, string[] message)
        {
            try
            {
                // Get Order ID
                marketOrder.OrderID = message[1];
                // Get Order Side
                marketOrder.OrderSide = message[2];
                // Get Order Size
                marketOrder.OrderSize = Convert.ToInt32(message[3]);
                // Get Order TIF value
                marketOrder.OrderTif = message[4];
                // Get Symbol
                marketOrder.Security = new Security()
                {
                    Symbol = message[5]
                };
                // Get Time Value
                marketOrder.OrderDateTime = DateTime.ParseExact(message[6], "M/d/yyyy h:mm:ss.fff tt",
                                                                CultureInfo.InvariantCulture);
                // Get Order Trigger Price
                marketOrder.TriggerPrice = Convert.ToDecimal(message[8]);
                // Get Slippage Value
                marketOrder.Slippage = Convert.ToDecimal(message[9]);
                // Get Order Remarks
                marketOrder.Remarks = message[10];

                return(true);
            }
            catch (Exception exception)
            {
                _asyncClassLogger.Error(exception, _type.FullName, "ParseToMarketOrder");
                return(false);
            }
        }
Exemplo n.º 4
0
        /// <summary>
        /// Starts custom strategy execution
        /// </summary>
        public void ExecuteStrategy()
        {
            try
            {
                // Verify Strategy Instance
                if (_tradeHubStrategy == null)
                {
                    //create DB strategy
                    Strategy strategy = new Strategy();
                    strategy.Name          = _strategyType.Name;
                    strategy.StartDateTime = DateTime.Now;

                    // Get new strategy instance
                    var strategyInstance = LoadCustomStrategy.CreateStrategyInstance(_strategyType, CtorArguments);

                    if (strategyInstance != null)
                    {
                        // Cast to TradeHubStrategy Instance
                        _tradeHubStrategy = strategyInstance as TradeHubStrategy;
                    }

                    if (_tradeHubStrategy == null)
                    {
                        if (_asyncClassLogger.IsInfoEnabled)
                        {
                            _asyncClassLogger.Info("Unable to initialize Custom Strategy: " + _strategyType.FullName, _type.FullName, "ExecuteStrategy");
                        }

                        // Skip execution of further actions
                        return;
                    }

                    // Set Strategy Name
                    _tradeHubStrategy.StrategyName = LoadCustomStrategy.GetCustomClassSummary(_strategyType);

                    // Register Events
                    _tradeHubStrategy.OnStrategyStatusChanged += OnStrategyStatusChanged;
                    _tradeHubStrategy.OnNewExecutionReceived  += OnNewExecutionReceived;
                }

                if (_asyncClassLogger.IsInfoEnabled)
                {
                    _asyncClassLogger.Info("Executing user strategy: " + _strategyType.FullName, _type.FullName, "ExecuteStrategy");
                }

                //Overriding if running on simulated exchange
                ManageBackTestingStrategy();

                // Start Executing the strategy
                _tradeHubStrategy.Run();
            }
            catch (Exception exception)
            {
                _asyncClassLogger.Error(exception, _type.FullName, "ExecuteStrategy");
            }
        }
Exemplo n.º 5
0
        /// <summary>
        /// Argument Constructor
        /// </summary>
        /// <param name="eventHandler">Event handler which will receive requested data</param>
        /// <param name="localPersistance">Indicates whether the data to be saved locally on initial request</param>
        public DataHandler(IEventHandler <MarketDataObject>[] eventHandler, bool localPersistance = false)
        {
            try
            {
                _classLogger = new AsyncClassLogger("SimulatedDataHandler");
                // Set logging level
                _classLogger.SetLoggingLevel();
                //set logging path
                _classLogger.LogDirectory(DirectoryStructure.CLIENT_LOGS_LOCATION);

                _persistanceDataCount = 0;
                _localPersistance     = localPersistance;
                _localPersistanceData = new SortedDictionary <int, MarketDataObject>();
                _tasksCollection      = new ConcurrentBag <Task>();

                _fetchMarketData = new FetchData(new ReadMarketData(_classLogger), _classLogger);

                // Initialize Lists
                BarSubscriptionList  = new List <string>();
                TickSubscriptionList = new List <string>();

                _fetchMarketData.InitializeDisruptor(eventHandler);
                _fetchMarketData.HistoricalDataFired += HistoricDataArrived;
            }
            catch (Exception exception)
            {
                _classLogger.Error(exception, _type.FullName, "DataHandler");
            }
        }
 public void onRequestFailed(string sRequestID, string sError)
 {
     if (_requestId.Equals(sRequestID))
     {
         _response = null;
         if (string.IsNullOrEmpty(sError))
         {
             _logger.Error("There is no more data", _type.FullName, "onRequestFailed");
         }
         else
         {
             _logger.Error("Request failed: " + sError, _type.FullName, "onRequestFailed");
         }
         _syncResponseEvent.Set();
     }
 }
Exemplo n.º 7
0
        /// <summary>
        /// Default Constructor
        /// </summary>
        public DataHandler()
        {
            try
            {
                _classLogger = new AsyncClassLogger("DataHandler");
                _classLogger.SetLoggingLevel();
                //set logging path
                string path = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData) +
                              "\\TradeHub Logs\\Client";
                _classLogger.LogDirectory(path);

                _fetchMarketData = new FetchData(new ReadMarketData(_classLogger), _classLogger);

                // Initialize Lists
                BarSubscriptionList  = new List <string>();
                TickSubscriptionList = new List <string>();

                _fetchMarketData.InitializeDisruptor(new IEventHandler <MarketDataObject>[] { this });
                _fetchMarketData.HistoricalDataFired += HistoricDataArrived;
            }
            catch (Exception exception)
            {
                _classLogger.Error(exception, _type.FullName, "DataHandler");
            }
        }
Exemplo n.º 8
0
        /// <summary>
        /// Loads user strategy and extracts constructor parameters
        /// </summary>
        private void LoadUserStrategy(LoadStrategy loadStrategy)
        {
            try
            {
                if (_asyncClassLogger.IsInfoEnabled)
                {
                    _asyncClassLogger.Info("Trying to load user defined strategy from: " +
                                           loadStrategy.StrategyAssembly.FullName.Substring(0, loadStrategy.StrategyAssembly.FullName.IndexOf(",", System.StringComparison.Ordinal)),
                                           _type.FullName, "LoadUserStrategy");
                }

                var strategyDetails = LoadCustomStrategy.GetConstructorDetails(loadStrategy.StrategyAssembly);

                if (strategyDetails != null)
                {
                    if (_asyncClassLogger.IsInfoEnabled)
                    {
                        _asyncClassLogger.Info("Successfully loaded custom strategy: " + strategyDetails.Item1.Name, _type.Name, "LoadUserStrategy");
                    }

                    // Create new Strategy Constructor Info object
                    StrategyConstructorInfo strategyConstructorInfo = new StrategyConstructorInfo(
                        strategyDetails.Item2, strategyDetails.Item1);

                    // Publish Event to Notify Listener.
                    EventSystem.Publish <StrategyConstructorInfo>(strategyConstructorInfo);
                }
            }
            catch (Exception exception)
            {
                _asyncClassLogger.Error(exception, _type.FullName, "LoadUserStrategy");
            }
        }
        /// <summary>
        /// Connects/Starts a client
        /// </summary>
        public bool Start()
        {
            try
            {
                // Read account credentials
                ReadConnectionParameters();

                if (_connectionParameters == null)
                {
                    _logger.Info("Connection Parameters unavailable", _type.FullName, "Start");

                    return(false);
                }

                // Send credential details to connection form
                _connectionForm.Connect(_connectionParameters.LoginId, _connectionParameters.Password,
                                        _connectionParameters.ProductId, _connectionParameters.ProductVersion);

                Thread.Sleep(4000);

                // Open connection with Data feed
                _barData.OpenBarDataConnection();
                _historicalData.OpenHistoricalDataConnection();
                _levelOneData.OpenLevelOneDataConnection();

                return(true);
            }
            catch (Exception exception)
            {
                _logger.Error(exception, _type.FullName, "Start");
            }
            return(false);
        }
        /// <summary>
        /// Connects/Starts a client
        /// </summary>
        public bool Start()
        {
            try
            {
                // Read account credentials
                ReadConnectionParameters();

                if (_connectionParameters == null)
                {
                    Logger.Info("Connection Parameters unavailable", _type.FullName, "Start");

                    return(false);
                }

                // Opens a new FXCM session
                OpenSession();

                return(true);
            }
            catch (Exception exception)
            {
                _logger.Error(exception, _type.FullName, "Start");
            }
            return(false);
        }
Exemplo n.º 11
0
        /// <summary>
        /// Called when new Tick message is received and processed by Disruptor
        /// </summary>
        /// <param name="message"></param>
        private void OnTickDataReceived(string[] message)
        {
            try
            {
                Tick tick = new Tick();

                // Parse incoming message to Tick
                if (ParseToTick(tick, message))
                {
                    // Notify Listeners
                    TickArrived(tick);
                }
            }
            catch (Exception exception)
            {
                _asyncClassLogger.Error(exception, _type.FullName, "OnTickDataReceived");
            }
        }
Exemplo n.º 12
0
        /// <summary>
        /// Constructor:
        /// Loads Setting From Xml File
        /// </summary>
        /// <param name="readMarketData"></param>
        /// <param name="classLogger"> </param>
        public FetchData(ReadMarketData readMarketData, AsyncClassLogger classLogger)
        {
            try
            {
                _classLogger    = classLogger;
                _readMarketData = readMarketData;

                //Reading Settings From Xml File
                string    path = "MarketDataConfiguration\\MarketDataController.xml";
                XDocument doc;
                if (File.Exists(path))
                {
                    _classLogger.Info("1st", _type.FullName, "FetchData");
                    doc = XDocument.Load("MarketDataConfiguration\\MarketDataController.xml");
                }
                else
                {
                    _classLogger.Info("2nd", _type.FullName, "FetchData");
                    doc = XDocument.Load("..\\Strategy Runner\\MarketDataConfiguration\\MarketDataController.xml");
                }
                var startDate = doc.Descendants("StartDate");
                foreach (var xElement in startDate)
                {
                    string[] start = xElement.Value.Split(',');
                    _startDate = new DateTime(Convert.ToInt32(start[0]), Convert.ToInt32(start[1]), Convert.ToInt32(start[2]));
                    if (_classLogger.IsInfoEnabled)
                    {
                        _classLogger.Info("StartDate:" + _startDate.ToString(CultureInfo.InvariantCulture), _type.FullName, "FetchData");
                    }
                }

                var endDate = doc.Descendants("EndDate");
                foreach (var xElement in endDate)
                {
                    string[] end = xElement.Value.Split(',');
                    _endDate = new DateTime(Convert.ToInt32(end[0]), Convert.ToInt32(end[1]), Convert.ToInt32(end[2]));
                    if (_classLogger.IsInfoEnabled)
                    {
                        _classLogger.Info("EndDate:" + _endDate.ToString(CultureInfo.InvariantCulture), _type.FullName, "FetchData");
                    }
                }

                var provider = doc.Descendants("Provider");
                foreach (var xElement in provider)
                {
                    _providerName = xElement.Value;
                    if (_classLogger.IsInfoEnabled)
                    {
                        _classLogger.Info("ProviderName:" + _providerName.ToString(CultureInfo.InvariantCulture), _type.FullName, "FetchData");
                    }
                }
            }
            catch (Exception exception)
            {
                _classLogger.Error(exception, _type.FullName, "FetchData");
            }
        }
        /// <summary>
        /// Opens a connection to the IQFeed Connector
        /// </summary>
        public void OpenHistoricalDataConnection()
        {
            try
            {
                // Initialize IQFeed COM object
                _historyLookupComObject = new DTNIQFeedCOMLib.HistoryLookup4();

                // Hook necessary IQ Feed events
                RegisterEvents();

                // Use request to initiate the connection and set our IQFeed protocol here.
                _historyLookupComObject.SetProtocol("5.2");
            }
            catch (Exception exception)
            {
                _logger.Error(exception, _type.FullName, "OpenBarDataConnection");
            }
        }
        /// <summary>
        /// Start Strategy Optimization
        /// </summary>
        /// <param name="optimizationParameters">Contains info for the parameters to be used for optimization</param>
        private void StartOptimization(OptimizeStrategyBruteForce optimizationParameters)
        {
            try
            {
                if (_asyncClassLogger.IsInfoEnabled)
                {
                    _asyncClassLogger.Info("Getting argument combinations", _type.FullName, "StartOptimization");
                }

                // Clear all previous information
                _strategiesCollection.Clear();

                // Save Parameter Details
                _parmatersDetails = optimizationParameters.ParmatersDetails;

                // Get all ctor arguments to be used for optimization
                CreateCtorCombinations(optimizationParameters.CtorArgs, optimizationParameters.ConditionalParameters);

                // Initialize Stratgey for each set of arguments
                foreach (object[] ctorArgument in _ctorArguments)
                {
                    // Get new Key.
                    string key = ApplicationIdGenerator.NextId();

                    // Save Strategy details in new Strategy Executor object
                    StrategyExecutor strategyExecutor = new StrategyExecutor(key, optimizationParameters.StrategyType, ctorArgument);

                    // Register Event
                    strategyExecutor.StatusChanged += OnStrategyExecutorStatusChanged;

                    // Add to local map
                    _strategiesCollection.AddOrUpdate(key, strategyExecutor, (ky, value) => strategyExecutor);
                }

                // Start executing each instance
                StartStrategyExecution();
            }
            catch (Exception exception)
            {
                _asyncClassLogger.Error(exception, _type.FullName, "StartOptimization");
            }
        }
Exemplo n.º 15
0
        /// <summary>
        /// Handles the new incoming Server Heartbeat
        /// </summary>
        /// <param name="serverHeartbeatInterval">Time Interval after which MDE will send response Heartbeat</param>
        public void Update(int serverHeartbeatInterval)
        {
            try
            {
                // Stop Timer for processing
                StopValidationTimer();

                if (_asyncClassLogger.IsDebugEnabled)
                {
                    _asyncClassLogger.Debug("Server Heartbeat received", _type.FullName, "Update");
                }

                // Start Timer after processing
                StartValidationTimer(serverHeartbeatInterval);
            }
            catch (Exception exception)
            {
                _asyncClassLogger.Error(exception, _type.FullName, "Update");
            }
        }
Exemplo n.º 16
0
        /// <summary>
        /// Start Position Engine Service
        /// </summary>
        public bool StartService()
        {
            try
            {
                if (_isConnected)
                {
                    if (_asyncClassLogger.IsInfoEnabled)
                    {
                        _asyncClassLogger.Info("Position engine service already running.", _type.FullName, "StartService");
                    }

                    return(true);
                }

                // Start PE-Client
                _positionEngineClient.Initialize();

                if (_asyncClassLogger.IsInfoEnabled)
                {
                    _asyncClassLogger.Info("Position engine service started.", _type.FullName, "StartService");
                }

                return(true);
            }
            catch (Exception exception)
            {
                _asyncClassLogger.Error(exception, _type.FullName, "StartService");
                return(false);
            }
        }
Exemplo n.º 17
0
        /// <summary>
        /// Connects/Starts a client
        /// </summary>
        public bool Start()
        {
            try
            {
                // Read account credentials
                _credentials = CredentialReader.ReadCredentials("RediParams.xml");

                if (!CheckParameterValidity())
                {
                    return(false);
                }

                // Create TCP Request
                _rediSocketConnection = new SocketCommunication(new Queue(), _credentials.Username,
                                                                _credentials.Password, _credentials.IpAddress, Convert.ToInt32(_credentials.Port), _logger);

                _rediSocketConnection.SendMessage += DataRecieved;
                _rediSocketConnection.ErrorInTcp  += new SocketCommunication.ConnectionError(RediSocketConnectionErrorInTcp);

                _isConnected = true;
                _rediSocketConnection.Connect();

                if (_logger.IsInfoEnabled)
                {
                    _logger.Info("Session is available.", _type.FullName, "Start");
                }

                if (LogonArrived != null)
                {
                    LogonArrived(_marketDataProviderName);
                }

                return(true);
            }
            catch (Exception exception)
            {
                _logger.Error(exception, _type.FullName, "Start");
            }
            return(false);
        }
Exemplo n.º 18
0
        /// <summary>
        /// Subscribes Tick data for the given symbol
        /// </summary>
        /// <param name="subscribe">Contains info for the symbol to be subscribed</param>
        public void SubscribeSymbol(Subscribe subscribe)
        {
            try
            {
                if (_classLogger.IsInfoEnabled)
                {
                    _classLogger.Info("New subscription request received " + subscribe, _type.FullName, "SubscribeSymbol");
                }

                // Add new symbol to the Tick list
                if (!TickSubscriptionList.Contains(subscribe.Security.Symbol))
                {
                    TickSubscriptionList.Add(subscribe.Security.Symbol);
                }

                // Fetch data if its not already fetched for bars
                if (!BarSubscriptionList.Contains(subscribe.Security.Symbol))
                {
                    FetchData(subscribe);
                }
            }
            catch (Exception exception)
            {
                _classLogger.Error(exception, _type.FullName, "SubscribeSymbol");
            }
        }
Exemplo n.º 19
0
 /// <summary>
 /// Parse String into bar
 /// </summary>
 /// <param name="line"></param>
 /// <param name="id"> </param>
 /// <returns></returns>
 private Bar ParseToBar(string line, string id)
 {
     try
     {
         string[] feilds = line.Split(',');
         Bar      newBar = new Bar(new Security {
             Symbol = feilds[5]
         }, Common.Core.Constants.MarketDataProvider.SimulatedExchange, id);
         newBar.Close    = Convert.ToDecimal(feilds[0]);
         newBar.Open     = Convert.ToDecimal(feilds[1]);
         newBar.High     = Convert.ToDecimal(feilds[2]);
         newBar.Low      = Convert.ToDecimal(feilds[3]);
         newBar.Volume   = (long)Convert.ToDouble(feilds[4]);
         newBar.DateTime = DateTime.ParseExact(feilds[6], "M/d/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);
         return(newBar);
     }
     catch (Exception exception)
     {
         _classLogger.Error(exception, _type.FullName, "ParseToBar");
         return(null);
     }
 }
Exemplo n.º 20
0
        /// <summary>
        /// Subscribe symbols price updates
        /// </summary>
        /// <param name="symbol"></param>
        public void Subscribe(string symbol)
        {
            if (_subscriptionList.Count == 0)
            {
                O2GTableManagerStatus managerStatus = _tableManager.getStatus();
                while (managerStatus == O2GTableManagerStatus.TablesLoading)
                {
                    Thread.Sleep(50);
                    managerStatus = _tableManager.getStatus();
                }

                if (managerStatus == O2GTableManagerStatus.TablesLoadFailed)
                {
                    _logger.Error("Table loading failed", _type.FullName, "Subscribe");

                    return;
                }

                SubscribeEvents(_tableManager);
            }

            _subscriptionList.Add(symbol);
        }
Exemplo n.º 21
0
        /// <summary>
        /// Connects to Server.
        /// </summary>
        public void Connect()
        {
            _stopping = false;
            if (_client != null)
            {
                throw new Exception("Connection already open!");
            }
            try
            {
                if (InitializeTcpClient())
                {
                    var loginMessage = LogonMessage();
                    StartReaderThread();
                    _networkStream.Write(loginMessage, 0, loginMessage.Length);

                    _streamWriter.Flush();
                }
            }
            catch (Exception exception)
            {
                _asyncClassLogger.Error(exception, _type.FullName, "Connect");
            }
        }
Exemplo n.º 22
0
        /// <summary>
        /// Creates a FIX4.4 OrderCancelRequest message for Fxcm
        /// </summary>
        /// <param name="order"></param>
        /// <returns></returns>
        public QuickFix.FIX44.OrderCancelRequest OrderCancelRequest(Order order)
        {
            char orderSide = default(char);

            if (order.OrderSide == Constants.OrderSide.BUY)
            {
                orderSide = Side.BUY;
            }
            else if (order.OrderSide == Constants.OrderSide.SELL)
            {
                orderSide = Side.SELL;
            }

            if (orderSide.Equals(default(char)))
            {
                _logger.Error("Invalid Order Side", _type.FullName, "OrderCancelRequest");
                return(null);
            }

            QuickFix.FIX44.OrderCancelRequest orderCancelRequest = new QuickFix.FIX44.OrderCancelRequest();

            QuickFix.Fields.OrderID orderId = new QuickFix.Fields.OrderID(order.BrokerOrderID);
            orderCancelRequest.SetField(orderId);

            QuickFix.Fields.OrigClOrdID origClOrdId = new QuickFix.Fields.OrigClOrdID(order.OrderID);
            orderCancelRequest.SetField(origClOrdId);

            QuickFix.Fields.ClOrdID clOrdId = new QuickFix.Fields.ClOrdID(DateTime.Now.ToString(("yyMMddHmsfff")));
            orderCancelRequest.SetField(clOrdId);

            var account = new QuickFix.Fields.Account(_account);

            orderCancelRequest.SetField(account);

            QuickFix.Fields.Symbol symbol = new QuickFix.Fields.Symbol(order.Security.Symbol);
            orderCancelRequest.SetField(symbol);


            QuickFix.Fields.Side side = new QuickFix.Fields.Side(orderSide);
            orderCancelRequest.SetField(side);

            QuickFix.Fields.TransactTime transactTime = new QuickFix.Fields.TransactTime(order.OrderDateTime);
            orderCancelRequest.SetField(transactTime);

            QuickFix.Fields.Product product = new QuickFix.Fields.Product(FixCommon.Constants.Product.Currency);
            orderCancelRequest.SetField(product);

            return(orderCancelRequest);
        }
Exemplo n.º 23
0
        /// <summary>
        /// Subscribes Tick data for the given symbol
        /// </summary>
        /// <param name="subscribe">Contains info for the symbol to be subscribed</param>
        public void SubscribeSymbol(Subscribe subscribe)
        {
            try
            {
                if (_classLogger.IsInfoEnabled)
                {
                    _classLogger.Info("New subscription request received " + subscribe, _type.FullName,
                                      "SubscribeSymbol");
                }

                // Add new symbol to the Tick list
                if (!TickSubscriptionList.Contains(subscribe.Security.Symbol))
                {
                    TickSubscriptionList.Add(subscribe.Security.Symbol);
                }

                // Fetch data if its not already fetched for bars
                if (!BarSubscriptionList.Contains(subscribe.Security.Symbol))
                {
                    // Use locally saved data
                    if (_persistanceDataCount > 0)
                    {
                        var task = Task.Factory.StartNew(UseLocalData);

                        _tasksCollection.Add(task);
                    }
                    // Fetch fresh data
                    else
                    {
                        FetchData(subscribe);
                    }
                }
            }
            catch (Exception exception)
            {
                _classLogger.Error(exception, _type.FullName, "SubscribeSymbol");
            }
        }
Exemplo n.º 24
0
        /// <summary>
        /// Argument Constructor
        /// </summary>
        /// <param name="classLogger"></param>
        public ReadMarketData(AsyncClassLogger classLogger)
        {
            try
            {
                _classLogger = classLogger;
                // The folder for the roaming current user
                string folder = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);

                // Combine the base folder with your specific folder....
                _specificFolder = Path.Combine(folder, "DataDownloader");

                // Check if folder exists and if not, create it
                if (!Directory.Exists(_specificFolder))
                {
                    Directory.CreateDirectory(_specificFolder);
                }
            }
            catch (Exception exception)
            {
                _classLogger.Error(exception, _type.FullName, "ReadMarketData");
            }
        }
        /// <summary>
        /// Execute Strategy iteration to calculate Fitness
        /// </summary>
        /// <returns>Return Strategy's Fitness for current execution</returns>
        public double ExecuteStrategy(double[] values)
        {
            try
            {
                _manualReset = new ManualResetEvent(false);

                //convert all parameters to object.
                object[] array = new object[values.Length];
                for (int i = 0; i < values.Length; i++)
                {
                    array[i] = values[i];
                }
                // Update Strategy Parameters
                _tradeHubStrategy.SetParameters(array);

                // Reset Statistics for current iteration
                _statistics.ResetAllValues();
                _orderExecutor.Clear();

                // Start Strategy Execution
                _tradeHubStrategy.Run();

                // Wait for the strategy to execute
                _manualReset.WaitOne();

                // Clear subscription maps
                _dataHandler.ClearMaps();
                _tradeHubStrategy.ClearOrderMap();

                // return current iterations risk
                return(-1 * (double)_tradeHubStrategy.GetObjectiveFunctionValue());
            }
            catch (Exception exception)
            {
                _logger.Error(exception, _type.FullName, "ExecuteStrategy");
                return(default(double));
            }
        }
Exemplo n.º 26
0
        /// <summary>
        /// Starts Order Execution Service
        /// </summary>
        public bool StartService()
        {
            try
            {
                if (_isConnected)
                {
                    if (_asyncClassLogger.IsInfoEnabled)
                    {
                        _asyncClassLogger.Info("Order execution service already running.", _type.FullName, "StartService");
                    }

                    return(true);
                }

                // Start OEE-Client
                _executionEngineClient.Start();

                if (_asyncClassLogger.IsInfoEnabled)
                {
                    _asyncClassLogger.Info("Order Execution service started.", _type.FullName, "StartService");
                }

                return(true);
            }
            catch (Exception exception)
            {
                _asyncClassLogger.Error(exception, _type.FullName, "StartService");
                return(false);
            }
        }
 /// <summary>
 /// Timer expired
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 private void TimerExpired(object sender, ElapsedEventArgs e)
 {
     foreach (var order in _ordersMap.Values.ToArray())
     {
         try
         {
             var orderStatus = _tradierManager.GetOrderStatus(order.BrokerOrderID);
             if (_logger.IsInfoEnabled)
             {
                 _logger.Info(orderStatus.order.ToString(), _type.FullName, "TimerExpired");
             }
             if (orderStatus.order.status.Equals("filled", StringComparison.InvariantCultureIgnoreCase))
             {
                 Fill fill = new Fill(new Security()
                 {
                     Symbol = order.Security.Symbol
                 },
                                      order.OrderExecutionProvider, order.OrderID);
                 fill.ExecutionId           = Guid.NewGuid().ToString();
                 fill.ExecutionType         = ExecutionType.Fill;
                 fill.LeavesQuantity        = orderStatus.order.remaining_quantity;
                 fill.CummalativeQuantity   = orderStatus.order.exec_quantity;
                 fill.ExecutionSize         = orderStatus.order.last_fill_quantity;
                 fill.AverageExecutionPrice = orderStatus.order.avg_fill_price;
                 fill.ExecutionPrice        = orderStatus.order.last_fill_price;
                 DateTime executionDateTime;
                 if (!DateTime.TryParse(orderStatus.order.transaction_date, out executionDateTime))
                 {
                     executionDateTime = DateTime.UtcNow;
                 }
                 fill.ExecutionDateTime = executionDateTime;
                 fill.ExecutionSide     = order.OrderSide;
                 order.OrderStatus      = OrderStatus.EXECUTED;
                 Order     orderClone = (Order)order.Clone();
                 Execution execution  = new Execution(fill, orderClone);
                 execution.OrderExecutionProvider = _provider;
                 if (ExecutionArrived != null)
                 {
                     ExecutionArrived(execution);
                 }
                 Order deleteOrder;
                 //remove order from the map
                 _ordersMap.TryRemove(order.OrderID, out deleteOrder);
             }
             else if (orderStatus.order.status.Equals("partially_filled", StringComparison.InvariantCultureIgnoreCase) && order.OrderStatus != OrderStatus.PARTIALLY_EXECUTED)
             {
                 Fill fill = new Fill(new Security()
                 {
                     Symbol = order.Security.Symbol
                 },
                                      order.OrderExecutionProvider, order.OrderID);
                 fill.ExecutionId           = Guid.NewGuid().ToString();
                 fill.ExecutionType         = ExecutionType.Partial;
                 fill.LeavesQuantity        = orderStatus.order.remaining_quantity;
                 fill.CummalativeQuantity   = orderStatus.order.exec_quantity;
                 fill.ExecutionSize         = orderStatus.order.last_fill_quantity;
                 fill.AverageExecutionPrice = orderStatus.order.avg_fill_price;
                 fill.ExecutionPrice        = orderStatus.order.last_fill_price;
                 DateTime executionDateTime;
                 if (!DateTime.TryParse(orderStatus.order.transaction_date, out executionDateTime))
                 {
                     executionDateTime = DateTime.UtcNow;
                 }
                 fill.ExecutionDateTime = executionDateTime;
                 fill.ExecutionSide     = order.OrderSide;
                 order.OrderStatus      = OrderStatus.PARTIALLY_EXECUTED;
                 Order     orderClone = (Order)order.Clone();
                 Execution execution  = new Execution(fill, orderClone);
                 execution.OrderExecutionProvider = _provider;
                 if (ExecutionArrived != null)
                 {
                     ExecutionArrived(execution);
                 }
             }
             else if (orderStatus.order.status == "submitted" && order.OrderStatus != OrderStatus.SUBMITTED)
             {
                 order.OrderStatus = OrderStatus.SUBMITTED;
                 if (NewArrived != null)
                 {
                     NewArrived((Order)order.Clone());
                 }
             }
             else if (orderStatus.order.status == "rejected")
             {
                 if (OrderRejectionArrived != null)
                 {
                     OrderRejectionArrived(new Rejection(order.Security, _provider)
                     {
                         OrderId = order.OrderID
                     });
                 }
                 Order deleteOrder;
                 //remove order from the map
                 _ordersMap.TryRemove(order.OrderID, out deleteOrder);
             }
         }
         catch (Exception exception)
         {
             _logger.Error(exception, _type.FullName, "TimerExpired");
         }
     }
 }
Exemplo n.º 28
0
        /// <summary>
        /// Start Strategy Optimization
        /// </summary>
        /// <param name="optimizationParameters">Contains info for the parameters to be used for optimization</param>
        private void StartOptimization(BruteForceParameters optimizationParameters)
        {
            try
            {
                // Save instance
                _optimizationParameters = optimizationParameters;

                if (_asyncClassLogger.IsInfoEnabled)
                {
                    _asyncClassLogger.Info("Getting argument combinations", _type.FullName, "StartOptimization");
                }

                // Change Status to indicate on UI
                _optimizationParameters.Status = OptimizationStatus.Working;

                // Clear all previous information
                _strategiesCollection.Clear();
                _ctorArguments.Clear();

                // Get Parameter values to be used in the Constructor
                object[] ctorArguments = optimizationParameters.GetParameterValues();

                // Get Conditional Parameter values to be used for creating Iterations
                Tuple <int, object, double>[] conditionalParameters = optimizationParameters.GetConditionalParameters();

                // Save Parameter Details
                _parmatersDetails = optimizationParameters.ParameterDetails;

                // Get all ctor arguments to be used for optimization
                CreateCtorCombinations(ctorArguments, conditionalParameters);

                // Initialize Stratgey for each set of arguments
                foreach (object[] ctorArgumentValues in _ctorArguments)
                {
                    // Get new Key.
                    string key = ApplicationIdGenerator.NextId();

                    var instanceParameterDetails = new Dictionary <string, ParameterDetail>();

                    for (int i = 0; i < ctorArgumentValues.Length; i++)
                    {
                        // Create new parameter details to be when creating Strategy Instance object
                        ParameterDetail tempParameterDetail = new ParameterDetail(_parmatersDetails[i].ParameterType, ctorArgumentValues[i]);

                        instanceParameterDetails.Add(_parmatersDetails[i].Description, tempParameterDetail);
                    }

                    // Create Strategy Instance object
                    var instance = new StrategyInstance(key, instanceParameterDetails, optimizationParameters.StrategyType);

                    // Save Strategy details in new Strategy Executor object
                    var strategyExecutor = new StrategyExecutor(instance, _currentDispatcher);

                    // Register Event
                    strategyExecutor.StatusChanged += OnStrategyExecutorStatusChanged;

                    // Add to local map
                    _strategiesCollection.AddOrUpdate(key, strategyExecutor, (ky, value) => strategyExecutor);

                    StringBuilder parametersInfo = new StringBuilder();
                    foreach (object ctorArgument in strategyExecutor.CtorArguments)
                    {
                        parametersInfo.Append(ctorArgument.ToString());
                        parametersInfo.Append(" | ");
                    }

                    // Create new object to be used with Event Aggregator
                    var optimizationStatistics = new OptimizationStatistics(strategyExecutor.StrategyKey);
                    optimizationStatistics.Description      = parametersInfo.ToString();
                    optimizationStatistics.ExecutionDetails = instance.ExecutionDetails;

                    // Raise event to Bind statistics to UI and will be updated as each instance is executed
                    EventSystem.Publish <OptimizationStatistics>(optimizationStatistics);
                }

                // Save total number of iterations count
                _optimizationParameters.TotalIterations = _strategiesCollection.Count;

                // Start executing each instance
                StartStrategyExecution();
            }
            catch (Exception exception)
            {
                _asyncClassLogger.Error(exception, _type.FullName, "StartOptimization");
            }
        }
Exemplo n.º 29
0
        /// <summary>
        /// Called when new limit order is recieved
        /// </summary>
        /// <param name="limitOrder">TradeHub LimitOrder</param>
        public void NewLimitOrderArrived(LimitOrder limitOrder)
        {
            try
            {
                if (ValideLimitOrder(limitOrder))
                {
                    var order = new Order(limitOrder.OrderID,
                                          limitOrder.OrderSide,
                                          limitOrder.OrderSize,
                                          limitOrder.OrderTif,
                                          limitOrder.OrderCurrency,
                                          limitOrder.Security,
                                          limitOrder.OrderExecutionProvider);
                    //change order status to open
                    order.OrderStatus = OrderStatus.OPEN;
                    order.StrategyId  = limitOrder.StrategyId;
                    if (_asyncClassLogger.IsInfoEnabled)
                    {
                        _asyncClassLogger.Info("New Arrived :" + order, _type.FullName, "NewLimitOrderArrived");
                    }


                    // get index
                    int index;
                    int.TryParse(limitOrder.Remarks.Split('-')[1], out index);

                    //add limit order to list
                    _limitOrders.Add(index, limitOrder);

                    if (NewOrderArrived != null)
                    {
                        NewOrderArrived(order);
                    }

                    //Tick tick=new Tick();
                    //tick.LastPrice = _lastTradePrice;
                    //tick.LastSize = _lastTradeSize;
                    //tick.DateTime = _lastdateTime;
                    //tick.Security = new Security() {Symbol = limitOrder.Security.Symbol};

                    //ExecuteLimitOrder(limitOrder,_latestBar);
                }
                else
                {
                    Rejection rejection = new Rejection(limitOrder.Security, OrderExecutionProvider.SimulatedExchange)
                    {
                        OrderId = limitOrder.OrderID, DateTime = DateTime.Now, RejectioReason = "Invaild Price Or Size"
                    };
                    limitOrder.OrderStatus = OrderStatus.REJECTED;
                    if (_asyncClassLogger.IsInfoEnabled)
                    {
                        _asyncClassLogger.Info("Rejection :" + rejection, _type.FullName, "NewLimitOrderArrived");
                    }
                    if (RejectionArrived != null)
                    {
                        RejectionArrived.Invoke(rejection);
                    }
                }
                //if (_orderRepository != null)
                //{
                //    _orderRepository.AddUpdate(limitOrder);
                //}
            }
            catch (Exception exception)
            {
                _asyncClassLogger.Error(exception, _type.FullName, "NewLimitOrderArrived");
            }
        }
        /// <summary>
        /// Connects/Starts a client
        /// </summary>
        public bool Start()
        {
            try
            {
                // Read account credentials
                _credentials = CredentialReader.ReadCredentials("TradierParams.xml");

                if (String.IsNullOrEmpty(_credentials.ApiUrl) || String.IsNullOrWhiteSpace(_credentials.ApiUrl))
                {
                    return(false);
                }

                // Create HTTP Request
                var client  = new RestClient(_credentials.ApiUrl + "/user/profile");
                var request = new RestRequest(Method.GET);
                request.AddHeader("authorization", "Bearer " + _credentials.AccessToken);
                request.AddHeader("accept", "application/json");

                // Send Request
                IRestResponse response = client.Execute(request);

                var requestResult = JsonConvert.DeserializeObject <dynamic>(response.Content);

                string profileId = requestResult.profile.id.ToString();

                if (!String.IsNullOrEmpty(profileId))
                {
                    _isConnected = true;

                    // Start process to consume quotes
                    StartDataConsumer();

                    if (Logger.IsInfoEnabled)
                    {
                        Logger.Info("Session is available.", _type.FullName, "Start");
                    }

                    if (LogonArrived != null)
                    {
                        LogonArrived(_marketDataProviderName);
                    }

                    return(_isConnected);
                }

                // Get error message
                string faultstring = requestResult.fault.faultstring.ToString();

                if (Logger.IsInfoEnabled)
                {
                    Logger.Info("Session not available " + faultstring, _type.FullName, "Start");
                }

                return(_isConnected);
            }
            catch (Exception exception)
            {
                _logger.Error(exception, _type.FullName, "Start");
            }
            return(false);
        }