Using VB2008 to acccess the Betfair API: A tutorial

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • apkent
    Junior Member
    • Jul 2009
    • 1

    #226
    I can't really help with items 1 or 2, but no. 3 is covered fully in the API documentation. Use the updatebets() function to specify either a new stake size or odds - very easy to do.

    Comment

    • supunsilva.
      Junior Member
      • Aug 2009
      • 32

      #227
      Hi...
      Thanks apkent...
      I think Mumbles can help me....
      If I have any doubt in update bets, i will ask you,

      Thank you very much.
      Supun Silva

      Comment

      • Mumbles0
        Junior Member
        • Jan 2009
        • 240

        #228
        Reply to supunsilva

        1. Race/Inplay times

        I don’t fully understand your question, but here is some info which may be of interest:

        Several API calls return a parameter containing the advertised event start time. getAllmarkets returns .eventDate, getMarket returns .marketTime. Both contain the same DateTime value.

        getAllMarkets returns the .turningInPlay parameter which tells you if a market will become an Inplay market after it starts (not all markets become Inplay).

        To determine when a market turns Inplay you can test the .delay parameter returned by getMarketPricesCompressed. This parameter changes to a non-zero value when the event starts.


        2. Time difference

        I think the reason is because all times returned by API are UTC (i.e. GMT). UK is currently on Daylight Saving Time, which is one hour ahead of UTC. To fix this use the .AddHours method, for example:
        Print(.marketId & " " & .eventDate.AddHours(1).TimeOfDay.ToString & " " & .marketName)

        3. Update bets

        I will soon post a step covering updateBets when time permits. Please be patient.
        Last edited by Mumbles0; 06-10-2009, 05:18 AM.

        Comment

        • tagorac
          Junior Member
          • Jan 2009
          • 3

          #229
          2. Time difference

          I'm not really sure about eventDate's type, but doesn't it have a ToLocalTime() method?

          Stephan

          Comment

          • clothcap
            Junior Member
            • Sep 2009
            • 7

            #230
            Originally posted by supunsilva. View Post
            Hi Mumbles.........

            I have three problems...

            1.
            How can I retrieve Race before time count and Inplay time count when race starts.

            2.
            When I press the Todays Card, It will display all events with one hour (-)
            Ex:
            100853281 14:25:00 Tipp (This should 15:25:00 Tipp)

            Please help me to solve these issues...

            Thank you,
            Regards,
            Supun Silva
            First of all thanks mumbles for a great thread

            sulpan
            for No2
            if you are in the uk

            you can use
            Public Sub daylight()

            If Now.IsDaylightSavingTime Then

            StartTime = StartTime.AddHours(1)
            End If

            End Sub


            for number 1 compare differences between times

            Public Sub Tdiff()
            ' works out time difference and puts it in TTS string


            Dim span As TimeSpan


            span = Starttime.Subtract(now)

            TTS = span.Hours & ":" & span.Minutes & ":" & span.Seconds

            'TTS gives a string time to start by having a one second timer to this sub you can put it in a label
            'and have a count down timer

            End Sub


            These may not be the correct way to do it but I'm self taught and mumbles taught
            Last edited by clothcap; 06-10-2009, 10:25 AM.

            Comment

            • Mumbles0
              Junior Member
              • Jan 2009
              • 240

              #231
              Re: Local time

              Tagorac has made a good suggestion: we use the ToLocalTime method. This is probably the easiest way to convert UTC into your local time. The example above would be better written as:
              Print(.marketId & " " & .eventDate.ToLocalTime.TimeOfDay.ToString & " " & .marketName)

              Using this method .NET takes care of time zones and daylight saving time.

              Comment

              • Mumbles0
                Junior Member
                • Jan 2009
                • 240

                #232
                Step 22. Changing the bet size and price

                Before we look at updateBets we will add a facility to make changing the bet size and price more convenient. The NumericUpDown control is well-suited to this task.

                From the Toolbox, place a NumericUpDown control onto the TestForm near the PlaceBet button we added in step 19. Name it nudPrice. Set these properties: TextAlign = Right, DecimalPlaces = 2, Minimum = 1.01, Maximum = 1000, Value = 10. Also add a label with Text = "Price".

                Now place another NumericUpDown control near this. Name it nudSize. Set these properties: TextAlign = Right, DecimalPlaces = 2 (or whatever suits your currency unit), Maximum = your maximum bet size (say 20), Minimum = your minimum bet size (say 2), Value = your typical bet size (say 5). Also add a label with Text = "Size".

                Also add another Button. Name it bUpdateBet and set its Text = "UpdateBet". We will us this in the next step.

                Now drag two RadioButtons from the toolbox onto the form. For the first one, set Name = rbBack, Text = "Back", Checked = True. For the second one, set Name = rbLay, Text = "Lay".

                Your “Bet UI” might now look something like this:

                Run the project and test the action of the NumericUpDown controls. Notice that they both change in steps of 1.00 between the maximum and minimum limits we have set. This may be OK for the bet size value, but it would be more convenient if the price value changed according to the preferred Betfair price increments (shown here). To achieve this we include a handler for the nudPrice.ValueChanged event, shown in this code:

                Code:
                'Price value increments --------------------------------------------------------------
                Private OddsLim() As Decimal = {2, 3, 4, 6, 10, 20, 30, 50, 100}   'Odd range limits
                Private OddsInc() As Decimal = {0.01, 0.02, 0.05, 0.1, 0.2, 0.5, 1, 2, 5, 10} 'Odds increments
                
                Private Sub nudPrice_ValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles nudPrice.ValueChanged
                  Dim i As Integer, v As Decimal
                  Static Vprev As Decimal   'Previous value
                  With nudPrice
                    v = .Value
                    For i = 0 To UBound(OddsLim)  'Determine price range
                      If v <= OddsLim(i) Then Exit For
                    Next i
                    Select Case Vprev   'Adjustments required for smooth incrementing
                      Case 3
                        If v = 3.02 Then v = 3.025
                      Case 10
                        If v = 10.2 Then v = 10.25
                      Case 50
                        If v = 52 Then v = 52.5
                    End Select
                    .Value = Decimal.Round(v / OddsInc(i), MidpointRounding.AwayFromZero) * OddsInc(i) 'Round to the nearest valid price
                    .Increment = OddsInc(i)  'Set the increment
                  End With
                  Vprev = v
                End Sub
                Here the OddsLim array holds the price range limits while OddsInc holds the corresponding increments. This sub executes whenever the price value changes. The price range is determined and the control’s Increment property is set to the appropriate value. The price is also rounded to the nearest preferred value. The purpose of the Select Case statement is to iron out some unexpected transition behaviours which would otherwise occur.

                Run the project to test this. When you spin the Price control up or down the value always remains on a preferred value. Also, if you enter an arbitrary price (e.g. 3.628), it will be rounded to the nearest preferred value (3.65) when you hit the enter key. Notice how quickly you can spin the control to any desired value.

                No code is required for the Size control. You can change its Increment property to a more convenient value if you wish.

                To link the two “spin” controls to the PlaceBet button, modify the test code of step 19 as follows:

                Code:
                [COLOR="Gray"]Dim Market As Integer = [i]YourMarketId[/i]    'The Id of your market
                Dim Selection As Integer = [i]YouSelectionId[/i]   'The Id of your selection
                [COLOR="Black"]Dim BetType As BFUK.BetTypeEnum      'Your bet type
                Dim BetPrice As Decimal              'Your desired odds
                Dim BetSize As Decimal               'Your bet amount in currency units[/COLOR] 
                Dim TheBetId As Long                 'The betId (returned from placeBets)
                
                Private Sub bPlaceBet_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bPlaceBet.Click
                  Print("*** PlaceBet ***")
                  [COLOR="Black"]If rbBack.Checked Then BetType = BFUK.BetTypeEnum.B Else BetType = BFUK.BetTypeEnum.L 'Select Back or Lay bet
                  BetPrice = nudPrice.Value    'The selected price
                  BetSize = nudSize.Value      'The selected bet size[/COLOR]
                  PlaceBet(Market, Selection, BetType, BetPrice, BetSize)    'The call to place the bet
                End Sub [/COLOR]
                Here we have deleted the constant values for BetType, BetPrice and BetSize, and assigned the values of the new controls to these variables instead. We determine betType by testing the state of the Checked property of the rbBack radio button. Sub PlaceBet remains unchanged.

                Now test the PlaceBet button as per step 19. We can now set the bet parameters far more conveniently using the controls we have added to the form.

                In the next step we look at updateBets.

                Comment

                • supunsilva.
                  Junior Member
                  • Aug 2009
                  • 32

                  #233
                  Hi...there is no propery call ..eventDate.AddHours(1).TimeOfDay.ToString. Only have .startTime.TimeOfDay.ToString.

                  I got this code from following Sub:

                  TextBox5.Text = ""
                  Dim oMarketsReq As New BFGlobal.GetEventsReq
                  Dim oMarketsResp As BFGlobal.GetEventsResp
                  With oMarketsReq
                  .header = oHeaderGL
                  .eventParentId = 13
                  End With
                  oMarketsResp = BetfairGL.getEvents(oMarketsReq) 'Call the UK API
                  With oMarketsResp
                  CheckHeader(.header)

                  If .errorCode = BFGlobal.GetEventsErrorEnum.OK Then '<<< change this!

                  For i = 0 To .eventItems.Length - 1
                  With .eventItems(i)
                  PrintToday( .eventId & " " & .eventName & " " & .eventTypeId & " " & .startTime)

                  End With
                  Next

                  For i = 0 To .marketItems.Length - 1
                  With .marketItems(i)
                  PrintToday( .marketId & " " & .eventParentId & " " & .marketName)
                  End With
                  Next

                  End If
                  End With

                  Comment

                  • Mumbles0
                    Junior Member
                    • Jan 2009
                    • 240

                    #234
                    Reply to supunsilva (re: ToLocalTime)

                    Several API calls return a parameter giving market start times, but, just to confuse you, these parameters have different names. For example, getAllmarkets returns .eventDate, getMarket returns .marketTime and getEvents returns .startTime. All are of type Date and contain the same value for the same market. All have the .ToLocalTime method.

                    Because you are calling getEvents, you can use .startTime.ToLocalTime.


                    By the way:

                    In your code example you are using .eventParentId = 13 (Horse racing - today’s card). For this case the .eventItems array always returns empty, so your first PrintToday(...) statement will not print anything.

                    All market data is returned in the .marketItems array. So, if you want start times, change the second PrintToday(...) statement to something like this:
                    PrintToday(.marketId & " " & .eventParentId & " " & .startTime.ToLocalTime & " " & .marketName)
                    Last edited by Mumbles0; 07-10-2009, 06:10 AM.

                    Comment

                    • supunsilva.
                      Junior Member
                      • Aug 2009
                      • 32

                      #235
                      Hi Mumbles, Thanks for your reply. your code working fine.. again thank you.
                      Still I have one question.
                      I want to know how do we find market is in In-Play or not? I mean how to set time counter.
                      EX:
                      Race start time: 14.30
                      Time now: 14.25
                      I need to set label that displaying
                      0:05:28
                      0:05:27
                      0:05:26
                      0:05:25
                      like this counter untill race starts.
                      After race starts it will be like this:
                      00:05
                      00:06
                      00:07
                      00:08
                      00:09
                      untill the race suspended.

                      Please help me when you have enough time,

                      Thank you,
                      Supun Silva

                      Comment

                      • supunsilva.
                        Junior Member
                        • Aug 2009
                        • 32

                        #236
                        Hi Mumbles, Thanks for your reply. your code working fine.. again thank you.
                        Still I have one question.
                        I want to know how do we find market is in In-Play or not? I mean how to set time counter.
                        EX:
                        Race start time: 14.30
                        Time now: 14.25
                        I need to set label that displaying
                        0:05:28
                        0:05:27
                        0:05:26
                        0:05:25
                        like this counter untill race starts.
                        After race starts it will be like this:
                        00:05
                        00:06
                        00:07
                        00:08
                        00:09
                        untill the race suspended.

                        Please help me when you have enough time,

                        Thank you,
                        Supun Silva
                        Edit/Delete Message

                        Comment

                        • Mumbles0
                          Junior Member
                          • Jan 2009
                          • 240

                          #237
                          Reply to supunsilva (re: Count down to start time)

                          If you have a Label named, say, TimeToGo, and you have saved the market start time in a variable named, say, MarketTime, you can update this label with a statement in your 1-second timer Tick event:

                          Code:
                          TimeToGo.Text = MarketTime.ToLocalTime.Subtract(Now).ToString.Substring(0, 8)
                          This makes a count-down indicator.

                          Note that MarketTime contains the scheduled start time only. The actual start time may be delayed. The count-down value does not provide an accurate indication of when the market will actually turn in-play.
                          Last edited by Mumbles0; 13-10-2009, 03:13 AM.

                          Comment

                          • supunsilva.
                            Junior Member
                            • Aug 2009
                            • 32

                            #238
                            Hi... Thanks for your reply. I has worked after small change. Again very big thanks!!!
                            Again I am disturbing you..... How do we get to know when race starts. I need timer to count in-paly time. How can I do it??
                            Please help me..

                            Thank you,
                            Supun Silva

                            Comment

                            • Mumbles0
                              Junior Member
                              • Jan 2009
                              • 240

                              #239
                              Reply to supunsilva (re: In-play time)

                              getMarketPricesCompressed returns a .marketPrices.delay parameter which becomes non-zero when a market turns in-play. You can assume that a race starts when this occurs. If you want to count up the elapsed time since the start of a race you could do something like this:

                              Define two global variables:

                              Code:
                              Dim RaceStart As Date         'The time when the race turns in-play
                              Dim RaceStarted As Boolean    'A flag, set True when the race has started
                              In the event handler Sub BetFairUK_getMarketPricesCompressedCompleted add some code to detect when the market turns in-play, and update a time indicator label (which I’ve named InPlayTime). This sub should execute frequently (typically once per second).

                              Code:
                              [COLOR="Gray"]..........................
                              ..........................[/COLOR]
                              
                              With oMarketPrices
                              
                                If .delay > 0 Then     'Race is in-play
                                  If RaceStarted Then
                                    InPlayTime.Text = Now.Subtract(RaceStart).ToString.Substring(0, 8) 'Update the time label
                                  Else           'Initialize the variables
                                    RaceStart = Now       'Save the race start time
                                    RaceStarted = True    'Set the flag
                                  End If
                                End If
                              
                                [COLOR="Gray"]...........................
                                ..........................[/COLOR] 
                              
                              End With
                              This will only work for an in-play market. Not all markets turn in-play.

                              Comment

                              • Mumbles0
                                Junior Member
                                • Jan 2009
                                • 240

                                #240
                                Step 23. Changing a Bet.

                                You can change the parameters of unmatched bets by calling updateBets. You can change the price or size of an unmatched bet, but not both at the same time. If you attempt to do this, only the price changes. You can also change the betPersistenceType (prior to the market turning in-play).

                                Note that updateBets can process a batch of bet changes at once, but again, to keep things simple, we will only change one bet at a time here. Add the following sub to the TestForm to perform the updateBets call:

                                Code:
                                Private Sub UpdateBet(ByVal BetId As Long, ByVal NewPrice As Decimal, ByVal OldPrice As Decimal, ByVal NewSize As Decimal, ByVal OldSize As Decimal)
                                
                                  Dim oUpdateBetsReq As New BFUK.UpdateBetsReq        'Create the request object
                                  Dim oUpdateBetsResp As BFUK.UpdateBetsResp          'A variable to hold the response object
                                  Dim oUpdateBet As New BFUK.UpdateBets               'An object to specify the changes
                                  With oUpdateBetsReq
                                    .header = oHeaderUK()           'The standard header
                                    With oUpdateBet                 'Specify the desired changes:
                                      .betId = BetId                'The betId of the existing bet to be changed
                                      .newBetPersistenceType = BFUK.BetPersistenceTypeEnum.NONE   'No change
                                      .oldBetPersistenceType = BFUK.BetPersistenceTypeEnum.NONE
                                      .newPrice = NewPrice          'The desired new price
                                      .oldPrice = OldPrice          'The existing price
                                      .newSize = NewSize            'The desired new bet size
                                      .oldSize = OldSize            'The existing bet size
                                    End With
                                    ReDim .bets(0)                  'Array length = 1 to hold single bet changes
                                    .bets(0) = oUpdateBet           'Put the bet changes object in element 0
                                  End With
                                
                                  oUpdateBetsResp = BetFairUK.updateBets(oUpdateBetsReq) 'Call the API to change the bet
                                
                                  With oUpdateBetsResp      'The response
                                    CheckHeader(.header)
                                    Print("ErrorCode = " & .errorCode.ToString)
                                    If .errorCode = BFUK.UpdateBetsErrorEnum.OK Then    'The call succeeded
                                      For i = 0 To .betResults.Length - 1        'In this case there should only be 1 result.
                                        With .betResults(i)
                                          Print(.resultCode.ToString)     'Print the result
                                          If .success Then                'Print details of the change if successful
                                            Print("BetId = " & .betId & "  NewBetId = " & .newBetId)
                                            Print("NewPrice = " & .newPrice & " NewSize = " & .newSize & " SizeCancelled = " & .sizeCancelled)
                                
                                            If .newBetId <> 0 Then TheBetId = .newBetId      'Save the new betId if there is one
                                            BetPrice = .newPrice           
                                            BetSize = .newSize                    'Update with the new values 
                                            nudPrice.Value = .newPrice
                                            nudSize.Value = .newSize
                                
                                          End If
                                        End With
                                      Next
                                    End If
                                  End With
                                
                                End Sub
                                This is a sync call which follows the normal calling procedure. We create an object oUpdateBet to hold the our desired changes. This object is then assigned to the first element of the .bets array in the request object and the API is called.

                                When the response is received the result of the call is printed. If the update succeeds we print details of the change and also update the variables and NumericUpDown controls with the new values.

                                In this example we don’t change betPersistenceType. The changes given in the sub’s calling parameters are assigned to oUpdateBet. The call syntax is:
                                UpdateBet(BetId, NewPrice, OldPrice, NewSize, OldSize)

                                You must specify both old and new values even though sometimes they may not appear necessary. Also, it’s good practice to use the “correct” old values otherwise you may get unexpected results.

                                To test this add this code to the click event handler of the UpdateBet button we added in Step 22:

                                Code:
                                Private Sub bUpdateBet_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bUpdateBet.Click
                                  Print("*** UpdateBet ***")
                                  UpdateBet(TheBetId, nudPrice.Value, BetPrice, nudSize.Value, BetSize)
                                End Sub
                                Here we take the new values from the NumericUpDown controls we added in Step 22. The existing values are held in TheBetId, BetPrice and BetSize (variables we added in Step 19).

                                To experiment, I suggest you log onto the Betfair website (as per previous steps) to observe the effects of the changes we will request. Select a suitable market and a short-priced runner and set the Market and Selection values accordingly (as per step 19).

                                Now place a test bet using the bet controls. My example: select Back, set Price = 25.00, Size = 10. Click PlaceBet. If successful this bet will appear on the “MyBets” tab on the web page. You should now have a bet: 10 units @25.00.

                                To change the bet price:

                                Set Price = 23 and click UpdateBet. Note that you now have a new bet: 10 units @23.00. The original bet has been cancelled.

                                To reduce the bet size:

                                Set Size = 6 and click UpdateBet. The existing bet is retained with reduced size. You now have 6 units @23.00.

                                To increase the bet size:

                                Set Size = 8 and click UpdateBet. The existing bet is retained as is, and a new bet is created to cover the size increase. You now have 2 bets: 6 units @23.00 and 2 units @23.00.


                                That’s how to change an unmatched bet via the API . You can experiment with the request parameters to further investigate the operation of updateBets.
                                Last edited by Mumbles0; 15-10-2009, 10:47 AM.

                                Comment

                                Working...
                                X