Thursday, 23 June 2016

VB Trading Platform updateportfolio 5

Make this a global variable place it a the top of the Public Class Form1
 Public timer1_counter As Integer = 5 ' used to count down 5 tenths of a second  
Place this code at the beginning of the cbSymbol_keyDown event
 AxTws1.reqAccountUpdates(0, "DU132564") ' number zero cancels request  
Place this code at the end of the cbSymbol keyDown event for the
 AxTws1.reqAccountUpdates(1, "DU132564") ' number 1 requests account updates  
 Timer1.Start() ' starts the count down timer  
 

Capture2

 

 

 

 

 

 

 

 

numLimitPrice KeyDown Event
 Private Sub numPrice_KeyDown(sender As Object, e As KeyEventArgs) Handles numPrice.KeyDown  
     numPrice.DecimalPlaces = 2  
     numPrice.Increment = 0.1  
   End Sub  
numLimitPrice Keyup Event
 Private Sub numPrice_KeyUp(sender As Object, e As KeyEventArgs) Handles numPrice.KeyUp  
     numPrice.DecimalPlaces = 2  
     numPrice.Increment = 0.01  
   End Sub  
Tick Event
 Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick  
     ' checks if the timer = 0  
     If (timer1_counter = 0) Then  
       ' puts the value of Bid from the text box into the limit price numericUpDown  
       numPrice.Value = Double.Parse(tbBid.Text)  
       Timer1.Stop() ' Stops the timer  
       timer1_counter = 5 ' resets the counter to 5  
     End If  
     ' counter counts down 1 every tick  
     timer1_counter -= 1  
   End Sub  
[showhide type="links2" more_text=" * Show the code for updatePortfolioEx click here" less_text=" * Hide the code for updatePortfolioEx click here"]
  Private Sub AxTws1_updatePortfolioEx(sender As Object, e As AxTWSLib._DTwsEvents_updatePortfolioExEvent) Handles AxTws1.updatePortfolioEx  
     Dim theSymbol1 As String  
     theSymbol1 = e.contract.symbol  
     ' e.averageCost  
     ' e.marketValue   
     ' e.realizedPNL    
     ' e.unrealizedPNL  
     ' e.position  
     ' e.marketValue  
     ' e.contract.symbol = stock symbol  
     ' if the symbol in the combo box is the same as the e.contract.symbol  
     ' then add the Position size and the average price to the text boxes  
     If theSymbol1 = cbSymbol.Text Then  
       ' Gets the average price of the current symbol  
       Dim averagePrice As Double = e.averageCost  
       'Rounds off the current price adds it to the text box  
       tbAvgPrice.Text = averagePrice.ToString("0.00")  
       ' puts the position size in the text box  
       tbPosition.Text = e.position.ToString()  
     End If  
   End Sub  
[/showhide]



 








Monday, 20 June 2016

VB Trading Platform How to send order 4

VB Trading platform - place order
  • Place order to buy or sell.
  • Add a buy, and sell button.
  • Get the nextValidId, and increase the next valid id by 1 every time an order to buy or sell is placed.
Add 2 buttons and change the properties as follows:
Name = btnBuy - Text = BUY
Name = btnSell - Text = SELL
 Private Sub btnSell_Click(sender As Object, e As EventArgs) Handles btnSell.Click  
     Dim strAction = "SELL"  
     'calls the order method to send the order to SELL  
     Call DoOrder(strAction)  
   End Sub  
 Private Sub btnSell_Click(sender As Object, e As EventArgs) Handles btnBuy.Click  
     Dim strAction = "BUY"  
     'calls the order method to send the order to SELL  
     Call DoOrder(strAction)  
   End Sub  

 Private Sub DoOrder(strAction As String)  
     ' variable to hold the contract information  
     Dim ContractInfo As TWSLib.IContract  
     ' variable to hold the order information  
     Dim OrderInfo As TWSLib.IOrder  
     ' Create a contract to represent the data we request  
     ContractInfo = AxTws1.createContract()  
     ' Create new order Object  
     OrderInfo = AxTws1.createOrder()  
     ' Now fill the ContractInfo object with the necessary information   
     ContractInfo.conId = 0    ' identifier  
     ' Stock symbol  
     ContractInfo.symbol = cbSymbol.Text  
     ' Security Type: Stock=STK, Option=OPT, Future=FUT, etc.  
     ContractInfo.secType = "STK"  
     ' The destination of order or request. "SMART" =IB order router  
     ContractInfo.exchange = "SMART"  
     ' The primary exchange where the instrument trades.   
     ContractInfo.primaryExchange = "NASDAQ"  
     ' The currency USD or GBP or CAD or EUR, etc.  
     ContractInfo.currency = "USD"  
     ' orderId is a *Unique* order identifier  
     OrderInfo.orderId = orderId  
     ' action will be BUY, SELL or SSHORT  
     OrderInfo.action = strAction  
     'totalQuantity is the number of shares (or contracts)  
     OrderInfo.totalQuantity = Integer.Parse(numQuantity.Value)  
     'orderType is one of the following MKT, LMT, STP, etc.  
     OrderInfo.orderType = cbOrderType.Text  
     'lmtPrice is the limit price for a limit order  
     OrderInfo.lmtPrice = numPrice.Value  
     'timeInForce is either DAY, GTC, IOC etc.  
     OrderInfo.timeInForce = cbTIF.Text  
     ' There are many other properties for different order types...  
     ' We don't need to specify them in this case  
     ' Submit the order. Parameters are  
     ' OrderId  - A different identifier for each order  
     ' Contract  - An object specifying the security to be ordered  
     ' OrderInfo - An object specifying the type, quantity, side and other order parameters  
     AxTws1.placeOrderEx(orderId, ContractInfo, OrderInfo)  
     'increases the order id by 1  
     orderId += 1  
   End Sub  

VBTradingForm4



















Make sure you add a public variable just under Public Class Form1 near the top of the class
 Public orderId As Integer = 0  
nextValidId Event
 Private Sub AxTws1_nextValidId(sender As Object, e As AxTWSLib._DTwsEvents_nextValidIdEvent) Handles AxTws1.nextValidId  
     ' sets the next order id number  
     orderId = e.id  
   End Sub  
Click Event
  Private Sub tbBid_Click(sender As Object, e As EventArgs) Handles tbBid.Click  
     'set the Bid price in the limit price text box  
     numPrice.Value = Double.Parse(tbBid.Text)  
   End Sub  
Click Event
 Private Sub tbAsk_Click(sender As Object, e As EventArgs) Handles tbAsk.Click  
     'set the Ask price in the limit price text box  
     numPrice.Value = Double.Parse(tbAsk.Text) 
   End Sub  











ib api ib api ib api placeorder ib api ib api ib abi ib api ib api ib api ib api ib api ib api placeorder ib api ib api ib api ib api ib api
ib api ib api send order ib api ib api ib api ib abi ib api ib api ib api ib api ib api ib api ib api ib api ib api ib api ib api ib api

Saturday, 18 June 2016

Visual Basic Trading Platform tutorial 2 Connect to TWS

Connect to TWS using VB Visual Studio




Private Sub btnConnect_Click(sender As Object, e As EventArgs) Handles btnConnect.Click
   ' the last string variable can be any number should be different  
   ' for more than one program connected to TWS you can have up to 8 different programs  
   ' connected to TWS  
   Call AxTws1.connect("", "7496", "28") ' The last number can be any number
End Sub  







VB Trading Platform Tutorial 3 Streaming Data

This is the 3rd installment in my Trading platform creation using Visual Basic.
I am using Visual Studio 2012
In this video:
  • you will add some textboxes, comboboxes, labels, numberupdown, to your form
  • request and receive live streaming data bid, ask, and last prices
    The videos are best viewed at the highest quality and full screen.






TradingPlatformLatest














Copy the highlighted text and past it into the code in Visual Studio


 Private Sub cbSymbol_KeyDown(sender As Object, e As KeyEventArgs) Handles cbSymbol.KeyDown
     Try  
       AxTws1.reqAccountUpdates(0, "DU132564") ' added this  
       If e.KeyCode = Keys.Enter Then  
         ' Cancels market data from previous request  
         AxTws1.cancelMktData(0)  
         ' removes the anoying beep sound every time you hit enter.  
         e.SuppressKeyPress = True  
         ' Create a Contract object to hold contract details  
         Dim ContractInfo As TWSLib.IContract  
         ' Connect to the IB Data Server  
         ' The First parameter is the IP address of the server. Leave it blank  
         ' The Second parameter is the network port. Used the default of 7496  
         ' The third parameter is the client application identifier  
         ' Create a new TagValueList object (for API version 9.71)   
         Dim mktDataOptions As TWSLib.ITagValueList  
         ' Create a new empty contract to represent the data we will request  
         ContractInfo = AxTws1.createContract()  
         ' Now fill the ContractInfo object with the necessary information   
         ContractInfo.conId = 0       ' identifier  
         ' Stock symbol  
         ContractInfo.symbol = cbSymbol.Text  
         ' Security Type: Stock=STK, Option=OPT, Future=FUT, etc.  
         ContractInfo.secType = "STK"  
         ' The destination of order or request. "SMART" =IB order router  
         ContractInfo.exchange = "SMART"  
         ' The primary exchange where the instrument trades.   
         ContractInfo.primaryExchange = "NASDAQ"  
         ' The currency USD or GBP or CAD or EUR, etc.  
         ContractInfo.currency = "USD"  
         ' Make the request for streaming market data  
         '  TickerID, ContractInfo, genericTicks and Snapshot (0 for streaming)  
         AxTws1.reqMktDataEx(0, ContractInfo, "", 0)
         ' AxTws1.reqMktDataEx(0, ContractInfo, "", 0, mktDataOptions)  
         'Selects all text in the combo box  
         cbSymbol.SelectAll()  
         AxTws1.reqAccountUpdates(1, "DU132564") ' added this  
         Timer1.Start() ' added this  
       End If  
     Catch ex As Exception  
       MsgBox("Nothing in combobox" & vbCrLf & ex.Message)  
     End Try  
   End Sub  




tickPrice Event

 Private Sub AxTws1_tickPrice(sender As Object, e As AxTWSLib._DTwsEvents_tickPriceEvent) Handles AxTws1.tickPrice 
     ' Call method handles market data Price change events  
     ' When the call method is activated, price changes  
     ' appear in the Events objects named "e"   
     ' Properties of e are as follows:  
     ' e.id       The id that was set in the call to reqMktData  
     ' e.price      The lastest Price  
     ' e.tickType    The tick type 1 = bid, 2 = ask,   
     ' 4 = last, 6 = high, 7 = low, 9 = close   
     ' e.canAutoExecute A flag 1= the order can be automatically executed  
     ' If this is a last price change, then display it in the text box  
     If (e.tickType = 4) Then  
       ' Adds the latest price to the list box  
       'lbPrice.Items.Add("price = " & e.price)  
       tbLast.Text = e.price.ToString("0.00") 'formats to 2 decimals  
     End If  
     If (e.tickType = 2) Then  
       'Adds the Ask price to the text box   
       tbAsk.Text = e.price.ToString("0.00") 'formats to 2 decimals  
     End If  
     If (e.tickType = 1) Then  
       'Adds the Bid price to the text box  
       tbBid.Text = e.price.ToString("0.00") 'formats to 2 decimals  
     End If 
   End Sub  

KeyPress Event

 Private Sub cbSymbol_KeyPress(sender As Object, e As KeyPressEventArgs) Handles cbSymbol.KeyPress
     ' when key is press changes it to uppercase  
     If Char.IsLetter(e.KeyChar) Then  
       e.KeyChar = Char.ToUpper(e.KeyChar)  
     End If      
   End Sub  







Thursday, 16 June 2016

VB Trading Platform Tutorial 1

This will be a series of video tutorials called Visual Basic trading platform.  The tutorial that will show you how to create parts of a trading platform.
The program will be coded in Visual Basic using Visual Studio 2012
The program will connect to Trader Workstation from Interactive Brokers.
You need to download and install the trading platform and the API from Interactive Brokers and install it.
Download and install Visual Studio 2010, 2012, or 2013

I am using an earlier version of the API_Version=9.70. I think if you use this version you will have to force it to install the 32 bit version.

Software you will need to download and install before we can start coding in Visual Basic
I am using Windows 8.1 also will work with Windows 7

Download and install Interactive Brokers Trader Workstation
Must be installed on the main drive
Here is the link:
https://www.interactivebrokers.com/en/index.php?f=14099&ns=T#tws-software

TwsDownloadTws1_

















TwsDownload32bit_





















Download and install Interactive Brokers API version 9.70
here is the link:
http://interactivebrokers.github.io/#
Agree to the terms.
IB API previous for Windows Version API 9.70



TWSAPIdownloaded





















Make sure yours looks the same as below
File > Global configuration > API > Settings (Mosaic)
or
Edit > Global configuration > API  > Settings (Classic)

settingsAPIsmallercropped_j














Pages: 1 2 3 4 5 6

Saturday, 11 June 2016

Trading Platform Tutorial in CSharp 1

Building a C# API Sample Application Tutorial.

Software you will need to download and install before we can start coding in C#
I am using Windows 8.1 also will work with Windows 7

Download and install Interactive Brokers Trader Workstation
Must be installed on the main drive
Here is the link:
https://www.interactivebrokers.com/en/index.php?f=14099&ns=T#tws-software

Download and install Interactive Brokers API version 9.70
here is the link:
http://interactivebrokers.github.io/#
Agree to the terms.
IB API previous for Windows Version API 9.70

Download and install Visual Studio 2010, 2012, or 2013

Make sure the API settings are the same as below
















Save

Tuesday, 7 June 2016

Trading Platform in CSharp c# 5 account update

In this video tutorial:
  • add the different order types to the order type combo box.
  • SelectAll() in the Symbol combo box so we don't have to click in the box and delete what is there,
    you just type a new symbol after you hit enter.
  • Add a count down timer to wait 5 tenths of a second before it adds the price of the bid text box into the limit price number box.
  • Add 2 text box for the current position size and the average price in the average price text box by requesting account updates.
Copy and paste the highlighted code into your project
  1. tip if you want the timer to tick every second you can set the interval in the properties window to 1000, but for this program make sure it is set to 100
private void timer1_Tick(object sender, EventArgs e)
{
     try
     {
          if (timer1_counter == 0) // checks to see if the timer counter is at zero
         {
              timer1.Stop(); // Stop the timer
              // add the bid price to the limit box
              numLimitPrice.Value = Convert.ToDecimal(tbBid.Text);
              timer1_counter = 5;  // reset timer counter back to 5
         }
         timer1_counter--; // subtract 1 every time there is tick
      }
      catch
      {
         timer1_counter = 5;
         timer1.Stop();
      }
}




make this a global variable

int timer1_counter = 5;

Add this to the bottom of the request for market data of the key down event of the symbol combobox (cbSymbol)

timer1.Start();
cbSymbol.SelectAll();
axTws1.reqAccountUpdates(1, myAccount); // requests account updates

Add this to the top of the request market data of the key down event

axTws1.reqAccountUpdates(0, myAccount); // cancels the account updates

updatePortfolioEx copy the highlighted text

 private void axTws1_updatePortfolioEx(object sender, AxTWSLib._DTwsEvents_updatePortfolioExEvent e)  
     {
       int idCon = e.contract.conId;  
       string theSymbol1 = Convert.ToString(e.contract.symbol);  
       // e.averageCost  
       // e.marketValue   
       // e.realizedPNL    
       // e.unrealizedPNL  
       // e.position  
       // e.marketValue  
       // e.contract.symbol = stock symbol  
       // if the symbol in the combo box is the same as the e.contract.symbol  
       // then add the Position size and the average price to the text boxes  
       if (theSymbol1 == cbSymbol.Text)  
       {  
         // Gets the average price of the current symbol  
         double averagePrice = e.averageCost;  
         //Rounds off the current price adds it to the text box  
         tbAvgPrice.Text = Convert.ToString(Math.Round(averagePrice, 2));  
         // puts the position size in the text box  
         tbPosition.Text = Convert.ToString(e.position);  
       }
     }