public static void Inject(string messageType, Form1 form) { // US culture is used. Must be carefull with it! DB Convert.ToDouble(command1.ExecuteScalar()) // 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 = form.parser.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": 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 2 of $" + symbol + " at 21.45 - text message'); var list = document.getElementById('x-auto-1'); list.insertBefore(newItem, list.childNodes[0]);"; //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>05/17 " + appendedTime + " - Bought 6500 of $FUSZ at 1.33 - I sold some...'); var list = document.getElementById('x-auto-1'); list.insertBefore(newItem, list.childNodes[0]);"; break; case "sold": 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 22.18 - text message'); var list = document.getElementById('x-auto-1'); list.insertBefore(newItem, list.childNodes[0]);"; break; case "else": 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) { ListViewLog.AddRecord(form, "parserListBox", "TestMessage.cs", "Error: " + err, "red"); } }
private void IbClient_MarketDataType(IBSampleApp.messages.MarketDataTypeMessage obj) // Market data type request event { if (obj.MarketDataType == 3) { ListViewLog.AddRecord(this, "brokerListBox", "Form1.cs", "IbClient_MarketDataType: " + obj.MarketDataType + ". Delayed market data type", "white"); } }
private void Form1_Load(object sender, EventArgs e) { ListViewLog.AddRecord(this, "parserListBox", "Form1.cs", "Current culture:" + CultureInfo.CurrentCulture.Name, "white"); ListViewLog.AddRecord(this, "parserListBox", "Form1.cs", "Version: 24/05/2018 07:13PM", "white"); ChromeDriver.Navigate().GoToUrl("https://profit.ly/profiding"); // Go to URL file:///D:/1/profitly.html https://profit.ly/profiding //ChromeDriver.Navigate().GoToUrl("file:///D:/1/profitly2.html"); // }
private void IbClient_NextValidId(IBSampleApp.messages.ConnectionStatusMessage obj) // Api is connected { //MessageBox.Show("IbClient_NextValidId"); // 1 - Realtime, 2 - Frozen, 3 - Delayed data, 4 - Delayed frozen ibClient.ClientSocket.reqMarketDataType(3); // https://interactivebrokers.github.io/tws-api/classIBApi_1_1EClient.html#ae03b31bb2702ba519ed63c46455872b6 ListViewLog.AddRecord(this, "brokerListBox", "Form1.cs", "API connected: " + obj.IsConnected, "white"); isConnected = true; if (obj.IsConnected) { status_CT.Text = "Connected"; button13.Text = "Disconnect"; } }
private void button13_Click(object sender, EventArgs e) // Api connect { if (!isConnected) // False on startup { try { ibClient.ClientId = 1; // Client id. Multiple clients can be connected to the same gateway with the same login/password ibClient.ClientSocket.eConnect("127.0.0.1", Settings.ibGateWayPort, ibClient.ClientId); //Create a reader to consume messages from the TWS. The EReader will consume the incoming messages and put them in a queue var reader = new EReader(ibClient.ClientSocket, signal); reader.Start(); //Once the messages are in the queue, an additional thread can be created to fetch them 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 exception) { ListViewLog.AddRecord(this, "brokerListBox", "Form1.cs", "Check your connection credentials. Exception: " + exception, "white"); } try { ibClient.ClientSocket.reqCurrentTime(); } catch (Exception exception) { ListViewLog.AddRecord(this, "brokerListBox", "Form1.cs", "req time. Exception: " + exception, "white"); } } else { isConnected = false; ibClient.ClientSocket.eDisconnect(); status_CT.Text = "Disconnected"; button13.Text = "Connect"; ListViewLog.AddRecord(this, "brokerListBox", "Form1.cs", "Disconnecting..", "white"); } }
private void IbClient_TickPrice(IBSampleApp.messages.TickPriceMessage msg) // reqMktData event. reqMarketData Request market data event { //ListViewLog.AddRecord(this, "brokerListBox", "Form1.cs", "TickPriceMessage. tick type: " + TickType.getField(msg.Field) + " price: " + msg.Price, "white"); if (TickType.getField(msg.Field) == "delayedLast") { double calculatedVolume = Settings.useFunds / (double)msg.Price; int calculatedVolumeRounded = (int)Math.Floor(calculatedVolume); ListViewLog.AddRecord(this, "brokerListBox", "Form1.cs", "IbClient_TickPrice. Funds to use: " + Settings.useFunds + "$ Ticker: " + parser.contractParser.Symbol + " Price: " + msg.Price + " Calculated volume (not rounded): " + calculatedVolume + " Rounded: " + calculatedVolumeRounded, "white"); Email.Send("Volume", "Funds to use: " + Settings.useFunds + "$ Ticker: " + parser.contractParser.Symbol + " Price: " + msg.Price + " Calculated volume (no round): " + calculatedVolume + " Rounded: " + calculatedVolumeRounded); // SEND ORDER GOES HERE (close orders is sent from parser when close signal is detected) apiManager.symbol = parser.contractParser.Symbol; apiManager.volume = calculatedVolumeRounded; apiManager.direction = "BUY"; apiManager.PlaceOrder(); } }
public void MessageSearch() { while (true) // Endless cycle. Each iteration reads the page content { System.Threading.Thread.Sleep(1000); // The delay between each page parse. 1000 - 1 sec //ListViewLogging.log_add(form, "parser.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, "parser.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) { goToFavTabDateTime = DateTime.Now; Navigation.FavoriteTabClick(); // Go to favorite tab and back in order to prevent outomatic logoff due to inactivity } if ((DateTime.Compare(DateTime.Now, goToTradesDateTime) > 0) && startTracking) // Go back to trades tab after a short delay { goToTradesDateTime = DateTime.Now; Navigation.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"); var InputString = Form1.ChromeDriver.FindElementsByCssSelector(".GLS-JUXDFAD"); //ListViewLog.AddRecord(form, "parserListBox", "parser.cs", "parsed with css: " + InputString.ToString(), "white"); //ListViewLog.AddRecord(form, "parserListBox", "parser.cs", "type: " + InputString2.GetType(), "white"); 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 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 when string is longer than 255 symbols // 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); ListViewLog.AddRecord(form, "parserListBox", "parser.cs", "Tracking messages started. First run. Last message date: " + match.Groups[1].Value, "white"); firstRunFlag = false; ListViewLog.AddRecord(form, "parserListBox", "parser.cs", "Date added. New added message with date later than this is considered as new: " + lastMessageDate.AddMinutes(1).ToString("h:mm:ss tt"), "white"); ListViewLog.AddRecord(form, "parserListBox", "parser.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) { ListViewLog.AddRecord(form, "parserListBox", "parser.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) { ListViewLog.AddRecord(form, "parserListBox", "parser.cs", "********************ACTION: Bought", "green"); bougtMessageFlag = false; messageTicker = match.Groups[4].Value; //form.textBox2.Text = messageTicker; // Error is thrown. When this line is uncommet - page can not be parsed using existing regex // 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", "Bought action. Ticker: " + match.Groups[4].Value + ". Parsed price: " + Double.Parse(price)); // Add ticker to the contract contractParser.Symbol = match.Groups[4].Value; // Call request market data method. Created contract with a ticker is passed as a parameter form.reqMarketDataParser(contractParser); } //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) { ListViewLog.AddRecord(form, "parserListBox", "parser.cs", "********************ACTION: Sold", "red"); bougtMessageFlag = true; //form.textBox2.Text = ""; // 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 and calculate values messageSoldVolume = 0; // Set volume to profit0. If Sold signal occured - we need to start increment volume from scratch // Boroker actions //form.placeOrder.SendOrder("sell", match.Groups[4].Value); // Send SELL order to the exchange Email.Send("Sold", "Sold action. Ticker: " + match.Groups[4].Value + ". Parsed price: " + Double.Parse(price)); // Add ticker to the contract //contractParser.Symbol = match.Groups[4].Value; // Call request market data method. Created contract with a ticker is passed as a parameter //form.reqMarketDataParser(contractParser); // CLOSE ORDER form.apiManager.direction = "SELL"; form.apiManager.PlaceOrder(); } } } } catch { ListViewLog.AddRecord(form, "parserListBox", "Parser.cs", "Regex error. Nothing to parse or content can't be parsed using existing regex", "red"); ListViewLog.AddRecord(form, "parserListBox", "Parser.cs", "Parsed string: " + z, "red"); // ADD ALERT EMAIL HERE Email.Send("Regex error", "Parser.cs, Regex error.Nothing to parse or content cant be parsed using existing regex. Parsed string: " + z); //Environment.Exit(1); // Die System.Windows.Forms.MessageBox.Show("Parser.cs regex error line 213. parsed string: " + z); } } // for } catch // var InputString { ListViewLog.AddRecord(form, "parserListBox", "Parser.cs", "Regex error. Chrome browser window is closed? Restart the program", "red"); // ADD ALERT EMAIL HERE Email.Send("Regex erro. No window", "Parser.cs, Regex error.Nothing to parse or content cant be parsed using existing regex"); //Environment.Exit(1); // Die System.Windows.Forms.MessageBox.Show("Parser.cs regex error2 line 223"); } } }
private void IbClient_Error(int arg1, int arg2, string arg3, Exception arg4) // Errors handling event { ListViewLog.AddRecord(this, "brokerListBox", "Form1.cs", "IbClient_Error: arg 1,2,3: " + arg1 + " " + arg2 + " " + arg3 + "exception: " + arg4, "white"); }
private void IbClient_CurrentTime(long obj) // Current exchange time request event { ListViewLog.AddRecord(this, "brokerListBox", "Form1.cs", "Exchange current time:" + UnixTimeStampToDateTime(obj).ToString(), "white"); }
private void IbClient_OrderStatus(IBSampleApp.messages.OrderStatusMessage obj) // Order status. Fires up when the order is executed { ListViewLog.AddRecord(this, "brokerListBox", "Form1.cs", "Order status. AvgFillPrice: " + obj.AvgFillPrice, "white"); Email.Send("Order status", "Order status. AvgFillPrice: " + obj.AvgFillPrice); }