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

    #256
    Reply to supunsilva (re: getMarketTradedVolumeCompressed)

    Your output shows that you have succeeded in getting the market traded volume data. This is good, but it is in compressed form. You must now decompress (unpack) the string.

    To do this you can use the classes shown in this post. (These classes are RunnerVolumeType, VolumeType and UnpackMarketTradedVolumeCompressed.) Then add some more code to unpack the data:

    Code:
    [COLOR="DimGray"]Dim ToMreq As New BFUK.GetMarketTradedVolumeCompressedReq
    Dim ToMresp As BFUK.GetMarketTradedVolumeCompressedResp
    
    With ToMreq
      .header = oHeaderUK()
      .marketId = marketId
    End With
    ToMresp = BetfairUK2.getMarketTradedVolumeCompressed(ToMreq)
    With ToMresp
      CheckHeader(.header)
      If .errorCode = BFUK.GetMarketTradedVolumeCompressedErrorEnum.OK Then
        txtstake.Text = .tradedVolume
    
    [COLOR="Black"]    Dim oTradedVolume As New UnpackMarketTradedVolumeCompressed(.tradedVolume)  'Unpack the data string
        With oTradedVolume
          For i = 0 To .RunnerVolume.Length - 1
            With .RunnerVolume(i)
              Print("selectionId = " & .selectionId)
              For j = 0 To .tradedVolume.Length - 1   'This is the table of traded amounts for each runner
                Print("odds = " & .tradedVolume(j).odds & " amt = " & .tradedVolume(j).totalMatchedAmount)
              Next
            End With
          Next
        End With[/COLOR]
    
       End If
    End With[/COLOR]
    All the data is now in the oTradedVolume object. Here we print out some values just to show you what’s in there.

    I will soon post a new step showing how to call getMarketTradedVolumeCompressedAsync.

    Comment

    • supunsilva.
      Junior Member
      • Aug 2009
      • 32

      #257
      Thanks buddy. I am waiting for your getMarketTradedVolumeCompressedAsync....

      Regards,
      Supun Silva

      Comment

      • Mumbles0
        Junior Member
        • Jan 2009
        • 240

        #258
        Step 24. Calling getMarketTradedVolumeCompressed

        The API service getMarketTradedVolumeCompressed returns the values shown in the ‘Price’ and ‘Traded’ columns on the ‘Market Information’ page for each runner shown on the website page for a market. This shows you the amounts that have been traded at each price increment.

        The returned data can be used in conjunction with data returned by getCompleteMarketPricesCompressed. For example, at a particular price value, if the back amount available reduces, you can determine whether this change was caused by bets being matched or unmatched bets being withdrawn.

        This service can be called 60/min on the free API. Because a typical app will call this fairly frequently It’s best to call getMarketTradedVolumeCompressedAsync because this is more efficient.

        This call returns the compressed .tradedVolume string which can be unpacked using these classes. (Add these to module Unpack2):

        Code:
        'Classes for unpacking getMarketTradedVolumeCompressed:
        
        Class RunnerVolumeType
          Public selectionId As Integer
          Public asianLineId As Integer
          Public actualBSP As Double
          Public totalBspBackMatchedAmount As Double
          Public totalBspLiabilityMatchedAmount As Double
          Public tradedVolume As VolumeType()
        End Class
        
        Class VolumeType
          Public odds As Double
          Public totalMatchedAmount As Double
        End Class
        
        Class UnpackMarketTradedVolumeCompressed
          Public RunnerVolume As RunnerVolumeType() = {}
        
          Sub New(ByVal TradedVolume As String)
            Dim Tvolume, Part, Field As String(), m, n As Integer
        
            Tvolume = TradedVolume.Split(":")    'Split volume data for each runner
            n = UBound(Tvolume) - 1
            ReDim RunnerVolume(n)
            For i = 0 To n    'For each runner
              Part = Tvolume(i + 1).Split("|")
              Field = Part(0).Split("~")
              RunnerVolume(i) = New RunnerVolumeType
              With RunnerVolume(i)
                .selectionId = Field(0)
                .asianLineId = Field(1)
                .actualBSP = Val(Field(2))
                .totalBspBackMatchedAmount = Val(Field(3))
                .totalBspLiabilityMatchedAmount = Val(Field(4))
                m = UBound(Part) - 1
                ReDim .tradedVolume(m)
                For j = 0 To m
                  Field = Part(j + 1).Split("~")
                  .tradedVolume(j) = New VolumeType
                  .tradedVolume(j).odds = Val(Field(0))
                  .tradedVolume(j).totalMatchedAmount = Val(Field(1))
                Next
              End With
            Next
          End Sub
        End Class
        When an new instance of class UnpackMarketTradedVolumeCompressed is created, Sub New unpacks the .tradedVolume string. Its operation is similar to that described in Step 10 for unpacking getCompleteMarketPricesCompressed, but the logic is slightly different to match the different data structure (it is a bit simpler). If you wish you can single step through this to see how it works.

        The object thus created contains an array of RunnerVolumeType. The properties of this are described in the API Guide.

        To test the call add another button to the TestForm. Name it bGetMTVComp and change its Text property to something like TradedVolume. Double-click it to create its event handler Sub bGetMTVComp_Click. Add this code:

        Code:
        Private Sub bGetMTVComp_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bGetMTVComp.Click
          Print("*** MarketTradedVolume ***")
          Dim oMTVCReq As New BFUK.GetMarketTradedVolumeCompressedReq      'The request object
          With oMTVCReq
            .header = oHeaderUK()
            .marketId = [i]YourMarketIdOfInterest[/i]       'An active market ID
          End With
          StateCount += 1
          BetFairUK.getMarketTradedVolumeCompressedAsync(oMTVCReq, StateCount)    'Call the API
        End Sub
        This is an Async call which requires an event handler. In the Class Name box select BetFairUK. In the Method Name box click on getMarketTradeVolumeCompressedCompleted. Add this code:

        Code:
        Private Sub BetFairUK_getMarketTradedVolumeCompressedCompleted(ByVal sender As Object, ByVal e As BFUK.getMarketTradedVolumeCompressedCompletedEventArgs) Handles BetFairUK.getMarketTradedVolumeCompressedCompleted
          Try
            If Not e.Cancelled Then
              With e.Result
                CheckHeader(.header)
                Print("ErrorCode = " & .errorCode.ToString)
                If .errorCode = BFUK.GetMarketTradedVolumeCompressedErrorEnum.OK Then
                  Dim oTradedVolume As New UnpackMarketTradedVolumeCompressed(.tradedVolume)  'Unpack the traded volume data
                  With oTradedVolume  'Process the unpacked data
                    For i = 0 To .RunnerVolume.Length - 1   'For each runner
                      With .RunnerVolume(i)
                        Print("selectionId = " & .selectionId & " -----")
                        For j = 0 To .tradedVolume.Length - 1  'Print the table of odds and amounts matched
                          Print("odds = " & .tradedVolume(j).odds & " amt = " & .tradedVolume(j).totalMatchedAmount)
                        Next
                      End With
                    Next
                  End With
                End If
              End With
            End If
        
          Catch ex As ApplicationException  'If problem
            Print(ex.Message)
          End Try
        End Sub
        This is the “callback” procedure which handles the response. To demonstrate what is returned, this sub prints the table of odds and amounts matched for each runner.

        Note that, unlike getMarketPricesCompressed, there is no .sortOrder parameter. To determine which table belongs to which runner you will have to match selectionIds.

        Comment

        • Chasing Mug
          Junior Member
          • Oct 2009
          • 3

          #259
          TimeZone field in GetBethistoryReq

          Hi,

          Can someone explain the functioning of timezone in GetBetHistoryReq...My betfair account's timezone preference is set to INT...In the client application, even though i assign timezone field as INT it seems that fromdate and todate fields are being taken as GMT times and corresponding history for bets in this time period are being returned...Is timezone working properly because it takes any string and process GetBetHistory and is there a way to send them as INT dates rather than GMT?

          Thanks in Advance,
          Chasing Mug.

          Comment

          • leeboy1
            Junior Member
            • Jul 2009
            • 1

            #260
            place a bet

            how to place a bet using .net application.

            Comment

            • supunsilva.
              Junior Member
              • Aug 2009
              • 32

              #261
              RE:: leeboy1... Please read all of pages in "Using VB2008 to acccess the Betfair API: A tutorial" under .NET. You can find how to do everything with .NET applications..


              Thank you,
              Supun Silva

              Comment

              • Drifter
                Junior Member
                • Mar 2009
                • 30

                #262
                where next...

                Mumbles,

                I'm curious how many more areas you can explore with this thread now. Do you have specific plans for new functionality? If not, it seems that there are a couple of common items which might be worth tackling (and I appreciate from your earlier comments that this is a part time / fun exercise for you). One would be database back-ends - perhaps for something simple like recording bets (though I appreciate this is not API as such, and could be considered far enough off topic to be irrelevant). The other would be (multi) threading - monitoring say 2 markets at once and how the API calls for data and bet placement might be locked and properly isolated. I appreciate again it isn't an API call tutorial as such, but it is just a suggestion of something which might interest a lot of folk.
                Last edited by Drifter; 29-10-2009, 01:24 PM.

                Comment

                • Mumbles0
                  Junior Member
                  • Jan 2009
                  • 240

                  #263
                  Reply to Chasing Mug (re: timezone)

                  The timezone parameter in the getBetHistory request doesn’t seem to do much. I wouldn’t include it because you don’t need it. The values produced by .NET’s standard DateTime methods (Today, Now, etc.) have timezone information “built in” which is obtained from your computer’s timezone setting.

                  For example, if you wish to get details of bets placed between, say, 9am and 6pm yesterday (your local time) you can write:

                  Code:
                    .placedDateFrom = Today.AddDays(-1).AddHours(9)
                    .placedDateTo = Today.AddDays(-1).AddHours(18)
                  This will work from any timezone, even though the API expects time values as GMT. How does this work? The expression Today.AddDays(-1).AddHours(9) evaluates to 9am yesterday (your local time). This gets serialized and sent to the API as something like:
                  “2009-10-27T09:00:00+05:30”

                  The “+05:30” part denotes your timezone. The API evaluates this to 2009-10-27 3:30am which is the equivalent GMT.



                  DateTime values returned in the response can simply be converted to local time using the ToLocalTime method, for example:

                  Code:
                    Dim BetPlaced as Date = Resp.placedDate.ToLocalTime
                  Last edited by Mumbles0; 29-10-2009, 05:00 AM.

                  Comment

                  • Chasing Mug
                    Junior Member
                    • Oct 2009
                    • 3

                    #264
                    Regarding discount field for commission calculation

                    Hi Mumbles,

                    Thanks for replying regarding timezones and it worked well. I din't quite understand because when i was fetching dates from a datetimepicker, it was taking them as GMT times (i.e without conversion), but now I'm using Timespan object to get the difference of dates and DateTime method Today.AddDays.This way API is understanding that the input is from a different timezone. Is there any specific reason for this?

                    I have another issue with discount field for commission calculation. To my knowledge, i guess we need user specific discount rate to calculate commission apart from Market Base Rate (commission rate on market). Is there a service with which we can fetch this field or any workaround to accomplish commission calculation?

                    Regards
                    Chasing Mug

                    Comment

                    • Mumbles0
                      Junior Member
                      • Jan 2009
                      • 240

                      #265
                      Reply to Chasing Mug (timezone & discount)

                      Timezone (continued)

                      The more I look at timezones and DateTime objects the more confused I become.

                      If you are using DateTimePicker controls from the VB Toolbox you could try something like this to ensure that their DateTime values are interpreted as local time:

                      Code:
                      .placedDateFrom = DateTime.SpecifyKind(DateTimePicker1.Value, DateTimeKind.Local)
                      .placedDateTo = DateTime.SpecifyKind(DateTimePicker2.Value, DateTimeKind.Local)
                      Here DateTimePicker1 and DateTimePicker2 are used to input the From and To dates. The .Value property of these controls must first be initialised to a specific date (e.g. Today).

                      Discount

                      I can’t see anything in the API guide about getting a user’s current discount. I don’t know much about this subject. You could try asking the question in the “General Betting” section.

                      Comment

                      • Mumbles0
                        Junior Member
                        • Jan 2009
                        • 240

                        #266
                        Reply to Drifter (re: where next?)

                        Drifter,

                        I started this thread to demonstrate just how easy it is to connect to the various API services using VB2008. Judging by some of the comments posted, I believe it has served this purpose (thanks to all for the kind remarks).

                        This thread has been largely unplanned and has gone where it wanted to go. It has looked at the basic access techniques and I don’t think there is much more to cover in this area. I have been thinking about adding a few steps covering some controls for the display of data returned from the API. Also, elementary project structure might be another topic of interest to newbies.

                        I am still open to suggestions and you have given a couple of good ones.

                        Database

                        This is a very large topic and would make a good subject for another thread (“Using SQL with API data”), but I would not be the one to write this. As yet I have not been up this learning curve.

                        Multithreading

                        Again a large topic worthy of it own thread. The tutorial has touched on this with async calls - where the system does the multithreading work for us. Apart from this, I don’t really know enough about this advanced subject to set examples. Personally, I get by with async calls. The main limitation seems to be the inability to control the timeout if calls don’t return.

                        M0.

                        Comment

                        • supunsilva.
                          Junior Member
                          • Aug 2009
                          • 32

                          #267
                          Taking 3 to 5 seconds to placebet

                          Hi.. Mo... and all.......

                          I have problem with placing bets. It is taking upto 3-5 seconds to place bet and until bet placement, the program is going stuck. Is there any solution to this issue???
                          This is my PlaceBet Coding

                          Code:
                          Sub PlaceBet(ByVal YourMarket As Integer, ByVal YourSelection As Integer, ByVal YourBetType As BFUK.BetTypeEnum, ByVal BetPrice As Decimal, ByVal BetSize As Decimal)
                          
                                  Dim oPlaceBetsReq As New BFUK.PlaceBetsReq     
                                  Dim oPlaceBetsResp As BFUK.PlaceBetsResp      
                                  Dim oBet As New BFUK.PlaceBets             
                                      .header = oHeaderUK()           
                                      With oBet                       
                                          .asianLineId = 0              
                                          .betCategoryType = BFUK.BetCategoryTypeEnum.E   
                                          If KeepInPlay_place = True Then
                                              .betPersistenceType = BFUK.BetPersistenceTypeEnum.IP 
                                          Else
                                              .betPersistenceType = BFUK.BetPersistenceTypeEnum.NONE
                                          End If
                          
                                          .betType = YourBetType        
                                          .marketId = YourMarket        
                                          .price = BetPrice              
                                          .selectionId = YourSelection 
                                          .size = BetSize                
                                          .bspLiability = 0             
                                      End With
                                      ReDim .bets(0)    
                                      .bets(0) = oBet  
                                  End With
                          
                                  oPlaceBetsResp = BetFairUK2.placeBets(oPlaceBetsReq)
                                  With oPlaceBetsResp  
                                      CheckHeader(.header)
                          
                                              If .errorCode = BFUK.PlaceBetsErrorEnum.OK Then  
                          
                                          For i = 0 To .betResults.Length - 1  
                                              With .betResults(i)
                                                  ListBox1.Items.Add(.resultCode.ToString)     
                                                  If .resultCode = 8 Then
                                                      MsgBox("No enough amount available", MsgBoxStyle.Exclamation)
                                                  End If
                                                  If .success Then
                                                      txtbetid.Text = .betId
                                                      txtodd.Text = .sizeMatched
                                                      txtstake.Text = .sizeMatched
                                                  End If
                                              End With
                                          Next
                          
                                      Else
                          
                          
                                      End If
                                  End With
                          
                              End Sub

                          Thank you,
                          Supun Silva

                          Comment

                          • Mumbles0
                            Junior Member
                            • Jan 2009
                            • 240

                            #268
                            Reply to supunsilva (re: placeBets time)

                            3 - 5 seconds sounds a bit long. To make a more accurate measurement of the placeBets call time add temporary code lines before and after the placeBets call as shown here:

                            Code:
                              .....
                            
                              [COLOR="Black"]Dim Tx As Date = Now[/COLOR]
                              [COLOR="Gray"]oPlaceBetsResp = BetfairUK2.placeBets(oPlaceBetsReq)[/COLOR]
                              [COLOR="Black"]Print("placeBets time = " & (Now - Tx).ToString)[/COLOR]
                              .....
                            Place a few bets and post the times.

                            Comment

                            • supunsilva.
                              Junior Member
                              • Aug 2009
                              • 32

                              #269
                              Thanks Buddy.. I will look into this as soon as possible.

                              Again I got a error from retreiving GetSilks. Its receiving error with marketDisplayDetails=Nothing or something like that. Please help me...

                              ListBox5.Items.Clear()
                              Dim SilkReq As New BFUK.GetSilksReq
                              Dim SilkResp As BFUK.GetSilksResp
                              With SilkReq
                              .header = oHeaderUK()
                              ReDim .markets(0)
                              .markets(0) = yourMarket
                              End With
                              SilkResp = BetFairUK.getSilks(SilkReq)
                              With SilkResp
                              CheckHeader(.header)
                              For i = 0 To .marketDisplayDetails.Length - 1
                              With .marketDisplayDetails(i)
                              ListBox5.Items.Add(.marketId)
                              For j = 0 To .racingSilks.Length - 1
                              With .racingSilks(j)
                              ListBox5.Items.Add("Age/Weight=" & .ageWeight)
                              ListBox5.Items.Add("DaysSince=" & .daysSince)
                              ListBox5.Items.Add("Form=" & .form)
                              ListBox5.Items.Add("JokeyClaim=" & .jockeyClaim)
                              ListBox5.Items.Add("saddleCloth=" & .saddleCloth)
                              ListBox5.Items.Add("Selection ID=" & .selectionId)
                              ListBox5.Items.Add("SilksText=" & .silksText)
                              ListBox5.Items.Add("SilksURL=" & .silksURL)
                              ListBox5.Items.Add("TrainerName=" & .trainerName)
                              ListBox5.Items.Add("Wearing=" & .wearing)
                              End With
                              Next
                              End With
                              Next
                              End With

                              Comment

                              • Mumbles0
                                Junior Member
                                • Jan 2009
                                • 240

                                #270
                                Reply to supunsilva (re: getSilks)

                                In the getSilks code you have made couple of obvious errors that have been covered in the tutorial steps. . Part of the fun of programming is finding out why your program does not work as expected. VB has excellent debugging facilities to help you. You should learn how to use them.

                                There are limits to how much help I can give you. I’m growing tired of doing your thinking for you.

                                M0.

                                Comment

                                Working...
                                X