Comments (16)
+1. I believe this is also related to my issue which is that the live trading (on the minute timeframe at least) even on the sample sma crossover script, attempts to place multiple orders within a minute and ends up timing out. Console log below:
Starting Portfolio Value: 100897.4409
2020-04-24T23:21:00, placing trade for AAPL. target size: 5.0
2020-04-24T23:24:00, placing trade for AAPL. target size: 0.0
2020-04-24T23:24:00, placing trade for AAPL. target size: -5.0
sleep 3 seconds and retrying https://paper-api.alpaca.markets/v2/positions 3 more time(s)...
sleep 3 seconds and retrying https://paper-api.alpaca.markets/v2/account 3 more time(s)...
'dict' object has no attribute 'order'
sleep 3 seconds and retrying https://paper-api.alpaca.markets/v2/positions 3 more time(s)...
sleep 3 seconds and retrying https://paper-api.alpaca.markets/v2/account 3 more time(s)...
sleep 3 seconds and retrying https://paper-api.alpaca.markets/v2/positions 3 more time(s)...
from alpaca-backtrader-api.
which sample code did you use?
from alpaca-backtrader-api.
It's working well for DELAYED data but not for LIVE data
class SmaCross1(bt.Strategy):
# list of parameters which are configurable for the strategy
params = dict(
pfast=10, # period for the fast moving average
pslow=30 # period for the slow moving average
)
def notify_data(self, data, status, *args, **kwargs):
print('*' * 5, data._name, 'DATA NOTIF:', data._getstatusname(status),
*args)
if status == data.LIVE:
self.data_live = True
def log(self, txt, dt=None):
dt = dt or self.data.datetime[0]
dt = bt.num2date(dt)
print('%s, %s' % (dt.isoformat(), txt))
def notify_trade(self, trade):
self.log("placing trade for {}. target size: {}".format(
trade.getdataname(),
trade.size))
#Added display functionality
def notify_order(self, order):
if order.status in [order.Completed, order.Cancelled, order.Rejected]:
self.order = None
print('Created: {} Price: {} Size: {}'.format(bt.num2date(order.created.dt), order.executed.price,
order.executed.size))
print('-' * 80)
print('{}: Order ref: {} / Type {} / Status {}'.format(
self.data.datetime.date(0),
order.ref, 'Buy' * order.isbuy() or 'Sell',
order.getstatusname()))
def stop(self):
print('==================================================')
print('Starting Value - %.2f' % self.broker.startingcash)
print('Ending Value - %.2f' % self.broker.getvalue())
print('==================================================')
def __init__(self):
sma1 = bt.ind.SMA(self.data0, period=self.p.pfast)
sma2 = bt.ind.SMA(self.data0, period=self.p.pslow)
self.crossover0 = bt.ind.CrossOver(sma1, sma2)
def next(self):
print('{}: O {}, H {}, L {}, C {}'.format(
self.data.datetime.datetime(),
self.data.open[0],
self.data.high[0],
self.data.low[0],
self.data.close[0]
))
# if fast crosses slow to the upside
if not self.positionsbyname["AAPL"].size and self.crossover0 > 0:
self.buy(data=data0, size=5) # enter long
# in the market & cross to the downside
if self.positionsbyname["AAPL"].size and self.crossover0 <= 0:
self.sell(data=data0, size=5) # close long position
if __name__ == '__main__':
cerebro = bt.Cerebro()
cerebro.addstrategy(SmaCross1)
store = alpacastore.AlpacaStore(
key_id=ALPACA_API_KEY,
secret_key=ALPACA_SECRET_KEY,
paper=True
)
DataFactory = store.getdata # or use alpaca_backtrader_api.AlpacaData
if ALPACA_PAPER:
data0 = DataFactory(dataname='AAPL',
backfill_start=True, #added backfill instead of historical
timeframe=bt.TimeFrame.Minutes, compression=1) #Convert days into 1 Minute
cerebro.resampledata(data0, name='AAPL', timeframe=bt.TimeFrame.Minutes, compression=1)
# or just alpaca_backtrader_api.AlpacaBroker()
broker = store.getbroker(use_positions=False)
cerebro.setbroker(broker)
else:
data0 = DataFactory(dataname='AAPL', historical=True, fromdate=datetime(
2015, 1, 1), timeframe=bt.TimeFrame.Days)
cerebro.adddata(data0)
if not ALPACA_PAPER:
# backtrader broker set initial simulated cash
cerebro.broker.setcash(100000.0)
print('Starting Portfolio Value: {}'.format(cerebro.broker.getvalue()))
cerebro.run()
print('Final Portfolio Value: {}'.format(cerebro.broker.getvalue()))
cerebro.plot()`
from alpaca-backtrader-api.
The sample code I used is from this repo: sample/sma_crossover_strategy.py
I only changed the api keys and set ALPACA_PAPER to true (to enable live paper trading). I also set the timeframe to timeframe=bt.TimeFrame.Minutes instead of Days so that more trades would be made, and the timeout error comes up. I then tried to leave it at the original timeframe bt.TimeFrame.Days and the same issue comes up (timing out, "sleep 3 seconds and retrying https://paper-api.alpaca.markets/v2/account 3 more time(s)").
Tried again today (while the markets were open), same result in live trading.
from alpaca-backtrader-api.
please try with current data source, updated to use the new alpaca python-sdk (0.47rc5). sma_crossover_strategy should work smoothly now.
install it like so: pip install git+https://github.com/alpacahq/alpaca-backtrader-api
from alpaca-backtrader-api.
Thanks Shlomi! There is a new issue with threading now when running the sample:
Starting Portfolio Value: 100000.0
C:\Users\anish\AppData\Local\Programs\Python\Python38-32\lib\site-packages\alpaca_trade_api\stream2.py:144: UserWarning: Discarding nonzero nanoseconds in conversion
await handler(self, channel, ent)
Exception in thread Thread-1:
Traceback (most recent call last):
File "C:\Users\anish\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 932, in _bootstrap_inner
self.run()
File "C:\Users\anish\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 870, in run
self._target(*self._args, **self._kwargs)
File "C:\Users\anish\AppData\Local\Programs\Python\Python38-32\lib\site-packages\alpaca_backtrader_api\alpacastore.py", line 328, in _t_streaming_listener
self._transaction(trans)
File "C:\Users\anish\AppData\Local\Programs\Python\Python38-32\lib\site-packages\alpaca_backtrader_api\alpacastore.py", line 650, in _transaction
oid = trans['id']
TypeError: 'Entity' object is not subscriptable
sleep 3 seconds and retrying https://paper-api.alpaca.markets/v2/account 3 more time(s)...
sleep 3 seconds and retrying https://paper-api.alpaca.markets/v2/account 3 more time(s)...
sleep 3 seconds and retrying https://paper-api.alpaca.markets/v2/account 3 more time(s)...
sleep 3 seconds and retrying https://paper-api.alpaca.markets/v2/account 3 more time(s)...
sleep 3 seconds and retrying https://paper-api.alpaca.markets/v2/account 3 more time(s)...
sleep 3 seconds and retrying https://paper-api.alpaca.markets/v2/account 3 more time(s)...
Am I missing a dependency? Were you able to get the sma_crossover_strategy test script working in live trading? I have a funded alpaca account, and am running the script locally on my computer.
from alpaca-backtrader-api.
so there are 2 issues in this log.
- sleep 3 seconds... - this is a known issue that should not trouble you and I will fix it soon
- TypeError: 'Entity' object is not subscriptable - this is new. did you use the sample code to get that?
let me know, and I will try to reproduce it locally so I could debug it.
from alpaca-backtrader-api.
Yes I updated the api as you described and then used the same sample/sma_crossover_strategy.py and performed the same changes as I mentioned in previous comment: #38 (comment)
No other changes have been made on my end.
from alpaca-backtrader-api.
could you update alpaca-trade-api to the latest version and try again?
from alpaca-backtrader-api.
I ran pip install git+https://github.com/alpacahq/alpaca-trade-api-python
and got the same issue when I ran the same sample script. The sleep 3 seconds issue appears to be gone, but the same 'Entity' issue is still there, it happens once upon first running the script.
from alpaca-backtrader-api.
try the new version and check if you still get this error: https://github.com/alpacahq/alpaca-backtrader-api/releases/tag/v0.8.0
from alpaca-backtrader-api.
It seems the issue is still there after updating. There was an order placed for the first time, and I was able to see it in my dashboard. However, the sleep 3 seconds issue returned after a few seconds.
Starting Portfolio Value: 99630.7294
C:\Users\anish\AppData\Local\Programs\Python\Python38-32\lib\site-packages\alpaca_trade_api\stream2.py:151: UserWarning: Discarding nonzero nanoseconds in conversion
await handler(self, channel, ent)
2020-05-11T12:44:00, placing trade for AAPL. target size: 5
Exception in thread Thread-1:
Traceback (most recent call last):
File "C:\Users\anish\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 932, in _bootstrap_inner
self.run()
File "C:\Users\anish\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 870, in run
self._target(*self._args, **self._kwargs)
File "C:\Users\anish\AppData\Local\Programs\Python\Python38-32\lib\site-packages\alpaca_backtrader_api\alpacastore.py", line 328, in _t_streaming_listener
self._transaction(trans)
File "C:\Users\anish\AppData\Local\Programs\Python\Python38-32\lib\site-packages\alpaca_backtrader_api\alpacastore.py", line 650, in _transaction
oid = trans['id']
TypeError: 'Entity' object is not subscriptable
sleep 3 seconds and retrying https://paper-api.alpaca.markets/v2/account 3 more time(s)...
sleep 3 seconds and retrying https://paper-api.alpaca.markets/v2/account 3 more time(s)...
sleep 3 seconds and retrying https://paper-api.alpaca.markets/v2/account 3 more time(s)...
from alpaca-backtrader-api.
try installing it like this: pip install git+https://github.com/alpacahq/[email protected]
I don't see the errors you see locally. try to run the example code and start from there
from alpaca-backtrader-api.
@shlomikushchi I seem to be getting the same exception (TypeError: 'Entity' object is not subscriptable
). Here is my requirements.txt
file, any help would be appreciated.
aiohttp==3.6.2 # via alpha-vantage
alpaca-backtrader-api==0.8.0 # via -r requirements.in
alpaca-trade-api==0.48 # via alpaca-backtrader-api
alpha-vantage==2.2.0 # via alpaca-trade-api
async-timeout==3.0.1 # via aiohttp
asyncio-nats-client==0.10.0 # via alpaca-trade-api
attrs==19.3.0 # via aiohttp
backtrader==1.9.74.123 # via alpaca-backtrader-api
certifi==2020.4.5.1 # via requests
chardet==3.0.4 # via aiohttp, requests
click==7.1.2 # via pip-tools
deprecated==1.2.10 # via alpaca-trade-api
flake8==3.8.1 # via -r requirements.in
idna==2.9 # via requests, yarl
importlib-metadata==1.6.0 # via flake8
isort==4.3.21 # via -r requirements.in
mccabe==0.6.1 # via flake8
multidict==4.7.6 # via aiohttp, yarl
numpy==1.18.4 # via pandas
pandas==1.0.3 # via alpaca-trade-api
pip-tools==5.1.2 # via -r requirements.in
pycodestyle==2.6.0 # via flake8
pyflakes==2.2.0 # via flake8
python-dateutil==2.8.1 # via pandas
python-dotenv==0.13.0 # via -r requirements.in
pytz==2020.1 # via pandas
requests==2.23.0 # via alpaca-trade-api, alpha-vantage
six==1.14.0 # via pip-tools, python-dateutil, websocket-client
urllib3==1.24.3 # via alpaca-trade-api, requests
websocket-client==0.57.0 # via alpaca-trade-api
websockets==8.1 # via alpaca-trade-api
wrapt==1.12.1 # via deprecated
yarl==1.4.2 # via aiohttp
zipp==3.1.0 # via importlib-metadata
from alpaca-backtrader-api.
@psugand could you provide the stacktrace and code you executed (if it is one of the example codes...) so I could try duplicating it?
from alpaca-backtrader-api.
this issue is similar to #53
closing this one.
from alpaca-backtrader-api.
Related Issues (20)
- Not a reliable API
- backtrader-api uses deprecated alpaca-trade-api - will it be migrated to alpaca-py?
- Documentation for creating new Alpaca is broken. HOT 1
- Trading Calender - Package Issue HOT 3
- Cannot import alpaca-backtrader-api (Python 3.9.9 MacOS) HOT 5
- backtest not going back far enough HOT 2
- Multiple datas has connection limited error?
- alpaca-trade-api uses UTC while `_clear_out_of_market_hours` assumes NY Time. HOT 1
- Alpaca AttributeError: 'Asset' has not attribute 'status'
- Data websocket error with paper trading. Error code = 1002 (protocol error)
- Multiple WebSocket Open or Proxy - for multiple strategies
- Cannot purchase Long and create a trailing stop
- The Default Value for 'stocklike'
- only getting minute data until 12pm EST everyday in historical mode HOT 1
- Multiple datas sample no longer works HOT 1
- alpaca-trade-api-python is being deprecated by alpaca-py HOT 1
- Replay with historical data only retrieve daily bars instead replaying every minute
- module 'finplot' has no attribute 'add_order' HOT 1
- error installing on Windows 11, Python 3.9 HOT 3
- Wrong timezone for DataFactory
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
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.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from alpaca-backtrader-api.