Exemplo n.º 1
0
def connect_session(uname, pw):


    """Returns a session token for authentication of future requests.

                       Parameters:
                           uname (str): username for smarkets account
                           pw (str): password for smarkets account

                       Returns:
                           success (boolean): True if api call is successful, else false

                           details (dictionary/string): If success is true then a dictionary with the bet
                           placement details, otherwise an error. Note that the success field does not necessarily
                           mean the bet is placed - it just means the request and response is all as expected. The
                           response might be that your bet was rejected."""

    data = {'username':uname, "password":pw}

    result = helpers.data_req('sessions/',{'Content-Type':"application/json"}, data)

    if result.status_code==201:
        success = True
        details = {'token':result.json()["token"], 'expires':helpers.timestamp_todatetime(result.json()['stop'])}
    else:
        success = False
        details = "Failed to generate a session token, error type: {0}".format(result.json()['error_type'])
    return success, details
Exemplo n.º 2
0
def get_base_events(sesstoken):
    """Returns a dataframe of the base events (golf/tennis etc).

                       Parameters:
                           sessiontoken (str): Smarkets session token

                       Returns:
                           success (boolean): True if api call is successful, else false

                           details (dataframe/string): If success is true then a dataframe with the
                           base event details including the event names/event ids. If success==false,
                           an error message"""

    endpoint = "events/?limit=100"

    headers = {"Authorization": "Session-Token {0}".format(sesstoken)}

    result = helpers.data_req(endpoint, headers)

    if result.status_code == 200:
        if 'events' in result.json():
            success = True
            data = result.json()['events']
            names = [x['name'] for x in data]
            ids = [x['id'] for x in data]
            details = pd.DataFrame({'Name': names, 'ID': ids})
        else:
            success = False
            details = "Response code 200, but no events retrieved."
    else:
        success = False
        details = "Request for events failed, status code: {0}".format(
            str(result.status_code))

    return success, details
Exemplo n.º 3
0
def get_live_odds(sesstoken, marketids, type):
    """Returns a dataframe of live market details for either quotes or trades.

                    Parameters:
                        sessiontoken (str): Smarkets session token
                        marketid list: (str/int): MarketIDs for which odds/trades are required
                        type (quote/trade): Determines if market quotes or trades are returned

                    Returns:
                        success (boolean): True if api call is successful, else false

                        details (Dataframe/string): If success is true then a dataframe with
                        live market odds/trades. If success==False, an error message."""

    marketidstring = ",".join([str(x) for x in marketids])
    if type == "quote":
        endpoint = "markets/{0}/quotes/".format(marketidstring)
    elif type == "trade":
        endpoint = "markets/{0}/last_executed_prices/".format(marketidstring)

    headers = {"Authorization": "Session-Token {0}".format(sesstoken)}

    result = helpers.data_req(endpoint, headers)
    success = False
    if result.status_code == 200:
        data = result.json()
        if type == "trade":
            if 'last_executed_prices' in data:
                data = data['last_executed_prices']
                success = True
            if success == False:
                details = "Response received but no trades for market ids {0} found".apply(
                    marketidstring)
        elif type == "quote":
            if len(data) > 0:
                success = True
            else:
                success = False
                details = "Response received but no quotes for market ids {0} found".apply(
                    marketidstring)

        if success:
            if type == "quote":
                details = helpers.parse_odds_to_df(data)

            elif type == "trade":
                details = {}
                for marketid in list(data.keys()):
                    tradedf = helpers.parse_trades_to_df(data[marketid])
                    details[marketid] = tradedf

    else:
        success = False
        details = str(result.json())
    return success, details
Exemplo n.º 4
0
def get_market_types(sesstoken, bettable_id):
    """Returns a dataframe of market types for a bettable event.

                       Parameters:
                           sesstoken (str): Smarkets session token
                           bettable_id(str/int): The bettable event ID for which you want the market types.

                       Returns:
                           success (boolean): True if api call is successful, else false

                           details (dataframe/string): If success is true then a dataframe of the
                           market names/ids and other metadata associated with each market.
                           If success==false, an error string."""

    endpoint = "events/{0}/markets?sort=event_id%2Cdisplay_order".format(
        str(bettable_id))

    headers = {"Authorization": "Session-Token {0}".format(sesstoken)}

    result = helpers.data_req(endpoint, headers)

    if result.status_code == 200:
        data = result.json()
        if 'markets' in data and len(data['markets']) > 0:
            success = True

            data = data['markets']
            df_dict = {}
            for field in [
                    'name', 'id', 'bet_delay', 'cashout_enabled',
                    'inplay_enabled', 'state', 'winner_count'
            ]:
                df_dict[field] = [x[field] for x in data]

            details = pd.DataFrame(df_dict)
        else:
            success = False
            details = "Reponse code 200, but no markets retrieved."
    else:
        success = False
        details = "Request for market types failed, status code: {0}".format(
            str(result.status_code))

    return success, details
Exemplo n.º 5
0
def get_contracts_for_market(sesstoken, marketid):
    """Returns a dataframe of contracts associated with a marketid.

    *By contracts I mean "choices". For example if the market ID passed is
    for the "Winner" market of a football game the contracts will be the 2 teams.

                           Parameters:
                               sesstoken (str): Smarkets session token
                               marketid(str/int): The market ID for which you want the contracts returned.

                           Returns:
                               success (boolean): True if api call is successful, else false

                               details (dataframe/string): If success is true then a dataframe of the
                               contracts (the names/ids/state). If success==false, an error string."""

    endpoint = "markets/{0}/contracts/".format(str(marketid))

    headers = {"Authorization": "Session-Token {0}".format(sesstoken)}

    result = helpers.data_req(endpoint, headers)

    if result.status_code == 200:
        data = result.json()
        if 'contracts' in data and len(data['contracts']) > 0:
            success = True
            data = data['contracts']
            df_dict = {}

            for colname in ['name', 'competitor_id', 'id', 'state_or_outcome']:
                df_dict[colname] = [x[colname] for x in data]
            details = pd.DataFrame(df_dict)
        else:
            success = False
            details = "Response received but not contracts found for market id {0}".format(
                marketid)
    else:
        success = False
        details = "Request for contracts failed, status code: {0}".format(
            str(result.status_code))

    return success, details
Exemplo n.º 6
0
def get_volume(sesstoken, marketid):
    """Returns a dataframe with 1 row indicating the market ID and volume for that market.

    **I believe the volume is returned in GBP instead of account currency at present**

                       Parameters:
                           sessiontoken (str): Smarkets session token
                           marketid (str/int): MarketID for which volume is required

                       Returns:
                           success (boolean): True if api call is successful, else false

                           details (Dataframe/string): If success is true then a dataframe with
                           1 row, columns market id and volume. If success==False, an error message."""

    endpoint = "markets/{0}/volumes/".format(str(marketid))

    headers = {"Authorization": "Session-Token {0}".format(sesstoken)}

    result = helpers.data_req(endpoint, headers)

    if result.status_code == 200:
        data = result.json()
        if 'volumes' in data and len(data['volumes']) > 0:
            success = True
            data = data['volumes'][0]
            details = pd.DataFrame({
                'market_id': [data['market_id']],
                'volume': [data['volume']]
            })
        else:
            success = False
            details = str(data)
    else:
        success = False
        error_code = str(result.status_code)
        error_details = str(result.json())
        details = "Failed, response code {0}, error details: {1}".format(
            str(error_code), str(error_details))

    return success, details
Exemplo n.º 7
0
def get_child_events(sesstoken, parentid, extra_filters={}):
    """Returns a dataframe of the child events of a given parent event.

    E.g. pass the golf event id as the parent id and it will return golf tournaments
    Pass the pga championship event id and it will return all markets for that tournament.

                       Parameters:
                           sessiontoken (str): Smarkets session token
                           parentid (str/int): parent id for which you want child events returned
                           extra_filters (dict): Any key:value pairs you want to pass as filters.
                           Check https://docs.smarkets.com/#/orders/create_order for the schema.

                       Returns:
                           success (boolean): True if api call is successful, else false

                           details (dataframe/string): If success is true then a dataframe of the
                           child events including the name, id, created date, state, start date,
                           start date time, and whether the event is bettable (are you at a leaf in
                           the tree)."""

    endpoint = "events/"

    headers = {"Authorization": "Session-Token {0}".format(sesstoken)}

    filt = {'parent_id': [parentid]}

    for filtr in extra_filters:
        filt.update({filtr: extra_filters[filtr]})

    result = helpers.data_req(endpoint, headers, filters=filt)

    if result.status_code == 200:
        if 'events' in result.json():
            success = True
            data = result.json()['events']
            names = [x['name'] for x in data]
            ids = [x['id'] for x in data]
            created = []
            for x in data:
                try:
                    created.append(helpers.timestamp_todatetime(x['created']))
                except:
                    created.append(str(x['created']))

            def try_timestamp(x):
                try:
                    return helpers.timestamp_todatetime(x)
                except:
                    return str(x)

            state = [x['state'] for x in data]
            start_date = [x['start_date'] for x in data]
            start_datetime = [try_timestamp(x['start_datetime']) for x in data]
            bettable = [x['bettable'] for x in data]

            details = pd.DataFrame({
                'Name': names,
                'ID': ids,
                'created': created,
                'state': state,
                'start_date': start_date,
                'start_datetime': start_datetime,
                'bettable': bettable
            })
        else:
            success = False
            details = "Response code 200, but no events retrieved."
    else:
        success = False
        details = "Request for events failed, status code: {0}".format(
            str(result.status_code))

    return success, details