示例#1
0
文件: Form1.cs 项目: dacoders77/tbr
        private void IbClient_Error(int arg1, int arg2, string arg3, Exception arg4) // Errors handling event
        {
            if (arg4 != null)                                                        // Show exception if it is not null. There are errors with no exceptions
            {
                MessageBox.Show(
                    "Form1.cs line 173. IbClient_Error" +
                    "link: " + arg4.HelpLink + "\r" +
                    "result" + arg4.HResult + "\r" +
                    "inner exception: " + arg4.InnerException + "\r" +
                    "message: " + arg4.Message + "\r" +
                    "source: " + arg4.Source + "\r" +
                    "stack trace: " + arg4.StackTrace + "\r" +
                    "target site: " + arg4.TargetSite + "\r"
                    );
            }

            // Must be carefull with these ticks! While debugging - disable this filter. Otherwise you can miss important information
            // https://interactivebrokers.github.io/tws-api/message_codes.html
            // 2104 - A market data farm is connected.
            // 2108 - A market data farm connection has become inactive but should be available upon demand.
            // 2106 - A historical data farm is connected.
            // 10167 - Requested market data is not subscribed. Displaying delayed market data
            // .. Not all codes are listed

            if (arg2 != 2104 && arg2 != 2119 && arg2 != 2108 && arg2 != 2106 && arg2 != 10167)
            //if (true)
            {
                // arg1 - requestId
                ListViewLog.AddRecord(this, "brokerListBox", "Form1.cs", "IbClient_Error: args: " + arg1 + " " + arg2 + " " + arg3 + "exception: " + arg4, "white");
                // id, code, text

                // A error can triggerd by any request: fx, quote or place order. Use place order for now
                basket.UpdateInfoJson(string.Format("Place order error! Error text: {2} . Error code:{1}  RequestID: {0}. ibClient.NextOrderId: {3}", arg1, arg2, arg3, ibClient.NextOrderId), "placeOrder", "error", arg1, "placeorder_request_id");                 // Update json info feild in DB
            }
        }
示例#2
0
        private void UpdatePlaceOrderStatus(int basketId, string symbol, int requestId, string currency, int volume)
        {
            using (var mySqlConnection = new MySqlConnection(connectionString))
            {
                if (mySqlConnection.State == System.Data.ConnectionState.Closed)
                {
                    mySqlConnection.Open();                     // If no connection to DB
                }
                else
                {
                    Console.WriteLine("BasketWatch.cs. Line 347. Connection state: " + dbConn.State + " .Connection open, no need to connect");
                }

                sqlQueryString = string.Format("UPDATE assets SET placeorder_request_id = {0}, order_placed = 1 WHERE basket_id = {1} AND symbol = '{2}' ", requestId, basketId, symbol);
                MySqlCommand updateRequestId = new MySqlCommand(sqlQueryString, mySqlConnection);
                updateRequestId.ExecuteNonQuery();
                mySqlConnection.Close();

                // Place order
                // MessageBox.Show("Basket.cs line 369. requestId: " + requestId);

                ListViewLog.AddRecord(form, "brokerListBox", "Basket.cs", "Line 371. Place order requestId :  " + requestId, "yellow");
                form.apiManager.PlaceOrder(symbol, currency, volume, requestId);
            }
        }
示例#3
0
文件: Form1.cs 项目: dacoders77/tbr
        private void IbClient_ContractDetailsEnd(int obj)         // When a search response is finished
        {
            ListViewLog.AddRecord(this, "brokerListBox", "Form1.cs", "IbClient_ContractDetailsEnd. Search response finished ", "white");
            foreach (var socket in allSockets.ToList())             // Loop through all connections/connected clients and send each of them a message
            {
                socket.Send(searchResponse.ReturnJson());
            }
            searchResponse.searchResponseList.Clear();             // Erase all elements after it was transmitted to the websocket connection

            //Console.WriteLine("contract end: " + searchResponse.ReturnJson()); // searchResponse
        }
示例#4
0
文件: Form1.cs 项目: dacoders77/tbr
        private void IbClient_UpdateAccountValue(IBSampleApp.messages.AccountValueMessage obj)         // Account info event. https://interactivebrokers.github.io/tws-api/interfaceIBApi_1_1EWrapper.html#ae15a34084d9f26f279abd0bdeab1b9b5
        {
            if (obj.Key == "AvailableFunds-S")
            {
                ListViewLog.AddRecord(this, "brokerListBox", "Form1.cs", "UpdateAccountValue: " + obj.Key + " " + obj.Value, "white");
                availableFundsResponse.availableFunds = Convert.ToDouble(obj.Value);

                foreach (var socket in allSockets.ToList())                 // Loop through all connections/connected clients and send each of them a message
                {
                    socket.Send(availableFundsResponse.ReturnJson());
                }
            }
            ibClient.ClientSocket.reqAccountUpdates(false, "U2314623");             // Unsubscribe. Otherwise on the next call it is not gonna work
        }
示例#5
0
文件: Form1.cs 项目: dacoders77/tbr
        private void button13_Click(object sender, EventArgs e) // Api connect button click
        {
            if (!isConnected)                                   // False on startup
            {
                try
                {
                    ibClient.ClientId = 2;                     // 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");
            }
        }
示例#6
0
文件: Form1.cs 项目: dacoders77/tbr
        private void IbClient_TickPrice(IBSampleApp.messages.TickPriceMessage obj)            // ReqMktData. Get quote. Tick types https://interactivebrokers.github.io/tws-api/rtd_simple_syntax.html
        {
            char requestCode = obj.RequestId.ToString()[obj.RequestId.ToString().Length - 1]; // First char is the code. C# requests: 5 - fx, 6 - stock. PHP: 7 - stock


            // Tick types: Close - for FX quotes. DelayedCLose - for stock quotes
            //ListViewLog.AddRecord(this, "brokerListBox", "Form1.cs line 215", "IbClient_TickPrice. Price " + obj.Price + " requestId: " + obj.RequestId + " tick type: " + TickType.getField(obj.Field), "yellow");

            // FX quote. C# while executing a basket
            // When a fx quote is received, ExecuteBasketThread() checks it and requests a stock quote
            if (TickType.getField(obj.Field) == "close")             // bidPrice = -1. This value returned when market is closed. https://interactivebrokers.github.io/tws-api/md_receive.html
            {
                basket.assetForexQuote = obj.Price;
                ListViewLog.AddRecord(this, "brokerListBox", "Form1.cs line 210", "IbClient_TickPrice. FX Quote: " + obj.Price + " " + obj.RequestId, "yellow");

                basket.UpdateInfoJson(string.Format("FX quote successfully recevied. FX quote: {0}. RequestID: {1}", obj.Price, obj.RequestId), "fxQuoteRequest", "ok", obj.RequestId, "fx_request_id"); // Update json info feild in DB
                basket.addForexQuoteToDB(obj.RequestId, obj.Price);                                                                                                                                      // Update fx quote in the BD
            }


            // For stock. A request from PHP. While adding an asset to a basket
            // In this case we do not record this price to the DB. It is recorded from PHP
            if (TickType.getField(obj.Field) == "delayedLast" && requestCode.ToString() == "7")             // PHP. Stock quote request
            {
                ListViewLog.AddRecord(this, "brokerListBox", "Form1.cs line 221", "IbClient_TickPrice. PHP req. price: " + obj.Price + " reqId: " + obj.RequestId, "white");

                quoteResponse.symbolPrice = obj.Price;
                quoteResponse.symbolName  = apiManager.symbolPass;          // We have to store symbol name and basket number as apiManager fields. Symbol name is not returned with IbClient_TickPrice response as well as basket number. Then basket number will be returnet to php and passed as the parameter to Quote.php class where price field will be updated. Symbol name and basket number are the key
                quoteResponse.basketNum   = apiManager.basketNumber;        // Pass basket number to api manager. First basket number was assigned to a class field basketNumber of apiManager class

                foreach (var socket in allSockets.ToList())                 // Loop through all connections/connected clients and send each of them a message
                {
                    socket.Send(quoteResponse.ReturnJson());
                }
            }


            // C#. ApiManager stock quote request
            if (TickType.getField(obj.Field) == "delayedLast" && requestCode.ToString() == "6")
            {
                // Updte quote value in DB
                basket.UpdateStockQuoteValue(obj.RequestId, obj.Price, this);
                ListViewLog.AddRecord(this, "brokerListBox", "Form1.cs", "IbClient_TickPrice. C# 6 req. price: " + obj.Price + " " + obj.RequestId, "white");

                basket.UpdateInfoJson(string.Format("Stock quote successfully recevied. Stock quote: {0}. RequestID: {1}", obj.Price, obj.RequestId), "stockQuoteRequest", "ok", obj.RequestId, "quote_request_id");                 // Update json info feild in DB
            }
        }
示例#7
0
文件: Form1.cs 项目: dacoders77/tbr
        private void IbClient_NextValidId(IBSampleApp.messages.ConnectionStatusMessage obj) // Api connection established
        {
            initialNextValidOrderID = ibClient.NextOrderId;                                 // Get initial value once. Then this value vill be encreased

            ListViewLog.AddRecord(this, "brokerListBox", "Form1.cs", "API connected: " + obj.IsConnected + " Next valid req id: " + ibClient.NextOrderId, "white");

            // 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

            isConnected = true;
            if (obj.IsConnected)
            {
                status_CT.Text = "Connected";
                button13.Text  = "Disconnect";
            }
            // 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
        }
示例#8
0
        // Cleare baskets table executed row. Used for basket force execution. DEBUG ONLY!
        public void ClearBasketsExecutedColumn()
        {
            ListViewLog.AddRecord(form, "brokerListBox", "Basket.cs", "Line 567. Basket executed table row reseted to 0", "white");
            using (var mySqlConnection = new MySqlConnection(connectionString))
            {
                if (mySqlConnection.State == System.Data.ConnectionState.Closed)
                {
                    mySqlConnection.Open();                     // If no connection to DB
                }
                else
                {
                    Console.WriteLine("Basket.cs. Line 562. Connection state: " + dbConn.State + " .Connection open, no need to connect");
                }

                sqlQueryString = string.Format("UPDATE baskets SET executed = 0");

                MySqlCommand updateFxQuote = new MySqlCommand(sqlQueryString, mySqlConnection);                 // Use the connection opened in the constructor
                updateFxQuote.ExecuteNonQuery();
                mySqlConnection.Close();
            }
        }
示例#9
0
        // Clear DB quotes. Dubug only
        public void ClearQuotesDB()
        {
            ListViewLog.AddRecord(form, "brokerListBox", "Basket.cs", "Line 544. Quotes in assets table cleared", "white");
            using (var mySqlConnection = new MySqlConnection(connectionString))
            {
                if (mySqlConnection.State == System.Data.ConnectionState.Closed)
                {
                    mySqlConnection.Open();                     // If no connection to DB
                }
                else
                {
                    Console.WriteLine("Basket.cs. Line 531. Connection state: " + dbConn.State + " .Connection open, no need to connect");
                }

                string blankJson = "{\"placeOrder\": {\"log\": \"\", \"status\": \"\"}, \"executeOrder\": {\"log\": \"\", \"filled\": \"\", \"status\": \"\", \"avgFillprice\": \"\"}, \"fxQuoteRequest\": {\"log\": \"\", \"status\": \"\"}, \"volumeCalculate\": {\"log\": \"\", \"status\": \"\"}, \"stockQuoteRequest\": {\"log\": \"\", \"status\": \"\"}}";
                sqlQueryString = string.Format("UPDATE assets SET stock_quote = 0, fx_quote = 0, fx_quote_processed = 0, fx_quote = 0, volume = 0, fx_request_id = 0, quote_request_id = 0, placeorder_request_id = 0, order_placed = 0, info = '{0}' ", blankJson);

                MySqlCommand updateFxQuote = new MySqlCommand(sqlQueryString, mySqlConnection);
                updateFxQuote.ExecuteNonQuery();
                mySqlConnection.Close();
            }
        }
示例#10
0
文件: Form1.cs 项目: dacoders77/tbr
        private void IbClient_ContractDetails(IBSampleApp.messages.ContractDetailsMessage obj)         // Ticker search event reqContractDetails
        {
            ListViewLog.AddRecord(this, "brokerListBox", "Form1.cs", "Ticker search: IbClient_ContractDetails: " +
                                  obj.ContractDetails.Summary.Exchange + " " +
                                  obj.ContractDetails.Summary.LocalSymbol + " " +
                                  obj.ContractDetails.Summary.SecType + " " +
                                  obj.ContractDetails.Summary.Currency + " " +
                                  obj.ContractDetails.Summary.Exchange + " " +
                                  obj.ContractDetails.Summary.PrimaryExch + " " +
                                  obj.ContractDetails.LongName, "white");

            // Add all returned values as the element to the collection which will be transformed to json
            searchResponse.searchResponseList.Add(new SearchResponseString
            {
                symbol          = obj.ContractDetails.Summary.Symbol,
                localSymbol     = obj.ContractDetails.Summary.LocalSymbol,
                type            = obj.ContractDetails.Summary.SecType,
                currency        = obj.ContractDetails.Summary.Currency,
                exchange        = obj.ContractDetails.Summary.Exchange,
                primaryExchnage = obj.ContractDetails.Summary.PrimaryExch,
                conId           = obj.ContractDetails.Summary.ConId,
                longName        = obj.ContractDetails.LongName
            });
        }
示例#11
0
文件: Form1.cs 项目: dacoders77/tbr
        private void search_Button2_Click(object sender, EventArgs e)         // Ticker search button click
        {
            ListViewLog.AddRecord(this, "brokerListBox", "Form1.cs", "Connection status: " + ibClient.ClientSocket.CheckConnection().ToString(), (ibClient.ClientSocket.CheckConnection() ? "white" : "red"));

            apiManager.Search(textBox1.Text);
        }
示例#12
0
文件: Form1.cs 项目: dacoders77/tbr
 private void IbClient_CurrentTime(long obj)         // Get exchnage current time event
 {
     ListViewLog.AddRecord(this, "brokerListBox", "Form1.cs", "Exchange current time:" + UnixTimeStampToDateTime(obj).ToString(), "white");
 }
示例#13
0
文件: Form1.cs 项目: dacoders77/tbr
        private void IbClient_OrderStatus(IBSampleApp.messages.OrderStatusMessage obj)
        {
            ListViewLog.AddRecord(this, "brokerListBox", "Form1.cs", "IbClient_OrderStatus. line 153. avgFillprice, filled, orderID, orderStatus: " + obj.AvgFillPrice + " | " + obj.Filled + " | " + obj.OrderId + " | " + obj.Status, "white");

            basket.UpdateInfoJsonExecuteOrder(string.Format("Order executed! Info text: {0}", obj.Status), "executeOrder", "ok", obj.OrderId, obj.AvgFillPrice, obj.Filled);             // Update json info feild in DB
        }