Comments (12)
no, this is an old approach to the problem which was not chosen eventually.
from alpaca-backtrader-api.
do you have a funded alpaca account ?
also, I don't see the log...
from alpaca-backtrader-api.
Yes I have funded alpaca account.
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
)
data_live = False
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_data(self, data, status, *args, **kwargs):
print('*' * 5, data0._name, 'DATA NOTIF:', data._getstatusname(status),
*args)
print('*' * 5, data1._name, 'DATA NOTIF:', data._getstatusname(status), *args)
if status == data.LIVE:
self.data_live = True
def notify_trade(self, trade):
self.log("placing trade for {}. target size: {}".format(
trade.getdataname(),
trade.size))
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)
#
# sma1 = bt.ind.SMA(self.data1, period=self.p.pfast)
# sma2 = bt.ind.SMA(self.data1, period=self.p.pslow)
# self.crossover1 = bt.ind.CrossOver(sma1, sma2)
def next(self):
# if fast crosses slow to the upside
print('{}: O {}, H {}, L {}, C {}'.format(
self.data0.datetime.datetime(),
self.data0.open[0],
self.data0.high[0],
self.data0.low[0],
self.data0.close[0]))
print('{}: O {}, H {}, L {}, C {}'.format(
self.data1.datetime.datetime(),
self.data1.open[0],
self.data1.high[0],
self.data1.low[0],
self.data1.close[0]))
if not self.data_live:
return
if not self.positionsbyname["AAPL"].size: #and self.crossover0 > 0:
self.buy(data=data0, size=5) # enter long
if not self.positionsbyname["GOOG"].size: #and self.crossover1 > 0:
self.buy(data=data1, 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
# in the market & cross to the downside
if self.positionsbyname["GOOG"].size: #and self.crossover1 <= 0:
self.sell(data=data1, 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,
timeframe=bt.TimeFrame.Minutes, compression=1)
data1 = DataFactory(dataname='GOOG',
backfill_start=True,
timeframe=bt.TimeFrame.Minutes, compression=1)
cerebro.resampledata(data0, name='AAPL', timeframe=bt.TimeFrame.Minutes, compression=1)
cerebro.resampledata(data1, name='GOOG', 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)
data1 = DataFactory(dataname='GOOG', historical=True, fromdate=datetime(
2015, 1, 1), timeframe=bt.TimeFrame.Days)
#cerebro.adddata(data0)
#cerebro.adddata(data1)
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.
I have just executed your code and it looks ok. this is what I get:
2020-05-04 16:42:00: O 1311.27, H 1311.27, L 1310.435, C 1310.96
2020-05-04 16:43:00: O 290.3, H 290.58, L 290.2551, C 290.49
2020-05-04 16:43:00: O 1311.2424, H 1311.8942, L 1311.2424, C 1311.8942
2020-05-04 16:45:00: O 290.48, H 290.5, L 290.33, C 290.37
2020-05-04 16:45:00: O 1311.29, H 1311.48, L 1311.13, C 1311.24
***** AAPL DATA NOTIF: LIVE
***** GOOG DATA NOTIF: LIVE
***** AAPL DATA NOTIF: LIVE
***** GOOG DATA NOTIF: LIVE
2020-05-04 16:46:00: O 290.33, H 290.42, L 290.25, C 290.28
2020-05-04 16:46:00: O 1311.34, H 1311.59, L 1311.12, C 1311.59
Created: 2020-05-04 16:46:00 Price: 0.0 Size: 0
--------------------------------------------------------------------------------
2020-05-04: Order ref: 1 / Type Buy / Status Rejected <=== rejected because of account limitations
2020-05-04 16:47:00: O 290.27, H 290.36, L 290.2, C 290.25
2020-05-04 16:47:00: O 1311.59, H 1312.08, L 1311.23, C 1312.01
is there another issue with that?
from alpaca-backtrader-api.
closing because there was no response for 20 days
from alpaca-backtrader-api.
Does the paper account with live data work on account with no funds?
I am able to run everything fine on a paper account while the market is open, but when I add a second data item (adddata) then I get this error:
Exception in thread Thread-6:
Traceback (most recent call last):
File "C:\Users\NEF\AppData\Local\Programs\Python\Python37\lib\threading.py", line 917, in _bootstrap_inner
self.run()
File "C:\Users\NEF\AppData\Local\Programs\Python\Python37\lib\threading.py", line 865, in run
self._target(*self._args, **self._kwargs)
File "C:\Users\NEF\AppData\Local\Programs\Python\Python37\lib\site-packages\alpaca_backtrader_api\alpacastore.py", line 483, in _t_streaming_prices
streamer.run()
File "C:\Users\NEF\AppData\Local\Programs\Python\Python37\lib\site-packages\alpaca_backtrader_api\alpacastore.py", line 132, in run
self.conn.run(channels)
File "C:\Users\NEF\AppData\Local\Programs\Python\Python37\lib\site-packages\alpaca_trade_api\stream2.py", line 275, in run
loop.run_until_complete(self.subscribe(initial_channels))
File "C:\Users\NEF\AppData\Local\Programs\Python\Python37\lib\asyncio\base_events.py", line 584, in run_until_complete
return future.result()
File "C:\Users\NEF\AppData\Local\Programs\Python\Python37\lib\site-packages\alpaca_trade_api\stream2.py", line 250, in subscribe
await self.data_ws.subscribe(data_channels)
File "C:\Users\NEF\AppData\Local\Programs\Python\Python37\lib\site-packages\alpaca_trade_api\stream2.py", line 104, in subscribe
await self._ensure_ws()
File "C:\Users\NEF\AppData\Local\Programs\Python\Python37\lib\site-packages\alpaca_trade_api\stream2.py", line 88, in _ensure_ws
await self._connect()
File "C:\Users\NEF\AppData\Local\Programs\Python\Python37\lib\site-packages\alpaca_trade_api\stream2.py", line 52, in _connect
raise Exception(f"Error while connecting to {self._endpoint}:"
Exception: Error while connecting to wss://data.alpaca.markets/stream:your connection is rejected while another connection is open under the same account
from alpaca-backtrader-api.
you were trying to run more than one script at once. we currently only allow 1 data connection at any given time
from alpaca-backtrader-api.
I am quite sure I was running only one script, but when add a second data source then I start getting this error:
data0 = DataFactory(dataname='AAPL',timeframe=bt.TimeFrame.TFrame("Minutes"),)
data1 = DataFactory(dataname='TSLA',timeframe=bt.TimeFrame.TFrame("Minutes"),)
cerebro.adddata(data0)
cerebro.adddata(data1) <<< error occurs when this is added
from alpaca-backtrader-api.
if you want to run another data source in the same script (can't be done with different python executions) you could use this branch:
https://github.com/alpacahq/alpaca-backtrader-api/tree/shared_websocket_streamer
install it like this: pip install -U git+https://github.com/alpacahq/alpaca-backtrader-api@shared_websocket_streamer
from alpaca-backtrader-api.
ok perfect, I will give it a try.
Are there any plans to merge this with the master branch?
Thanks for the prompt response.
from alpaca-backtrader-api.
not yet, I'm waiting for feedback from users
from alpaca-backtrader-api.
if you want to run another data source in the same script (can't be done with different python executions) you could use this branch:
https://github.com/alpacahq/alpaca-backtrader-api/tree/shared_websocket_streamer
install it like this:pip install -U git+https://github.com/alpacahq/alpaca-backtrader-api@shared_websocket_streamer
Hi,
by following your instructions on the readme (with the proxy agent), we can already run multiple data sources in the same script. Does this branch change something?
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.