-
Notifications
You must be signed in to change notification settings - Fork 147
/
examplestreaming.py
83 lines (65 loc) · 2.43 KB
/
examplestreaming.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
import logging
import queue
import threading
import betfairlightweight
from betfairlightweight.filters import (
streaming_market_filter,
streaming_market_data_filter,
)
# setup logging
logging.basicConfig(level=logging.INFO) # change to DEBUG to see log all updates
# create trading instance (app key must be activated for streaming)
trading = betfairlightweight.APIClient("username", "password", app_key="appKey")
# login
trading.login()
# create queue
output_queue = queue.Queue()
# create stream listener
listener = betfairlightweight.StreamListener(output_queue=output_queue)
# create stream
stream = trading.streaming.create_stream(listener=listener)
# create filters (GB WIN racing)
market_filter = streaming_market_filter(
event_type_ids=["7"], country_codes=["GB"], market_types=["WIN"]
)
market_data_filter = streaming_market_data_filter(
fields=["EX_BEST_OFFERS", "EX_MARKET_DEF"], ladder_levels=3
)
# subscribe
streaming_unique_id = stream.subscribe_to_markets(
market_filter=market_filter,
market_data_filter=market_data_filter,
conflate_ms=1000, # send update every 1000ms
)
# start stream in a new thread (in production would need err handling)
t = threading.Thread(target=stream.start, daemon=True)
t.start()
"""
Data can also be accessed by using the snap function in the listener, e.g:
market_books = listener.snap(
market_ids=[1.12345323]
)
Errors need to be caught at stream.start, resubscribe can then be used to
prevent full image being sent, e.g:
streaming_unique_id = stream.subscribe_to_markets(
market_filter=market_filter,
market_data_filter=market_data_filter,
conflate_ms=1000, # send update every 1000ms
initial_clk=listener.initial_clk,
clk=listener.clk,
)
The streaming unique id is returned in the market book which allows multiple
streams to be differentiated if multiple streams feed into the same queue.
"""
# check for updates in output queue
while True:
market_books = output_queue.get()
print(market_books)
for market_book in market_books:
print(
market_book,
market_book.streaming_unique_id, # unique id of stream (returned from subscribe request)
market_book.streaming_update, # json update received
market_book.market_definition, # streaming definition, similar to catalogue request
market_book.publish_time, # betfair publish time of update
)