Skip to content

Instantly share code, notes, and snippets.

@imvision
Created May 20, 2014 17:50
Show Gist options
  • Save imvision/ca727e583dc340f27f3a to your computer and use it in GitHub Desktop.
Save imvision/ca727e583dc340f27f3a to your computer and use it in GitHub Desktop.
Main application code, market row view, and place bet code
using System;
using CSharpAPI6;
using System.Collections;
using System.Windows.Forms;
using CSharpAPI6.betfair.api;
using System.Threading;
using System.Collections.Generic;
using CSharpAPI6.betfair.api.global;
namespace CSharpAPI6
{
public class frmMain : System.Windows.Forms.Form
{
//Global Variables
public SimpleAPIWrapper simpleAPIWrapper;
private IDictionary m_marketViewRows;
private System.Windows.Forms.MainMenu mainMenu1;
private System.Windows.Forms.MenuItem menuItemFile;
private System.Windows.Forms.MenuItem menuItemExit;
private System.Windows.Forms.Panel panelMain;
private System.Windows.Forms.Panel panelMenu;
public System.Windows.Forms.TreeView tvMain;
private System.Windows.Forms.Button btnAllActiveMenu;
private System.Windows.Forms.Splitter splitter1;
private System.Windows.Forms.Panel panelRunnerInfo;
public System.Windows.Forms.Label labelRunnerInfo;
private System.Windows.Forms.Timer timer1;
private System.Windows.Forms.Splitter splitter4;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label lblLastRefresh;
private System.Windows.Forms.Panel panelInPlay;
private System.Windows.Forms.Label lblInPlay;
private System.Windows.Forms.Label lblMarketStatus;
private System.Windows.Forms.Label label3;
private Panel panelExceptions;
private Panel panelRunners;
private Splitter splitter2;
private ListBox lstBoxErrors;
private Label label2;
private System.ComponentModel.IContainer components;
#region frmMain
public frmMain()
{
InitializeComponent();
this.m_marketViewRows = new Hashtable();
simpleAPIWrapper = new SimpleAPIWrapper();
}
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
[STAThread]
static void Main()
{
Application.Run(new frmMain());
}
#endregion
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.mainMenu1 = new System.Windows.Forms.MainMenu(this.components);
this.menuItemFile = new System.Windows.Forms.MenuItem();
this.menuItemExit = new System.Windows.Forms.MenuItem();
this.panelMain = new System.Windows.Forms.Panel();
this.panelRunners = new System.Windows.Forms.Panel();
this.splitter2 = new System.Windows.Forms.Splitter();
this.panelExceptions = new System.Windows.Forms.Panel();
this.lstBoxErrors = new System.Windows.Forms.ListBox();
this.label2 = new System.Windows.Forms.Label();
this.panelRunnerInfo = new System.Windows.Forms.Panel();
this.lblMarketStatus = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.panelInPlay = new System.Windows.Forms.Panel();
this.lblInPlay = new System.Windows.Forms.Label();
this.lblLastRefresh = new System.Windows.Forms.Label();
this.label1 = new System.Windows.Forms.Label();
this.splitter4 = new System.Windows.Forms.Splitter();
this.labelRunnerInfo = new System.Windows.Forms.Label();
this.splitter1 = new System.Windows.Forms.Splitter();
this.panelMenu = new System.Windows.Forms.Panel();
this.tvMain = new System.Windows.Forms.TreeView();
this.btnAllActiveMenu = new System.Windows.Forms.Button();
this.timer1 = new System.Windows.Forms.Timer(this.components);
this.panelMain.SuspendLayout();
this.panelExceptions.SuspendLayout();
this.panelRunnerInfo.SuspendLayout();
this.panelInPlay.SuspendLayout();
this.panelMenu.SuspendLayout();
this.SuspendLayout();
//
// mainMenu1
//
this.mainMenu1.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.menuItemFile});
//
// menuItemFile
//
this.menuItemFile.Index = 0;
this.menuItemFile.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.menuItemExit});
this.menuItemFile.Text = "&File";
//
// menuItemExit
//
this.menuItemExit.Index = 0;
this.menuItemExit.Text = "E&xit";
this.menuItemExit.Click += new System.EventHandler(this.menuItemExit_Click);
//
// panelMain
//
this.panelMain.Controls.Add(this.panelRunners);
this.panelMain.Controls.Add(this.splitter2);
this.panelMain.Controls.Add(this.panelExceptions);
this.panelMain.Controls.Add(this.panelRunnerInfo);
this.panelMain.Controls.Add(this.splitter1);
this.panelMain.Controls.Add(this.panelMenu);
this.panelMain.Dock = System.Windows.Forms.DockStyle.Fill;
this.panelMain.Location = new System.Drawing.Point(0, 0);
this.panelMain.Name = "panelMain";
this.panelMain.Size = new System.Drawing.Size(795, 564);
this.panelMain.TabIndex = 4;
//
// panelRunners
//
this.panelRunners.BackColor = System.Drawing.Color.White;
this.panelRunners.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.panelRunners.Dock = System.Windows.Forms.DockStyle.Fill;
this.panelRunners.Location = new System.Drawing.Point(239, 72);
this.panelRunners.Name = "panelRunners";
this.panelRunners.Padding = new System.Windows.Forms.Padding(2);
this.panelRunners.Size = new System.Drawing.Size(556, 375);
this.panelRunners.TabIndex = 33;
this.panelRunners.Paint += new System.Windows.Forms.PaintEventHandler(this.panelRunners_Paint);
//
// splitter2
//
this.splitter2.Dock = System.Windows.Forms.DockStyle.Bottom;
this.splitter2.Location = new System.Drawing.Point(239, 447);
this.splitter2.Name = "splitter2";
this.splitter2.Size = new System.Drawing.Size(556, 3);
this.splitter2.TabIndex = 32;
this.splitter2.TabStop = false;
//
// panelExceptions
//
this.panelExceptions.Controls.Add(this.lstBoxErrors);
this.panelExceptions.Controls.Add(this.label2);
this.panelExceptions.Dock = System.Windows.Forms.DockStyle.Bottom;
this.panelExceptions.Location = new System.Drawing.Point(239, 450);
this.panelExceptions.Name = "panelExceptions";
this.panelExceptions.Size = new System.Drawing.Size(556, 114);
this.panelExceptions.TabIndex = 30;
//
// lstBoxErrors
//
this.lstBoxErrors.BackColor = System.Drawing.SystemColors.InactiveBorder;
this.lstBoxErrors.Dock = System.Windows.Forms.DockStyle.Fill;
this.lstBoxErrors.FormattingEnabled = true;
this.lstBoxErrors.HorizontalScrollbar = true;
this.lstBoxErrors.Location = new System.Drawing.Point(0, 17);
this.lstBoxErrors.MultiColumn = true;
this.lstBoxErrors.Name = "lstBoxErrors";
this.lstBoxErrors.Size = new System.Drawing.Size(556, 95);
this.lstBoxErrors.TabIndex = 1;
this.lstBoxErrors.SelectedIndexChanged += new System.EventHandler(this.lstBoxErrors_SelectedIndexChanged);
//
// label2
//
this.label2.AutoSize = true;
this.label2.Dock = System.Windows.Forms.DockStyle.Top;
this.label2.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label2.Location = new System.Drawing.Point(0, 0);
this.label2.Name = "label2";
this.label2.Padding = new System.Windows.Forms.Padding(2);
this.label2.Size = new System.Drawing.Size(62, 17);
this.label2.TabIndex = 0;
this.label2.Text = "Error List";
//
// panelRunnerInfo
//
this.panelRunnerInfo.BackColor = System.Drawing.SystemColors.ActiveBorder;
this.panelRunnerInfo.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.panelRunnerInfo.Controls.Add(this.lblMarketStatus);
this.panelRunnerInfo.Controls.Add(this.label3);
this.panelRunnerInfo.Controls.Add(this.panelInPlay);
this.panelRunnerInfo.Controls.Add(this.lblLastRefresh);
this.panelRunnerInfo.Controls.Add(this.label1);
this.panelRunnerInfo.Controls.Add(this.splitter4);
this.panelRunnerInfo.Controls.Add(this.labelRunnerInfo);
this.panelRunnerInfo.Dock = System.Windows.Forms.DockStyle.Top;
this.panelRunnerInfo.Location = new System.Drawing.Point(239, 0);
this.panelRunnerInfo.Name = "panelRunnerInfo";
this.panelRunnerInfo.Size = new System.Drawing.Size(556, 72);
this.panelRunnerInfo.TabIndex = 28;
this.panelRunnerInfo.Paint += new System.Windows.Forms.PaintEventHandler(this.panelRunnerInfo_Paint);
//
// lblMarketStatus
//
this.lblMarketStatus.BackColor = System.Drawing.SystemColors.ActiveBorder;
this.lblMarketStatus.Dock = System.Windows.Forms.DockStyle.Fill;
this.lblMarketStatus.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.lblMarketStatus.ForeColor = System.Drawing.SystemColors.ControlDarkDark;
this.lblMarketStatus.Location = new System.Drawing.Point(296, 43);
this.lblMarketStatus.Name = "lblMarketStatus";
this.lblMarketStatus.Size = new System.Drawing.Size(194, 27);
this.lblMarketStatus.TabIndex = 14;
this.lblMarketStatus.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// label3
//
this.label3.BackColor = System.Drawing.SystemColors.ActiveBorder;
this.label3.Dock = System.Windows.Forms.DockStyle.Left;
this.label3.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label3.ForeColor = System.Drawing.Color.Black;
this.label3.Location = new System.Drawing.Point(216, 43);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(80, 27);
this.label3.TabIndex = 13;
this.label3.Text = "Market Status: ";
this.label3.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
//
// panelInPlay
//
this.panelInPlay.BackColor = System.Drawing.SystemColors.ActiveBorder;
this.panelInPlay.Controls.Add(this.lblInPlay);
this.panelInPlay.Dock = System.Windows.Forms.DockStyle.Right;
this.panelInPlay.Location = new System.Drawing.Point(490, 43);
this.panelInPlay.Name = "panelInPlay";
this.panelInPlay.Size = new System.Drawing.Size(64, 27);
this.panelInPlay.TabIndex = 12;
this.panelInPlay.Visible = false;
//
// lblInPlay
//
this.lblInPlay.BackColor = System.Drawing.Color.Lime;
this.lblInPlay.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.lblInPlay.ForeColor = System.Drawing.Color.Black;
this.lblInPlay.Location = new System.Drawing.Point(8, 6);
this.lblInPlay.Name = "lblInPlay";
this.lblInPlay.Size = new System.Drawing.Size(48, 16);
this.lblInPlay.TabIndex = 8;
this.lblInPlay.Text = "In-Play";
this.lblInPlay.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// lblLastRefresh
//
this.lblLastRefresh.BackColor = System.Drawing.SystemColors.ActiveBorder;
this.lblLastRefresh.Dock = System.Windows.Forms.DockStyle.Left;
this.lblLastRefresh.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.lblLastRefresh.ForeColor = System.Drawing.SystemColors.ControlDarkDark;
this.lblLastRefresh.Location = new System.Drawing.Point(80, 43);
this.lblLastRefresh.Name = "lblLastRefresh";
this.lblLastRefresh.Size = new System.Drawing.Size(136, 27);
this.lblLastRefresh.TabIndex = 11;
this.lblLastRefresh.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// label1
//
this.label1.BackColor = System.Drawing.SystemColors.ActiveBorder;
this.label1.Dock = System.Windows.Forms.DockStyle.Left;
this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label1.ForeColor = System.Drawing.Color.Black;
this.label1.Location = new System.Drawing.Point(0, 43);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(80, 27);
this.label1.TabIndex = 10;
this.label1.Text = "Last Refresh: ";
this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
//
// splitter4
//
this.splitter4.BackColor = System.Drawing.SystemColors.ActiveBorder;
this.splitter4.Dock = System.Windows.Forms.DockStyle.Top;
this.splitter4.Enabled = false;
this.splitter4.Location = new System.Drawing.Point(0, 40);
this.splitter4.Name = "splitter4";
this.splitter4.Size = new System.Drawing.Size(554, 3);
this.splitter4.TabIndex = 8;
this.splitter4.TabStop = false;
//
// labelRunnerInfo
//
this.labelRunnerInfo.BackColor = System.Drawing.SystemColors.ActiveBorder;
this.labelRunnerInfo.Dock = System.Windows.Forms.DockStyle.Top;
this.labelRunnerInfo.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.labelRunnerInfo.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.labelRunnerInfo.Location = new System.Drawing.Point(0, 0);
this.labelRunnerInfo.Name = "labelRunnerInfo";
this.labelRunnerInfo.Size = new System.Drawing.Size(554, 40);
this.labelRunnerInfo.TabIndex = 1;
this.labelRunnerInfo.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// splitter1
//
this.splitter1.Location = new System.Drawing.Point(236, 0);
this.splitter1.Name = "splitter1";
this.splitter1.Size = new System.Drawing.Size(3, 564);
this.splitter1.TabIndex = 24;
this.splitter1.TabStop = false;
//
// panelMenu
//
this.panelMenu.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.panelMenu.Controls.Add(this.tvMain);
this.panelMenu.Controls.Add(this.btnAllActiveMenu);
this.panelMenu.Dock = System.Windows.Forms.DockStyle.Left;
this.panelMenu.Location = new System.Drawing.Point(0, 0);
this.panelMenu.Name = "panelMenu";
this.panelMenu.Size = new System.Drawing.Size(236, 564);
this.panelMenu.TabIndex = 23;
//
// tvMain
//
this.tvMain.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.tvMain.Dock = System.Windows.Forms.DockStyle.Fill;
this.tvMain.Font = new System.Drawing.Font("Verdana", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.tvMain.ForeColor = System.Drawing.Color.Navy;
this.tvMain.ItemHeight = 16;
this.tvMain.Location = new System.Drawing.Point(0, 0);
this.tvMain.Name = "tvMain";
this.tvMain.Size = new System.Drawing.Size(234, 539);
this.tvMain.TabIndex = 13;
this.tvMain.AfterSelect += new System.Windows.Forms.TreeViewEventHandler(this.tvMain_AfterSelect);
this.tvMain.AfterExpand += new System.Windows.Forms.TreeViewEventHandler(this.tvMain_AfterExpand);
//
// btnAllActiveMenu
//
this.btnAllActiveMenu.Dock = System.Windows.Forms.DockStyle.Bottom;
this.btnAllActiveMenu.FlatStyle = System.Windows.Forms.FlatStyle.System;
this.btnAllActiveMenu.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.btnAllActiveMenu.Location = new System.Drawing.Point(0, 539);
this.btnAllActiveMenu.Name = "btnAllActiveMenu";
this.btnAllActiveMenu.Size = new System.Drawing.Size(234, 23);
this.btnAllActiveMenu.TabIndex = 10;
this.btnAllActiveMenu.Text = "Show All Event Types";
this.btnAllActiveMenu.Click += new System.EventHandler(this.btnAllActiveMenu_Click);
//
// timer1
//
this.timer1.Interval = 500;
this.timer1.Tick += new System.EventHandler(this.timer1_Tick);
//
// frmMain
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(795, 564);
this.Controls.Add(this.panelMain);
this.Menu = this.mainMenu1;
this.Name = "frmMain";
this.Text = "C-Sharp API Example";
this.WindowState = System.Windows.Forms.FormWindowState.Maximized;
this.Load += new System.EventHandler(this.frmMain_Load);
this.Closing += new System.ComponentModel.CancelEventHandler(this.frmMain_Closed);
this.panelMain.ResumeLayout(false);
this.panelExceptions.ResumeLayout(false);
this.panelExceptions.PerformLayout();
this.panelRunnerInfo.ResumeLayout(false);
this.panelInPlay.ResumeLayout(false);
this.panelMenu.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
#region Form Load
private void frmMain_Load(object sender, System.EventArgs e)
{
/*** Start Login ***/
new frmLogin(this).ShowDialog();
}
#endregion
#region Form Close
private void frmMain_Closed(object sender, System.ComponentModel.CancelEventArgs e)
{
//TODO: SessionTokenManager.Logout();
}
#endregion
#region Menu Exit Click
private void menuItemExit_Click(object sender, System.EventArgs e)
{
this.Close();
}
#endregion
#region TreeView Expand
private void tvMain_AfterExpand(object sender, System.Windows.Forms.TreeViewEventArgs e)
{
if (e.Node != null)
{
// Clear the nodes and indicate we're loading
e.Node.Nodes.Clear();
e.Node.Nodes.Add(new TreeNode("Loading..."));
int eventParentId = 0;
if (e.Node != null)
{
CSharpAPI6.betfair.api.global.BFEvent eventItem = (CSharpAPI6.betfair.api.global.BFEvent)e.Node.Tag;
eventParentId = eventItem.eventId;
}
GetEventAsyncRequest(eventParentId, e.Node);
}
}
#endregion
#region Load events to the treeView
private void tvMain_load_EventTypes(eventTypesEnum taskType)
{
// Clear the nodes and indicate we're loading
tvMain.Nodes.Clear();
if (taskType == eventTypesEnum.ALL)
tvMain.Nodes.Add("Loading All Event Types...");
else if (taskType == eventTypesEnum.ACTIVE)
tvMain.Nodes.Add("Loading Active Event Types...");
//Step 1://
GetEventTypesAsyncRequest(taskType);
}
#endregion
#region btnAllActiveMenu_Click
private void btnAllActiveMenu_Click(object sender, System.EventArgs e)
{
tvMain.Enabled = false;
tvMain.Nodes.Clear();
btnAllActiveMenu.Enabled = false;
if (btnAllActiveMenu.Text == "Show All Event Types")
{
tvMain_load_EventTypes(eventTypesEnum.ALL);
btnAllActiveMenu.Text = "Show Active Event Types";
}
else if (btnAllActiveMenu.Text == "Show Active Event Types")
{
tvMain_load_EventTypes(eventTypesEnum.ACTIVE);
btnAllActiveMenu.Text = "Show All Event Types";
}
tvMain.Enabled = true;
btnAllActiveMenu.Enabled = true;
}
#endregion
#region tvMain_AfterSelect
private void tvMain_AfterSelect(object sender, System.Windows.Forms.TreeViewEventArgs e)
{
startCreateMarketTask(e.Node, "");
}
private void startCreateMarketTask(TreeNode e, string menuStructure)
{
if (e != null && e.Tag is CSharpAPI6.betfair.api.global.MarketSummary)
{
clearMarketView();
lblMarketStatus.Text = "Loading Market Data...";
if (timer1.Enabled) timer1.Enabled = false;
panelRunners.Controls.Clear();
CSharpAPI6.betfair.api.global.MarketSummary marketInfo = (CSharpAPI6.betfair.api.global.MarketSummary)e.Tag;
GetMarketAsyncRequest(marketInfo.marketId, marketInfo.exchangeId);
labelRunnerInfo.Text = menuStructure + " " + marketInfo.marketName + " - " + marketInfo.startTime.ToShortDateString() + " - " + marketInfo.startTime.ToShortTimeString();
}
}
#endregion
#region MarketSummaryComparer IComparer Members
public class MarketSummaryComparer : IComparer
{
public int Compare(object x, object y)
{
return ((CSharpAPI6.betfair.api.global.MarketSummary)x).orderIndex.CompareTo(((CSharpAPI6.betfair.api.global.MarketSummary)y).orderIndex);
}
}
#endregion
#region CreateMarketView
private void CreateMarketView(betfair.api.exchange.Market market)
{
try
{
//Clear the panel
panelRunners.Controls.Clear();
timer1.Stop();
panelRunners.SuspendLayout();
// Create the container
Panel pnl = new Panel();
pnl.Dock = DockStyle.Fill;
pnl.AutoScroll = true;
pnl.BorderStyle = BorderStyle.None;
pnl.Tag = market.marketId;
pnl.Name = market.marketId.ToString();
try
{
pnl.SuspendLayout();
//Got data from UK exchange
if (market != null)
{
betfair.api.exchange.Runner[] reversedRunners = (betfair.api.exchange.Runner[])market.runners.Clone();
Array.Reverse(reversedRunners);
// Create the rows
foreach (betfair.api.exchange.Runner runner in reversedRunners)
{
MarketViewRow row = new MarketViewRow(market, runner);
row.Dock = DockStyle.Top;
row.Name = string.Format("{0}+{1}+{2}", market.marketId, runner.selectionId, runner.asianLineId);
pnl.Controls.Add(row);
m_marketViewRows[row.Name] = row;
}
// Create a market name labelLabel lbl = new Label();
Label lbl = new Label();
lbl.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
lbl.Text = market.name;
lbl.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
lbl.Height = 20;
lbl.Dock = DockStyle.Top;
pnl.Controls.Add(lbl);
/* Ref: #TML3 */
// Added ToLocalTime conversion to below.
labelRunnerInfo.Text = string.Format("{0}\\{1}", market.menuPath, market.name) + "\n\r\n\rExpected Start Time: " + "" + market.marketTime.ToLocalTime().ToShortDateString() + " - " + market.marketTime.ToLocalTime().ToShortTimeString();
}
}
finally
{
pnl.ResumeLayout();
}
// Add the rows to panel1
panelRunners.Controls.Add(pnl);
}
finally
{
panelRunners.ResumeLayout();
this.timer1.Interval = 1;/* Ref: #TML1 */
timer1.Start();
}
}
#endregion
#region Clear market view
private void clearMarketView()
{
timer1.Stop();
panelRunners.Controls.Clear();
panelInPlay.Visible = false;
lblLastRefresh.Text = "";
lblMarketStatus.Text = "";
}
#endregion
#region timer1_Tick
private delegate void timer1_TickDelegate(object sender, System.EventArgs e);
private void timer1_Tick(object sender, System.EventArgs e)
{
if(this.InvokeRequired)
try
{
timer1_TickDelegate d = new timer1_TickDelegate(timer1_Tick);
this.Invoke(d, new object[] { sender, e });
}
catch (Exception ex)
{
AddErrorToList(ex.ToString());
}
if (simpleAPIWrapper.isFreeAPI && !simpleAPIWrapper.useCompressedPrices)
timer1.Interval = 100;
else if (simpleAPIWrapper.isFreeAPI && simpleAPIWrapper.useCompressedPrices)
timer1.Interval = 200;
else
timer1.Interval = 100;
if (simpleAPIWrapper.marketResp.market.marketId > 0)
{
if(this.simpleAPIWrapper.useCompressedPrices)
GetMarketPricesCompressedAsyncRequest();
else
GetMarketPricesAsyncRequest();
}
else
timer1.Interval = 100;
}
#endregion
/*** Display Data ***/
#region AddErrorToList
private delegate void AddErrorToListDelegate(string message);
private void AddErrorToList(string message)
{
if (this.lstBoxErrors.InvokeRequired)
{
AddErrorToListDelegate d = new AddErrorToListDelegate(AddErrorToList);
this.Invoke(d, new object[] { message });
}
else
{
this.lstBoxErrors.Items.Add(DateTime.Now + " - " + message);
if (this.lstBoxErrors.BackColor != System.Drawing.Color.LightPink)
this.lstBoxErrors.BackColor = System.Drawing.Color.LightPink;
}
}
#endregion
#region DisplayLogin
private void DisplayLogin(CSharpAPI6.betfair.api.global.LoginResp resp, CustomAsyncStateContainer state)
{
try
{
frmLogin loginForm = null;
if (state != null && state.sender is frmLogin)
loginForm = (frmLogin)state.sender;
//Process response
if (resp.header.errorCode != APIErrorEnum.OK || resp.errorCode != LoginErrorEnum.OK)
{
//Show error if login failed
if (loginForm == null)
new frmLogin(this).ShowDialog();
else
{
loginForm.BringToFront();
loginForm.ButtonLoginEnabled = true;
}
MessageBox.Show("The API returned the following error codes\r\n\r\nHeader Error Code: " + resp.header.errorCode.ToString().Replace("_", " ") + "\r\nLogin Error Code: " + resp.errorCode.ToString().Replace("_", " "), "Login Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
if (loginForm != null)
{
loginForm.Close();
/*** Start Populate TreeView Thread ***/
tvMain.Focus();
tvMain_load_EventTypes(eventTypesEnum.ACTIVE);
}
}
}
catch (Exception Ex)
{
//Catch and display detailed error info to operator
MessageBox.Show("Detailed Error Message:\r\n" + Ex + "\r\n\r\nClick \"OK\" to exit the application", "Fatal Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
#endregion
#region DisplayGetEventTypes
private void DisplayGetEventTypes(CSharpAPI6.betfair.api.global.GetEventTypesResp resp, CustomAsyncStateContainer state)
{
// We need to display information from the provided API response
tvMain.Nodes.Clear();
if (resp.eventTypeItems != null)
{
CSharpAPI6.betfair.api.global.EventType[] eventItems = resp.eventTypeItems;
int nodeCount = eventItems.Length;
TreeNode[] nodes = new TreeNode[nodeCount];
for (int i = 0; i < nodeCount; i++)
{
CSharpAPI6.betfair.api.global.BFEvent eventItem = new CSharpAPI6.betfair.api.global.BFEvent();
eventItem.eventName = eventItems[i].name;
eventItem.eventId = eventItems[i].id;
nodes[i] = new TreeNode(eventItems[i].name);
nodes[i].Tag = eventItem;
nodes[i].Nodes.Add(new TreeNode("")); // Create a fake child node
}
tvMain.Nodes.AddRange(nodes);
}
}
public enum eventTypesEnum
{
ACTIVE,
ALL
}
#endregion
#region DisplayGetEventDelegate
private void DisplayGetEvent(CSharpAPI6.betfair.api.global.GetEventsResp resp, CustomAsyncStateContainer state)
{
TreeNode node = new TreeNode();
if (state.sender is TreeNode)
node = (TreeNode)state.sender;
//We need to display information from the provided API response under the specified node.
node.Nodes.Clear();
if (resp.eventItems != null)
{
CSharpAPI6.betfair.api.global.BFEvent[] eventItems = resp.eventItems;
Array.Sort(eventItems, new SimpleAPIWrapper.BFEventComparer());
int nodeCount = eventItems.Length;
TreeNode[] nodes = new TreeNode[nodeCount];
for (int i = 0; i < nodeCount; i++)
{
nodes[i] = new TreeNode(eventItems[i].eventName);
nodes[i].Tag = eventItems[i];
nodes[i].Nodes.Add(new TreeNode("")); // Create a fake child node
}
node.Nodes.AddRange(nodes);
}
if (resp.marketItems != null)
{
CSharpAPI6.betfair.api.global.MarketSummary[] marketItems = resp.marketItems;
Array.Sort(marketItems, new MarketSummaryComparer());
int nodeCount = marketItems.Length;
TreeNode[] nodes = new TreeNode[nodeCount];
for (int i = 0; i < nodeCount; i++)
{
/* Ref: #TML3 */
//nodes[i] = new TreeNode(marketItems[i].marketName);
if (marketItems[i].startTime.Year != 1)
nodes[i] = new TreeNode(marketItems[i].startTime.ToLocalTime().ToShortTimeString() + " " + marketItems[i].marketName);
else
nodes[i] = new TreeNode(marketItems[i].marketName);
/* End Ref: #TML3 */
nodes[i].Tag = marketItems[i];
}
node.Nodes.AddRange(nodes);
}
}
#endregion
#region DisplayGetMarket
private void DisplayGetMarket(CSharpAPI6.betfair.api.exchange.GetMarketResp resp, CustomAsyncStateContainer state)
{
CreateMarketView(resp.market);
timer1_Tick(this, null);
}
#endregion
#region DisplayGetMarketPrices
private void DisplayGetMarketPrices(CSharpAPI6.betfair.api.exchange.GetMarketPricesResp resp, CustomAsyncStateContainer state)
{
if (resp.marketPrices.marketStatus != betfair.api.exchange.MarketStatusEnum.CLOSED)
{
if (resp.marketPrices.delay > 0)
{
panelInPlay.Visible = true;
}
else
{
panelInPlay.Visible = false;
}
lblMarketStatus.Text = resp.marketPrices.marketStatus.ToString();
if (lblMarketStatus.Text == "ACTIVE")
lblMarketStatus.ForeColor = System.Drawing.Color.Black;
else
lblMarketStatus.ForeColor = System.Drawing.Color.Red;
foreach (betfair.api.exchange.RunnerPrices runnerPrices in resp.marketPrices.runnerPrices)
{
string rowName = string.Format("{0}+{1}+{2}", simpleAPIWrapper.marketResp.market.marketId, runnerPrices.selectionId, runnerPrices.asianLineId);
MarketViewRow row = (MarketViewRow)m_marketViewRows[rowName];
double backPrice1 = 0.0;
double backAmountAvailable1 = 0.0;
if (runnerPrices.bestPricesToBack != null && runnerPrices.bestPricesToBack.Length > 0)
{
backPrice1 = runnerPrices.bestPricesToBack[0].price;
backAmountAvailable1 = runnerPrices.bestPricesToBack[0].amountAvailable;
}
double backPrice2 = 0.0;
double backAmountAvailable2 = 0.0;
if (runnerPrices.bestPricesToBack != null && runnerPrices.bestPricesToBack.Length > 1)
{
backPrice2 = runnerPrices.bestPricesToBack[1].price;
backAmountAvailable2 = runnerPrices.bestPricesToBack[1].amountAvailable;
}
double backPrice3 = 0.0;
double backAmountAvailable3 = 0.0;
if (runnerPrices.bestPricesToBack != null && runnerPrices.bestPricesToBack.Length > 2)
{
backPrice3 = runnerPrices.bestPricesToBack[2].price;
backAmountAvailable3 = runnerPrices.bestPricesToBack[2].amountAvailable;
}
double layPrice1 = 0.0;
double layAmountAvailable1 = 0.0;
if (runnerPrices.bestPricesToLay != null && runnerPrices.bestPricesToLay.Length > 0)
{
layPrice1 = runnerPrices.bestPricesToLay[0].price;
layAmountAvailable1 = runnerPrices.bestPricesToLay[0].amountAvailable;
}
double layPrice2 = 0.0;
double layAmountAvailable2 = 0.0;
if (runnerPrices.bestPricesToLay != null && runnerPrices.bestPricesToLay.Length > 1)
{
layPrice2 = runnerPrices.bestPricesToLay[1].price;
layAmountAvailable2 = runnerPrices.bestPricesToLay[1].amountAvailable;
}
double layPrice3 = 0.0;
double layAmountAvailable3 = 0.0;
if (runnerPrices.bestPricesToLay != null && runnerPrices.bestPricesToLay.Length > 2)
{
layPrice3 = runnerPrices.bestPricesToLay[2].price;
layAmountAvailable2 = runnerPrices.bestPricesToLay[2].amountAvailable;
}
lblLastRefresh.Text = resp.header.timestamp.ToLocalTime().ToLongTimeString();
row.DisplayPrices(resp.marketPrices.currencyCode, backPrice1, backAmountAvailable1, backPrice2, backAmountAvailable2, backPrice3, backAmountAvailable3, layPrice1, layAmountAvailable1, layPrice2, layAmountAvailable2, layPrice3, layAmountAvailable3, simpleAPIWrapper);
}
}
else if (resp.marketPrices.marketStatus == betfair.api.exchange.MarketStatusEnum.CLOSED)
{
timer1.Stop();
lblLastRefresh.Text = DateTime.Now.ToShortDateString() + DateTime.Now.ToLongTimeString();
lblMarketStatus.Text = resp.marketPrices.marketStatus.ToString();
lblMarketStatus.ForeColor = System.Drawing.Color.Red;
}
}
#endregion
#region DisplayGetMarketPricesCompressed
private void DisplayGetMarketPricesCompressed(Betfair.DataTypes.Sports.MarketPricesInfoDemo resp, CustomAsyncStateContainer state)
{
if (resp.MarketStatus != CSharpAPI6.betfair.api.exchange.MarketStatusEnum.CLOSED)
{
if (resp.InPlayDelay > 0)
{
panelInPlay.Visible = true;
}
else
{
panelInPlay.Visible = false;
}
lblMarketStatus.Text = resp.MarketStatus.ToString();
if (lblMarketStatus.Text == "ACTIVE")
lblMarketStatus.ForeColor = System.Drawing.Color.Black;
else
lblMarketStatus.ForeColor = System.Drawing.Color.Red;
foreach (Betfair.DataTypes.Sports.MarketPricesInfoDemo.SelectionPricesInfo runnerPrices in resp.CompletePriceInfo)
{
string rowName = string.Format("{0}+{1}+{2}", simpleAPIWrapper.marketResp.market.marketId, runnerPrices.SelectionId, runnerPrices.AsianLineId);
MarketViewRow row = (MarketViewRow)m_marketViewRows[rowName];
double[] Price = new double[6];
double[] Size = new double[6];
int count = 0;
foreach(Betfair.DataTypes.Sports.MarketPricesInfoDemo.SelectionPricesInfo.OddsAvailablePriceInfo odds in runnerPrices.PriceInfo.Values)
{
Price[count] = odds.Odds;
Size[count] = 0;
if(odds.BackAmountAvailable > 0)
Size[count] = odds.BackAmountAvailable;
if (odds.LayAmountAvailable > 0)
Size[count] = odds.LayAmountAvailable;
count++;
}
lblLastRefresh.Text = DateTime.Now.ToLocalTime().ToLongTimeString();
row.DisplayPrices(resp.CurrencyCode, Price[2], Size[2], Price[1], Size[1], Price[0], Size[0], Price[3], Size[3], Price[4], Size[4], Price[5], Size[5], simpleAPIWrapper);
}
}
else if (resp.MarketStatus == CSharpAPI6.betfair.api.exchange.MarketStatusEnum.CLOSED)
{
timer1.Stop();
lblLastRefresh.Text = DateTime.Now.ToShortDateString() + DateTime.Now.ToLongTimeString();
lblMarketStatus.Text = resp.MarketStatus.ToString();
lblMarketStatus.ForeColor = System.Drawing.Color.Red;
}
}
#endregion
/*** Betfair API Async Calls and response handling ***/
#region Login
public string MakeSession()
{
string session = null;
var async = LoginAsyncRequest(simpleAPIWrapper.username, simpleAPIWrapper.password, simpleAPIWrapper.productId, simpleAPIWrapper.softwareId, null);
int count = 0;
while (!async.IsCompleted || !SessionTokenManager.HasSessions)
{
Thread.Sleep(500);
if ((count++) == 20)
{
throw new Exception("Time out occured in \"public string MakeSession()\"");
}
}
session = SessionTokenManager.GetSessionToken();
if (session == null)
{
throw new Exception("String session is NULL in \"public string MakeSession()\"");
}
return session;
}
public void OnLoadLoginLogin(string username, string password, int productId, int vendorSoftwareId, object sender, bool useCompressedPrices)
{
this.simpleAPIWrapper.useCompressedPrices = useCompressedPrices;
LoginAsyncRequest(username, password, productId, vendorSoftwareId, sender);
}
public IAsyncResult LoginAsyncRequest(string username, string password, int productId, int vendorSoftwareId, object sender)
{
simpleAPIWrapper.username = username;
simpleAPIWrapper.password = password;
simpleAPIWrapper.productId = productId;
simpleAPIWrapper.softwareId = vendorSoftwareId;
simpleAPIWrapper.loginDateTime = DateTime.Now;
CSharpAPI6.betfair.api.global.LoginReq request = null;
request = new CSharpAPI6.betfair.api.global.LoginReq();
request.username = username;
request.password = password;
request.productId = productId;
request.vendorSoftwareId = vendorSoftwareId;
var myAsyncStateContainer = new CustomAsyncStateContainer(0, sender, new object[]{username,password,productId,vendorSoftwareId,sender}, DateTime.Now);
return simpleAPIWrapper.BFGlobalService.Beginlogin(request, LoginAsyncCallback, myAsyncStateContainer);
}
private delegate void LoginAsyncCallbackDelegate(IAsyncResult result);
private void LoginAsyncCallback(IAsyncResult result)
{
if (this.InvokeRequired)
{
try
{
LoginAsyncCallbackDelegate d = new LoginAsyncCallbackDelegate(LoginAsyncCallback);
this.Invoke(d, new object[] { result });
}
catch (Exception ex)
{
AddErrorToList(ex.ToString());
}
}
else
{
CSharpAPI6.betfair.api.global.LoginResp resp = simpleAPIWrapper.BFGlobalService.Endlogin(result);
var state = (CustomAsyncStateContainer)result.AsyncState;
// Return session to session manager
if (resp != null && resp.header != null && resp.header.sessionToken != null)
SessionTokenManager.ReturnSessionToken(resp.header.sessionToken);
DisplayLogin(resp, state);
}
}
#endregion
#region GetEventTypes
private IAsyncResult GetEventTypesAsyncRequest(eventTypesEnum taskType)
{
// Get session from session manager
string session = SessionTokenManager.GetSessionToken();
// If no session, log in and get another one
if (session == null)
{
session = MakeSession();
}
CSharpAPI6.betfair.api.global.GetEventTypesReq request = new CSharpAPI6.betfair.api.global.GetEventTypesReq();
request.header = new CSharpAPI6.betfair.api.global.APIRequestHeader();
request.header.sessionToken = session;
var myAsyncStateContainer = new CustomAsyncStateContainer(0, taskType, new object[]{taskType}, DateTime.Now);
if (taskType == eventTypesEnum.ALL)
{
return simpleAPIWrapper.BFGlobalService.BegingetAllEventTypes(request, GetEventTypesAsyncCallback, myAsyncStateContainer);
}
else if (taskType == eventTypesEnum.ACTIVE)
{
return simpleAPIWrapper.BFGlobalService.BegingetActiveEventTypes(request, GetEventTypesAsyncCallback, myAsyncStateContainer);
}
return null;
}
private delegate void GetEventTypesAsyncCallbackDelegate(IAsyncResult result);
private void GetEventTypesAsyncCallback(IAsyncResult result)
{
if (this.InvokeRequired)
{
try
{
GetEventTypesAsyncCallbackDelegate d = new GetEventTypesAsyncCallbackDelegate(GetEventTypesAsyncCallback);
this.Invoke(d, new object[] { result });
}
catch (Exception ex)
{
AddErrorToList(ex.ToString());
}
}
else
{
CSharpAPI6.betfair.api.global.GetEventTypesResp resp = simpleAPIWrapper.BFGlobalService.EndgetActiveEventTypes(result);
var state = (CustomAsyncStateContainer)result.AsyncState;
// Return session to session manager
if (resp != null && resp.header != null && resp.header.sessionToken != null)
SessionTokenManager.ReturnSessionToken(resp.header.sessionToken);
DisplayGetEventTypes(resp, state);
}
}
#endregion
#region GetEvent
private IAsyncResult GetEventAsyncRequest(int eventParentId, TreeNode node)
{
// Get session from session manager
string session = SessionTokenManager.GetSessionToken();
// If no session, log in and get another one
if (session == null)
{
session = MakeSession();
}
CSharpAPI6.betfair.api.global.GetEventsReq request = null;
request = new CSharpAPI6.betfair.api.global.GetEventsReq();
request.header = new CSharpAPI6.betfair.api.global.APIRequestHeader();
request.header.sessionToken = session;
request.eventParentId = eventParentId;
var state = new CustomAsyncStateContainer(0, node, new object[] { eventParentId, node }, DateTime.Now);
return simpleAPIWrapper.BFGlobalService.BegingetEvents(request, GetEventAsyncCallback, state);
}
private delegate void GetEventAsyncCallbackDelegate(IAsyncResult result);
private void GetEventAsyncCallback(IAsyncResult result)
{
if (this.InvokeRequired)
{
try
{
GetEventAsyncCallbackDelegate d = new GetEventAsyncCallbackDelegate(GetEventAsyncCallback);
this.Invoke(d, new object[] { result });
}
catch (Exception ex)
{
AddErrorToList(ex.ToString());
}
}
else
{
CSharpAPI6.betfair.api.global.GetEventsResp resp = simpleAPIWrapper.BFGlobalService.EndgetEvents(result);
var state = (CustomAsyncStateContainer)result.AsyncState;
// Return session to session manager
if (resp != null && resp.header != null && resp.header.sessionToken != null)
SessionTokenManager.ReturnSessionToken(resp.header.sessionToken);
DisplayGetEvent(resp, state);
}
}
#endregion
#region GetMarket
private IAsyncResult GetMarketAsyncRequest(int marketID, int exchangeId)
{
// Get session from session manager
string session = SessionTokenManager.GetSessionToken();
// If no session, log in and get another one
if (session == null)
{
session = MakeSession();
}
CSharpAPI6.betfair.api.exchange.GetMarketReq request = new CSharpAPI6.betfair.api.exchange.GetMarketReq();
request.header = new CSharpAPI6.betfair.api.exchange.APIRequestHeader();
request.header.sessionToken = session;
request.marketId = marketID;
var myAsyncStateContainer = new CustomAsyncStateContainer(exchangeId, this, new object[]{marketID, exchangeId}, DateTime.Now);
return simpleAPIWrapper.BFExchangeServiceByExchange(exchangeId).BegingetMarket(request, GetMarketAsyncCallback, myAsyncStateContainer);
}
private delegate void GetMarketAsyncCallbackDelegate(IAsyncResult result);
private void GetMarketAsyncCallback(IAsyncResult result)
{
if (this.InvokeRequired)
{
try
{
GetMarketAsyncCallbackDelegate d = new GetMarketAsyncCallbackDelegate(GetMarketAsyncCallback);
this.Invoke(d, new object[] { result });
}
catch (Exception ex)
{
AddErrorToList(ex.ToString());
}
}
else
{
var state = (CustomAsyncStateContainer)result.AsyncState;
CSharpAPI6.betfair.api.exchange.GetMarketResp resp = simpleAPIWrapper.BFExchangeServiceByExchange((Int32)state.exchangeID).EndgetMarket(result);
// Return session to session manager
if (resp != null && resp.header != null && resp.header.sessionToken != null)
SessionTokenManager.ReturnSessionToken(resp.header.sessionToken);
// Cache the response
simpleAPIWrapper.marketResp = resp;
DisplayGetMarket(resp, state);
}
}
#endregion
#region GetMarketPrices
private IAsyncResult GetMarketPricesAsyncRequest()
{
// Stop the timer
timer1.Enabled = false;
// Get session from session manager
string session = SessionTokenManager.GetSessionToken();
// If no session, log in and get another one
if (session == null)
{
session = MakeSession();
}
CSharpAPI6.betfair.api.exchange.GetMarketPricesReq request = new CSharpAPI6.betfair.api.exchange.GetMarketPricesReq();
request.header = new CSharpAPI6.betfair.api.exchange.APIRequestHeader();
request.header.sessionToken = session;
request.marketId = simpleAPIWrapper.marketResp.market.marketId;
var myAsyncStateContainer = new CustomAsyncStateContainer(simpleAPIWrapper.marketResp.market.licenceId, this, new object[] { simpleAPIWrapper.marketResp.market.marketId }, DateTime.Now);
return simpleAPIWrapper.BFExchangeServiceByExchange(myAsyncStateContainer.exchangeID).BegingetMarketPrices(request, GetMarketPricesAsyncCallback, myAsyncStateContainer);
}
private delegate void GetMarketPricesAsyncCallbackDelegate(IAsyncResult result);
private void GetMarketPricesAsyncCallback(IAsyncResult result)
{
if (this.InvokeRequired)
{
try
{
try
{
GetMarketPricesAsyncCallbackDelegate d = new GetMarketPricesAsyncCallbackDelegate(GetMarketPricesAsyncCallback);
this.Invoke(d, new object[] { result });
}
catch (Exception ex)
{
AddErrorToList(ex.ToString());
}
}
catch (Exception ex)
{
AddErrorToList(ex.ToString());
}
}
else
{
var state = (CustomAsyncStateContainer)result.AsyncState;
CSharpAPI6.betfair.api.exchange.GetMarketPricesResp resp = simpleAPIWrapper.BFExchangeServiceByExchange(state.exchangeID).EndgetMarketPrices(result);
// Return session to session manager
if (resp != null && resp.header != null && resp.header.sessionToken != null)
SessionTokenManager.ReturnSessionToken(resp.header.sessionToken);
// Cache the response
simpleAPIWrapper.pricesResp = resp;
// Start the timer
timer1.Enabled = true;
DisplayGetMarketPrices(resp, state);
}
}
#endregion
#region GetMarketPricesCompressed
private IAsyncResult GetMarketPricesCompressedAsyncRequest()
{
// Stop the timer
timer1.Enabled = false;
// Get session from session manager
string session = SessionTokenManager.GetSessionToken();
// If no session, log in and get another one
if (session == null)
{
session = MakeSession();
}
CSharpAPI6.betfair.api.exchange.GetMarketPricesCompressedReq request = new CSharpAPI6.betfair.api.exchange.GetMarketPricesCompressedReq();
request.header = new CSharpAPI6.betfair.api.exchange.APIRequestHeader();
request.header.sessionToken = session;
request.marketId = simpleAPIWrapper.marketResp.market.marketId;
var myAsyncStateContainer = new CustomAsyncStateContainer(simpleAPIWrapper.marketResp.market.licenceId, this, new object[] { simpleAPIWrapper.marketResp.market.marketId }, DateTime.Now);
return simpleAPIWrapper.BFExchangeServiceByExchange(myAsyncStateContainer.exchangeID).BegingetMarketPricesCompressed(request, GetMarketPricesCompressedAsyncCallback, myAsyncStateContainer);
}
private delegate void GetMarketPricesCompressedAsyncCallbackDelegate(IAsyncResult result);
private void GetMarketPricesCompressedAsyncCallback(IAsyncResult result)
{
if (this.InvokeRequired)
{
try
{
GetMarketPricesAsyncCallbackDelegate d = new GetMarketPricesAsyncCallbackDelegate(GetMarketPricesCompressedAsyncCallback);
this.Invoke(d, new object[] { result });
}
catch (Exception ex)
{
AddErrorToList(ex.ToString());
}
}
else
{
// Start the timer
timer1.Enabled = true;
var state = (CustomAsyncStateContainer)result.AsyncState;
var resp = simpleAPIWrapper.BFExchangeServiceByExchange(state.exchangeID).EndgetMarketPricesCompressed(result);
// Return session to session manager
if (resp != null && resp.header != null && resp.header.sessionToken != null)
SessionTokenManager.ReturnSessionToken(resp.header.sessionToken);
// Cache the response
simpleAPIWrapper.pricesCompressedResp = resp;
try
{
//Hammad//
Betfair.DataTypes.Sports.MarketPricesInfoDemo MarketPricesInfo = new Betfair.DataTypes.Sports.MarketPricesInfoDemo(resp);
// All Selections
foreach (Betfair.DataTypes.Sports.MarketPricesInfoDemo.SelectionPricesInfo info in MarketPricesInfo.CompletePriceInfo)
{
int gridIndex = 0;
// All 6 prices, left to right.
foreach(Betfair.DataTypes.Sports.MarketPricesInfoDemo.SelectionPricesInfo.OddsAvailablePriceInfo oddsPriceInfo in info.BestPrices(6))
{
/************* Populate grid here ***********************/
gridIndex++;
}
}
DisplayGetMarketPricesCompressed(MarketPricesInfo, state);
}
catch(Exception ex)
{
AddErrorToList(ex.ToString());
}
}
}
#endregion
private void panelRunnerInfo_Paint(object sender, PaintEventArgs e)
{
}
private void panelRunners_Paint(object sender, PaintEventArgs e)
{
}
private void lstBoxErrors_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
#region class CustomAsyncStateContainer
public class CustomAsyncStateContainer
{
public CustomAsyncStateContainer() { }
public CustomAsyncStateContainer(int exchangeID, object sender, object[] args, DateTime requestTimeStamp)
{
this.exchangeID = exchangeID;
this.sender = sender;
this.requestTimeStamp = requestTimeStamp;
this.args = args;
}
public int exchangeID;
public object sender;
public object[] args;
public DateTime requestTimeStamp;
}
#endregion
#region class SimpleAPIWrapper
/// <summary>
/// Just a simple class to store the working data neatly and some utiliterian functions
/// </summary>
public class SimpleAPIWrapper
{
private string _username;
public string username
{
get
{
if (_username == null) _username = "";
lock (_username)
return _username;
}
set
{
if (_username == null) _username = value;
else
lock (_username)
_username = value;
}
}
private string _password;
public string password
{
get
{
if (_password == null) _password = "";
lock (_password)
return _password;
}
set
{
if (_password == null) _password = value;
else
lock (_password)
_password = value;
}
}
public int productId;
public int softwareId;
public DateTime loginDateTime;
public bool useCompressedPrices;
public bool isFreeAPI
{
get
{
if (this.productId == 82)
return true;
else
return false;
}
}
public betfair.api.exchange.GetMarketResp marketResp;
public betfair.api.exchange.GetMarketPricesResp pricesResp;
public betfair.api.exchange.GetMarketPricesCompressedResp pricesCompressedResp;
public DateTime getMarketPricesHeaderTimeStamp;
/*** Global API Selector ***/
private betfair.api.global.BFGlobalService _BFGlobalService;
public betfair.api.global.BFGlobalService BFGlobalService
{
get
{
if (_BFGlobalService == null)
{
_BFGlobalService = new CSharpAPI6.betfair.api.global.BFGlobalService();
_BFGlobalService.EnableDecompression = true;
_BFGlobalService.Timeout = 5000;
_BFGlobalService.Url = "https://api.betfair.com/global/v3/BFGlobalService";
_BFGlobalService.UserAgent = "Betfair API6 C-Sharp Example Application";
_BFGlobalService.Timeout = 5000;
return _BFGlobalService;
}
else
return _BFGlobalService;
}
}
/*** Exchange API Selector ***/
private Dictionary<int, betfair.api.exchange.BFExchangeService> _BFExchangeService;
public betfair.api.exchange.BFExchangeService BFExchangeServiceByExchange(int exchangeId)
{
if (_BFExchangeService == null)
{
_BFExchangeService = new Dictionary<int, CSharpAPI6.betfair.api.exchange.BFExchangeService>();
}
if (exchangeId == 1)
{
if (_BFExchangeService.ContainsKey(exchangeId))
{
return _BFExchangeService[exchangeId];
}
else
{
betfair.api.exchange.BFExchangeService service = new CSharpAPI6.betfair.api.exchange.BFExchangeService();
service.EnableDecompression = true;
service.Url = "https://api.betfair.com/exchange/v5/BFExchangeService";
service.UserAgent = "Betfair API6 C-Sharp Example Application";
service.Timeout = 5000;
_BFExchangeService.Add(exchangeId, service);
return service;
}
}
if (exchangeId == 2)
{
if (_BFExchangeService.ContainsKey(exchangeId))
{
return _BFExchangeService[exchangeId];
}
else
{
betfair.api.exchange.BFExchangeService service = new CSharpAPI6.betfair.api.exchange.BFExchangeService();
service.EnableDecompression = true;
service.Url = "https://api-au.betfair.com/exchange/v5/BFExchangeService";
service.UserAgent = "Betfair API6 C-Sharp Example Application";
service.Timeout = 10000;
_BFExchangeService.Add(exchangeId, service);
return service;
}
}
return null;
}
/// <summary>
/// Returns the BFExchangeService based on the current this.marketResp.market.licenceId value
/// </summary>
public betfair.api.exchange.BFExchangeService BFExchangeService
{
get
{
return BFExchangeServiceByExchange(marketResp.market.licenceId);
}
}
public class BFEventComparer : IComparer
{
public int Compare(object x, object y)
{
return ((CSharpAPI6.betfair.api.global.BFEvent)x).orderIndex.CompareTo(((CSharpAPI6.betfair.api.global.BFEvent)y).orderIndex);
}
}
}
#endregion
}
using System;
using System.Collections.Generic;
namespace CSharpAPI6
{
public class frmPlacebet : System.Windows.Forms.Form
{
private int m_marketID;
private int m_selectionID;
private int m_asianLineID;
private string m_betType;
private SimpleAPIWrapper m_simpleAPIWrapper;
private System.Windows.Forms.TextBox txtStake;
private System.Windows.Forms.TextBox txtOdds;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label lblProgress;
private System.Windows.Forms.Button btnCancel;
private System.Windows.Forms.Button btnSubmit;
private System.ComponentModel.Container components = null;
public frmPlacebet(int marketID, int selectionID, int asianLineID, string betType, double odds, SimpleAPIWrapper simpleAPIWrapper)
{
InitializeComponent();
//
// TODO: Add any constructor code after InitializeComponent call
//
// Store the runner/market info
m_marketID = marketID;
m_selectionID = selectionID;
m_asianLineID = asianLineID;
m_betType = betType;
m_simpleAPIWrapper = simpleAPIWrapper;
// Set default odds
txtOdds.Text = odds.ToString();
}
#region Dispose
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#endregion
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.btnSubmit = new System.Windows.Forms.Button();
this.txtStake = new System.Windows.Forms.TextBox();
this.txtOdds = new System.Windows.Forms.TextBox();
this.label1 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.lblProgress = new System.Windows.Forms.Label();
this.btnCancel = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// btnSubmit
//
this.btnSubmit.Location = new System.Drawing.Point(224, 24);
this.btnSubmit.Name = "btnSubmit";
this.btnSubmit.TabIndex = 8;
this.btnSubmit.Text = "Submit";
this.btnSubmit.Click += new System.EventHandler(this.btnSubmit_Click);
//
// txtStake
//
this.txtStake.Location = new System.Drawing.Point(120, 24);
this.txtStake.Name = "txtStake";
this.txtStake.TabIndex = 7;
this.txtStake.Text = "2";
//
// txtOdds
//
this.txtOdds.Location = new System.Drawing.Point(8, 24);
this.txtOdds.Name = "txtOdds";
this.txtOdds.TabIndex = 6;
this.txtOdds.Text = "";
//
// label1
//
this.label1.Location = new System.Drawing.Point(8, 8);
this.label1.Name = "label1";
this.label1.TabIndex = 9;
this.label1.Text = "Odds";
//
// label2
//
this.label2.Location = new System.Drawing.Point(120, 8);
this.label2.Name = "label2";
this.label2.TabIndex = 10;
this.label2.Text = "Stake";
//
// lblProgress
//
this.lblProgress.Location = new System.Drawing.Point(8, 56);
this.lblProgress.Name = "lblProgress";
this.lblProgress.Size = new System.Drawing.Size(368, 40);
this.lblProgress.TabIndex = 11;
//
// btnCancel
//
this.btnCancel.Location = new System.Drawing.Point(304, 24);
this.btnCancel.Name = "btnCancel";
this.btnCancel.TabIndex = 12;
this.btnCancel.Text = "Close";
this.btnCancel.Click += new System.EventHandler(this.btnCancel_Click);
//
// frmPlacebet
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(386, 98);
this.Controls.Add(this.btnCancel);
this.Controls.Add(this.btnSubmit);
this.Controls.Add(this.txtStake);
this.Controls.Add(this.txtOdds);
this.Controls.Add(this.label1);
this.Controls.Add(this.label2);
this.Controls.Add(this.lblProgress);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow;
this.Name = "frmPlacebet";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "Place Bet";
this.ResumeLayout(false);
}
#endregion
#region btnCancel_Click
private void btnCancel_Click(object sender, System.EventArgs e)
{
this.Close();
}
#endregion
private void btnSubmit_Click(object sender, System.EventArgs e)
{
btnSubmit.Enabled=false;
btnCancel.Enabled=false;
placeBet();
btnSubmit.Enabled=true;
btnCancel.Enabled=true;
}
#region placeBet
private void placeBet()
{
// Get a session, or login
string session = SessionTokenManager.GetSessionToken();
if (session == null)
{
lblProgress.Text = "Connecting..."; lblProgress.Refresh();
throw new Exception("No session in \"private void placeBet()\"");
}
// Create a bet placement request and set the session token
CSharpAPI6.betfair.api.exchange.PlaceBetsReq req = new CSharpAPI6.betfair.api.exchange.PlaceBetsReq();
req.header = new CSharpAPI6.betfair.api.exchange.APIRequestHeader();
req.header.sessionToken = session;
// Create a single bet and set the market/runner/bet information
CSharpAPI6.betfair.api.exchange.PlaceBets bet = new CSharpAPI6.betfair.api.exchange.PlaceBets();
bet.asianLineId = m_asianLineID;
if(m_betType.ToLower()=="b")
bet.betType = CSharpAPI6.betfair.api.exchange.BetTypeEnum.B;
if(m_betType.ToLower()=="l")
bet.betType = CSharpAPI6.betfair.api.exchange.BetTypeEnum.L;
bet.marketId = m_marketID;
bet.price = Convert.ToDouble(txtOdds.Text);
bet.selectionId = m_selectionID;
bet.size = Convert.ToDouble(txtStake.Text);
bet.bspLiability = 0;
bet.betCategoryType = CSharpAPI6.betfair.api.exchange.BetCategoryTypeEnum.E;
bet.betPersistenceType = CSharpAPI6.betfair.api.exchange.BetPersistenceTypeEnum.NONE;
// Store the bet in the request
req.bets = new CSharpAPI6.betfair.api.exchange.PlaceBets[1];
req.bets[0] = bet;
// Display progress, and place the bet
lblProgress.Text = "Placing bet..."; lblProgress.Refresh();
CSharpAPI6.betfair.api.exchange.PlaceBetsResp resp = m_simpleAPIWrapper.BFExchangeService.placeBets(req);
// Display success or error message depending on result
if (resp.errorCode == CSharpAPI6.betfair.api.exchange.PlaceBetsErrorEnum.OK)
{
if (resp.betResults[0].sizeMatched > 0)
{
lblProgress.Text = string.Format("Placed bet {0:C}@{1}", resp.betResults[0].sizeMatched,
resp.betResults[0].averagePriceMatched);
}
else
{
lblProgress.Text = string.Format("Placed unmatched bet {0:C}@{1}", bet.size, bet.price);
}
}
else
{
lblProgress.Text = string.Format("Failed to place bet. Error codes: Sys {0}, Svc {1}",
resp.header.errorCode, resp.errorCode);
}
// Return the token to the session manager
SessionTokenManager.ReturnSessionToken(resp.header.sessionToken);
}
#endregion
}
}
using System;
using System.Windows.Forms;
using Market = CSharpAPI6.betfair.api.exchange.Market;
using Runner = CSharpAPI6.betfair.api.exchange.Runner;
namespace CSharpAPI6
{
/// <summary>
/// Summary description for MarketViewRow.
/// </summary>
public class MarketViewRow : System.Windows.Forms.UserControl
{
private Market m_market;
private Runner m_runner;
private SimpleAPIWrapper m_simpleAPIWrapper;
private System.Windows.Forms.Button btnLay3;
private System.Windows.Forms.Button btnLay2;
private System.Windows.Forms.Button btnLay;
private System.Windows.Forms.Button btnBack;
private System.Windows.Forms.Button btnBack2;
private System.Windows.Forms.Button btnBack3;
private System.Windows.Forms.Label lblRunner;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
public MarketViewRow(Market market, Runner runner)
{
// This call is required by the Windows.Forms Form Designer.
InitializeComponent();
if(runner!=null)
{
m_market = market;
m_runner = runner;
lblRunner.Text = runner.name;
}
}
public Runner Runner
{
get
{
return m_runner;
}
}
public void DisplayPrices(string currency, double backPrice1, double backAmountAvailable1, double backPrice2, double backAmountAvailable2, double backPrice3, double backAmountAvailable3, double layPrice1, double layAmountAvailable1, double layPrice2, double layAmountAvailable2, double layPrice3, double layAmountAvailable3, SimpleAPIWrapper simpleAPIWrapper)
{
m_simpleAPIWrapper = simpleAPIWrapper;
if (currency == "GBP") currency = "£";
if (currency == "USD") currency = "$";
if (currency == "ZAR") currency = "R";
btnBack.Text = (backPrice1 != 0.0)
? backPrice1.ToString() + "\n" + currency + " " + Math.Round(backAmountAvailable1, 0)
: string.Empty;
btnBack2.Text = (backPrice2 != 0.0)
? backPrice2.ToString() + "\n" + currency + " " + Math.Round(backAmountAvailable2, 0)
: string.Empty;
btnBack3.Text = (backPrice3 != 0.0)
? backPrice3.ToString() + "\n" + currency + " " + Math.Round(backAmountAvailable3, 0)
: string.Empty;
btnLay.Text = (layPrice1 != 0.0)
? layPrice1.ToString() + "\n" + currency + " " + Math.Round(layAmountAvailable1, 0)
: string.Empty;
btnLay2.Text = (layPrice2 != 0.0)
? layPrice2.ToString() + "\n" + currency + " " + Math.Round(layAmountAvailable2, 0)
: string.Empty;
btnLay3.Text = (layPrice3 != 0.0)
? layPrice3.ToString() + "\n" + currency + " " + Math.Round(layAmountAvailable3, 0)
: string.Empty;
}
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.btnLay3 = new System.Windows.Forms.Button();
this.btnLay2 = new System.Windows.Forms.Button();
this.btnLay = new System.Windows.Forms.Button();
this.btnBack = new System.Windows.Forms.Button();
this.btnBack2 = new System.Windows.Forms.Button();
this.btnBack3 = new System.Windows.Forms.Button();
this.lblRunner = new System.Windows.Forms.Label();
this.SuspendLayout();
//
// btnLay3
//
this.btnLay3.BackColor = System.Drawing.Color.White;
this.btnLay3.Dock = System.Windows.Forms.DockStyle.Right;
this.btnLay3.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.btnLay3.Font = new System.Drawing.Font("Microsoft Sans Serif", 8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.btnLay3.Location = new System.Drawing.Point(823, 0);
this.btnLay3.Name = "btnLay3";
this.btnLay3.Size = new System.Drawing.Size(55, 46);
this.btnLay3.TabIndex = 29;
this.btnLay3.UseVisualStyleBackColor = false;
this.btnLay3.Click += new System.EventHandler(this.btnLay_Click);
//
// btnLay2
//
this.btnLay2.BackColor = System.Drawing.Color.White;
this.btnLay2.Dock = System.Windows.Forms.DockStyle.Right;
this.btnLay2.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.btnLay2.Font = new System.Drawing.Font("Microsoft Sans Serif", 8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.btnLay2.Location = new System.Drawing.Point(768, 0);
this.btnLay2.Name = "btnLay2";
this.btnLay2.Size = new System.Drawing.Size(55, 46);
this.btnLay2.TabIndex = 30;
this.btnLay2.UseVisualStyleBackColor = false;
this.btnLay2.Click += new System.EventHandler(this.btnLay_Click);
//
// btnLay
//
this.btnLay.BackColor = System.Drawing.Color.Orchid;
this.btnLay.Dock = System.Windows.Forms.DockStyle.Right;
this.btnLay.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.btnLay.Font = new System.Drawing.Font("Microsoft Sans Serif", 8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.btnLay.Location = new System.Drawing.Point(713, 0);
this.btnLay.Name = "btnLay";
this.btnLay.Size = new System.Drawing.Size(55, 46);
this.btnLay.TabIndex = 31;
this.btnLay.UseVisualStyleBackColor = false;
this.btnLay.Click += new System.EventHandler(this.btnLay_Click);
//
// btnBack
//
this.btnBack.BackColor = System.Drawing.Color.LightBlue;
this.btnBack.Dock = System.Windows.Forms.DockStyle.Right;
this.btnBack.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.btnBack.Font = new System.Drawing.Font("Microsoft Sans Serif", 8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.btnBack.Location = new System.Drawing.Point(658, 0);
this.btnBack.Name = "btnBack";
this.btnBack.Size = new System.Drawing.Size(55, 46);
this.btnBack.TabIndex = 32;
this.btnBack.UseVisualStyleBackColor = false;
this.btnBack.Click += new System.EventHandler(this.btnBack_Click);
//
// btnBack2
//
this.btnBack2.BackColor = System.Drawing.Color.White;
this.btnBack2.Dock = System.Windows.Forms.DockStyle.Right;
this.btnBack2.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.btnBack2.Font = new System.Drawing.Font("Microsoft Sans Serif", 8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.btnBack2.Location = new System.Drawing.Point(603, 0);
this.btnBack2.Name = "btnBack2";
this.btnBack2.Size = new System.Drawing.Size(55, 46);
this.btnBack2.TabIndex = 33;
this.btnBack2.UseVisualStyleBackColor = false;
this.btnBack2.Click += new System.EventHandler(this.btnBack_Click);
//
// btnBack3
//
this.btnBack3.BackColor = System.Drawing.Color.White;
this.btnBack3.Dock = System.Windows.Forms.DockStyle.Right;
this.btnBack3.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.btnBack3.Font = new System.Drawing.Font("Microsoft Sans Serif", 8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.btnBack3.Location = new System.Drawing.Point(548, 0);
this.btnBack3.Name = "btnBack3";
this.btnBack3.Size = new System.Drawing.Size(55, 46);
this.btnBack3.TabIndex = 34;
this.btnBack3.UseVisualStyleBackColor = false;
this.btnBack3.Click += new System.EventHandler(this.btnBack_Click);
//
// lblRunner
//
this.lblRunner.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.lblRunner.Dock = System.Windows.Forms.DockStyle.Fill;
this.lblRunner.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.lblRunner.Location = new System.Drawing.Point(2, 0);
this.lblRunner.Name = "lblRunner";
this.lblRunner.Size = new System.Drawing.Size(546, 46);
this.lblRunner.TabIndex = 35;
this.lblRunner.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.lblRunner.Click += new System.EventHandler(this.lblRunner_Click);
//
// MarketViewRow
//
this.BackColor = System.Drawing.Color.White;
this.Controls.Add(this.lblRunner);
this.Controls.Add(this.btnBack3);
this.Controls.Add(this.btnBack2);
this.Controls.Add(this.btnBack);
this.Controls.Add(this.btnLay);
this.Controls.Add(this.btnLay2);
this.Controls.Add(this.btnLay3);
this.Name = "MarketViewRow";
this.Padding = new System.Windows.Forms.Padding(2, 0, 2, 2);
this.Size = new System.Drawing.Size(880, 48);
this.ResumeLayout(false);
}
#endregion
#region btnBack_Click
private void btnBack_Click(object sender, System.EventArgs e)
{
Button pressedButton = (Button)sender;
int marketId=0;
int runnerId=0;
int asianLineId=0;
int exchangeId = 0;
double backPrice= 1.01;
try
{
backPrice= Convert.ToDouble(pressedButton.Text.ToString());
}
catch
{}
marketId = m_market.marketId;
runnerId = m_runner.selectionId;
asianLineId = m_runner.asianLineId;
exchangeId = m_market.licenceId;
using (frmPlacebet sbm = new frmPlacebet(marketId, runnerId, asianLineId,"B", backPrice, m_simpleAPIWrapper))
{
sbm.ShowDialog();
sbm.Dispose();
}
}
#endregion
#region btnLay_Click
private void btnLay_Click(object sender, System.EventArgs e)
{
Button pressedButton = (Button)sender;
int marketId=0;
int runnerId=0;
int asianLineId = 0;
int exchangeId = 0;
double layPrice= 1.01;
try
{
layPrice= Convert.ToDouble(pressedButton.Text.ToString());
}
catch
{}
marketId = m_market.marketId;
runnerId = m_runner.selectionId;
asianLineId = m_runner.asianLineId;
exchangeId = m_market.licenceId;
using (frmPlacebet sbm = new frmPlacebet(marketId, runnerId, asianLineId,"L", layPrice, m_simpleAPIWrapper))
{
sbm.ShowDialog();
sbm.Dispose();
}
}
#endregion
private void lblRunner_Click(object sender, EventArgs e)
{
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment