Coder Social home page Coder Social logo

betfair's Introduction

Betfair

A lightweight ruby wrapper for the Betfair Exchange API (API-NG).

Full API description, including API parameters etc, is available from Betfair's dedicated API site.

Oh, and always bet responsibly. Duh.

Installation

Add this line to your application's Gemfile:

gem 'betfair-ng'

And then execute:

$ bundle

Or install it yourself as:

$ gem install betfair-ng

Usage

# create a client with app code
client = Betfair::Client.new("X-Application" => "your_app_code")

# let's log in.
client.interactive_login("your_username", "your_password")

# you can do stuff like list event types:
event_types = client.list_event_types(filter: {})
# =>  [
#       {
#         "eventType"=>{
#           "id"=>"7",
#           "name"=>"Horse Racing"
#         },
#         "marketCount"=>215
#       },
#       ..etc..
#     ]

# todays GB & Ireland horse racing win & place markets
racing_et_id = event_types.find{|et| et["eventType"]["name"] == "Horse Racing"}["eventType"]["id"]

racing_markets = client.list_market_catalogue({
  filter: {
    eventTypeIds: [racing_et_id],
    marketTypeCodes: ["WIN", "PLACE"],
    marketStartTime: {
      from: Time.now.beginning_of_day.iso8601,
      to: Time.now.end_of_day.iso8601
    },
    marketCountries: ["GB", "IRE"]
  },
  maxResults: 200,
  marketProjection: [
    "MARKET_START_TIME",
    "RUNNER_METADATA",
    "RUNNER_DESCRIPTION",
    "EVENT_TYPE",
    "EVENT",
    "COMPETITION"
  ]
})

# given an eventId from the market catalogue (the first for example),
# let's have a flutter shall we?
market = racing_markets.first
market_id = market["marketId"]
selection_id = market["runners"].find { |r| r["runnerName"] == "Imperial Commander" }["selectionId"]

# this places an Betfair SP bet with a price limit of 3.0 .
# see the API docs for the different types of orders.
client.place_orders({
  marketId: market_id,
  instructions: [{
    orderType: "LIMIT_ON_CLOSE",
    selectionId: selection_id,
    side: "BACK",
    limitOnCloseOrder: {
      liability: liability,
      price: 3.0
    }
  }]
})

# log back out.
client.logout

Settings

You can change the endpoint from the default api.betfair.com .. to api-au.betfair.com by using the endpoint option when you initialize the Betfair client.

client = Betfair::Client.new({ "X-Application" => "your_app_code" }, { endpoint: :aus })

The default is :default.

Best practices

Persistent HTTP connection

Betfair recommends that we pass the Connection: keep-alive header with each request in order to take advantage of HTTP 1.1's ability to have persistent connections which reduces latency for subsequent requests.

This library uses the httpi gem, which supports a number of different ruby http client adapters. httpclient and net-http-persistent are two which utilise persistent connections by default. To use net-http-persistent you should ensure that the gem is installed and in your load path, then set the HTTPI adapter:

require 'betfair'
HTTPI.adapter = :net_http_persistent

The same goes for httpclient, but it's not strictly necessary to explicitly set the adapter as it has a higher load order precedence than the other adapters.

Account security and authentication

Despite the example in this readme, you should definitely use the non-interactive login for your bots; check the Betfair docs about how to set that up. To login this way, use the non_interactive_login method:

# Performs the login procedure recommended for applications which run autonomously
#   username: Betfair account username string
#   password: Betfair account password string
#   cert_key_file_path: Path to Betfair client certificate private key file
#   cert_key_path: Path to Betfair client certificate public key file associated with Betfair account
client.non_interactive_login(username, password, cert_key_file_path, cert_file_path)

This also allows you to use 2-factor authentication for your online account access, which I'd also strongly recommend that you do. I'm pretty sure you wouldn't be comfortable if your bank accounts had nothing more advanced than credential access, and seeing as a lot of you will have a reasonable amount of money stored in your Betfair accounts, I don't think you should settle for that there, either.

Todo

  1. Error handling

Contributing

  1. Fork it ( https://github.com/mikecmpbll/betfair/fork )
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -am 'Add some feature')
  4. Push to the branch (git push origin my-new-feature)
  5. Create a new Pull Request

betfair's People

Contributors

hellola avatar mikecmpbll avatar paulgillard avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

betfair's Issues

Login via Proxy / VPN

My server is located on a country where betfair could not be accessed, is there any simple way or some relevant tutorial /gems you could share that could help me fixing this? Like connect via proxy / openvpn, etc (I have a PIA account..) thanks

Initialisation

Not sure what I'm doing wrong here? Many thanks in advance.

[1] pry(main)> gem 'betfair-ng'
[2] pry(main)> client = Betfair::Client.new("X-Application" => "...............")
NameError: uninitialized constant Betfair

Using RPC to access the API

Hi @mikecmpbll ,

I'm very happy with your gem, great work.

I'm interested in contributing actually. I'd like to extend the gem to allow it to use the Race Status API

The API only allows connections via RPC according to the docs though. I'm trying to setup my integration to use RPC but I'm kinda confused about how to do that.

Can you point me in the right direction to get RPC working and I can begin adding the Race Status functionality.

Much appreciated!

Socket

Is there any sample code for socket integration with betfair?

list_market_book not working?

I have tried for a while now to get simple list_market_book working I constantly bump into "MandatoryNotDefined" error. There is good possibility that error is in my code, but it doesn't hurt to check.

I am able to get market catalogue just fine and to keep everything simple I have tried to fetch information for one marketId (1.118451619) and I was able to fo just that with following and was also able to put market id into variable (not really needed atm, but double checking)

soccer = client.list_market_catalogue({
    filter: {
        marketIds: [1.118451619] },
        maxResults: 200 
    })
id = soccer.first["marketId"]    

But when I try to fetch market book for that same id with following I get an error about mandatory no defined. Even though to my understanding marketid is the only required field for this.

book = client.list_market_book({
   filter: {
     marketIds: id }
})

Is it something I did or is there really an issue?

Error I get is:

{"detail"=>{}, "faultcode"=>"Client", "faultstring"=>"DSC-0018"}

Which according to this https://github.com/betfair/cougar-documentation/blob/master/legacy/Cougar_Fault_Reporting.md is described as "A parameter marked as mandatory was not provided"

[Question] - Listen for events

Hi, thanks for creating a much loved ruby gem for betfair. Question. Does this works with stream-api.betfair.com? How about listening for events when using the non interactive login?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.