Skip to content

Commit 7829ee2

Browse files
author
Shlomi Kushchi
authored
Merge pull request #44 from shlomikushchi/master
Support the new alpaca data api
2 parents e21cb62 + 34aaf20 commit 7829ee2

File tree

8 files changed

+51
-25
lines changed

8 files changed

+51
-25
lines changed

alpaca_backtrader_api/alpacabroker.py

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -86,12 +86,7 @@ def update_positions(self):
8686

8787
for name, data in iteritems(self.cerebro.datasbyname):
8888
if name in broker_positions_symbols:
89-
90-
is_sell = broker_positions_mapped_by_symbol[name].side ==\
91-
'short'
9289
size = int(broker_positions_mapped_by_symbol[name].qty)
93-
if is_sell:
94-
size = -size
9590
positions[data] = Position(
9691
size,
9792
float(broker_positions_mapped_by_symbol[

alpaca_backtrader_api/alpacadata.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -166,7 +166,7 @@ def setenvironment(self, env):
166166

167167
def start(self):
168168
"""
169-
Starts the Alpaca connecction and gets the real contract and
169+
Starts the Alpaca connection and gets the real contract and
170170
contractdetails if it exists
171171
"""
172172
super(AlpacaData, self).start()

alpaca_backtrader_api/alpacastore.py

Lines changed: 41 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -58,11 +58,17 @@ def __init__(self):
5858

5959
class API(tradeapi.REST):
6060

61-
def _request(self, method, path, data=None):
61+
def _request(self,
62+
method,
63+
path,
64+
data=None,
65+
base_url=None,
66+
api_version=None):
6267

6368
# Added the try block
6469
try:
65-
return super(API, self)._request(method, path, data)
70+
return super(API, self)._request(
71+
method, path, data, base_url, api_version)
6672
except requests.RequestException as e:
6773
resp = AlpacaRequestError().error_response
6874
resp['description'] = str(e)
@@ -89,14 +95,19 @@ def __init__(
8995
instrument='',
9096
method='',
9197
base_url='',
98+
data_stream='',
9299
*args,
93100
**kwargs):
94101
try:
95102
# make sure we have an event loop, if not create a new one
96103
asyncio.get_event_loop()
97104
except RuntimeError:
98105
asyncio.set_event_loop(asyncio.new_event_loop())
99-
self.conn = tradeapi.StreamConn(api_key, api_secret, base_url)
106+
self.data_stream = data_stream
107+
self.conn = tradeapi.StreamConn(api_key,
108+
api_secret,
109+
base_url,
110+
data_stream=self.data_stream)
100111
self.instrument = instrument
101112
self.method = method
102113
self.q = q
@@ -110,7 +121,10 @@ def run(self):
110121
if not self.method:
111122
channels = ['trade_updates'] # 'account_updates'
112123
else:
113-
maps = {"quote": "Q."}
124+
if self.data_stream == 'polygon':
125+
maps = {"quote": "Q."}
126+
elif self.data_stream == 'alpacadatav1':
127+
maps = {"quote": "alpacadatav1/Q."}
114128
channels = [maps[self.method] + self.instrument]
115129

116130
loop = asyncio.new_event_loop()
@@ -177,6 +191,7 @@ class AlpacaStore(with_metaclass(MetaSingleton, object)):
177191
('key_id', ''),
178192
('secret_key', ''),
179193
('paper', False),
194+
('usePolygon', False),
180195
('account_tmout', 10.0), # account balance refresh timeout
181196
('api_version', None)
182197
)
@@ -318,7 +333,10 @@ def _t_streaming_events(self, q, tmout=None):
318333
streamer = Streamer(q,
319334
api_key=self.p.key_id,
320335
api_secret=self.p.secret_key,
321-
base_url=self.p.base_url)
336+
base_url=self.p.base_url,
337+
data_stream='polygon' if self.p.usePolygon else
338+
'alpacadatav1'
339+
)
322340

323341
streamer.run()
324342

@@ -384,13 +402,20 @@ def _t_candles(self, dataname, dtbegin, dtend, timeframe, compression,
384402
start_dt = None
385403
if dtkwargs['start']:
386404
start_dt = dtkwargs['start'].isoformat()
387-
response = \
388-
self.oapi.polygon.historic_agg_v2(
389-
dataname,
390-
compression,
391-
granularity,
392-
_from=self.iso_date(start_dt),
393-
to=self.iso_date(end_dt))
405+
if self.p.usePolygon:
406+
response = \
407+
self.oapi.polygon.historic_agg_v2(
408+
dataname,
409+
compression,
410+
granularity,
411+
_from=self.iso_date(start_dt),
412+
to=self.iso_date(end_dt))
413+
else:
414+
response = self.oapi.get_aggs(dataname,
415+
compression,
416+
granularity,
417+
self.iso_date(start_dt),
418+
self.iso_date(end_dt))
394419
except AlpacaError as e:
395420
print(str(e))
396421
q.put(e.error_response)
@@ -451,7 +476,9 @@ def _t_streaming_prices(self, dataname, q, tmout):
451476
api_secret=self.p.secret_key,
452477
instrument=dataname,
453478
method='quote',
454-
base_url=self.p.base_url)
479+
base_url=self.p.base_url,
480+
data_stream='polygon' if self.p.usePolygon else
481+
'alpacadatav1')
455482

456483
streamer.run()
457484

@@ -581,7 +608,7 @@ def _t_order_create(self):
581608
trans = tpending.popleft()
582609
if trans is None:
583610
break
584-
self._process_transaction(oid, trans.order)
611+
self._process_transaction(oid, trans)
585612
except Exception as e:
586613
print(str(e))
587614

sample/github_example_strategy.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,8 @@ def __init__(self):
2525
store = alpaca_backtrader_api.AlpacaStore(
2626
key_id=ALPACA_API_KEY,
2727
secret_key=ALPACA_SECRET_KEY,
28-
paper=True
28+
paper=True,
29+
usePolygon=False
2930
)
3031

3132
DataFactory = store.getdata # or use alpaca_backtrader_api.AlpacaData

sample/multiple_data_strategy.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -70,7 +70,8 @@ def next(self):
7070
store = alpaca_backtrader_api.AlpacaStore(
7171
key_id=ALPACA_API_KEY,
7272
secret_key=ALPACA_SECRET_KEY,
73-
paper=True
73+
paper=True,
74+
usePolygon=False
7475
)
7576

7677
DataFactory = store.getdata # or use alpaca_backtrader_api.AlpacaData

sample/multiple_indicator_strategy.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,8 @@ def next(self):
7272
store = alpaca_backtrader_api.AlpacaStore(
7373
key_id=ALPACA_API_KEY,
7474
secret_key=ALPACA_SECRET_KEY,
75-
paper=True
75+
paper=True,
76+
usePolygon=False
7677
)
7778

7879
DataFactory = store.getdata # or use alpaca_backtrader_api.AlpacaData

sample/sma_crossover_strategy.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,8 @@ def next(self):
5858
store = alpaca_backtrader_api.AlpacaStore(
5959
key_id=ALPACA_API_KEY,
6060
secret_key=ALPACA_SECRET_KEY,
61-
paper=True
61+
paper=True,
62+
usePolygon=False
6263
)
6364

6465
DataFactory = store.getdata # or use alpaca_backtrader_api.AlpacaData

setup.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@
2626
packages=['alpaca_backtrader_api'],
2727
install_requires=[
2828
'backtrader',
29-
'alpaca-trade-api',
29+
'alpaca-trade-api==0.47rc5',
3030
],
3131
tests_require=[
3232
'pytest',

0 commit comments

Comments
 (0)