Using VB2008 to acccess the Betfair API: A tutorial

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Mumbles0
    Junior Member
    • Jan 2009
    • 240

    #571
    BigSprout,

    Graphics is indeed an interesting topic.

    As you've got it, the sub will only draw a rectangle on Me - being the form on which the sub is located. If you want to draw a rectangle on another form then add an extra parameter to specify the target form:

    Code:
    [COLOR="Gray"]Sub AddRectangle([COLOR="Black"]ByVal TheForm As Form,[/COLOR] ByVal Lt As Integer, ByVal Tp As Integer, ByVal Wd As Integer, ByVal Ht As Integer)
        'Add rectangles to the Web Page Form for the Price/Volume charts
    
        Dim myBrush As New System.Drawing.SolidBrush(System.Drawing.Color.Red)
        Dim myPen As New System.Drawing.Pen(System.Drawing.Color.Black)
        Dim formGraphics As System.Drawing.Graphics
    
        formGraphics = [COLOR="Black"]TheForm[/COLOR].CreateGraphics()
        formGraphics.DrawRectangle(myPen, New Rectangle(Lt, Tp, Wd, Ht))
        formGraphics.FillRectangle(myBrush, New Rectangle(Lt, Tp, Wd, Ht))
        myPen.Dispose()
        myBrush.Dispose()
        formGraphics.Dispose()
    
      End Sub[/COLOR]
    You can then call it from any form like this:

    AddRectangle(Me, 20, 10, 200, 300)
    or perhaps:
    AddRectangle(Form2, 20, 10, 200, 300)

    Comment

    • BigSprout
      Junior Member
      • Feb 2011
      • 60

      #572
      Thanks for that Mumbles, your way is going to be much neater than how I resolved the problem (temporarily), I added this on Form2:

      Code:
         [COLOR="Gray"]Sub wb_AddRectangle([COLOR="Black"]ByVal e As System.Windows.Forms.PaintEventArgs[/COLOR], ByVal Lt As Integer, ByVal Tp As Integer, ByVal Wd As Integer, ByVal Ht As Integer)
      
              ...the code...
      
          End Sub[/COLOR]
      on the main Form did this:

      Code:
          [COLOR="Gray"]Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
      
              [COLOR="Black"]Dim f As System.Windows.Forms.PaintEventArgs[/COLOR]
              FmWebPage.Show()
              FmWebPage.Left = Me.Left + Me.Width
              FmWebPage.WindowState = FormWindowState.Maximized
              FmWebPage.wb_AddRectangle([COLOR="Black"]f[/COLOR], 20, 20, 500, 400)
      
          End Sub[/COLOR]


      I got this warning, but the the rectangle displayed on FmWebPage okay:

      Warning 1 Variable 'f' is used before it has been assigned a value. A null reference exception could result at runtime...
      Away this weekend, so will have another play next week and report - this is a steep learning curve for me from Delphi-6 (which was outdated by the new millennia)

      cheers Les



      Edited:
      Just re-read your post:
      As you've got it, the sub will only draw a rectangle on Me - being the form on which the sub is located...
      the sub "AddRectangle" was on Form2 but would not display the rectangle on Form2 until I added "ByVal e As System.Windows.Forms.PaintEventArgs" as a parameter, this then added the "f" warning.
      Note. deleted using the "Paint" Sub method as it continually fired (which I didn't want happening
      Last edited by BigSprout; 25-02-2011, 12:57 AM. Reason: re-read answer

      Comment

      • Sports API + VB .Net
        Junior Member
        • Sep 2010
        • 11

        #573
        Thanks for your reply bro. but the treeview is not working for me i am using service buk.getallmarkets and it displays main events correctly Cricket , Snooker , Horse Racing but when i double click on Cricket event it shows child markets in groups like Group C then other perticular market and sometime it double the same event and sometime more then 2 times double .. the treeview i want is as same as on betfair website how is it possible please help me out

        Comment

        • BigSprout
          Junior Member
          • Feb 2011
          • 60

          #574
          Sports,
          checking out how the treeview has been used in the tutorial, I assume you have done the same and you are using:

          Code:
             Private Sub TreeView1_AfterSelect(ByVal sender As System.Object, ByVal e As System.Windows.Forms.TreeViewEventArgs) Handles TreeView1.AfterSelect
          
          	My code is here
          
              End Sub
          if that is the case then every time you click on a node it will fire, double click causing double readings, the computer(Treeview) is doing what you are telling it to do.

          What you need to do is investigate using:

          Code:
             Private Sub TreeView1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles TreeView1.Click
          
          	Code for single click events
          
              End Sub
          
          
          
              Private Sub TreeView1_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles TreeView1.DoubleClick
          
           	Code for double click events
          
             End Sub
          One problem is that the Treeview_click/doubleclick do not have the parameter "ByVal e As System.Windows.Forms.TreeViewEventArgs" and so you will not be able to use "e.node" without declaring "....TreeviewEventArgs"

          I didn't need a treeview, so did not investigate further on its workings, but when I have a problem I click on "Help" in the VS2010 and use a few key words for a search.

          Here is something that come up on "Treeview doubleclick" search:
          http://social.msdn.microsoft.com/for...2-5543A60467A3


          cheers Les

          Comment

          • Mumbles0
            Junior Member
            • Jan 2009
            • 240

            #575
            Graphics (continued)

            BigSprout,

            I think you are getting a bit confused by the graphics.
            Let’s look at some fundamentals...

            This code draws a rectangle on a form:

            Code:
            Private Sub bDraw_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bDraw.Click
            
              Dim Graph As Graphics = Me.CreateGraphics   'The graphics object
              Graph.DrawRectangle(Pens.Blue, 20, 10, 200, 300)  'Draw the rectangle
            
            End Sub
            Here Graph is a System.Drawing.Graphics object which incorporates all of the drawing methods we require. I like to think of this object as representing the drawing surface of the current form. We draw the desired rectangle using the DrawRectangle method.

            There you have it. But ......

            The drawing is very fragile. If you put something in front of it on the desktop, it will erase.

            To overcome this problem, graphics are typically drawn from within a form’s Paint event. This event fires whenever the form is required to be redrawn. If you put a Beep() statement in the Paint event handler and rearrange your Desktop a bit you will see what I mean.

            So alternatively we can draw the rectangle from within the Paint event like this:

            Code:
            Private Sub Form1_Paint(ByVal sender As Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles Me.Paint
            
              e.Graphics.DrawRectangle(Pens.Blue, 20, 10, 200, 300)  'Draw the rectangle
            
            End Sub
            Now the rectangle persists. It is redrawn by the Paint event whenever the system deems that repainting is required. Note that here we do not have to create a Graphics object. One is given to us in the e.Graphics parameter.

            So that’s what the Paint event is for. Personally I find this quite dumb, but there is a better way using buffered graphics. We might have a look at this in a future step.

            Comment

            • BigSprout
              Junior Member
              • Feb 2011
              • 60

              #576
              Personally I find this quite dumb, but there is a better way using buffered graphics.
              You're right, with a nice break and starting afresh, it kind of all fell into place - I do not know what I was doing wrong in not getting the graphics to display on another form, but after removing the parameter "dim g As System.Windows.Forms.PaintEventArgs"...etc it still all worked.

              Moved on to now displaying graphs of the price changes and updating every second.

              Eagerly awaiting future steps in displaying graphics to see how far off track I have gone.

              cheers Les

              Comment

              • 1nner
                Junior Member
                • Mar 2011
                • 11

                #577
                Session not expiring

                Hi,

                Thanks for the great tutorial, it's extremely helpful. One thing I noticed when loading the saved session ID is that it continues to successfully work (ie I don't have to re login) for many hours (10+) after I've been away from the computer. I thought it was meant to time out after 20 minutes for security. Do you have any idea why this might be happening?

                Regards,

                Andrew
                Last edited by 1nner; 01-03-2011, 03:40 PM.

                Comment

                • Sports API + VB .Net
                  Junior Member
                  • Sep 2010
                  • 11

                  #578
                  Thanks mumble everything is fine on befairtester form but where to place this lines so that everytime when i double click on a market from treeviewer it display selectionids and their prices (as happens on betfair website)

                  With MpriceResp.marketPrices
                  For i = 0 To .runnerPrices.Length - 1 'Look up the runnerPrices array
                  With .runnerPrices(i)
                  If .selectionId = 3013615 Then 'selectionId match

                  'The price data for Rio Royale is available here

                  Exit For
                  End If
                  End With
                  Next
                  End With

                  one more thing i want to ask how to make treeview as same as betfair means where and when to fire getmarkets and other required services and what will be a piece of code to display data from respond array to grid (and also suggest me which grid of vb2010 is more efficient) i want to design a bot as same as betfair main website . please dont ignore i will be waiting for your kind reply Mumble.......

                  Comment

                  • Sports API + VB .Net
                    Junior Member
                    • Sep 2010
                    • 11

                    #579
                    Hi Mumble thanks for help but i want little more help , i am using the same piece of code on my tester and populate treeview function in module unpack but the result is not as same as i expected this is what i am getting:
                    1st of all my treeview loads like:
                    +Soccer
                    +Tennis
                    +Cricket
                    +HorseRacing
                    when i click on cricket it shows like :
                    -Cricket
                    +Group C
                    +Group C
                    +Group C
                    when i click on Group C then:
                    -Cricket
                    -Group C
                    +ICC Cricket World Cup 2011 (some have childs)
                    ICC Cricket World Cup 2011 (some dont have childs)
                    +ICC Cricket World Cup 2011
                    +ICC Cricket World Cup 2011
                    ICC Cricket World Cup 2011
                    ICC Cricket World Cup 2011
                    +ICC Cricket World Cup 2011
                    When i click on 1st +icc cricketworldcup 2011 it shows
                    +fixture 02March
                    When i click on 2nd +icc cricketworldcup 2011 it shows
                    +fixture 03March
                    why this is happening you have mention in your help that it is prefereble to use menu name instead of ids but when i run the for loop in populate treeview function in module unpack you had mention then i did'nt get any id for further getmarkets and other services please help me out

                    Comment

                    • Mumbles0
                      Junior Member
                      • Jan 2009
                      • 240

                      #580
                      Session timeout

                      1nner,

                      The API Guide mentions that a session will expire after about 20 minutes of inactivity. For as long as I have been using the API (about 3 years) this does not seem to be the case. From my experience, inactive session tokens persist a lot longer than 20 minutes. They usually remain current for a day or two. I don’t know why this is so.

                      However, this does not unduly worry me (in fact I find it convenient). Saves me having to log in all the time.

                      Note that all communications (which will contain the session token) between your computer and the API are encrypted. This level of security should be adequate for most purposes.

                      If you are using a computer that can be accessed by others, and you don’t like the idea of having an active session token hanging around, then it’s a good idea to log out rather than leave your session idle.

                      Comment

                      • Mumbles0
                        Junior Member
                        • Jan 2009
                        • 240

                        #581
                        Reply to Sports API + VB. Net

                        App to show runners & prices

                        I have said this before - I am not going to write your application for you. But you can proceed like this:

                        The grid to use is a DataGridView, which you will find in the ToolBox. You place this on your form and set up columns for runner name, selectionId, best back prices, and best lay prices. You must learn how to do this.

                        When you click on a market in your TreeView, the AfterSelect event fires. From this event handler you call getMarket to return the list of runners (see Step 12). You load a column of the DataGridView with the list of runners, and put the selectionIds in another column.

                        From the Tick event of a timer you can call getMarketPricesCompressed to get the best back and lay prices (see Step 14). You then update the appropriate columns in the grid with these prices.

                        Cricket Group C

                        There is a problem with getAllMarkets, affecting Tennis, Golf, Cricket and Rugby Union. An unwanted GROUP heading is given in the menuPath. You can eliminate this by modifying the PopulateTreeView sub as shown here:

                        Code:
                        [COLOR="Gray"]Friend Sub PopulateTreeView(ByVal AllMarkets As UnpackAllMarkets, ByVal TreeView As TreeView)
                          Dim Ids, Names As String(), Nodes As TreeNodeCollection
                        
                          TreeView.Nodes.Clear()             'Start afresh
                          With AllMarkets
                            For i = 0 To .marketData.Length - 1   'For each market
                              With .marketData(i)
                                Ids = .eventHeirachy.Split("/")  'Array of Ids
                                Names = .menuPath.Split("\")   'Array of names
                        
                        [COLOR="Black"]        If Ids.Length = Names.Length Then  'Workaround to remove "Group" names in tennis, golf, cricket & rugby union
                                  Dim n = UBound(Names)
                                  For j = 3 To n
                                    Names(j - 1) = Names(j)
                                  Next
                                  ReDim Preserve Names(n - 1)
                                End If[/COLOR]
                        
                                Nodes = TreeView.Nodes      'Initial collection of child nodes
                                For j = 1 To UBound(Ids)  'For each event list item
                                  If Not Nodes.ContainsKey(Ids(j)) Then
                                    Dim Node As New TreeNode   'Add a new node if it doesn't exist
                                    Node.Text = If(j <= UBound(Names), Names(j), .marketName)
                                    Node.Name = Ids(j)  'This is the key
                                    Nodes.Add(Node)
                                  End If
                                  Nodes = Nodes(Ids(j)).Nodes  'Next level down
                                Next
                              End With
                            Next
                          End With
                        
                        End Sub[/COLOR]

                        Comment

                        • Sports API + VB .Net
                          Junior Member
                          • Sep 2010
                          • 11

                          #582
                          Mumble Thanks for your kind reply but let me tell you that my intention was'nt to bother you but to understand the basic of how to design a bot for my use because i am not a expert developer but with your help now i am able to accomplish my pending tasks plus in future if i stuck somewhere in programming a bot i will again ask for your help i hope you will not mind this..... Thanks Again Brother.

                          Comment

                          • Sports API + VB .Net
                            Junior Member
                            • Sep 2010
                            • 11

                            #583
                            Hi Mumble regarding this post my question is that , through this tutorial i have learned to call the api service like "getmarket" through button but if requirment is that when using treeview we double click on anymarket so how will we assign some values of button "bRunners" like .marketstatus or .name to any lable on our project will we make globle variable or how ? please sorry if i have again bother you.........
                            i want to use some values from different api calls to my project like on banner i want to show selected marketstatus, marketname, numberofrunners, no.ofwinners etc etc how will this task done please help me out.......... i have no one but only you to ask question ... please reply

                            Comment

                            • 1nner
                              Junior Member
                              • Mar 2011
                              • 11

                              #584
                              Originally posted by Mumbles0 View Post
                              1nner,

                              The API Guide mentions that a session will expire after about 20 minutes of inactivity. For as long as I have been using the API (about 3 years) this does not seem to be the case. From my experience, inactive session tokens persist a lot longer than 20 minutes. They usually remain current for a day or two. I don’t know why this is so.

                              However, this does not unduly worry me (in fact I find it convenient). Saves me having to log in all the time.

                              Note that all communications (which will contain the session token) between your computer and the API are encrypted. This level of security should be adequate for most purposes.

                              If you are using a computer that can be accessed by others, and you don’t like the idea of having an active session token hanging around, then it’s a good idea to log out rather than leave your session idle.
                              Thanks for that - as long as they do expire eventually I'm not too worried.

                              Cheers

                              Comment

                              • vrps1991
                                Junior Member
                                • Mar 2011
                                • 1

                                #585
                                Hi people.
                                I would like how can i modified it:

                                Code:
                                Module Unpack
                                    Class MarketDataType           'For getAllMarkets data
                                        Public marketId As Integer
                                        Public marketName As String
                                        Public marketType As String
                                        Public marketStatus As String
                                        Public eventDate As DateTime
                                        Public menuPath As String
                                        Public eventHeirachy As String
                                        Public betDelay As Integer
                                        Public exchangeId As Integer
                                        Public countryCode As String
                                        Public lastRefresh As DateTime
                                        Public noOfRunners As Integer
                                        Public noOfWinners As Integer
                                        Public totalAmountMatched As Double
                                        Public bspMarket As Boolean
                                        Public turningInPlay As Boolean
                                    End Class
                                
                                    Class UnpackAllMarkets       'For getAllMArkets
                                        Public marketData As MarketDataType() = {}  'The returned array of market data
                                        Private Const BaseDate As DateTime = #1/1/1970#
                                        Private Const ColonCode = "&%^@"  'The substitute code for "\:"
                                
                                        Sub New(ByVal MarketString As String)
                                            Dim n As Integer, Mdata, Field As String()
                                
                                            Mdata = MarketString.Replace("\:", ColonCode).Split(":") 'Get array of Market substrings
                                            n = UBound(Mdata) - 1
                                            ReDim marketData(n)
                                
                                            For i = 0 To n
                                                Field = Mdata(i + 1).Replace("\~", "-").Split("~") 'Get array of data fields
                                                marketData(i) = New MarketDataType
                                                With marketData(i)
                                                    .marketId = Field(0)   'Load the array items
                                                    .marketName = Field(1).Replace(ColonCode, ":")
                                                    .marketType = Field(2)
                                                    .marketStatus = Field(3)
                                                    .eventDate = BaseDate.AddMilliseconds(Field(4))
                                                    .menuPath = Field(5).Replace(ColonCode, ":")
                                                    .eventHeirachy = Field(6)
                                                    .betDelay = Field(7)
                                                    .exchangeId = Field(8)
                                                    .countryCode = Field(9)
                                                    .lastRefresh = BaseDate.AddMilliseconds(Field(10))
                                                    .noOfRunners = Field(11)
                                                    .noOfWinners = Field(12)
                                                    .totalAmountMatched = Val(Field(13))
                                                    .bspMarket = (Field(14) = "Y")
                                                    .turningInPlay = (Field(15) = "Y")
                                
                                                End With
                                            Next
                                        End Sub
                                    End Class
                                End Module
                                to obtain:

                                Market Info;
                                Selections (First runner);
                                Winner ;
                                Back Prices
                                and
                                Profit/Loss

                                ?

                                Someone can help me?

                                Comment

                                Working...
                                X