Giter VIP home page Giter VIP logo

Comments (16)

anishdhesikan avatar anishdhesikan commented on July 28, 2024

+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.

shlomiku avatar shlomiku commented on July 28, 2024

which sample code did you use?

from alpaca-backtrader-api.

monilshah2322 avatar monilshah2322 commented on July 28, 2024

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.

anishdhesikan avatar anishdhesikan commented on July 28, 2024

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.

shlomiku avatar shlomiku commented on July 28, 2024

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.

anishdhesikan avatar anishdhesikan commented on July 28, 2024

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.

shlomiku avatar shlomiku commented on July 28, 2024

so there are 2 issues in this log.

  1. sleep 3 seconds... - this is a known issue that should not trouble you and I will fix it soon
  2. 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.

anishdhesikan avatar anishdhesikan commented on July 28, 2024

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.

shlomiku avatar shlomiku commented on July 28, 2024

could you update alpaca-trade-api to the latest version and try again?

from alpaca-backtrader-api.

anishdhesikan avatar anishdhesikan commented on July 28, 2024

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.

shlomiku avatar shlomiku commented on July 28, 2024

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.

anishdhesikan avatar anishdhesikan commented on July 28, 2024

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.

shlomiku avatar shlomiku commented on July 28, 2024

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.

psugand avatar psugand commented on July 28, 2024

@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.

shlomiku avatar shlomiku commented on July 28, 2024

@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.

shlomiku avatar shlomiku commented on July 28, 2024

this issue is similar to #53
closing this one.

from alpaca-backtrader-api.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo 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.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.