// ibClient event handlers void ibClient_NextValidId(int orderId) { IsConnected = true; HandleMessage(new ConnectionStatusMessage(true)); //ShowMessageOnPanel("void ibClient_NextValidId(int orderId): " + orderId); // Does not work. Invoke required ListViewLogging.log_add(this, "parserListBox", "void ibClient_NextValidId(int orderId)", "ibClient_NextValidId: " + orderId, "white"); }
private void button10_Click(object sender, EventArgs e) // Buy button click { //Contract contract = GetOrderContract(); //Order order = GetOrder(); //orderManager.PlaceOrder(contract, order); ListViewLogging.log_add(this, "parserListBox", "Form1.cs", "placeOrder.SendOrder('buy')", "green"); placeOrder.SendOrder("buy", textBox1.Text); }
private void Form1_Load(object sender, EventArgs e) { ListViewLogging.log_add(this, "parserListBox", "Form1.cs", "Current culture:" + CultureInfo.CurrentCulture.Name, "white"); ListViewLogging.log_add(this, "parserListBox", "Form1.cs", "Version: 03/01/2018 07:05PM", "white"); //var chromeDriverService = ChromeDriverService.CreateDefaultService(); //chromeDriverService.HideCommandPromptWindow = true; //var driver = new ChromeDriver(chromeDriverService, new ChromeOptions()); //ChromeDriver.Navigate().GoToUrl("https://profit.ly/profiding2222"); // Go to URL file:///D:/1/profitly.html https://profit.ly/profiding }
private void ShowMessageOnPanel(string message) { ListViewLogging.log_add(this, "brokerListBox", "Form1.cs ShowMessageOnPanel", message, "white"); message = ensureMessageHasNewline(message); if (numberOfLinesInMessageBox >= MAX_LINES_IN_MESSAGE_BOX) { linesInMessageBox.RemoveRange(0, MAX_LINES_IN_MESSAGE_BOX - REDUCED_LINES_IN_MESSAGE_BOX); messageBox.Lines = linesInMessageBox.ToArray(); numberOfLinesInMessageBox = REDUCED_LINES_IN_MESSAGE_BOX; } linesInMessageBox.Add(message); numberOfLinesInMessageBox += 1; this.messageBox.AppendText(message); }
// Control events handlers. Button clicks etc. private void connect_Button(object sender, EventArgs e) // Connect button click { if (!IsConnected) // False on startup { ListViewLogging.log_add(this, "parserListBox", "Form1.cs", "Connect button clicked", "white"); int port; string host = "127.0.0.1"; if (host == null || host.Equals("")) { host = "127.0.0.1"; } try { port = TfrSettingsJson.ibGateWayPort; // 7496 - TWS. 4002 - IB Gateway ibClient.ClientId = 1; ibClient.ClientSocket.eConnect(host, port, ibClient.ClientId); // Connection var reader = new EReader(ibClient.ClientSocket, signal); // Put the websocket stream to the reader variable reader.Start(); new Thread(() => { while (ibClient.ClientSocket.IsConnected()) { signal.waitForSignal(); reader.processMsgs(); } }) { IsBackground = true }.Start(); // https://interactivebrokers.github.io/tws-api/connection.html#gsc.tab=0 } catch (Exception) { ListViewLogging.log_add(this, "parserListBox", "Form1.cs", "Please check your connection attributes", "white"); } } else { IsConnected = false; ibClient.ClientSocket.eDisconnect(); ListViewLogging.log_add(this, "parserListBox", "Form1.cs", "Connect button clicked while connection establichet - disconnect", "white"); } }
public static void InjectMsg(string messageType, Form1 form) { // US culture is used. Must be carefull with it! In DB Convert.ToDouble(command1.ExecuteScalar()) is used // It is sensetive to (,) and (.) symbold. If you turn all project into us-US culture sove feilds in DB like accumulated_sum_pcnt or // accumulated_balance can turn values 19.99999 to 1999999! // Experienced big trubble in DataBase.UpdateProfit() - Get the value of accumulated_sum_prcnt from the previous record then it will be used in a second query string appendedTime = GetAndTrackMMessages.lastMessageDate.AddHours(++addedHouh).ToString("h:mm:ss tt"); // Add an hour to the date of last message and inject it to the page thus it will be read as a new one switch (messageType) { case "bought": //Console.WriteLine("bought case detected"); jsString = "var newItem = document.createElement('div'); newItem.style = ('background-color:green'); newItem.className = ('GLS-JUXDFAD'); newItem.innerHTML = ('<img src=\"./profitly_files/TimCover1_bigger.jpg\" width=50 height=50> 11/28 " + appendedTime + " - Bought 3000 of $" + symbol + " at 1.59 - text message'); var list = document.getElementById('x-auto-1'); list.insertBefore(newItem, list.childNodes[0]);"; break; case "sold": //Console.WriteLine("sold case detected"); jsString = "var newItem = document.createElement('div'); newItem.style = ('background-color:red'); newItem.className = ('GLS-JUXDFAD'); newItem.innerHTML = ('<img src=\"./profitly_files/TimCover1_bigger.jpg\" width=50 height=50> 11/28 " + appendedTime + " - Sold 2000 of $" + symbol + " at 1.60 - text message'); var list = document.getElementById('x-auto-1'); list.insertBefore(newItem, list.childNodes[0]);"; break; case "else": //Console.WriteLine("else case detected"); jsString = "var newItem = document.createElement('div'); newItem.style = ('background-color:gray'); newItem.className = ('GLS-JUXDFAD'); newItem.innerHTML = ('<img src=\"./profitly_files/TimCover1_bigger.jpg\" width=50 height=50> 11/28 " + appendedTime + " - " + elseMessages[(new Random()).Next(0, 3)] + " 2000 of $ELSESYMBOL at 2.24 - text message'); var list = document.getElementById('x-auto-1'); list.insertBefore(newItem, list.childNodes[0]);"; break; } try { Form1.js.ExecuteScript(jsString); //Console.WriteLine("Test message injected to the page"); } catch (Exception err) { ListViewLogging.log_add(form, "parserListBox", "IngectTestMessage.cs", "Error: " + err, "red"); //Console.WriteLine("JS error. Can't inject test message" + err); } }
private void button11_Click(object sender, EventArgs e) // Sell button click { ListViewLogging.log_add(this, "parserListBox", "Form1.cs", "placeOrder.SendOrder('sell')", "red"); placeOrder.SendOrder("sell", textBox1.Text); }
private void UpdateUI(IBMessage message) { // http://nlog-project.org/download/ Logging lib // These messages are generated for evry event. Uncomment to see what type of messages are comeing. Importand for debugging ListViewLogging.log_add(this, "messageTypeListBox", "Form1.cs", message.Type.ToString(), "white"); // Output to the separate listView switch (message.Type) { case MessageType.ConnectionStatus: { ConnectionStatusMessage statusMessage = (ConnectionStatusMessage)message; ShowMessageOnPanel("Connection status: " + statusMessage.IsConnected); if (statusMessage.IsConnected) { status_CT.Text = "Connected"; button13.Text = "Disconnect"; } else { status_CT.Text = "Disconnected..."; button13.Text = "Connect"; } break; } case MessageType.Error: { ErrorMessage error = (ErrorMessage)message; ShowMessageOnPanel("ERROR. Request " + error.RequestId + ", Code: " + error.ErrorCode + " - " + error.Message); HandleErrorMessage(error); break; } case MessageType.TickOptionComputation: case MessageType.TickPrice: case MessageType.TickSize: { //HandleTickMessage((MarketDataMessage)message); break; } case MessageType.MarketDepth: case MessageType.MarketDepthL2: { //deepBookManager.UpdateUI(message); break; } case MessageType.HistoricalData: case MessageType.HistoricalDataEnd: { //historicalDataManager.UpdateUI(message); break; } case MessageType.RealTimeBars: { //realTimeBarManager.UpdateUI(message); break; } case MessageType.ScannerData: case MessageType.ScannerParameters: { //scannerManager.UpdateUI(message); break; } case MessageType.OpenOrder: { var castedMessage = (OpenOrderMessage)message; ShowMessageOnPanel("OpenOrder. Contract: " + castedMessage.Contract + " Order: " + castedMessage.Order + " OrderID: " + castedMessage.OrderId + " OrderState: " + castedMessage.OrderState + " Type:" + castedMessage.Type); break; } case MessageType.OrderStatus: { var castedMessage = (OrderStatusMessage)message; ShowMessageOnPanel("OrderStatus. AvgFillPrice: " + castedMessage.AvgFillPrice + " ClientId: " + castedMessage.ClientId + " Filled: " + castedMessage.Filled + " LastFillPrice: " + castedMessage.LastFillPrice + " OrderId:" + castedMessage.OrderId + " ParentID:" + castedMessage.ParentId + " PermID:" + castedMessage.PermId + " Remaining:" + castedMessage.Remaining + " Status:" + castedMessage.Status + " Type:" + castedMessage.Type + " WhyHwld:" + castedMessage.WhyHeld); break; } case MessageType.OpenOrderEnd: case MessageType.ExecutionData: case MessageType.CommissionsReport: { //orderManager.UpdateUI(message); ******************************************************** placeOrder.UpdateUI(message); break; } case MessageType.ManagedAccounts: { MessageBox.Show("case MessageType.ManagedAccounts: no message"); //orderManager.ManagedAccounts = ((ManagedAccountsMessage)message).ManagedAccounts; //accountManager.ManagedAccounts = ((ManagedAccountsMessage)message).ManagedAccounts; //exerciseAccount.Items.AddRange(((ManagedAccountsMessage)message).ManagedAccounts.ToArray()); break; } case MessageType.AccountSummaryEnd: { //accSummaryRequest.Text = "Request"; //accountManager.UpdateUI(message); break; } case MessageType.AccountDownloadEnd: { break; } case MessageType.AccountUpdateTime: { //accUpdatesLastUpdateValue.Text = ((UpdateAccountTimeMessage)message).Timestamp; break; } case MessageType.PortfolioValue: { //accountManager.UpdateUI(message); //if (exerciseAccount.SelectedItem != null) // optionsManager.HandlePosition((UpdatePortfolioMessage)message); break; } case MessageType.AccountSummary: case MessageType.AccountValue: case MessageType.Position: case MessageType.PositionEnd: { //accountManager.UpdateUI(message); break; } case MessageType.ContractDataEnd: // This event occur after symbol search { //searchContractDetails.Enabled = true; //contractManager.UpdateUI(message); break; } case MessageType.ContractData: // This event occur after symbol search { //HandleContractDataMessage((ContractDetailsMessage)message); // Type cast var castedMessage = (ContractDetailsMessage)message; ShowMessageOnPanel("SYMBOL: " + castedMessage.ContractDetails.Summary.Symbol + " successfully found at: " + castedMessage.ContractDetails.Summary.PrimaryExch + " exchange"); break; } case MessageType.FundamentalData: { //fundamentalsQueryButton.Enabled = true; //contractManager.UpdateUI(message); break; } case MessageType.ReceiveFA: { //advisorManager.UpdateUI((AdvisorDataMessage)message); break; } case MessageType.PositionMulti: case MessageType.AccountUpdateMulti: case MessageType.PositionMultiEnd: case MessageType.AccountUpdateMultiEnd: { //acctPosMultiManager.UpdateUI(message); break; } case MessageType.SecurityDefinitionOptionParameter: case MessageType.SecurityDefinitionOptionParameterEnd: { //optionsManager.UpdateUI(message); break; } case MessageType.SoftDollarTiers: { //orderManager.UpdateUI(message); placeOrder.UpdateUI(message); var castedMessage = (ExecutionMessage)message; ListViewLogging.log_add(this, "brokerListBox", "case MessageType.SoftDollarTiers:", castedMessage.ToString(), "yellow"); // ("PlaceOrder.cs private void HandleExecutionMessage(ExecutionMessage message): " + message.Execution.OrderId + " orderRef: " + message.Execution.OrderRef + " price: " + message.Execution.Price + " time: " + message.Execution.Time + " accountNumber" + message.Execution.AcctNumber); break; } default: { HandleMessage(new ErrorMessage(-1, -1, message.ToString())); break; } } }
public static bool startTracking = true; // False by default. When set to true - start tracking messages at the page public static void MessageSearch(Form1 form) { while (true) // Continues cycle. Each iteration reads the page content { System.Threading.Thread.Sleep(1000); // Delay between each page parse. 1000 - 1 sec //ListViewLogging.log_add(form, "GetAndTrackMessages.cs", "Page parsed at: " + DateTime.Now.ToString("hh.mm.ss.fff"), "white"); form.BeginInvoke(new Action(delegate() { form.progressBar1.Minimum = 0; form.progressBar1.Maximum = 100; form.progressBar1.Step = 10; form.label2.Text = DateTime.Now.ToString("hh.mm.ss.fff"); if (form.progressBar1.Value == 100) { //form.progressBar1.CreateGraphics().DrawString(DateTime.Now.ToString("hh.mm.ss.fff").ToString(), new Font("Arial", (float)8.25, FontStyle.Regular), Brushes.Black, new PointF(form.progressBar1.Width / 2 - 10, form.progressBar1.Height / 2 - 7)); form.progressBar1.Value = 0; } form.progressBar1.PerformStep(); } )); // Invoke if (firstMessageDisplayed) // Last line is not cleared at the first run { //ListViewLogging.log_add(form, "GetAndTrackMessages.cs", "Console.SetCursorPosition(0, Console.CursorTop - 1); // Returned cursor to the previous line", "white"); //Helpers.ClearCurrentConsoleLine(); // Clear last line with parsed time } firstMessageDisplayed = true; if (dateTimerFlag) { goToFavTabDateTime = DateTime.Now.AddSeconds(30); goToTradesDateTime = DateTime.Now.AddSeconds(32); dateTimerFlag = false; // When date is recorded set flag to false until going to the Favorites tab } if ((DateTime.Compare(DateTime.Now, goToFavTabDateTime) > 0) && startTracking) { //ListViewLogging.log_add(form, "GetAndTrackMessages.cs", "Go to Favorite tab: ", "white"); goToFavTabDateTime = DateTime.Now; Helpers.FavTabClick(); } if ((DateTime.Compare(DateTime.Now, goToTradesDateTime) > 0) && startTracking) // Go back to trades tab after a short delay { //ListViewLogging.log_add(form, "GetAndTrackMessages.cs", "Go to Trades tab: ", "white"); goToTradesDateTime = DateTime.Now; Helpers.TradesTabClick(); dateTimerFlag = true; } int filter_couner = 0; // Counter for filtering messages. We need to get rid of messages with 2017 year mentined. There is no year in message and 12/28/17 date is considered the latest while parsing throught the whole page. Logic breaks in this case. Last message is the only one which is last on the screen. try { var InputString = Form1.ChromeDriver.FindElementsByClassName("GLS-JUXDFAD"); foreach (var z in InputString) // Run cycle through all found elements on the page { try { Match match = Regex.Match(z.Text, @"(.+?PM|.+?AM)\s-\s(.+?)\s(\d+)\s.+?\s\$(.+)\sat\s(.+?)\s-\s(.+\s*.+)"); // Run through all found groups. Group - (). Regex online: https://regexr.com/ string price = match.Groups[5].Value; // Need to get rid of (,) otherwise double.parse throws a error //price = price.Replace('.', ','); // , Replace. Can be used in differen cultures enviroment string message_text = match.Groups[6].Value; // Need to get rid of (') because when sentence "i don't need it" goes to SQL query (') it interpreted as a an escape symbol message_text = message_text.Replace('\'', '*'); // Remove \ symbols from the parsed string. Otherwise - SQL error message_text = message_text.Truncate_x(255); // Crop the string to not longer than 255 sybols. Otherwise - SQL error // Last message date detection. When new message appears - its date must be > than current. For this purpuse we need to record the date ol last detected message // ! = "" There are other empty classes on the page. There are no message in them. Pass them if (match.Groups[1].Value != "" && filter_couner < 5) // Read only 5 messages. Messgaes that are later than 5th belong to 2017. We do not need to read 2017 { //Console.WriteLine("msg num***: " + filter_couner + "\nTRACE\nDate: " + match.Groups[1].Value + "\nDirection: " + match.Groups[2].Value + "\nQuantity: " + match.Groups[3].Value + "\nTicker: " + match.Groups[4].Value + "\nPrice: " + Double.Parse(price)); filter_couner++; if (firstRunFlag) { lastMessageDate = DateTime.ParseExact(match.Groups[1].Value, "M/d h:mm:ss tt", CultureInfo.InvariantCulture); //Console.WriteLine("Tracking messages started. First run. Last message date: " + match.Groups[1].Value); ListViewLogging.log_add(form, "parserListBox", "GetAndTrackMessages.cs", "Tracking messages started. First run. Last message date: " + match.Groups[1].Value, "white"); firstRunFlag = false; ListViewLogging.log_add(form, "parserListBox", "GetAndTrackMessages.cs", "Date added. New added message with date later than this is considered as new: " + GetAndTrackMMessages.lastMessageDate.AddMinutes(1).ToString("h:mm:ss tt"), "white"); ListViewLogging.log_add(form, "parserListBox", "GetAndTrackMessages.cs", "Last message parsing example. This output must be the same as the message at the page. Is everything correct?\nDate: " + match.Groups[1].Value + "\nDirection: " + match.Groups[2].Value + "\nQuantity: " + match.Groups[3].Value + "\nTicker: " + match.Groups[4].Value + "\nPrice: " + Double.Parse(price), "white"); //Console.WriteLine("Date added. New added message with date later than this is considered as new: " + GetAndTrackMMessages.lastMessageDate.AddMinutes(1).ToString("h:mm:ss tt")); // DateTime.Now.Date.ToString("MM/dd/yyyy") //Console.WriteLine("Last message parsing example. This output must be the same as the message at the page. Is everything correct?\nDate: " + match.Groups[1].Value + "\nDirection: " + match.Groups[2].Value + "\nQuantity: " + match.Groups[3].Value + "\nTicker: " + match.Groups[4].Value + "\nPrice: " + Double.Parse(price)); } // New message detected. Message date > lastMessageDate DateTime h = DateTime.ParseExact(match.Groups[1].Value, "M/d h:mm:ss tt", CultureInfo.InvariantCulture); //Console.WriteLine("TRACE: DateTime.Compare(h, lastMessageDate) > 0: " + (DateTime.Compare(h, lastMessageDate) > 0) + ". h: " + h + ". lastMessageDate: " + lastMessageDate); if (DateTime.Compare(h, lastMessageDate) > 0) { ListViewLogging.log_add(form, "parserListBox", "GetAndTrackMessages.cs", "New message on the page is detected!", "white"); lastMessageDate = DateTime.ParseExact(match.Groups[1].Value, "M/d h:mm:ss tt", CultureInfo.InvariantCulture); // Bought if (match.Groups[2].Value == "Bought" && bougtMessageFlag == true) { ListViewLogging.log_add(form, "parserListBox", "GetAndTrackMessages.cs", "********************ACTION: Bought", "green"); bougtMessageFlag = false; messageTicker = match.Groups[4].Value; // DB Actions DataBase.InsertTicker(match.Groups[4].Value); // Added ticker, record created then update it DataBase.UpdateRecordOpenPosition("open", "long", DateTime.ParseExact(match.Groups[1].Value, "M/d h:mm:ss tt", CultureInfo.InvariantCulture), Double.Parse(price), 0, 0, 0, 0, 0, message_text); messageSoldVolume = Int32.Parse(match.Groups[3].Value); // Boroker actions form.placeOrder.SendOrder("buy", match.Groups[4].Value); // Send BUY order to the exchange Email.Send("Bought action. Ticker: " + match.Groups[4].Value + ". PLEASE CHECK THE ACCOUNT!!! "); } //Console.WriteLine("TRACE: sold: " + match.Groups[2].Value + " ticker: " + messageTicker + " current ticker: " + match.Groups[4].Value + " boughMessageFlag: " + bougtMessageFlag); // Sold if (match.Groups[2].Value == "Sold" && messageTicker == match.Groups[4].Value && bougtMessageFlag == false) { ListViewLogging.log_add(form, "parserListBox", "GetAndTrackMessages.cs", "********************ACTION: Sold", "red"); bougtMessageFlag = true; // DB Actions DataBase.UpdateRecordClosePosition(DateTime.ParseExact(match.Groups[1].Value, "M/d h:mm:ss tt", CultureInfo.InvariantCulture), messageSoldVolume, Double.Parse(price), message_text); DataBase.UpdateProfit(); // Uptade profit and calculate values messageSoldVolume = 0; // Set volume to 0. If Sold signal occured - we need to start increment volume from scratch // Boroker actions MessageBox.Show("sold"); form.placeOrder.SendOrder("sell", match.Groups[4].Value); // Send SELL order to the exchange Email.Send("Sold action. Ticker: " + match.Groups[4].Value + ". PLEASE CHECK THE ACCOUNT!!! "); } } } /* * * // Open message appeared * if (match.Groups[2].Value == "Bought" && bougtMessageFlag) * { * bougtMessageFlag = false; // Next cycle run dont go into this if until Sold message is receive * messageTicker = match.Groups[4].Value; * Console.WriteLine("Bought detected. Ticker: " + match.Groups[4].Value); * } * * // Sold message appeared * if (match.Groups[2].Value == "Sold" && match.Groups[4].Value == messageTicker) * { * bougtMessageFlag = true; // Next cycle run go into Bought message if * //messageTicker = match.Groups[4].Value; * Console.WriteLine("Close detected. Ticker: " + match.Groups[4].Value); * } * * // Condition: direction is Bought, we must start with only Sold message, we must follow the secuence with the same ticker excluding different tickers. The sequence (ticker) resets at the bought message * if (match.Groups[2].Value == "Bought" && !boughtFirstTIme && messageTicker == match.Groups[4].Value) * { * DataBase.UpdateRecordOpenPosition(DateTime.ParseExact(match.Groups[1].Value, "M/d h:mm:ss tt", CultureInfo.InvariantCulture), Double.Parse(price), 0, 0, 0, 0, 0, message_text); * DataBase.UpdateProfit(); // Uptade profit and calculate values * soldFlag = true; // Set soldFlag to true. Means that series of sold messages is over an bought message accured. Sold, Sold, Bought. Next sold will have to add ticker * messageSoldVolume = 0; // Set volume to 0. If Bought signal occured - we need to start increment volume from scratch * messageTicker = ""; // Reset ticker * } * * // Condition: sell message and ticker is the same as in the first Sold message. We need this in order to pass other tickers in middle of the secuence * // There may be other messages with different ticker between Sold and other Solds messages - dont count them. * if (match.Groups[2].Value == "Sold" && (messageTicker == match.Groups[4].Value || messageTicker == "")) * { * if (soldFlag) // If series of Sold messages occures - add ticker to DB only ones at the first message * { * messageTicker = match.Groups[4].Value;// remember ticker * DataBase.InsertTicker(match.Groups[4].Value); // Added ticker, record created then update it * soldFlag = false; * } * * // At each occurance of sold message - update a recoed * // Update close position no matter whether it is the only message or the series * messageSoldVolume = messageSoldVolume + Int32.Parse(match.Groups[3].Value); // * DataBase.UpdateRecordClosePosition("closed", "long", DateTime.ParseExact(match.Groups[1].Value, "M/d h:mm:ss tt", CultureInfo.InvariantCulture), messageSoldVolume, Double.Parse(price), message_text); // match.Groups[6].Value * boughtFirstTIme = false; // We start from bought message the go to Bought * } * * i++; * */ //Console.ReadLine(); } catch { Console.WriteLine("Regex error. Nothing to parse or content can't be parsed using existing regex"); } } } catch // var InputString { Console.WriteLine("Regex error. Chrome browser window is closed? Restart the program"); } } }