Code Monkey home page Code Monkey logo

betfair.py's Introduction

image

image

betfair.py is a Python wrapper for the Betfair API

Installation

$ pip install betfair.py

Requirements

  • Python >= 2.7 or >= 3.3

Testing

To run tests :

$ py.test

Application Keys

You will need an Application Key to log in to the Betfair API. You can find instructions for creating a key at https://api.developer.betfair.com/services/webapps/docs/display/1smk3cen4v3lu3yomq5qye0ni/Application+Keys

SSL Certificates

For non-interactive login, you must generate a self-signed SSL certificate and upload it to your Betfair account. Betfair.py includes tools for simplifying this process. To create a self-signed certificate, run :

invoke ssl

This will generate the following files in the certs directory :

betfair.crt
betfair.csr
betfair.key
betfair.pem

You can write SSL certificates to another directory by passing the --name parameter :

invoke ssl --name=path/to/certs/betfair

Once you have generated the files, you can upload the betfair.crt file to Betfair at https://myaccount.betfair.com/accountdetails/mysecurity?showAPI=1.

Examples

Create a Betfair client and log in :

from betfair import Betfair
client = Betfair('app_key', 'certs/betfair.pem')
client.login('username', 'password')

Refresh session token :

client.keep_alive()

Log out :

client.logout()

List all tennis markets :

from betfair.models import MarketFilter
event_types = client.list_event_types(
    MarketFilter(text_query='tennis')
)
print(len(event_types))                 # 2
print(event_types[0].event_type.name)   # 'Tennis'
tennis_event_type = event_types[0]
markets = client.list_market_catalogue(
    MarketFilter(event_type_ids=[tennis_event_type.event_type.id])
)
markets[0].market_name                  # 'Djokovic Tournament Wins'

Author

Joshua Carp (jmcarp)

License

MIT licensed. See the bundled LICENSE file for more details

betfair.py's People

Contributors

anderustarroz avatar goetzk avatar jmcarp avatar jontonsoup avatar ms5 avatar petedmarsh avatar seriousdude avatar skozilla avatar

Stargazers

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

Watchers

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

betfair.py's Issues

list_current_orders fields should be optional

Hi,
According to the API docs listCurrentOrders doesn't require any of its fields to be true.
"Optionally you can filter and sort your current orders using the various parameters, setting none of the parameters will return all of your current orders up to a maximum of 1000 bets, ordered BY_BET and sorted EARLIEST_TO_LATEST. "
https://api.developer.betfair.com/services/webapps/docs/display/1smk3cen4v3lu3yomq5qye0ni/listCurrentOrders

This change allows running list_current_orders without any parameters but I'm not submitting a pull request as this fails on an empty list being returned - something considered valid by the API. I'm guessing there is something else in betfair.py that needs tweaking and I will submit a pul if I figure it out.

--- b/betfair/betfair.py
+++ b/betfair/betfair.py
@@ -318,8 +321,8 @@ class Betfair(object):

     @utils.requires_login
     def list_current_orders(
-            self, bet_ids, market_ids, order_projection, date_range, order_by,
-            sort_dir, from_record, record_count):
+            self, bet_ids=None, market_ids=None, order_projection=None, date_range=None, order_by=None,
+            sort_dir=None, from_record=None, record_count=None):
         """

         :param bet_ids:

SSL Handshake issue

I get an SSL handshake issue after uploading my .crt file and running:

from betfair import Betfair
client = Betfair('my_appid','certs/betfair.pem')
client.login('my_user_name', 'my_pw')

where my_appid is taken from https://developer.betfair.com/visualisers/api-ng-account-operations/getDeveloperAppKeys

and my_user_name and my_pw are my usual login details.

any ideas?

Problem on install betfair.py

Hi.
I'm trying to install betfair.py but I've got this problem :

Microsoft Windows [Versione 6.1.7601]
Copyright (c) 2009 Microsoft Corporation. Tutti i diritti riservati.

C:\Users\MyUser>pip install betfair.py
Collecting betfair.py
  Using cached betfair.py-0.1.4.tar.gz
    Complete output from command python setup.py egg_info:
    Traceback (most recent call last):
      File "<string>", line 20, in <module>
      File "c:\users\MyUser\appdata\local\temp\pip-build-c0m5pp\betfair.py\set
up.py", line 79, in <module>
        license=read('LICENSE'),
      File "c:\users\MyUser\appdata\local\temp\pip-build-c0m5pp\betfair.py\set
up.py", line 61, in read
        with open(fname) as fp:
    IOError: [Errno 2] No such file or directory: 'LICENSE'

    ----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in c:\users\MyUser
\appdata\local\temp\pip-build-c0m5pp\betfair.py

C:\Users\MyUser>

Can someone help me?
Thanks!

New endpoints from 20 December

I presume the following in betfair.py needs to be changed to accommodate this?

IDENTITY_URLS = collections.defaultdict(
    lambda: 'https://identitysso.betfair.com/api/',
    italy='https://identitysso.betfair.it/api/',
)

SSL Cert Generation cannot find the file specified

Hi,

I am having issues generating the SSL cerificate required for the login process.
I have recently installed via pip install betfair. This process didn't pull down the tasks.py file so I have also downloaded that and placed it in the betfair folder. Not sure if I am missing other files also?

I have tried running invoke ssl but I keep getting "The system cannot find the file specified" which seems like a fairly obvious error message but as I am new to python / SSL certificate generation I am not sure where to go from here,

I have search google / stack overflow but I have had no luck.

Any help would be greatly appreciated.

JSON can't handle datetime objects

The issue is that JSON can't handle datetime objects nor enum objects.
A fix is to suppy a handler function to json.dumps() like this:

(EDIT: I tried to paste a patch here, but it was interpreted as markup. The essential bit is this in betfair.py)

def make_api_request(self, method, params, codes=None, model=None):

    def _dthandler(obj):
        """
        fix datetime objects for JSON
        """
        # for datetime objects
        if hasattr(obj, 'isoformat'):
            return obj.isoformat()
        # for enum objects
        if hasattr(obj,'name'):
            return obj.name
        else:
            raise TypeError, 'Object of type %s with value of %s is not JSON serializable$

     payload = utils.make_payload(method, params)
     response = self.session.post(
         API_URL,
         data=json.dumps(payload, default=_dthandler),
         headers=self.headers,
     )
     utils.check_status_code(response, codes=codes)

get_account_funds returning Exception

The call to get_account_funds() is returning a betfair.exceptions.ApiError: UNKNOWN
I tested other Account apis and got the same issue.
The Sports APIs work fine.

Thanks.

Code breaks if betfair add a new field to their models

Recently Betfair added a new field to their model, which appears only to certain market queries. I found out, that in such a case to code will break till the model is adjusted to the new field.

I understand the logic behind and I think the effort to try to keep the python api in sync with the real Betfair model is the right way to go. Unfortunately it takes sometimes a little while till the model can be fixed and if the code breaks (raises exceptions) during this period the bot is useless for that day.

In an effort to make the code more reliable I came up with a little patch, that does instead of raising an exception on new (unknown) fields, just logs a warning.

The benefit is see is:

  • if betfair adds new fields: existing code does not break and gives time to fix/adjust to now model

what you guys think about this?

setup.py fails on pip = 1.1

pip install betfair.py
Downloading/unpacking betfair.py
  Running setup.py egg_info for package betfair.py
    Traceback (most recent call last):
      File "<string>", line 14, in <module>
      File "/home/nishant/venvs/datafootball/build/betfair.py/setup.py", line 76, in <module>
        for requirement in parse_requirements('requirements.txt')
      File "/home/nishant/venvs/datafootball/local/lib/python2.7/site-packages/pip-1.1-py2.7.egg/pip/req.py", line 1240, in parse_requirements
        skip_regex = options.skip_requirements_regex
    AttributeError: 'NoneType' object has no attribute 'skip_requirements_regex'
    Complete output from command python setup.py egg_info:
    Traceback (most recent call last):

  File "<string>", line 14, in <module>

  File "/home/nishant/venvs/datafootball/build/betfair.py/setup.py", line 76, in <module>

    for requirement in parse_requirements('requirements.txt')

  File "/home/nishant/venvs/datafootball/local/lib/python2.7/site-packages/pip-1.1-py2.7.egg/pip/req.py", line 1240, in parse_requirements

    skip_regex = options.skip_requirements_regex

AttributeError: 'NoneType' object has no attribute 'skip_requirements_regex'

invoke ssl throws errors (likely related to some path variable...?)

C:\Users\ECALDOW\Dropbox\OSIRIS\API\Betfair\betfair.py-master>invoke ssl
Traceback (most recent call last):
File "c:\python27\lib\runpy.py", line 162, in run_module_as_main
"main", fname, loader, pkg_name)
File "c:\python27\lib\runpy.py", line 72, in run_code
exec code in run_globals
File "C:\Python27\Scripts\invoke.exe__main
.py", line 9, in
File "c:\python27\lib\site-packages\invoke\program.py", line 270, in run
self.execute()
File "c:\python27\lib\site-packages\invoke\program.py", line 381, in execute
executor.execute(_self.tasks)
File "c:\python27\lib\site-packages\invoke\executor.py", line 113, in execute
result = call.task(_args, *_call.kwargs)
File "c:\python27\lib\site-packages\invoke\tasks.py", line 111, in call
result = self.body(_args, *_kwargs)
File "C:\Users\ECALDOW\Dropbox\OSIRIS\API\Betfair\betfair.py-master\tasks.py",
line 49, in ssl
generate_key(name, bits)
File "c:\python27\lib\site-packages\invoke\tasks.py", line 111, in call
result = self.body(args, *kwargs)
File "C:\Users\ECALDOW\Dropbox\OSIRIS\API\Betfair\betfair.py-master\tasks.py",
line 14, in generate_key
run(cmd)
File "c:\python27\lib\site-packages\invoke__init
.py", line 32, in run
return Context().run(command, *_kwargs)
File "c:\python27\lib\site-packages\invoke\context.py", line 53, in run
return runner_class(context=self).run(command, **kwargs)
File "c:\python27\lib\site-packages\invoke\runners.py", line 259, in run
self.start(command, shell, env)
File "c:\python27\lib\site-packages\invoke\runners.py", line 966, in start
stdin=PIPE,
File "c:\python27\lib\subprocess.py", line 710, in init
errread, errwrite)
File "c:\python27\lib\subprocess.py", line 958, in _execute_child
startupinfo)
WindowsError: [Error 3] The system cannot find the path specified

Extracting timing information from requests

Hi,
Since (at least) Requests 2.6.2 elapsed time is recorded and stored in Response.elapsed. I'm about to hackishly expose it for my own purposes (not sure how yet) and was wondering if there was a way you could recommend or if you would be interested in including such a change.

follow up on issue #24, code breaks on rogue fields

I come back to issue #24 , since with the move to schematics the problem is again here. For example I get the following exception on rogue fields and that breaks the data of that market, so my bot is useless again...

schematics.exceptions.ModelConversionError: {'description': {'each_way_divisor': 'Rogue field'}}

In general I think, there is no need to raise an exception on rogue fields, because the model/bot will continue to work, even if betfair decides to add new data. this new fields can latter be added to the betfair.py model.

pip install betair.py not working

ip install betfair.py
Downloading/unpacking betfair.py
Downloading betfair.py-0.1.3.tar.gz
Running setup.py egg_info for package betfair.py
Traceback (most recent call last):
File "", line 16, in
File "/private/var/folders/2j/nbr55chx0hn2z9f8fvf663_w0000gp/T/pip_build_kennethmarritt/betfair.py/setup.py", line 76, in
for requirement in parse_requirements('requirements.txt')
File "/usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pip-1.4.1-py2.7.egg/pip/req.py", line 1403, in parse_requirements
filename, content = get_file_content(filename, comes_from=comes_from)
File "/usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pip-1.4.1-py2.7.egg/pip/download.py", line 95, in get_file_content
raise InstallationError('Could not open requirements file: %s' % str(e))
pip.exceptions.InstallationError: Could not open requirements file: [Errno 2] No such file or directory: 'requirements.txt'
Complete output from command python setup.py egg_info:
Traceback (most recent call last):

File "", line 16, in

File "/private/var/folders/2j/nbr55chx0hn2z9f8fvf663_w0000gp/T/pip_build_kennethmarritt/betfair.py/setup.py", line 76, in

for requirement in parse_requirements('requirements.txt')

File "/usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pip-1.4.1-py2.7.egg/pip/req.py", line 1403, in parse_requirements

filename, content = get_file_content(filename, comes_from=comes_from)

File "/usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pip-1.4.1-py2.7.egg/pip/download.py", line 95, in get_file_content

raise InstallationError('Could not open requirements file: %s' % str(e))

pip.exceptions.InstallationError: Could not open requirements file: [Errno 2] No such file or directory: 'requirements.txt'

how to debug betfair.exceptions.BetfairAPIError: INVALID_APP_KEY

Firt of al, thanks alot for the great wrapper!

When I execute the code from the readme,

from betfair import Betfair
client = Betfair('test', 'certs/betfair.pem')
client.login('username', 'password')

from betfair.models import MarketFilter
event_types = client.list_event_types(
    MarketFilter(text_query='tennis')
)

I get this error:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 2, in list_event_types
  File "betfair/utils.py", line 125, in requires_login
    return func(*args, **kwargs)
  File "betfair/betfair.py", line 125, in list_event_types
    model=models.EventTypeResult,
  File "betfair/betfair.py", line 62, in make_api_request
    result = utils.result_or_error(response)
  File "betfair/utils.py", line 67, in result_or_error
    raise exceptions.BetfairAPIError(response, data)
betfair.exceptions.BetfairAPIError: INVALID_APP_KEY

The invalid app key error is not mentioned on the developers help site here:
https://api.developer.betfair.com/services/webapps/docs/display/1smk3cen4v3lu3yomq5qye0ni/Non-Interactive+%28bot%29+login

So I guess the reason is somewhere on the plugin side?

Problem

My code:

from betfair import Betfair
client = Betfair('test', ('certs/client-2048.crt', 'certs/client-2048.key'))
client.login('name', 'password')
print(client) # all good

from betfair.models import MarketFilter
event_types = client.list_event_types(
    MarketFilter(text_query='tennis')
)
print(len(event_types))

Print a error:
TypeError: list_event_types() missing 1 required positional argument: 'locale'

Problem running example.

I can login, however when run this line:
event_types = client.list_event_types(MarketFilter(text_query='tennis'))

I get this error:
python2.7/site-packages/betfair/utils.py", line 109, in make_payload
'method': '{base}APING/v1.0/{endpoint}'.format(**locals()),
KeyError: 'endpoint'

pip install error

Using pip 6.1.1, Python 3.4.3 I get the following error:

$ pip install betfair.py
Collecting betfair.py
  Downloading betfair.py-0.1.4.tar.gz
    Complete output from command python setup.py egg_info:
    Traceback (most recent call last):
      File "<string>", line 20, in <module>
      File "/tmp/user/1000/pip-build-8mzy35ag/betfair.py/setup.py", line 79, in <module>
        license=read('LICENSE'),
      File "/tmp/user/1000/pip-build-8mzy35ag/betfair.py/setup.py", line 61, in read
        with open(fname) as fp:
    FileNotFoundError: [Errno 2] No such file or directory: 'LICENSE'

Calls to place order not working

Hi,

Calls to place_orders are returning INVALID_INPUT_DATA. Here is the code I am using below. The market and selection ids are correct.

instructions = []
limit = LimitOrder(size=2, price=5, persistence_type=PersistenceType.LAPSE)

instruction = PlaceInstruction(order_type=OrderType.LIMIT, selection_id=120027, handicap=0, side=Side.BACK, limit_order=limit)
instructions.append(instruction)

order = client.place_orders("1.11962314", instructions)

tasks doesn't work from a pypi install

If you install from pip:

pip install betfair.py

As in the instructions and then issue a:

invoke ssl

You get the error:

Can't find any collection named 'tasks'!

In order for tasks to work you have to clone the repository but that sort of negates the point of publishing on pypi.

ImportError: No module named treq

Traceback (most recent call last):
File "Betfair.py", line 5, in
from betfair import Betfair
File "C:\Python27\lib\site-packages\betfair.py-0.1.3-py2.7.egg\betfair__init__.py", line 3, in
from .betfair import Betfair
File "C:\Python27\lib\site-packages\betfair.py-0.1.3-py2.7.egg\betfair\betfair.py", line 14, in
from network import Network
File "C:\Python27\lib\site-packages\betfair.py-0.1.3-py2.7.egg\betfair\network.py", line 1, in
import treq
ImportError: No module named treq

Any idea what is missing?

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.