private void Form1_Load(object sender, EventArgs e)
        {
            ILogger baseLogger = new LoggerConsole();

            logger         = new LoggerGUI(lbStatus.Items, baseLogger);
            tradeProcessor = new TradeProcessor();
        }
        public void OutputStillMatchesCharacterization()
        {
            var inputsAndExpectations = new Dictionary <string, string>()
            {
                { "empty-fie.txt", "expectation-empty-file.text" },
                { "one-field.txt", "expectation-one-field.txt" },
                { "malformed-currency-pair.txt", "expectation-malformed-currency-pair.txt" },
                { "trade-volume-invalid.txt", "expectation-trade-volume-invalid.txt" },
                { "trade-amount-invalid.txt", "expectation-trade-amount-invalid.txt" },
                { "correct-format.txt", "expectation-correct-format.txt" }
            };

            var originalConsoleOut = Console.Out;

            foreach (var pair in inputsAndExpectations)
            {
                var input = typeof(TradeProcessor).Assembly.GetManifestResourceStream(typeof(TradeProcessor), pair.Key);

                var    expectation = File.ReadAllText(Path.Combine(CharacterizationTestOutput, pair.Value));
                string actual      = null;
                using (var memoryStream = new MemoryStream())
                {
                    using (var streamwriter = new StreamWriter(memoryStream))
                    {
                        Console.SetOut(streamwriter);
                        var tradeProcessor = new TradeProcessor();
                        tradeProcessor.ProcessTrades(input);
                        streamwriter.Flush();
                        memoryStream.Seek(0, SeekOrigin.Begin);
                        actual = new StreamReader(memoryStream).ReadToEnd();
                    }
                }
            }
        }
Beispiel #3
0
        private static void Main(string[] args)
        {
            var             inputFilePath  = @""; // absolute path
            var             outputFilePath = @""; // absolute path
            var             logFilePath    = @""; // absolute path
            ITradeProcessor tradeProcessor = new TradeProcessor();

            tradeProcessor.Process(inputFilePath, outputFilePath, logFilePath);
        }
        static void Main(string[] args)
        {
            ITradeDataProvider dataProvider = Dependancies.TradeDataProvider;
            ITradeParser       tradeParser  = Dependancies.TradeParser;
            ITradeStorage      tradeStorage = Dependancies.TradeStorage;

            var batchProcessor = new TradeProcessor(dataProvider, tradeParser, tradeStorage);

            batchProcessor.ProcessTrades();
        }
Beispiel #5
0
        //[ExpectedException(typeof(ArgumentNullException))]
        public void EmptyTestFile()
        {
            //Arrange
            var tradeStream = "http://faculty.css.edu/tgibbons/trades4.txt"; var tradeProcessor = new TradeProcessor();

            //Act
            tradeProcessor.ProcessTrades(tradeStream);

            //Assert
        }
Beispiel #6
0
 public void run()
 {
     if (TestFileCount.HasValue)
     {
         Tester.CreateTestFile(AppDomain.CurrentDomain.BaseDirectory, TestFileCount.Value);
     }
     if (TradeProcessor != null)
     {
         TradeProcessor.Process();
     }
 }
        //[ExpectedException(typeof(ArgumentNullException))]
        public void EmptyTestFile()
        {
            //Arrange
            var tradeStream    = Assembly.GetExecutingAssembly().GetManifestResourceStream("SingleResponsibilityPrincipleTests.tradesEmpty.txt");
            var tradeProcessor = new TradeProcessor();

            //Act
            tradeProcessor.ProcessTrades(tradeStream);

            //Assert
        }
        public void NoTestFile()
        {
            //Arrange
            var tradeStream    = Assembly.GetExecutingAssembly().GetManifestResourceStream("");
            var tradeProcessor = new TradeProcessor();

            //Act
            tradeProcessor.ProcessTrades(tradeStream);

            //Assert
        }
Beispiel #9
0
        private async void LoadTrades_Click(object sender, RoutedEventArgs e)
        {
            Windows.Storage.StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
            Windows.Storage.StorageFile   sampleFile    = await storageFolder.CreateFileAsync("sample.txt", Windows.Storage.CreationCollisionOption.ReplaceExisting);

            var trademodels = await TradeProcessor.LoadTrades();

            using (StreamWriter streamW = new StreamWriter(sampleFile.Path, true))
            {
                streamW.WriteLine($"{DateTime.Now} Wczytano 300 tradow");
            }

            Price.Text    = $"Cena: {trademodels[0].R}";
            Amoundof.Text = $"Ilosc: {trademodels[0].A}";
            Time.Text     = $"Czas: {trademodels[0].T}";
            Type.Text     = $"Typ: {trademodels[0].Ty}";
            Id.Text       = $"Id: {trademodels[0].Id}";
            using (StreamWriter streamW = new StreamWriter(sampleFile.Path, true))
            {
                streamW.WriteLine($"{DateTime.Now} Wyświetlono ostatni trade");
            }
            var trades = new List <Trade>();

            foreach (var trade in trademodels)
            {
                trades.Add(trade.ToTrade());
            }

            TraderContext context = null;

            try
            {
                context = new TraderContext();
                foreach (var trade in trades)
                {
                    if (!context.Trades.Any(t => t.Tid == trade.Tid))
                    {
                        context.Trades.Add(trade);
                        using (StreamWriter streamW = new StreamWriter(sampleFile.Path, true))
                        {
                            streamW.WriteLine($"{DateTime.Now} Dodano do bazy trade {trade}");
                        }
                    }
                }
                context.SaveChanges();
            }
            finally
            {
                if (context != null)
                {
                    context.Dispose();
                }
            }
        }
        public void NewExecutionSellSide_UpdateTrade_OverallPositionIsNegative()
        {
            // Create Trade Processor
            TradeProcessor tradeProcessor = new TradeProcessor(new Security()
            {
                Symbol = "GOOG"
            }, OrderExecutionProvider.Simulated);

            // Create Order Object
            Order order = new Order(OrderExecutionProvider.Simulated);

            {
                // Create Fill Object
                Fill fill = new Fill(new Security()
                {
                    Symbol = "GOOG"
                }, OrderExecutionProvider.Simulated, "1");
                fill.ExecutionId   = "1";
                fill.ExecutionSide = OrderSide.SELL;
                fill.ExecutionSize = 40;
                // Create Execution Object
                Execution execution = new Execution(fill, order);
                // Update Trade Processor
                tradeProcessor.NewExecutionArrived(execution);
            }

            {
                // Create Fill Object
                Fill fillTwo = new Fill(new Security()
                {
                    Symbol = "GOOG"
                }, OrderExecutionProvider.Simulated, "1");
                fillTwo.ExecutionId   = "2";
                fillTwo.ExecutionSide = OrderSide.BUY;
                fillTwo.ExecutionSize = 20;
                // Create Execution Object
                Execution executionTwo = new Execution(fillTwo, order);
                // Update Trade Processor
                tradeProcessor.NewExecutionArrived(executionTwo);
            }

            // Get Trades Map
            var tradeMap = tradeProcessor.OpenTrades;

            // Get Open Trade
            Trade trade = tradeMap.Values.First();

            Assert.AreEqual(-20, tradeProcessor.Position, "Overall Position");
            Assert.AreEqual(TradeSide.Sell, trade.TradeSide, "Trade Side");
            Assert.AreEqual(20, trade.ExecutionDetails["2"], "Execution Size");
            Assert.AreEqual(false, trade.IsComplete(), "Trade.IsComplete");
        }
Beispiel #11
0
        public DataSet GetBMFIntraday(string Cd_Usuario, string Ds_Senha, long lastSequence)
        {
            TradeProcessor trProc = new TradeProcessor();

            string user = ConfigurationManager.AppSettings["username"].ToString();
            string pwd  = ConfigurationManager.AppSettings["password"].ToString();

            if (user.Equals(Cd_Usuario) == false ||
                pwd.Equals(Ds_Senha) == false)
            {
                DataSet    ds    = new DataSet("NewDataSet");
                DataTable  table = new DataTable("Table1");
                DataColumn col   = new DataColumn("ERRO");
                table.Columns.Add(col);
                ds.Tables.Add(table);

                DataRow dr = ds.Tables["Table1"].NewRow();

                dr["Erro"] = "Usuario / senha invalidos";

                ds.Tables["Table1"].Rows.Add(dr);

                logger.Fatal("Usuario / senha invalidos");
                return(ds);
            }

            logger.Info("GetBMFIntraday(" + lastSequence + ") Inicio");

            //string xmlTrades = trProc.GetTrades(lastSequence);

            //string xmlRet = "<QueryTradesStrResponse>";

            //string xmlRet = "<QueryTradesStrResult>";
            //xmlRet += xmlTrades;
            //xmlRet += "</QueryTradesStrResult>";
            //xmlRet += "<pTradeID>";
            //xmlRet += pTradeID.ToString("yyyy/MM/dd HH:mm:ss");
            //xmlRet += "</pTradeID>";
            //xmlRet += "</QueryTradesStrResponse>";

            //logger.Debug("XML Trades [" + xmlTrades + "]");

            // logger.Info("QueryTradesStr(" + lastSequence + ") FIM");

            return(trProc.GetTradesDataset(lastSequence));

            //QueryTradesStr1 resp = new QueryTradesStr1();
            //resp.pTradeID = pTradeID.ToString("yyyy/MM/dd HH:mm:ss");
            //resp.QueryTradesStrResult = xmlTrades;

            //return resp;
        }
Beispiel #12
0
        public void TestTradeAmountBoounds()
        {
            // Arrange
            var tradeStream = "http://faculty.css.edu/tgibbons/trades4.txt"; var tradeProcessor = new TradeProcessor();
            int startCount = CountDbRecords();

            // Act
            tradeProcessor.ProcessTrades(tradeStream);
            int endCount = CountDbRecords();

            // Assert
            Assert.AreEqual(endCount - startCount, 2);
        }
Beispiel #13
0
        public void NoTestFile()
        {
            //Arrange
            string url = "";

            var tradeProcessor = new TradeProcessor();

            //Act


            tradeProcessor.ProcessTrades(url);

            //Assert
        }
Beispiel #14
0
        private async void Process_Trade(object sender, RoutedEventArgs e)
        {
            if (start < end)
            {
                TradeProcessor tradeProcessor = new TradeProcessor();
                await tradeProcessor.TradeExecute(start, end);

                ShowSymbolsList();
            }
            else
            {
                MessageBox.Show("Select START date and END date correctly!");
            }
        }
        public void TestTradeAmountBoounds()
        {
            // Arrange
            var tradeStream    = Assembly.GetExecutingAssembly().GetManifestResourceStream("SingleResponsibilityPrincipleTests.tradesBounds.txt");
            var tradeProcessor = new TradeProcessor();
            int startCount     = CountDbRecords();

            // Act
            tradeProcessor.ProcessTrades(tradeStream);
            int endCount = CountDbRecords();

            // Assert
            Assert.AreEqual(endCount - startCount, 2);
        }
Beispiel #16
0
        //[ExpectedException(typeof(ArgumentNullException))]
        public void EmptyTestFile()
        {
            //Arrange

            string url            = "http://faculty.css.edu/tgibbons/tradesempty.txt";
            var    tradeProcessor = new TradeProcessor();

            //Act


            tradeProcessor.ProcessTrades(url);

            //Assert
        }
        public void Process_should_write_csv_file(string inputFile, string outputFile, string expectedFile, string logFile)
        {
            var             inputFilePath    = Path.Combine(GetDataFolder(), inputFile);
            var             outputFilePath   = Path.Combine(GetDataFolder(), outputFile);
            var             expectedFilePath = Path.Combine(GetDataFolder(), expectedFile);
            var             logFilePath      = Path.Combine(GetDataFolder(), logFile);
            ITradeProcessor tradeProcessor   = new TradeProcessor();

            tradeProcessor.Process(inputFilePath, outputFilePath, logFilePath);
            Assert.IsTrue(File.Exists(outputFilePath));
            CollectionAssert.AreEqual(File.ReadAllLines(expectedFilePath), File.ReadAllLines(outputFilePath));
            var outputLogFile = logFilePath + DateTime.Today.ToString("yyyyMMdd");

            Assert.IsTrue(File.Exists(outputLogFile));
        }
Beispiel #18
0
        static void Main(string[] args)
        {
            var serilogLogger = new LoggerConfiguration()
                                .WriteTo.File("log.txt", rollingInterval: RollingInterval.Day)
                                .CreateLogger();

            IRateMyAgentLogger logger     = new RateMyAgentLogger(serilogLogger);
            IRepository        repository = new SqlServerRepository();
            ITradeRecordParser parser     = new TradeRecordParser(logger);
            ITradeStreamReader reader     = new HardcodedTradeStreamReader();

            ITradeProcessor processor = new TradeProcessor(logger, repository, parser, reader);

            processor.ProcessTrades();
        }
Beispiel #19
0
void Main(){

    Stream s = new();
    System.Data.SqlClient.SqlConnection coneccion = new();

//    ITradeDataProvider provider = new ITradeDataProvider(s);   
    
    ITradeDataProvider provider = new ProvidePrueba();   
    ITradeParser parse = new tradeParser();
    StoreNull store = new StoreNull();

    TradeProcessor t = new TradeProcessor(provider, parse, store);
    t.ProcessTrades();
    Console.WriteLine($"Se grabaron {store.contador}");   
}
Beispiel #20
0
        public Program(params string[] args)
        {
            LoggerSetting.init();

            o = new OptionSet()
            {
                { "f|filePath=", "the input {FILE} path of Trade datafeed. Defaul is current dir + '/TradesList.xml'.", v => FeedFilePath = v },
                { "t|targetPath=", "the {DESTINATION} path. Default is current dir.", v => TargetLocation = v },
                { "g|testFile=", "generate TradesList.xml of {COUNT} elements in current dir.", v => TestFileCount = Int32.Parse(v) },
                { "b|batchSize=", "Batch {SIZE}. Default is 1000.", v => BatchSize = Int32.Parse(v) },
                { "h|help", "Show this help.", v => Help = v != null }
            };

            List <string> extra;

            try
            {
                extra = o.Parse(args);
            }
            catch (OptionException e)
            {
                Console.Write("datafeeds: ");
                Console.WriteLine(e.Message);
                Console.WriteLine("Try `--help' for more information.");
                return;
            }

            if (Help)
            {
                printHelp();
                return;
            }
            if (FeedFilePath == null)
            {
                FeedFilePath = AppDomain.CurrentDomain.BaseDirectory + "/TradesList.xml";
            }
            if (TargetLocation == null)
            {
                TargetLocation = AppDomain.CurrentDomain.BaseDirectory;
            }
            if (BatchSize == null)
            {
                BatchSize = 1000;
            }

            TradeProcessor = new TradeProcessor(this.FeedFilePath, this.TargetLocation, BatchSize.Value);
            Tester         = new CTSTestApplication.Tester();
        }
Beispiel #21
0
        public void TestTradeAmountBoounds()
        {
            // Arrange
            //var tradeStream = Assembly.GetExecutingAssembly().GetManifestResourceStream("SingleResponsibilityPrincipleTests.tradesBounds.txt");
            string url            = "http://faculty.css.edu/tgibbons/tradesBounds.txt";
            var    tradeProcessor = new TradeProcessor();
            int    startCount     = CountDbRecords();

            // Act
            //tradeProcessor.ProcessTrades(tradeStream);
            tradeProcessor.ProcessTrades(url);
            int endCount = CountDbRecords();

            // Assert
            Assert.AreEqual(endCount - startCount, 2);
        }
Beispiel #22
0
        private bool ValidateSymbol()
        {
            status = false;
            TradeProcessor   tp               = new TradeProcessor();
            MySqlCommand     sqlCommand       = new MySqlCommand(query, connection);
            MySqlDataAdapter MysqlDataAdapter = new MySqlDataAdapter(sqlCommand);

            using (MysqlDataAdapter)
            {
                sqlCommand.Parameters.AddWithValue("@symbol", Symbol.Text.ToString());

                try
                {
                    SelectedSymbol = Symbol.Text.ToString();
                }
                catch      //NullReferenceException e
                {
                    MessageBox.Show("Please select Symbol");
                }

                if (SelectedSymbol.Length <= 5)
                {
                    if (!CheckForSQLInjection(SelectedSymbol))
                    {
                        string query = "SELECT count(distinct `SecurityName`) FROM `algotrade`.`symbols` where `Symbol` = '" + SelectedSymbol + "' ;";


                        if (tp.DBA(query) > 0)
                        {
                            status = true;
                        }
                    }
                    else
                    {
                        status = false;
                        Symbol.Clear();
                    }
                }
                else
                {
                    status = false;
                    MessageBox.Show("Please enter Symbol with correct number of characters!");
                    Symbol.Clear();
                }
            }
            return(status);
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            var    tradeStream = Assembly.GetExecutingAssembly().GetManifestResourceStream("SingleResponsibilityPrinciple.trades.txt");
            String tradeUrl    = "http://faculty.css.edu/tgibbons/trades100.txt";

            var logger = new ConsoleLogger();
            //var logger = new GuiLogger(lbStatus.Items);

            //var tradeDataProvider = new StreamTradeDataProvider(tradeStream);
            var tradeDataProvider = new AdjustTradeDataProvider(tradeUrl); //changed to AdjustTradeDataProvider

            var tradeValidator = new SimpleTradeValidator(logger);
            var tradeMapper    = new SimpleTradeMapper();
            var tradeParser    = new SimpleTradeParser(tradeValidator, tradeMapper);

            var tradeStorage = new AdoNetTradeStorage(logger);

            tradeProcessor = new TradeProcessor(tradeDataProvider, tradeParser, tradeStorage);
        }
Beispiel #24
0
        public async Task TestMethod1()
        {
            ApiHelper.InitializeClient();
            List <int> numbers = new List <int> {
                1, 26, 70, 5
            };
            List <Type> expected = new List <Type> {
                typeof(TradeModel[]), typeof(TradeModel[]), typeof(TradeModel[]), typeof(TradeModel[])
            };
            List <Type> actual = new List <Type>();

            for (int i = 0; i < 4; i++)
            {
                var trades = await TradeProcessor.LoadTrades(numbers[i]);

                actual.Add(trades.GetType());
            }

            CollectionAssert.AreEqual(expected, actual);
        }
Beispiel #25
0
        /// <summary>
        /// Called when new Execution is received
        /// </summary>
        /// <param name="execution">Order Execution Object</param>
        public void NewExecutionArrived(Execution execution)
        {
            try
            {
                if (Logger.IsDebugEnabled)
                {
                    Logger.Debug("New Execution received " + execution, _type.FullName, "NewExecutionArrived");
                }

                // Create Object
                Dictionary <Security, TradeProcessor> tradeProcessorsBySecurityMap;

                // Get Trade Processor object for the received Execution Message's Provider
                if (!_tradeProcessorMap.TryGetValue(execution.OrderExecutionProvider, out tradeProcessorsBySecurityMap))
                {
                    if (Logger.IsDebugEnabled)
                    {
                        Logger.Debug("New Trade Processor created for:" + execution.OrderExecutionProvider, _type.FullName, "NewExecutionArrived");
                    }

                    // Initialize a new Trade Processor object
                    TradeProcessor tradeProcessorObject = new TradeProcessor(execution.Fill.Security, execution.OrderExecutionProvider);

                    // Initialize local Map
                    tradeProcessorsBySecurityMap = new Dictionary <Security, TradeProcessor>();

                    // Add to local Map
                    tradeProcessorsBySecurityMap.Add(execution.Fill.Security, tradeProcessorObject);

                    // Add to Global Map
                    _tradeProcessorMap.Add(execution.OrderExecutionProvider, tradeProcessorsBySecurityMap);

                    // Forward Execution to Trade Processor
                    tradeProcessorObject.NewExecutionArrived(execution);
                }
                else
                {
                    TradeProcessor tradeProcessorObject;

                    // Get Trade Processor object for the received Execution Message's Security
                    if (!tradeProcessorsBySecurityMap.TryGetValue(execution.Fill.Security, out tradeProcessorObject))
                    {
                        if (Logger.IsDebugEnabled)
                        {
                            Logger.Debug("New Trade Processor created for:" + execution.Fill.Security, _type.FullName, "NewExecutionArrived");
                        }

                        // Initialize a new Trade Processor object
                        tradeProcessorObject = new TradeProcessor(execution.Fill.Security, execution.OrderExecutionProvider);

                        // Add to local Map
                        tradeProcessorsBySecurityMap.Add(execution.Fill.Security, tradeProcessorObject);
                    }
                    // Forward Execution to Trade Processor
                    tradeProcessorObject.NewExecutionArrived(execution);
                }
            }
            catch (Exception exception)
            {
                Logger.Error(exception, _type.FullName, "NewExecutionArrived");
            }
        }
        public void NewExecutionBuySideMultiple_OpenNewTradeMultiple_OverallPositionIsPositive()
        {
            // Create Trade Processor
            TradeProcessor tradeProcessor = new TradeProcessor(new Security()
            {
                Symbol = "GOOG"
            }, OrderExecutionProvider.Simulated);

            // Create Order Object
            Order order = new Order(OrderExecutionProvider.Simulated);

            {
                // Create Fill Object
                Fill fill = new Fill(new Security()
                {
                    Symbol = "GOOG"
                }, OrderExecutionProvider.Simulated, "1");
                fill.ExecutionId   = "1";
                fill.ExecutionSide = OrderSide.BUY;
                fill.ExecutionSize = 40;
                // Create Execution Object
                Execution execution = new Execution(fill, order);
                // Update Trade Processor
                tradeProcessor.NewExecutionArrived(execution);
            }

            {
                // Create Fill Object
                Fill fillTwo = new Fill(new Security()
                {
                    Symbol = "GOOG"
                }, OrderExecutionProvider.Simulated, "1");
                fillTwo.ExecutionId   = "2";
                fillTwo.ExecutionSide = OrderSide.BUY;
                fillTwo.ExecutionSize = 40;
                // Create Execution Object
                Execution executionTwo = new Execution(fillTwo, order);
                // Update Trade Processor
                tradeProcessor.NewExecutionArrived(executionTwo);
            }

            // Get Trades Map
            var tradeMap = tradeProcessor.OpenTrades;

            // Open Trade Count
            var openTradeCount = tradeMap.Count;

            // Get Open Trade Size
            int tradeOneSize = tradeMap[1].TradeSize;
            int tradeTwoSize = tradeMap[2].TradeSize;

            Assert.AreEqual(80, tradeProcessor.Position, "Overall Position");
            Assert.AreEqual(2, openTradeCount, "Open Trade Count");

            Assert.AreEqual(TradeSide.Buy, tradeMap[1].TradeSide, "Trade One Side");
            Assert.AreEqual(TradeSide.Buy, tradeMap[2].TradeSide, "Trade Two Side");

            Assert.AreEqual(40, tradeOneSize, "Trade One Size");
            Assert.AreEqual(40, tradeTwoSize, "Trade Two Size");

            Assert.AreEqual(false, tradeMap[1].IsComplete(), "Trade One Completion Status");
            Assert.AreEqual(false, tradeMap[2].IsComplete(), "Trade Two Completion Status");
        }
Beispiel #27
0
        public string QueryTradesStr(string pUser,
                                     string pPassword,
                                     int pInstitutionID,
                                     DateTime pInitialDate,
                                     DateTime pFinalDate,
                                     ref DateTime pTradeID,
                                     string pTradeStatus,
                                     string pProduct,
                                     string pAfterHour,
                                     string pTraderID)
        {
            try
            {
                TradeProcessor trProc = new TradeProcessor();

                string pwd64 = base64Encode(pPassword);

                if (pUser.Equals(_config.OpenBlotterUsr) == false || pwd64.Equals(_config.OpenBlotterPwd) == false)
                {
                    return("pUser or pPassword is invalid!");

                    //QueryTradesStr1 error = new QueryTradesStr1();
                    //error.pTradeID = pTradeID.ToString("yyyy/MM/dd HH:mm:ss");
                    //error.QueryTradesStrResult = "pUser or pPassword is invalid!";

                    //return error;
                }

                logger.Info("QueryTradesStr(" + pTradeID.ToString("yyyy/MM/dd HH:mm:ss") + ") Inicio");

                string xmlTrades = trProc.GetTrades(pTradeID);

                //string xmlRet = "<QueryTradesStrResponse>";

                //string xmlRet = "<QueryTradesStrResult>";
                //xmlRet += xmlTrades;
                //xmlRet += "</QueryTradesStrResult>";
                //xmlRet += "<pTradeID>";
                //xmlRet += pTradeID.ToString("yyyy/MM/dd HH:mm:ss");
                //xmlRet += "</pTradeID>";
                //xmlRet += "</QueryTradesStrResponse>";

                logger.Debug("XML Trades [" + xmlTrades + "]");

                logger.Info("QueryTradesStr(" + pTradeID.ToString("yyyy/MM/dd HH:mm:ss") + ") FIM");

                return(xmlTrades);

                //QueryTradesStr1 resp = new QueryTradesStr1();
                //resp.pTradeID = pTradeID.ToString("yyyy/MM/dd HH:mm:ss");
                //resp.QueryTradesStrResult = xmlTrades;

                //return resp;
            }
            catch (Exception ex)
            {
                logger.Error("QueryTradesStr: " + ex.Message, ex);
            }

            return("<trades/>");
        }
        public void NewExecutionSellSideMultiple_OpenNewTradeMultipleAndUpdateTrade_OverallPositionIsBalanced()
        {
            // Create Trade Processor
            TradeProcessor tradeProcessor = new TradeProcessor(new Security()
            {
                Symbol = "GOOG"
            }, OrderExecutionProvider.Simulated);

            // Create Order Object
            Order order = new Order(OrderExecutionProvider.Simulated);

            {
                // Create Fill Object
                Fill fill = new Fill(new Security()
                {
                    Symbol = "GOOG"
                }, OrderExecutionProvider.Simulated, "1");
                fill.ExecutionId   = "1";
                fill.ExecutionSide = OrderSide.SELL;
                fill.ExecutionSize = 40;
                // Create Execution Object
                Execution execution = new Execution(fill, order);
                // Update Trade Processor
                tradeProcessor.NewExecutionArrived(execution);
            }

            {
                // Create Fill Object
                Fill fillTwo = new Fill(new Security()
                {
                    Symbol = "GOOG"
                }, OrderExecutionProvider.Simulated, "1");
                fillTwo.ExecutionId   = "2";
                fillTwo.ExecutionSide = OrderSide.SELL;
                fillTwo.ExecutionSize = 50;
                // Create Execution Object
                Execution executionTwo = new Execution(fillTwo, order);
                // Update Trade Processor
                tradeProcessor.NewExecutionArrived(executionTwo);
            }

            {
                // Create Fill Object
                Fill fillThree = new Fill(new Security()
                {
                    Symbol = "GOOG"
                }, OrderExecutionProvider.Simulated, "1");
                fillThree.ExecutionId   = "3";
                fillThree.ExecutionSide = OrderSide.BUY;
                fillThree.ExecutionSize = 90;
                // Create Execution Object
                Execution executionThree = new Execution(fillThree, order);
                // Update Trade Processor
                tradeProcessor.NewExecutionArrived(executionThree);
            }

            // Get Trades Map
            var tradeMap = tradeProcessor.OpenTrades;

            // Open Trade Count
            var openTradeCount = tradeMap.Count;

            Assert.AreEqual(0, tradeProcessor.Position, "Overall Position");
            Assert.AreEqual(0, openTradeCount, "Open Trade Count");
        }
        public void NewExecutionBuySideMultiple_OpenNewTradeMultipleAndUpdateTrade_OverallPositionIsNegativeWithSingleOpenOrderOnSellSide()
        {
            // Create Trade Processor
            TradeProcessor tradeProcessor = new TradeProcessor(new Security()
            {
                Symbol = "GOOG"
            }, OrderExecutionProvider.Simulated);

            // Create Order Object
            Order order = new Order(OrderExecutionProvider.Simulated);

            {
                // Create Fill Object
                Fill fill = new Fill(new Security()
                {
                    Symbol = "GOOG"
                }, OrderExecutionProvider.Simulated, "1");
                fill.ExecutionId   = "1";
                fill.ExecutionSide = OrderSide.BUY;
                fill.ExecutionSize = 40;
                // Create Execution Object
                Execution execution = new Execution(fill, order);
                // Update Trade Processor
                tradeProcessor.NewExecutionArrived(execution);
            }

            {
                // Create Fill Object
                Fill fillTwo = new Fill(new Security()
                {
                    Symbol = "GOOG"
                }, OrderExecutionProvider.Simulated, "1");
                fillTwo.ExecutionId   = "2";
                fillTwo.ExecutionSide = OrderSide.BUY;
                fillTwo.ExecutionSize = 30;
                // Create Execution Object
                Execution executionTwo = new Execution(fillTwo, order);
                // Update Trade Processor
                tradeProcessor.NewExecutionArrived(executionTwo);
            }

            {
                // Create Fill Object
                Fill fillThree = new Fill(new Security()
                {
                    Symbol = "GOOG"
                }, OrderExecutionProvider.Simulated, "1");
                fillThree.ExecutionId   = "3";
                fillThree.ExecutionSide = OrderSide.SELL;
                fillThree.ExecutionSize = 80;
                // Create Execution Object
                Execution executionThree = new Execution(fillThree, order);
                // Update Trade Processor
                tradeProcessor.NewExecutionArrived(executionThree);
            }

            // Get Trades Map
            var tradeMap = tradeProcessor.OpenTrades;

            // Open Trade Count
            var openTradeCount = tradeMap.Count;

            // Get Open Trade Size
            int tradeThreeSize = tradeMap[3].TradeSize;

            Assert.AreEqual(-10, tradeProcessor.Position, "Overall Position");
            Assert.AreEqual(1, openTradeCount, "Open Trade Count");
            Assert.AreEqual(TradeSide.Sell, tradeMap[3].TradeSide, "Trade Three Side");
            Assert.AreEqual(-10, tradeThreeSize, "Trade Three Size");
            Assert.AreEqual(false, tradeMap[3].IsComplete(), "Trade Three Completion Status");
        }
Beispiel #30
0
 public Trades(int instrument, TradeProcessor tradeProcessingStrategy)
 {
     Instrument = instrument;
     TradeProcessingStrategy = tradeProcessingStrategy;
 }
 public void Run()
 {
     TradeProcessor processor = new TradeProcessor();
     processor.ProcessTrades();
 }
 public Trades(Instrument instrument, TradeProcessor tradeProcessingStrategy)
 {
     Instrument = instrument;
     TradeProcessingStrategy = tradeProcessingStrategy;
 }