Build a Trading Platform in C# Part 8 - Historical Data
# | Control | Name | Text | Tabs | Chart Type |
---|---|---|---|---|---|
1 | TabControl | tabControl2 | Historical Data, Chart | ||
2 | List Box | lbHistoricalData | |||
3 | Button | btnSelectAll | Select All | ||
4 | Button | btnCopy | Copy | ||
5 | Chart | chart1 | Candlestick | ||
using System.Threading;
using System.Windows.Forms.DataVisualization.Charting;
using IBApi;
private void Form1_Load(object sender, EventArgs e)
{
// creates the rows for dataGridView1
for (int i = 0; i < 10; i++)
{
dataGridView1.Rows.Add();
}
// creates the rows for dataGridView2
for (int i = 0; i < 10; i++)
{
dataGridView2.Rows.Add();
}
dataGridView2.Columns[3].DefaultCellStyle.Format = "#.00\\%";
chart1.Series["Series1"].ChartType = SeriesChartType.Candlestick; // type of chart to display the data
chart1.Series["Series1"].BorderColor = Color.Black; // boarder color of the candlestick
chart1.Series["Series1"].Color = Color.Black; // wick (shadow) color of the candle
chart1.Series["Series1"].CustomProperties = "PriceDownColor=Green, PriceUpColor=Red";
//chart1.Series["Series1"].XValueType = ChartValueType.Date;
chart1.ChartAreas[0].AxisX.MajorGrid.LineWidth = 0;
chart1.ChartAreas[0].AxisY.MajorGrid.LineWidth = 0;
chart1.ChartAreas[0].AxisY.MinorGrid.Enabled = false;
chart1.ChartAreas[0].AxisX.IsStartedFromZero = false; // don't start from zero
chart1.ChartAreas[0].AxisY.IsStartedFromZero = false; // don't start from zero
}
private void btnSelectAll_Click(object sender, EventArgs e)
{
for (int i = 0; i < lbHistoricalData.Items.Count; i++)
{
lbHistoricalData.SetSelected(i, true);
}
}
private void btnCopy_Click(object sender, EventArgs e)
{
try
{
StringBuilder sb = new StringBuilder();
foreach (object row in lbHistoricalData.SelectedItems)
{
sb.Append(row.ToString());
sb.AppendLine();
}
sb.Remove(sb.Length - 1, 1); // Just to avoid copying last empty row
Clipboard.SetData(System.Windows.Forms.DataFormats.Text, sb.ToString());
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Link to the different contract examples
https://interactivebrokers.github.io/tws-api/basic_contracts.html
private void getData()
{
listViewTns.Items.Clear();
DateTime now = DateTime.Now;
lbHistoricalData.Items.Clear(); // clears the historical data list box
ibClient.ClientSocket.cancelHistoricalData(99);
chart1.Series[0].Points.Clear(); // clears the chart
string strEndDate = now.ToString("yyyyMMdd 16:05:00");
// Time duration
String strDuration = "1 D";
// Bar size
String strBarSize = "5 mins";
ibClient.ClientSocket.cancelMktData(87); // cancel market data
//ibClient.ClientSocket.cancelRealTimeBars(88);
// Create a new contract to specify the security we are searching for
IBApi.Contract contract = new IBApi.Contract();
// Create a new TagValueList object (for API version 9.71 and later)
List<IBApi.TagValue> mktDataOptions = new List<IBApi.TagValue>();
//List realTimeBarsOptions = new List();
// Set the underlying stock symbol from the tbSymbol text box
contract.Symbol = cbSymbol.Text; //"ES"
// Set the Security type to STK for a Stock FUT = Futures,
contract.SecType = "STK"; // "FUT"
// Use "SMART" as the general exchange
contract.Exchange = "SMART"; // "GLOBEX"
// Set the primary exchange (sometimes called Listing exchange)
// Use either NYSE or ISLAND for Futures use GLOBEX
contract.PrimaryExch = "ISLAND";
// Set the currency to USD
contract.Currency = "USD";
//contract.LastTradeDateOrContractMonth = "202103";
// Link to contract example for different securities
// https://interactivebrokers.github.io/tws-api/basic_contracts.html
// If using delayed market data subscription
// use number 3 in the parenthesis
ibClient.ClientSocket.reqMarketDataType(1); // delayed data = 3, live data = 1
// Kick off the subscription for real-time data (add the mktDataOptions list for API v9.71)
//ibClient.ClientSocket.reqMktData(1, contract, "", false, mktDataOptions); // ****************************************
// For API v9.72 and higher, add one more parameter for regulatory snapshot
ibClient.ClientSocket.reqMktData(87, contract, "233", false, false, mktDataOptions);
//tickerId, identifier which will serve to identify the incoming data.
//contract, Contract you are interested in.
//endDateTime, end date and time (the empty string indicates current present moment).
//durationString, The amount of time(or Valid Duration String units) to go back from the request's given end date and time.
//barSizeSetting, The Valid Bar Sizes
//whatToShow, The type of data to retrieve. "TRADES", "MIDPOINT"
//useRTH, Whether(1) or not(0) to retrieve data generated only within Regular Trading Hours(RTH)
// Link to requesting historical data https://interactivebrokers.github.io/tws-api/historical_bars.html
ibClient.ClientSocket.reqHistoricalData(99, contract, "", strDuration, strBarSize, "TRADES", 1, 1, false, null);
timer1.Start();
}
Link to requesting Historical Data: https://interactivebrokers.github.io/tws-api/historical_bars.html
# | Duration | Description | Bar Sizes | |||||||
---|---|---|---|---|---|---|---|---|---|---|
1 | S | Seconds | 1 secs | 5 secs | 10 secs | 15 secs | 30 secs | |||
2 | D | Day | 1 min | 2 mins | 3 mins | 5 mins | 10 mins | 15 mins | 20 mins | 30 mins |
3 | W | Week | 1 hour | 2 hours | 3 hours | 4 hours | 8 hours | |||
4 | M | Month | 1 day | |||||||
5 | Y | Year | 1 week | 1 month | ||||||
This code here goes in the EWrapperImpl.cs file within the historicalData function
public virtual void historicalData(int reqId, Bar bar)
{
//Console.WriteLine("HistoricalData. " + reqId + " - Time: " + bar.Time + ", Open: " + bar.Open + ", High: " + bar.High + ", Low: " + bar.Low + ", Close: " + bar.Close + ", Volume: " + bar.Volume + ", Count: " + bar.Count + ", WAP: " + bar.WAP);
string strHistoricalData = reqId + "," + bar.Time + "," + bar.Open + "," + bar.High + "," + bar.Low + "," + bar.Close + "," + bar.Volume;
myform.AddItemHistoricalData(strHistoricalData);
}
delegate void SetCallbackHistoricalData(string strHistoricalData);
public void AddItemHistoricalData(string strHistoricalData)
{
if (this.tbLast.InvokeRequired)
{
SetCallbackHistoricalData d = new SetCallbackHistoricalData(AddItemHistoricalData);
try
{
this.Invoke(d, new object[] { strHistoricalData });
}
catch (Exception e)
{
Console.WriteLine("this is from Historical Data ", e);
}
}
else
{
//lbHistoricalData.Items.Add(strHistoricalData);
string[] chart_val = strHistoricalData.Split(',');
// reqId 0, Date and time 1, Open 2, High 3, Low 4, Close 5, Volume 6, Count 7, WAP 0
string newVal = chart_val[1].Trim();
string OutputString = chart_val[0] + "," +
newVal + "," +
chart_val[2] + "," +
chart_val[3] + "," +
chart_val[4] + "," +
chart_val[5];
// display the stock data in a list box
lbHistoricalData.Items.Add(OutputString);
// adds the ohlc data to the chart
chart1.Series["Series1"].Points.AddXY(chart_val[1], chart_val[3], chart_val[4], chart_val[5], chart_val[2]);
}
}
No comments:
Post a Comment