def login(appid, login, pword): import json import betfair from betfair import Betfair client = Betfair(appid, ('../../Certs/client-2048.crt', '../../Certs/client-2048.key')) print 'Logging in' client.login(login, pword) return client
def login(appid, login, pword): import json import betfair from betfair import Betfair client = Betfair(appid, ('../../../../Certs/client-2048.crt', '../../../../Certs/client-2048.key')) print 'Logging in' client.login(login, pword) return client
class Command(BaseCommand): def __init__(self, *args, **kwargs): super(Command, self).__init__(*args, **kwargs) # Setup connection to Betfair API-NG self.client = Betfair(settings.BETFAIR_APP, settings.BETFAIR_CERT) self.client.login(settings.BETFAIR_USER, settings.BETFAIR_PASS) def handle(self, *args, **kwargs): # XXX: Hardcodign msk = timezone('Europe/Moscow') utc = timezone('UTC') # Loop over configured targets for competition in settings.TARGETS: cid = self.get_competition_id(competition) # Get event list for each target team for target in settings.TARGETS[competition]: events = self.client.list_events( MarketFilter(text_query=target, competition_ids=cid) ) # Event processing for e in events: event_id = int(e.event.id) raw_time = make_aware(e.event.open_date, utc) start_time = localtime(raw_time, msk) # Save persistent data try: event = Event.objects.create(id=event_id, title=e.event.name, start_time=start_time) event.save() self.stdout.write('Event #%d \'%s\' saved' % (event.id, event.title)) except IntegrityError: pass def get_competition_id(self, name): competitions = self.client.list_competitions( MarketFilter(text_query=name) ) for obj in competitions: return obj.competition.id
from flask import Flask from flask.ext.cache import Cache from flask.ext.cors import CORS from betfair import Betfair from betfair.utils import BetfairEncoder import logging app = application = Flask(__name__) app.config.from_object(__name__) app.config.from_envvar('BETFAIR_API_CONFIG') app.json_encoder = BetfairEncoder client = Betfair(app.config['BETFAIR_APPLICATION_KEY'], app.config['BETFAIR_PEM_PATH']) client.login(app.config['BETFAIR_USER_NAME'], app.config['BETFAIR_PASSWORD']) cache = Cache(config={'CACHE_TYPE': 'simple'}) cache.init_app(app) CORS(app, origins=[ 'http://localhost:4200', 'http://stringerer.s3-website-eu-west-1.amazonaws.com' ]) stream_handler = logging.StreamHandler() app.logger.addHandler(stream_handler) import betfair_tennis_api.endpoints from betfair_tennis_api.matches import matches_api from betfair_tennis_api.account import account_api
def betfair_get(self, is_ip, counter, sport='Tennis'): start = timezone.now() ip = 'ip' if is_ip else 'ni' client = Betfair('GkhXY3b3KmncnwLe', 'certs/bf.pem') # client = Betfair('uv9hV1EjlFimHmgr', 'certs/bf.pem') client.login('sherst', 'osT1G11nRe35') client.keep_alive() tennis_event_type = self.sports[sport] markets = client.list_market_catalogue( MarketFilter(event_type_ids=[tennis_event_type], market_type_codes=["MATCH_ODDS"], in_play_only=is_ip), market_projection=["EVENT", "RUNNER_METADATA", "COMPETITION"], max_results=200) mids = [m.market_id for m in markets] mids_portions = [mids[x:x + 40] for x in xrange(0, len(mids), 40)] for mp in mids_portions: print(','.join(mp)) books = client.list_market_book( mp, price_projection=PriceProjection( price_data=betfair.constants.PriceData.EX_BEST_OFFERS)) for b in books: m = next((x for x in markets if x.market_id == b.market_id), None) if m.competition == None: continue bfcid = m.competition.id champname = m.competition.name country = m.event.country_code event_id = m.event.id ds = timezone.make_aware(m.event.open_date) p1 = m.runners[0].runner_name if (p1 == None or '/' in p1): continue rid1 = m.runners[0].selection_id p2 = m.runners[1].runner_name rid2 = m.runners[1].selection_id event, created = BFEvent.objects.get_or_create(bfid=event_id) if (created): champ = self.save_champ(bfcid, champname, tennis_event_type, country) player1 = self.save_player(p1) player2 = self.save_player(p2) event.cid = champ event.rid1 = rid1 event.rid2 = rid2 event.pid1 = player1 event.pid2 = player2 event.dt = ds event.status = 1 if is_ip else 0 event.save() p1b1_odds = b.runners[0].ex.available_to_back[0].price if len( b.runners[0].ex.available_to_back) > 0 else 0 p1b1_size = b.runners[0].ex.available_to_back[0].size if len( b.runners[0].ex.available_to_back) > 0 else 0 p1l1_odds = b.runners[0].ex.available_to_lay[0].price if len( b.runners[0].ex.available_to_lay) > 0 else 0 p1l1_size = b.runners[0].ex.available_to_lay[0].size if len( b.runners[0].ex.available_to_lay) > 0 else 0 p2b1_odds = b.runners[1].ex.available_to_back[0].price if len( b.runners[1].ex.available_to_back) > 0 else 0 p2b1_size = b.runners[1].ex.available_to_back[0].size if len( b.runners[1].ex.available_to_back) > 0 else 0 p2l1_odds = b.runners[1].ex.available_to_lay[0].price if len( b.runners[1].ex.available_to_lay) > 0 else 0 p2l1_size = b.runners[1].ex.available_to_lay[0].size if len( b.runners[1].ex.available_to_lay) > 0 else 0 if (self.is_debug): self.stdout.write('*** evid [%s] %s - %s at %s, changed %s\n' % (event.id, event.pid1.name, event.pid2.name, event.dt, event.dtc), ending='') try: odds = BFOdds.objects.filter(eid=event).latest('dtc') if (odds.b1odds != p1b1_odds or odds.b2odds != p2b1_odds or odds.l1odds != p1l1_odds or odds.l2odds != p2l1_odds): self.save_odds(event, p1b1_odds, p2b1_odds, p1l1_odds, p2l1_odds, p1b1_size, p2b1_size, p1l1_size, p2l1_size, is_ip) if (self.is_debug): self.stdout.write( 'evid[%s], mid[%s] %s %s - %s in %s: %s/%s\n' % (event_id, b.market_id, ds, p1.replace( '\\', ''), p2.replace('\\', ''), country, b.total_matched, b.total_available), ending='') self.stdout.write( '[%s]%s:%s@%s\t|%s@%s\n' % (rid1, p1.replace('\\', ''), p1b1_size, p1b1_odds, p1l1_size, p1l1_odds), ending='') self.stdout.write( '[%s]%s:%s@%s\t|%s@%s\n' % (rid2, p2.replace('\\', ''), p2b1_size, p2b1_odds, p2l1_size, p2l1_odds), ending='') except: self.save_odds(event, p1b1_odds, p2b1_odds, p1l1_odds, p2l1_odds, p1b1_size, p2b1_size, p1l1_size, p2l1_size, is_ip) if (self.is_debug): self.stdout.write( 'evid[%s], mid[%s] %s %s - %s in %s: %s/%s\n' % (event_id, b.market_id, ds, p1.replace( '\\', ''), p2.replace('\\', ''), country, b.total_matched, b.total_available), ending='') self.stdout.write('[%s]%s:%s@%s\t|%s@%s\n' % (rid1, p1.replace('\\', ''), p1b1_size, p1b1_odds, p1l1_size, p1l1_odds), ending='') self.stdout.write('[%s]%s:%s@%s\t|%s@%s\n' % (rid2, p2.replace('\\', ''), p2b1_size, p2b1_odds, p2l1_size, p2l1_odds), ending='') end = timezone.now() log = ALog() log.name = 'update_bf_%s_%s' % (sport, ip) log.dts = start log.counter = counter log.duration = (end - start).total_seconds() log.save() if (self.is_debug): self.stdout.write('total execution is %s seconds\n' % (end - start), ending='')
from urllib.error import HTTPError import json from bet356 import getCardCompetitionData, getListCompetition, driver ITERATION = 50 # connect to API and keep alive session key dir = os.path.abspath(os.path.dirname(__file__)) key = 'betfair.pem' out_file_name = 'betfeir.xlsx' base_dir = os.path.join(dir, 'cert', key) out_file_dir = os.path.join(dir, 'data', out_file_name) client = Betfair('OclZSgXWwsQNpQky', '{}'.format(base_dir)) client.login(username='******', password='******') client.keep_alive() url = client.api_url headers = client.headers def callAping(jsonrpc_req): try: req = request.Request(url, jsonrpc_req.encode('utf-8'), headers) response = urllib.request.urlopen(req) jsonResponse = response.read() return jsonResponse.decode('utf-8') except HTTPError: print('Not a valid operation from the service ' + str(url)) exit()
#!/usr/bin/env python '''get_betfair_races.py: Capture daily racing event data (UK win markets).''' import time import betfair from betfair import Betfair from betfair.models import MarketFilter, MarketCatalogue from betfair.constants import MarketProjection import pymysql.cursors client = Betfair('APP_KEY', ('certs/api.crt', 'certs/api.key')) client.login('BF_USERNAME', 'BF_PASSWORD') client.keep_alive() date_today = time.strftime("%Y-%m-%d") connection = pymysql.connect(host='localhost', user='******', password='******', db='DATABASE NAME', charset='utf8mb4', autocommit=True, cursorclass=pymysql.cursors.DictCursor) marketFilter = { 'eventTypeIds': [7], 'marketCountries': ['GB'], 'marketTypeCodes': ["WIN"] }
import json import betfair from betfair import Betfair client = Betfair('eTnX7n6jsiaoGA9g', ('certs/client-2048.crt', 'certs/client-2048.key')) print 'Logging in' client.login('*****@*****.**', 'wyeslsc10') print 'Keeping alive' client.keep_alive() account_details = client.get_account_details() print account_details a = account_details.currency_code print a from betfair.models import MarketFilter event_types = client.list_event_types(MarketFilter(text_query='tennis')) print event_types print event_types[0] print event_types[0].event_type 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])) print markets[0].market_name # 'Djokovic Tournament Wins' client.logout()
import json import betfair from betfair import Betfair client = Betfair('eTnX7n6jsiaoGA9g', ('certs/client-2048.crt', 'certs/client-2048.key')) print 'Logging in' client.login('*****@*****.**', 'wyeslsc10') print 'Keeping alive' client.keep_alive() account_details = client.get_account_details() print account_details a = account_details.currency_code print a from betfair.models import MarketFilter event_types = client.list_event_types(MarketFilter(text_query='tennis')) print event_types print event_types[0] print event_types[0].event_type 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])) print markets[0].market_name # 'Djokovic Tournament Wins'
#!/usr/bin/env python from betfair import Betfair import sys print "HugeHard Test Script" client = Betfair('fxmlhjiDhNghfmLP', 'C:/Users/Cong/Desktop/betfair/keys/shang.pem') client.login('*****@*****.**', 'wabjtam@123') print 'login successful' sys.exit from betfair.models import MarketFilter event_types = client.list_event_types(MarketFilter(text_query='basketball')) #print (len(event_types)) #print (event_types[0].event_type.name) football_event_type = event_types[0] competitions = client.list_competitions() for comp in competitions: a = comp['competition'] if a.name == u'NBA Matches': id_NBA = a.id events = client.list_events(MarketFilter(competition_ids=[id_NBA])) f = open('C:/Users/Cong/Desktop/betfair/log_basketball.txt', 'w') for eventResult in events: e = eventResult.event c = eventResult.market_count
class Container(object, metaclass=Singleton): interested_types = ['WIN'] refresh_interval = 1 pre_match_interval = 30 historic_data_url = r'https://historicdata.betfair.com/api/GetMyData' def __init__(self, sandbox_key=False): self.selected_events = {} self.markets = {} self.client = None self.sandbox_key = sandbox_key # if true use sandbox,, if false use prod self.do_login() def do_login(self): __location = os.path.realpath( os.path.join(os.getcwd(), os.path.dirname(__file__))) username = config.get('Betfair', 'username') password = config.get('Betfair', 'password') certfile = config.get('Betfair', 'cert_file') devkey = config.get('Betfair', 'dev_app') prodkey = config.get('Betfair', 'prod_app') full_certfile = os.path.join(__location, certfile) self.client = Betfair(prodkey if not self.sandbox_key else devkey, full_certfile) self.client.login(username, password) def get_all_races(self): # Get all games, even those with no scores API feed, search 2 hours in the past delta = datetime.timedelta(seconds=60 * 70) to_time = datetime.datetime.now() + delta event_types = self.client.list_event_types( MarketFilter(text_query='horse')) horse_racing_id = event_types[0].event_type.id countries = config.get('Scraping', 'countries').split() events = self.client.list_events( filter=MarketFilter(event_type_ids=[horse_racing_id], market_countries=countries, market_start_time=TimeRange(to=to_time))) # market_type_codes=self.interested_types) if len(events) == 0: return [], [] # TODO: shouldn't these be returned as defaultdict? markets = defaultdict(list) for m in self.client.list_market_catalogue( MarketFilter(event_ids=[e.event.id for e in events], market_start_time=TimeRange(to=to_time), market_type_codes=self.interested_types), market_projection=[ MarketProjection['RUNNER_DESCRIPTION'], MarketProjection['EVENT'], MarketProjection['MARKET_DESCRIPTION'], MarketProjection['MARKET_START_TIME'] ]): markets[m.event.id].append((m.market_id, m)) return events, markets def get_single_race(self, market_id): events = self.client.list_events(filter=MarketFilter( market_ids=[market_id])) if len(events) == 0: return [], [] # TODO: shouldn't these be returned as defaultdict? markets = defaultdict(list) for m in self.client.list_market_catalogue( MarketFilter(market_ids=[market_id]), market_projection=[ MarketProjection['RUNNER_DESCRIPTION'], MarketProjection['EVENT'], MarketProjection['MARKET_DESCRIPTION'], MarketProjection['MARKET_START_TIME'] ]): markets[m.event.id].append((m.market_id, m)) return events, markets def update_markets(self, events, markets): pp = PriceProjection(price_data=[ 'EX_BEST_OFFERS', 'EX_TRADED', 'SP_AVAILABLE', 'SP_TRADED' ]) market_ids = [] for m in markets.values(): for r in m: market_ids.append(r[0]) markets_resp = [] for market_list in _split_list(market_ids): markets_resp.extend( self.client.list_market_book(market_ids=market_list, price_projection=pp)) return markets_resp def get_single_market(self, market_id): pp = PriceProjection( price_data=['EX_BEST_OFFERS', 'SP_AVAILABLE', 'SP_TRADED']) markets = self.client.list_market_book(market_ids=[market_id], price_projection=pp) return markets def place_limit_order(self, market, selection, stake, odds, side='BACK', persist='LAPSE', strategy=None): persist = config.getboolean("Betting", "persist") persist = 'LAPSE' if persist == False else 'PERSIST' bet = LimitOrder( size=max(2, stake) if side == 'BACK' else stake, # stake is minimum 2 GBP price=odds, persistence_type=persist) order = PlaceInstruction(order_type='LIMIT', selection_id=int(selection), side=side, limit_order=bet) return self.client.place_orders(market, [order], customer_ref="MRE-{}-{}".format( market, selection), strategy_ref=strategy) def place_fill_or_kill(self, market, selection, stake, odds, side='BACK', strategy=None): bet = LimitOrder( size=max(2, stake) if side == 'BACK' else stake, price=odds, persistence_type='LAPSE', time_in_force='FILL_OR_KILL', min_fill_size=max(2, stake) if side == 'BACK' else stake) order = PlaceInstruction(order_type='LIMIT', selection_id=int(selection), side=side, limit_order=bet) return self.client.place_orders(market, [order], customer_ref="MRE-{}-{}".format( market, selection), strategy_ref=strategy) def welcome_message(self): acc = self.client.get_account_details() first_name = acc['first_name'] acc = self.client.get_account_funds() funds = acc.available_to_bet_balance return "Welcome %s, your account balance is %s" % (first_name, funds) def get_open_orders(self): """ Get current unfilled orders by market :return: dictionary of list of orders """ projection = OrderProjection['EXECUTABLE'] orders = self.client.list_current_orders(order_projection=projection) orders_by_market = defaultdict(list) for o in orders.current_orders: orders_by_market[o.market_id].append(o) return orders_by_market def replace_orders(self, market, bet_ids, new_prices): """ Replace current orders with new prices :param market: :param bet_ids: :param new_prices: :return: """ instructions = [] for bet_id, np in zip(bet_ids, new_prices): instruction = ReplaceInstruction(bet_id=bet_id, new_price=np) instructions.append(instruction) return self.client.replace_orders(market_id=market, instructions=instructions) def get_cleared_orders(self, from_time=datetime.datetime.today() + datetime.timedelta(-1)): orders = self.client.list_cleared_orders( event_type_ids=[7], bet_status='SETTLED', settled_date_range=TimeRange(from_=from_time)) trades_df = pd.DataFrame.from_records( [x.values() for x in orders['cleared_orders']]) total_commission = 0. if not trades_df.empty: trades_df.columns = orders['cleared_orders'][0].keys() total_commission_req = self.client.list_cleared_orders( event_type_ids=[7], bet_status='SETTLED', group_by='EVENT_TYPE', settled_date_range=TimeRange(from_=from_time)) total_commission = total_commission_req['cleared_orders'][ 0].commission return trades_df, total_commission def get_account_balance(self): result = self.client.get_account_funds() return {k: result.get(k) for k in result.keys()} def get_race_status(self, events): results = self.client.list_race_details(events) if results: return pd.DataFrame.from_records([x.values() for x in results], columns=results[0].keys()) def download_historic_data(self, start, end, countries=('GB', 'IE')): ssoid = self.client.session_token headers = {'ssoid': ssoid} d = { "sport": "Horse Racing", "plan": "Basic Plan", "fromDay": start.day, "fromMonth": start.month, "fromYear": start.year, "toDay": end.day, "toMonth": end.month, "toYear": end.year, "marketTypesCollection": ["WIN"], "countriesCollection": list(countries), "fileTypeCollection": ["M"] } response = requests.get( 'https://historicdata.betfair.com/api/DownloadListOfFiles', params=d, headers=headers) file_names = json.loads(response.text) races = [] def inner(f): race_data = requests.get( 'http://historicdata.betfair.com/api/DownloadFile', params={'filePath': f}, headers=headers) race_str = bz2.decompress(race_data.content).decode('utf8') return BetFairRace.create_from_json(race_str) pool = ThreadPool() for file in file_names: races.append(pool.apply_async(inner, args=tuple([file]))) pool.close() pool.join() return [r.get() for r in races]
@author: obod ''' from __future__ import print_function from betfair.models import MarketFilter from betfair import Betfair import betfair_pandas as bp import datetime import dateutil import pandas as pd if __name__ == '__main__': # ssologin # To use this you will need app_key,cert_file,username,password client = Betfair(app_key, cert_file) client.login(username, password) # List horse racing event ids event_types = bp.list_event_types( client, filter={'textQuery': "Horse Racing" }) # First 5 UK horse races, win market, from now country_code = 'GB' marketFilter = { 'eventTypeIds': [event_types.id[0]], 'marketCountries': [country_code], 'marketTypeCodes': ["WIN"], 'marketStartTime': { 'from': datetime.datetime.now() } } # First 5 horse races, win market, from now races = bp.list_market_catalogue(client,
@author: obod ''' from __future__ import print_function from betfair.models import MarketFilter from betfair import Betfair import betfair_pandas as bp import datetime import dateutil import pandas as pd if __name__ == '__main__': # ssologin # To use this you will need app_key,cert_file,username,password client=Betfair(app_key,cert_file) client.login(username,password) # List horse racing event ids event_types=bp.list_event_types(client,filter={'textQuery':"Horse Racing"}) # First 5 UK horse races, win market, from now country_code='GB' marketFilter={'eventTypeIds':[event_types.id[0]], 'marketCountries':[country_code], 'marketTypeCodes':["WIN"], 'marketStartTime':{'from':datetime.datetime.now()}} # First 5 horse races, win market, from now races=bp.list_market_catalogue(client, filter=marketFilter, market_projection=['COMPETITION','EVENT','EVENT_TYPE','MARKET_DESCRIPTION', 'RUNNER_DESCRIPTION','MARKET_START_TIME'], sort="FIRST_TO_START", max_results=5 )
import threading from datetime import datetime, timedelta from betfair import Betfair from betfair.exceptions import ApiError from betfair.models import MarketFilter, PriceProjection from betfair.constants import MarketProjection, PriceData, OrderProjection, MatchProjection, MarketStatus from config import DEVELOPER_APP_KEY, CERT_FILE, USERNAME, PASSWORD, APP_KEY, STATUS, DEBUG from marketsdb import MarketsDB from datetime import datetime client = Betfair(APP_KEY, CERT_FILE) client.login(USERNAME, PASSWORD) class CaptureMatch(threading.Thread): def __init__(self, queue, thread_no, db=MarketsDB()): """ :param time_stop: *datetime* time to stop exectuion of code :param delta: *int* number of seconds to wait :param game_name: *string* String representation of game :param db: **MarketsDb** - Object to reading/writing DB data to DB :return: """ threading.Thread.__init__(self) self.queue = queue self.thread_no = thread_no self.db = db self.client = client if DEBUG: print("Thread no: {} initialised".format(self.thread_no))
import boto3 import logging from flask import Flask from flask_cache import Cache from flask_cors import CORS from betfair import Betfair from selenium import webdriver from selenium.common.exceptions import WebDriverException app = application = Flask(__name__) app.config.from_object('stringer_api.config.secrets') client = Betfair(app.config['BETFAIR_APPLICATION_KEY'], app.config['BETFAIR_PEM_PATH']) client.login(app.config['BETFAIR_USER_NAME'], app.config['BETFAIR_PASSWORD']) cache = Cache(config=app.config['CACHE_CONFIG']) cache.init_app(app) CORS(app, origins=app.config['CORS']) dynamo = boto3.client('dynamodb', region_name='eu-west-1') phantom = None try: phantom = webdriver.PhantomJS(app.config['PHANTOM_PATH']) except WebDriverException as e: app.logger.error(e) except Exception as e: app.logger.error(e) from stringer_api.matches import matches_api