betfair 0.0.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
data/Gemfile ADDED
@@ -0,0 +1,11 @@
1
+ source 'http://rubygems.org'
2
+
3
+ gem 'rake'
4
+ gem 'savon'
5
+ gem 'gemcutter'
6
+
7
+ gem 'rspec'
8
+ gem 'savon_spec'
9
+
10
+ gemspec
11
+
data/README ADDED
@@ -0,0 +1,110 @@
1
+ ===========
2
+ BETFAIR API
3
+ ===========
4
+
5
+ ------------
6
+ Installation
7
+ ------------
8
+
9
+ Betfair is available through [Rubygems](http://rubygems.org/gems/betfair) and can be installed via:
10
+
11
+ gem install betfair OR with bundler: gem 'betfair' and `bundle install`
12
+
13
+ ------------
14
+ Introduction
15
+ ------------
16
+ irb
17
+
18
+ require 'betfair'
19
+
20
+ or from a Gemfile
21
+
22
+ gem 'betfair'
23
+
24
+ # create a client for the General API so that you can log in.
25
+ bf = Betfair::API.new
26
+
27
+ If you want to use a proxy or turn on Savon's logging then just pass in like so:
28
+
29
+ proxy = ' http://localhost:8888' # This is a local squid proxy I tunnel to from my local machine to access the host server in UK for dev purposes.
30
+ logging = true
31
+ bf = Betfair::API.new(proxy, logging)
32
+
33
+ Proxy's can be useful if you want to host on a cloud service such as Heroku, as you will be denied access to the Betfair API from the USA.
34
+
35
+ Just proxy via a server from a country that Betfair allow's, such as the UK.
36
+
37
+ At the heart of the Betfair API is the session_token.
38
+
39
+ In order to get one of these simply call:
40
+
41
+ session_token = bf.login('username', 'password', 82, 0, 0, nil)
42
+
43
+ Username and Password are fairly obvious.
44
+
45
+ 82 is the standard Product Id, you may have a different one depending on the level of Betfair API access that you have.
46
+
47
+ You can ignore the rest as leave as is, but they refer to Vendor Software Id, Location Id, Ip Address as required by the Betfair API.
48
+
49
+ -----
50
+ Read
51
+ -----
52
+
53
+ markets = bf.get_all_markets(session_token, 1, [1,3], nil, nil, nil, nil)
54
+
55
+ details = bf.get_market(session_token, 2, 100386338)
56
+ prices = bf.get_market_prices_compressed(session_token, 2, 100386338)
57
+
58
+ helpers = Betfair::Helpers.new
59
+
60
+ helpers.market_info(details)
61
+ helpers.combine(details, prices)
62
+
63
+ # The get_all_markets api call returns all markets in one huge string, this helper provides them all in handy hashes with market id as key.
64
+ helpers.all_markets(markets)
65
+
66
+ ---
67
+ Bet
68
+ ---
69
+ bf.place_bet(session_token, 1, 104184109, 58805, 'B', 10.0, 5.0)
70
+ bf.cancel_bet(session_token, 1, 16939730542)
71
+
72
+ ------------
73
+ Requirements
74
+ ------------
75
+ savon
76
+
77
+ ------------------------
78
+ Requirements for testing
79
+ ------------------------
80
+ savon_spec
81
+ rspec
82
+ rake
83
+
84
+ ----------
85
+ To Do
86
+ ----------
87
+ - Add some error checking to the Betfair::Helper methods
88
+ - Finish of the mash method, to return a nice hash of all market and runner info
89
+ - Write a spec for the mashed method
90
+
91
+ ----------
92
+ Contribute
93
+ ----------
94
+ I have only added the Betfair API method calls that I need.
95
+
96
+ Feel free to fork this repo, add what you need to with the relevant RSpec tests and send me a pull request.
97
+
98
+ -------
99
+ License
100
+ -------
101
+
102
+ (The MIT License)
103
+
104
+ Copyright (c) 2011 Luke Byrne
105
+
106
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
107
+
108
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
109
+
110
+ THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
data/Rakefile ADDED
@@ -0,0 +1,2 @@
1
+ require 'bundler'
2
+ Bundler::GemHelper.install_tasks
data/betfair.gemspec ADDED
@@ -0,0 +1,26 @@
1
+ # -*- encoding: utf-8 -*-
2
+ $:.push File.expand_path("../lib", __FILE__)
3
+ require "betfair/version"
4
+
5
+ Gem::Specification.new do |s|
6
+ s.name = "betfair"
7
+ s.version = Betfair::VERSION
8
+ s.authors = ["Luke Byrne"]
9
+ s.email = ["lukeb@lukebyrne.com"]
10
+ s.homepage = "https://github.com/lukebyrne/betfair"
11
+ s.summary = %q{Betfair API gem.}
12
+ s.description = %q{Gem for accessing the Betfair API.}
13
+
14
+ s.rubyforge_project = "betfair"
15
+
16
+ s.files = `git ls-files`.split("\n")
17
+ s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
18
+ s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) }
19
+ s.require_paths = ["lib"]
20
+
21
+ s.add_runtime_dependency 'savon'
22
+
23
+ s.add_development_dependency 'rake'
24
+ s.add_development_dependency 'rspec'
25
+ s.add_development_dependency 'savon_spec'
26
+ end
data/examples/foo.rb ADDED
@@ -0,0 +1,42 @@
1
+ require 'betfair'
2
+
3
+ bf = Betfair::API.new
4
+ helpers = Betfair::Helpers.new
5
+
6
+ session_token = bf.login('username', 'password', 82, 0, 0, nil).to_s
7
+ puts session_token
8
+ puts ""
9
+
10
+ # This call just returns back a huge string, markets ar edeliminated by ':', run the split method to convert string to a array
11
+ markets = bf.get_all_markets(session_token, 1, [1,3], nil, nil, nil, nil).split(':')
12
+
13
+ # puts helpers.all_markets(markets)
14
+
15
+ # Loop though the markets array
16
+ markets.each do |market|
17
+
18
+ # Once we have a market then the fields with in this are delimnated by '~', run the split method to convert string to a array
19
+ market = market.split('~')
20
+
21
+ market_id = market[0]
22
+ market_name = market[1].to_s
23
+ menu_path = market[5]
24
+
25
+ # Now lets just look for Match Odds for Tottenham for the English Premier League
26
+ if market_name == 'Match Odds' and menu_path.include? 'Barclays Premier League' and menu_path.include? 'Tottenham'
27
+ # Run the API call to get the Market Info
28
+ details = bf.get_market(session_token, 1, market_id)
29
+ # Run the API call to get the prices
30
+ prices = bf.get_market_prices_compressed(session_token, 1, market_id)
31
+
32
+ # Pump the data into the helpers
33
+
34
+ puts helpers.market_info(details)
35
+ puts ""
36
+ puts helpers.combine(details, prices)
37
+ puts ""
38
+ puts helpers.prices_complete(prices)
39
+
40
+ end
41
+
42
+ end
data/lib/betfair.rb ADDED
@@ -0,0 +1,3 @@
1
+ require 'savon'
2
+ require 'betfair/version'
3
+ require 'betfair/api'
@@ -0,0 +1,288 @@
1
+ module Betfair
2
+
3
+ class API
4
+
5
+ def place_bet(session_token, exchange_id, market_id, runner_id, bet_type, price, size)
6
+ bf_bet = { :marketId => market_id, :selectionId => runner_id, :betType => bet_type, :price => price, :size => size, :asianLineId => 0, :betCategoryType => 'E', :betPersistenceType => 'NONE', :bspLiability => 0 }
7
+ response = exchange(exchange_id).request :bf, :placeBets do
8
+ soap.body = { 'bf:request' => { :header => api_request_header(session_token), :bets => { 'PlaceBets' => [bf_bet] } } }
9
+ end
10
+ error_code = response.to_hash[:place_bets_response][:result][:error_code]
11
+ return error_code == 'OK' ? response.to_hash[:place_bets_response][:result][:bet_results][:place_bets_result] : error_code
12
+ end
13
+
14
+ def cancel_bet(session_token, exchange_id, bet_id)
15
+ response = exchange(exchange_id).request :bf, :cancelBets do
16
+ soap.body = { 'bf:request' => { :header => api_request_header(session_token), :bets => { 'CancelBets' => [ { :betId => bet_id } ] } } } # "CancelBets" has to be a string, not a symbol!
17
+ end
18
+ error_code = response.to_hash[:cancel_bets_response][:result][:error_code]
19
+ return error_code == 'OK' ? response.to_hash[:cancel_bets_response][:result][:bet_results][:cancel_bets_result] : error_code
20
+ end
21
+
22
+ def get_market(session_token, exchange_id, market_id, locale = nil)
23
+ response = exchange(exchange_id).request :bf, :getMarket do
24
+ soap.body = { 'bf:request' => { :header => api_request_header(session_token), :marketId => market_id, :locale => locale } }
25
+ end
26
+ error_code = response.to_hash[:get_market_response][:result][:error_code]
27
+ return error_code == 'OK' ? response.to_hash[:get_market_response][:result][:market] : error_code
28
+ end
29
+
30
+ def get_market_prices_compressed(session_token, exchange_id, market_id, currency_code = nil)
31
+ response = exchange(exchange_id).request :bf, :getMarketPricesCompressed do
32
+ soap.body = { 'bf:request' => { :header => api_request_header(session_token), :marketId => market_id, :currencyCode => currency_code } }
33
+ end
34
+ error_code = response.to_hash[:get_market_prices_compressed_response][:result][:error_code]
35
+ return error_code == 'OK' ? response.to_hash[:get_market_prices_compressed_response][:result][:market_prices] : error_code
36
+ end
37
+
38
+ def get_active_event_types(session_token, locale = nil)
39
+ response = @global_service.request :bf, :getActiveEventTypes do
40
+ soap.body = { 'bf:request' => { :header => api_request_header(session_token),
41
+ :locale => locale
42
+ }
43
+ }
44
+ end
45
+ error_code = response.to_hash[:get_active_event_types_response][:result][:error_code]
46
+ return error_code == 'OK' ? response.to_hash[:get_active_event_types_response][:result][:event_type_items][:event_type] : error_code
47
+ end
48
+
49
+ def get_all_markets(session_token, exchange_id, event_type_ids = nil, locale = nil, countries = nil, from_date = nil, to_date = nil)
50
+ response = exchange(exchange_id).request :bf, :getAllMarkets do
51
+ soap.body = { 'bf:request' => { :header => api_request_header(session_token),
52
+ :eventTypeIds => { 'int' => event_type_ids },
53
+ :locale => locale, :countries => { 'country' => countries },
54
+ :fromDate => from_date,
55
+ :toDate => to_date
56
+ }
57
+ }
58
+ end
59
+ error_code = response.to_hash[:get_all_markets_response][:result][:error_code]
60
+ return error_code == 'OK' ? response.to_hash[:get_all_markets_response][:result][:market_data] : error_code
61
+ end
62
+
63
+ def login(username, password, product_id, vendor_software_id, location_id, ip_address)
64
+ response = @global_service.request :bf, :login do
65
+ soap.body = { 'bf:request' => { :username => username,
66
+ :password => password,
67
+ :productId => product_id,
68
+ :vendorSoftwareId => vendor_software_id,
69
+ :locationId => location_id,
70
+ :ipAddress => ip_address
71
+ }
72
+ }
73
+ end
74
+ session_token(response.to_hash[:login_response][:result][:header])
75
+ end
76
+
77
+ def exchange(exchange_id)
78
+ exchange_id == 2 ? @aus_service : @uk_service
79
+ end
80
+
81
+ def api_request_header(session_token)
82
+ { :client_stamp => 0, :session_token => session_token }
83
+ end
84
+
85
+ def session_token(response_header)
86
+ response_header[:error_code] == 'OK' ? response_header[:session_token] : response_header[:error_code]
87
+ end
88
+
89
+ def initialize(proxy = nil, logging = nil)
90
+
91
+ logging == true ? Savon.log = true : Savon.log = false
92
+
93
+ @global_service = Savon::Client.new do |wsdl, http|
94
+ wsdl.endpoint = 'https://api.betfair.com/global/v3/BFGlobalService'
95
+ wsdl.namespace = 'https://www.betfair.com/global/v3/BFGlobalService'
96
+ http.proxy = proxy if !proxy.nil?
97
+ end
98
+
99
+ @uk_service = Savon::Client.new do |wsdl, http|
100
+ wsdl.endpoint = 'https://api.betfair.com/exchange/v5/BFExchangeService'
101
+ wsdl.namespace = 'http://www.betfair.com/exchange/v3/BFExchangeService/UK'
102
+ http.proxy = proxy if !proxy.nil?
103
+ end
104
+
105
+ @aus_service = Savon::Client.new do |wsdl, http|
106
+ wsdl.endpoint = 'https://api-au.betfair.com/exchange/v5/BFExchangeService'
107
+ wsdl.namespace = 'http://www.betfair.com/exchange/v3/BFExchangeService/AUS'
108
+ http.proxy = proxy if !proxy.nil?
109
+ end
110
+
111
+ end
112
+
113
+ end
114
+
115
+ class Helpers
116
+
117
+ def all_markets(markets)
118
+ market_hash = {}
119
+ markets.gsub! '\:', "\0"
120
+ markets = markets.split ":"
121
+ markets.each do |piece|
122
+ piece.gsub! "\0", '\:'
123
+ market_hash[piece.split('~')[0].to_i] = { :market_id => piece.split('~')[0].to_i,
124
+ :market_name => piece.split('~')[1].to_s,
125
+ :market_type => piece.split('~')[2].to_s,
126
+ :market_status => piece.split('~')[3].to_s,
127
+ # bf returns in this case time in Epoch, but in milliseconds
128
+ :event_date => Time.at(piece.split('~')[4].to_i/1000),
129
+ :menu_path => piece.split('~')[5].to_s,
130
+ :event_hierarchy => piece.split('~')[6].to_s,
131
+ :bet_delay => piece.split('~')[7].to_s,
132
+ :exchange_id => piece.split('~')[8].to_i,
133
+ :iso3_country_code => piece.split('~')[9].to_s,
134
+ # bf returns in this case time in Epoch, but in milliseconds
135
+ :last_refresh => Time.at(piece.split('~')[10].to_i/1000),
136
+ :number_of_runners => piece.split('~')[11].to_i,
137
+ :number_of_winners => piece.split('~')[12].to_i,
138
+ :total_amount_matched => piece.split('~')[13].to_f,
139
+ :bsp_market => piece.split('~')[14] == 'Y' ? true : false,
140
+ :turning_in_play => piece.split('~')[15] == 'Y' ? true : false
141
+ }
142
+ end
143
+ return market_hash
144
+ end
145
+
146
+ def market_info(details)
147
+ { :exchange_id => nil,
148
+ :market_type_id => nil,
149
+ :market_matched => nil,
150
+ :menu_path => details[:menu_path],
151
+ :market_id => details[:market_id],
152
+ :market_name => details[:name],
153
+ :market_type_name => details[:menu_path].to_s.split('\\')[1]
154
+ }
155
+ end
156
+
157
+ def combine(market, prices)
158
+ market = details(market)
159
+ prices = prices(prices)
160
+ market[:runners].each do |runner|
161
+ runner.merge!( { :market_id => market[:market_id] } )
162
+ runner.merge!( { :market_type_id => market[:market_type_id] } )
163
+ runner.merge!(price_string(prices[runner[:runner_id]]))
164
+ end
165
+ end
166
+
167
+ def details(market)
168
+ runners = []
169
+ market[:runners][:runner].each { |runner| runners << { :runner_id => runner[:selection_id].to_i, :runner_name => runner[:name] } }
170
+ return { :market_id => market[:market_id].to_i, :market_type_id => market[:event_type_id].to_i, :runners => runners }
171
+ end
172
+
173
+ def prices(prices)
174
+ price_hash = {}
175
+ prices.gsub! '\:', "\0"
176
+ pieces = prices.split ":"
177
+ pieces.each do |piece|
178
+ piece.gsub! "\0", '\:'
179
+ price_hash[piece.split('~')[0].to_i] = piece
180
+ end
181
+ return price_hash
182
+ end
183
+
184
+ ##
185
+ #
186
+ # Complete representation of market price data response,
187
+ # except "removed runners" which is returned as raw string.
188
+ #
189
+ ##
190
+ def prices_complete(prices)
191
+ aux_hash = {}
192
+ price_hash = {}
193
+
194
+ prices.gsub! '\:', "\0"
195
+ pieces = prices.split ":"
196
+
197
+ # parsing first the auxiliary price info
198
+ aux = pieces.first
199
+ aux.gsub! "\0", '\:'
200
+ aux_hash = { :market_id => aux.split('~')[0].to_i,
201
+ :currency => aux.split('~')[1].to_s,
202
+ :market_status => aux.split('~')[2].to_s,
203
+ :in_play_delay => aux.split('~')[3].to_i,
204
+ :number_of_winners => aux.split('~')[4].to_i,
205
+ :market_information => aux.split('~')[5].to_s,
206
+ :discount_allowed => aux.split('~')[6] == 'true' ? true : false,
207
+ :market_base_rate => aux.split('~')[7].to_s,
208
+ :refresh_time_in_milliseconds => aux.split('~')[8].to_i,
209
+ :removed_runners => aux.split('~')[9].to_s,
210
+ :bsp_market => aux.split('~')[10] == 'Y' ? true : false
211
+ }
212
+
213
+ # now iterating over the prices excluding the first piece that we already parsed above
214
+ pieces[1..-1].each do |piece|
215
+ piece.gsub! "\0", '\:'
216
+
217
+ # using the selection_id as hash key
218
+ price_hash_key = piece.split('~')[0].to_i
219
+
220
+ price_hash[price_hash_key] = { :selection_id => piece.split('~')[0].to_i,
221
+ :order_index => piece.split('~')[1].to_i,
222
+ :total_amount_matched => piece.split('~')[2].to_f,
223
+ :last_price_matched => piece.split('~')[3].to_f,
224
+ :handicap => piece.split('~')[4].to_f,
225
+ :reduction_factor => piece.split('~')[5].to_f,
226
+ :vacant => piece.split('~')[6] == 'true' ? true : false,
227
+ :far_sp_price => piece.split('~')[7].to_f,
228
+ :near_sp_price => piece.split('~')[8].to_f,
229
+ :actual_sp_price => piece.split('~')[9].to_f
230
+ }
231
+
232
+ # merge lay and back prices into price_hash
233
+ price_hash[price_hash_key].merge!(price_string(piece, true))
234
+ end
235
+
236
+ price_hash.merge!(aux_hash)
237
+
238
+ return price_hash
239
+ end
240
+
241
+ def price_string(string, prices_only = false)
242
+ string_raw = string
243
+ string = string.split('|')
244
+
245
+ price = { :prices_string => nil, :runner_matched => 0, :last_back_price => 0, :wom => 0,
246
+ :b1 => 0, :b1_available => 0, :b2 => 0, :b2_available => 0, :b3 => 0, :b3_available => 0,
247
+ :l1 => 0, :l1_available => 0, :l2 => 0, :l2_available => 0, :l3 => 0, :l3_available => 0
248
+ }
249
+
250
+ if !string[0].nil? and !prices_only
251
+ str = string[0].split('~')
252
+ price[:prices_string] = string_raw
253
+ price[:runner_matched] = str[2].to_f
254
+ price[:last_back_price] = str[3].to_f
255
+ end
256
+
257
+ # Get the b prices (which are actually the l prices)
258
+ if !string[1].nil?
259
+ b = string[1].split('~')
260
+ price[:b1] = b[0].to_f if !b[0].nil?
261
+ price[:b1_available] = b[1].to_f if !b[1].nil?
262
+ price[:b2] = b[4].to_f if !b[5].nil?
263
+ price[:b2_available] = b[5].to_f if !b[6].nil?
264
+ price[:b3] = b[8].to_f if !b[8].nil?
265
+ price[:b3_available] = b[9].to_f if !b[9].nil?
266
+ combined_b = price[:b1_available] + price[:b2_available] + price[:b3_available]
267
+ end
268
+
269
+ # Get the l prices (which are actually the l prices)
270
+ if !string[2].nil?
271
+ l = string[2].split('~')
272
+ price[:l1] = l[0].to_f if !l[0].nil?
273
+ price[:l1_available] = l[1].to_f if !l[1].nil?
274
+ price[:l2] = l[4].to_f if !l[4].nil?
275
+ price[:l2_available] = l[5].to_f if !l[5].nil?
276
+ price[:l3] = l[8].to_f if !l[8].nil?
277
+ price[:l3_available] = l[9].to_f if !l[9].nil?
278
+ combined_l = price[:l1_available] + price[:l2_available] + price[:l3_available]
279
+ end
280
+
281
+ price[:wom] = combined_b / ( combined_b + combined_l ) unless combined_b.nil? or combined_l.nil?
282
+
283
+ return price
284
+ end
285
+
286
+ end
287
+
288
+ end