Giter Site home page Giter Site logo

alpacahq / alpaca-trade-api-python Goto Github PK

View Code? Open in Web Editor NEW
1.7K 106.0 525.0 900 KB

Python client for Alpaca's trade API

Home Page: https://pypi.org/project/alpaca-trade-api/

License: Apache License 2.0

Python 99.35% Shell 0.65%
alpaca trade api python algo-trading websocket rest-api trading market-data hacktoberfest

alpaca-trade-api-python's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

alpaca-trade-api-python's Issues

Request ability to cancel order by client order id

If we are able to tag our orders with a Client Order ID, it seems reasonable for a call like api.cancel_order_by_client_order_id('my_custom_client_order_id') to exist. I ask because it seems rather confusing to provide developers with a nice way of tagging orders internally, then forcing them to query for the proper id with a call to get_order_by_client_order_id if they chose to use that feature.

Question: Can someone explain how the sector weighting in the BenGraham.py file works?

I was wondering how the sector weighting in the BenGraham file works. My program lists the sectors by name, and displays an int usually growing from 1.0 to 6.0 next to them. It then assigns stocks a super small decimal for sector weighting say .01011 which I think the code then implies is divided by the sector weight, say 2.0, to give our stock weight. Why is the sector weight not a % of 100.
output.xlsx

API install

I am having troubles installing the alpaca trade api. Currently I'm getting an error when I try to install either via pipenv or pip. Let me know what other printouts would help in troubleshooting.
OS: Ubuntu 18.04

Full error:
The directory '/home/garrick/.cache/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
The directory '/home/garrick/.cache/pip' or its parent directory is not owned by the current user and caching wheels has been disabled. check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
Collecting alpaca-trade-api
Downloading https://files.pythonhosted.org/packages/45/a5/7ceb9477f9d87c50ef47b4b1a504b37c4ec1ff5c0f72a449eb786e127887/alpaca-trade-api-0.19.tar.gz
Collecting asyncio-nats-client (from alpaca-trade-api)
Downloading https://files.pythonhosted.org/packages/f6/a0/3e9a55cfe262699a2ce98714e14a7381bc674112f567af80457d16ea9b2f/asyncio-nats-client-0.8.2.tar.gz
Complete output from command python setup.py egg_info:
Traceback (most recent call last):
File "", line 1, in
File "/tmp/pip-build-dsdJrG/asyncio-nats-client/setup.py", line 2, in
from nats.aio.client import version
File "nats/init.py", line 22
yield from nc.connect(**options)
^
SyntaxError: invalid syntax

----------------------------------------

Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-dsdJrG/asyncio-nats-client/

Initializing the REST api fails to connect

Running a python application inside Docker container.

api = tradeapi.REST('<api-key>', '<api-secret>', api_version='v2')
account = api.get_account()
api.list_positions()

Also, have environment var APCA_API_BASE_URL="https://paper-api.alpaca.markets"

I get this error:

Traceback (most recent call last):
  File "/usr/local/lib/python3.7/site-packages/urllib3/connection.py", line 159, in _new_conn
    (self._dns_host, self.port), self.timeout, **extra_kw)
  File "/usr/local/lib/python3.7/site-packages/urllib3/util/connection.py", line 57, in create_connection
    for res in socket.getaddrinfo(host, port, family, socket.SOCK_STREAM):
  File "/usr/local/lib/python3.7/socket.py", line 748, in getaddrinfo
    for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
socket.gaierror: [Errno -2] Name or service not known

Adding limit to Polygon historic_agg_v2()

Hi,

I've been having a conversation with Polygon support and it turns out you can set a limit for historic_agg_v2(), which is absent from the current method.

So we'd now have:

def historic_agg_v2(self, symbol, multiplier, timespan, _from, to,
                        unadjusted=False, limit=None):
        path = '/aggs/ticker/{}/range/{}/{}/{}/{}'.format(
            symbol, multiplier, timespan, _from, to
        )
        params = {}
        params['unadjusted'] = unadjusted
        if limit is not None:
            params['limit'] = limit
        raw = self.get(path, params, version='v2')
        return Aggsv2(raw)

Simply adding a limit parameter.
I don't know how to propose this change but wanted to bring it up. Thanks.

Improve error message

As a user, I want more clear error message as to what happened in the case of error. For example, if you catch an exception from submit_order() and try to print the exception, it would just say ("402 Forbidden") instead of saying the actual server error message.

failing OPEN WebSocket connection with code 1011

The following exception is happening due to pong time out of websockets any one have any idea how can i fix it or restart the connection?
Error in data transfer Traceback (most recent call last): File "/home/r00t/PycharmProjects/algotry/venv/lib/python3.6/site-packages/websockets/protocol.py", line 795, in transfer_data message = await self.read_message() File "/home/r00t/PycharmProjects/algotry/venv/lib/python3.6/site-packages/websockets/protocol.py", line 863, in read_message frame = await self.read_data_frame(max_size=self.max_size) File "/home/r00t/PycharmProjects/algotry/venv/lib/python3.6/site-packages/websockets/protocol.py", line 962, in read_data_frame await self.pong(frame.data) File "/home/r00t/PycharmProjects/algotry/venv/lib/python3.6/site-packages/websockets/protocol.py", line 734, in pong await self.ensure_open() File "/home/r00t/PycharmProjects/algotry/venv/lib/python3.6/site-packages/websockets/protocol.py", line 771, in ensure_open raise self.connection_closed_exc() websockets.exceptions.ConnectionClosedError: code = 1006 (connection closed abnormally [internal]), no reason

[Feature]: Rest methods should take pd.Timestamp types as well for consistency

Entities return pd.Timestamp for time related entries, but calls that accept time don't accept that as a valid format.

So doing something like:

orders = api.list_orders(after='2018-01-01', status='all', direction='asc')
orders.extend( api.list_orders(after=orders[-1].submitted_at, status='all', direction='asc') )

results in a API format error on the after str(pd.Timestamp).

Perhaps this library could check the isinstance and use the .isoformat() automatically?

Websocket Error - Anyone else getting this?

Several months back I installed alpaca, zipline, pylivetrader etc to test these platforms out and play around with them. After some trouble-shooting everything went well and it all worked as expected.

I've just come back and tried to reinstall (as I no longer have the original test installation) and now I am confronted with this error:
Collecting websockets>=8.0 (from alpaca-trade-api>=0.38->pylivetrader) ERROR: Could not find a version that satisfies the requirement websockets>=8.0 (from alpaca-trade-api>=0.38->pylivetrader) (from versions: 1.0, 2.0, 2.1, 2.2, 2.3, 2.4, 2.5, 2.6, 2.7, 3.0, 3.1, 3.2, 3.3, 3.4, 4.0, 4.0.1, 5.0, 5.0.1, 6.0, 7.0) ERROR: No matching distribution found for websockets>=8.0 (from alpaca-trade-api>=0.38->pylivetrader)

I've spent as much time as I can trying to resolve it but am not able to make any progress on it.

For clarification:

  • Host Machine Macbook
  • VMware
  • Guest OS = Ubuntu 16.04

I have changed nothing on this particular machine other than delete the original pylivetrader (etc) installation after I had finished several months back yet now this error is raised no matter which method I use to install pylivetrader, alpaca-trade-api, zipline, pipeline-live etc.

If anyone has any insight onto this I'd be particularly grateful.

insufficient qty available for order

is there a way of checking the availability of stock so that I don't get
alpaca_trade_api.rest.APIError: insufficient qty available for order (requested: X, available: Y)
what do I need to do to get Y instead?
In other words, how do I get how many available stocks there are for a specific stock?

How to Access Values in the Order Object

Hi,

This is regarding the order object that is returned upon submitting an order.

I am using python to submit orders and track them but can't seem to access the order values. The order object looks like a dictionary but its type is alpaca_trade_api.entity.Order.

I looked for any related info on the website but couldn't find it.

Can anyone please point me to an example or reply with a code snippet to show how do you normally access an order's values.

Thanks

APIError: access key verification failed

Hello,

I am new to using APIs and I am trying to connect to the API.

I am doing the following steps on Windows 7.

  1. pip3 install alpaca-trade-api

I install this to the folder with my anaconda packages. I am on Python 3.6.3

  1. I am running the anaconda prompt to run the Curl function. I remove the '' because I am on windows.

curl -X GET -H "APCA-API-KEY-ID: NOTTHECODET70" -H "APCA-API-SECRET-KEY: I6/NOTTHECODECKNOTTHECODE" https://api.alpaca.markets/v1/account

I get this from the following link :
https://docs.alpaca.markets/web-api/

  1. I go back into Python I run the following code.

import alpaca_trade_api as tradeapi
api = tradeapi.REST('NOTTHECODE', 'NOTTHECODENOTTHECODENOTTHECODE')
api.get_account()

I am given the following response.

APIError: access key verification failed : access key not found (Code = 40110000) (Code = 40110000)

I am not sure what I have to do. I appreciate the help.

Thank you,

Eric

Disallow redirect

One of the users reported POST /orders didn't work. Turns out, the base URL was set to http. requests package has a parameter to disallow auto redirect and in our case, it should be better to error out rather than silently fail.

Is it possible to place a next day trade order after closing of the market?

This is not an issue related to the api but about alpaca and I dont know where else I can ask this. Is it possible to place a next day trade order after market closing?

I want to place an order like this at night ( new york time ) for next day's trade.

order=api.submit_order(
                symbol='FB',
                qty='15',
                side='buy',
                type='stop_limit',
                limit_price='160',
                stop_price='157',
                time_in_force='day',
            )

Is it possible to place such an order in alpaca? Else what is the earliest I can place a trade before market opening?

  • I am only running my paper-trading script once a day and placing the orders at night for the next day

Error parsing missing Polygon data

Reported by a user on Slack:

I am trying to get historical data from:
   polygon/REST.historic_quotes(symbol, date, offset=None, limit=None)
   Returns a Quotes which is a list of Quote entities.
   date is a date string such as '2018-2-2'. The returned quotes are from this day only.
   offset is an integer in Unix Epoch millisecond as the lower bound filter, inclusive.
   limit is an integer for the number of ticks to return. Default and max is 30000.

When I call api.polygon.historic_quotes('BND', '2018-08-26',limit=10 ).df it gives me an:         “TypeError: 'NoneType' object is not iterable”

I can get data from earlier:
   api.polygon.historic_quotes('BND', '2018-09-19',limit=10 ).df
I can also get data from later in the year:
     api.polygon.historic_quotes('BND', '2018-6-29',limit=10 ).df
I can also get data from different tickers/symbols:
     api.polygon.historic_quotes('SPY', '2018-08-26',limit=10 ).df
I tried to get a calender object and pass it as the date parameter:
date = api.get_calendar(
       start='2018-08-26',
       end='2018-08-26'
   )[0].date
api.polygon.historic_quotes('BND', date ,limit=10 ).df
It just will not return the data I need!!!

While we can't fix the issue of the missing data, we should see if we can handle it more gracefully when creating the dataframe.

bar df data type issues when converting

In Entity.py,
You are converting the timestamp by multiply 1e9 and this cause the datatype to change to Float64 which is not accepted in the panda library and returns TypeError.

Can we do something like this?

if not df.empty:
                df.index = pd.to_datetime(
                    (df.index * 1e9).astype('int64'), utc=True,
                ).tz_convert(NY)

File "/Users/jiawensun/Alpaca/samplealgo/algo.py", line 59, in _get_prices
return barset.df
File "/usr/local/lib/python3.7/site-packages/alpaca_trade_api/entity.py", line 107, in df
df = bars.df.copy()
File "/usr/local/lib/python3.7/site-packages/alpaca_trade_api/entity.py", line 85, in df
df.index * 1e9, utc=True,
File "/usr/local/lib/python3.7/site-packages/pandas/core/tools/datetimes.py", line 603, in to_datetime
result = convert_listlike(arg, box, format)
File "/usr/local/lib/python3.7/site-packages/pandas/core/tools/datetimes.py", line 223, in _convert_listlike_datetimes
arg, _ = maybe_convert_dtype(arg, copy=False)
File "/usr/local/lib/python3.7/site-packages/pandas/core/arrays/datetimes.py", line 1914, in maybe_convert_dtype
data = data.astype(_NS_DTYPE)
File "/usr/local/lib/python3.7/site-packages/pandas/core/indexes/numeric.py", line 330, in astype
raise TypeError(msg)
TypeError: Cannot convert Float64Index to dtype datetime64[ns]; integer values are required for conversion

Allow omission of order type in submit_order()

Since supported order types are only the basic four ones, it is possible to determine the type from parameter set.

  • if both limit_price and stop_price are specified, then limit stop
  • if stop_price is specified but limit_price is not, then stop
  • if limit_price is specified but stop_price is not, then limit
  • otherwise, market

Missing market data

Hi, I have been a big fan of Alpaca so far and all it has to offer 😄

I am grabbing market data for specific dates. It is inconsistently missing, even for very large, reputable and consistent assets such as GOOG.

The following will return an empty dataframe: (2019-07-01 is a Monday)

bars = alpaca_client_factory().get_barset(
    symbols=['GOOG'],
    start='2019-07-01T00:00:00-00:00',
    end='2019-07-02T00:00:00-00:00',
    timeframe='15Min',
)

print(bars.df)

Results:

Empty DataFrame
Columns: [(GOOG, open), (GOOG, high), (GOOG, low), (GOOG, close), (GOOG, volume)]
Index: []

If I query for this same data in another iex data source I can see the data:
You'll need a token to run this (it's free).

https://api.tiingo.com/iex/GOOG/prices?startDate=2019-07-01&endDate=2019-07-02&resampleFreq=15min&token=<use_a_free_token_from_tiingo>

This issue has nothing wrong with the python package (sorry for placing it in the repo, I wasn't sure where else to take this). I confirmed I can successfully retrieve market data for other start and end times.

For 2019-06-03T00:00:00-00:00 -- 2019-06-04T00:00:00-00:00:

                            GOOG                                    
                            open      high      low     close volume
time                                                                   
2019-06-03 09:30:00-04:00  1065.010  1065.010  1040.50  1041.700  28399
2019-06-03 09:45:00-04:00  1041.345  1041.785  1031.02  1032.480  18473
2019-06-03 10:00:00-04:00  1031.505  1034.860  1030.30  1034.465  11078
2019-06-03 10:15:00-04:00  1034.590  1041.410  1032.46  1040.340  13750
2019-06-03 10:30:00-04:00  1040.705  1042.010  1034.91  1034.910   8126

My questions are:

  • Am I doing something wrong? Is this a user-error on my end?
  • Is this expected?
    • Is the iex data meant to show data for "all" stocks or just their daily list? (will need an account to see that, also free)
  • How stable is the market data endpoint considered to be?
  • Why is the data missing?
    • Is this expected?
    • Are there notifications for this?
  • Will the data be backfilled in the future?
    • If so, what is the timeframe for backfilling missing data?

My intentions are just to find out what's going on so I can best handle this situation. Thanks for your help!

Event loop is already running and websocket question

Hello, I am trying to run the code example that trades on slight moves in the bid/ask spread, posted here on github.

Using alpaca_trade_api StreamConn object, I get a runtime error "This event loop is already running"

I have also tried directly connecting to the alpaca api just using the websockets library but I need a wss: url and alpaca only provides the https .../stream address.

can someone help and/or point me to a good source/tutorial for establishing multiple websockets and asyncio?

I have a polygon account for streaming data and I can simply connect to that as a websocket but I want to use the alpaca stream 'trade_updates' as well.

Websocket streaming does not work with paper trading creds

For lack of a better place to post this upstream API issue, I'm posting it here. The Alpaca websocket streaming API appears to have an issue that prevents paper trading credentials from being used to stream account_updates and trade_updates. I would like to be able to use this to develop and test these features for production usage. The sample program below shows how this fails, the paper credentials successfully obtain the account information, but will fail to authorize the websocket stream.

Note that this Exception below is a result of #46 PR, otherwise you would just see the authorization failure in the channel messages, which, in the provided examples, would also not be printed. e.g.

authenticated
Entity({'action': 'authenticate', 'status': 'unauthorized'})
authorization
Entity({'action': 'listen', 'status': 'unauthorized'})
% ./testWatch.py 
Account({   'account_blocked': False,
    'buying_power': '100000',
...
    'transfers_blocked': False})
Traceback (most recent call last):
  File "./testWatch.py", line 22, in <module>
    conn.run(['account_updates', 'trade_updates', 'A.SPY'])
  File ".../alpaca/src/alpaca-trade-api-python/alpaca_trade_api/stream2.py", line 104, in run
    loop.run_until_complete(self.subscribe(initial_channels))
  File "/home/bdowling/.pyenv/versions/3.7.1/lib/python3.7/asyncio/base_events.py", line 573, in run_until_complete
    return future.result()
  File ".../alpaca/src/alpaca-trade-api-python/alpaca_trade_api/stream2.py", line 86, in subscribe
    await self._ensure_ws()
  File ".../alpaca/src/alpaca-trade-api-python/alpaca_trade_api/stream2.py", line 71, in _ensure_ws
    self._ws = await self._connect()
  File ".../alpaca/src/alpaca-trade-api-python/alpaca_trade_api/stream2.py", line 35, in _connect
    raise ValueError("Invalid Alpaca API credentials, Failed to authenticate: {}".format(msg))
ValueError: Invalid Alpaca API credentials, Failed to authenticate: {'stream': 'authorization', 'data': {'action': 'authenticate', 'status': 'unauthorized'}}

#!/usr/bin/env python

import alpaca_trade_api as tradeapi
from userauth_paper import UserAuth
from alpaca_trade_api.stream2 import StreamConn
from pprint import pprint

conn = StreamConn(UserAuth.key, UserAuth.secret)
api = tradeapi.REST(UserAuth.key, UserAuth.secret, base_url=UserAuth.url)
account = api.get_account()
pprint(account)

@conn.on(r'.*')
async def on_data(conn, channel, data):
    print(channel)
    pprint(data)

# A.SPY will work, because it only goes to Polygon
# conn.run(['A.SPY'])

# account_updates fail, being sent to websocket stream
conn.run(['account_updates', 'trade_updates', 'A.SPY'])

Possible to add attribute to Position object?

For my given algorithm I need to keep track of how many days each position has been held. So far, I haven't been able to find any built-in functionality for this. Correct me if I'm wrong please.

Is it possible to add an attribute called "Duration" to each position object and increment the time held myself?

cancel_order not working

The cancel_order call in the REST api that calls Alpaca seem to execute fine but the order is still open. I tested this outside regular trading hours. Not sure if it works during normal trading hours. Regardless, it should throw an exception if the order was not cancelled.

get_barset() still ignores start and end date

I've looked through #66 and the advice doesn't work.

bars = api.get_barset(['AAPL'], '1D', limit=100, start=pd.Timestamp('2010-01-01', tz='America/New_York').isoformat())
print(bars.df)
                               AAPL                                        
                               open      high       low     close    volume
time                                                                       
2019-03-27 00:00:00-04:00  188.7500  189.7600  186.5500  188.4700  26586290
2019-03-28 00:00:00-04:00  188.9500  189.5590  187.5300  188.7100  19309376
2019-03-29 00:00:00-04:00  189.9900  190.0800  188.5400  189.9400  18489986
2019-04-01 00:00:00-04:00  191.6400  191.6800  188.3800  191.2400  12098014
2019-04-02 00:00:00-04:00  191.0900  194.4600  191.0500  194.0400  19797454
2019-04-03 00:00:00-04:00  193.2500  196.5000  193.1500  195.3500  19793141
2019-04-04 00:00:00-04:00  194.7900  196.3700  193.1400  195.7200  17091108
2019-04-05 00:00:00-04:00  196.4500  197.1000  195.9300  196.9700  15842943
2019-04-08 00:00:00-04:00  196.4200  200.2300  196.3400  200.0800  23231403
2019-04-09 00:00:00-04:00  200.3200  202.8500  199.2300  199.5000  32840959
2019-04-10 00:00:00-04:00  198.6800  200.7400  198.1800  200.6600  19861942
2019-04-11 00:00:00-04:00  200.8500  201.0000  198.4431  198.9500  17931789
2019-04-12 00:00:00-04:00  199.2000  200.1400  196.2100  198.8800  24667735
2019-04-15 00:00:00-04:00  198.5800  199.8500  198.0100  199.2300  14551176
2019-04-16 00:00:00-04:00  199.4600  201.3700  198.5600  199.2500  24002891
2019-04-17 00:00:00-04:00  199.5400  203.3800  198.6100  203.1200  27366117
2019-04-18 00:00:00-04:00  203.1200  204.1500  202.5200  203.8600  21928367
2019-04-22 00:00:00-04:00  202.8300  204.9400  202.3400  204.6400  13720923
2019-04-23 00:00:00-04:00  204.4300  207.7500  203.9000  207.5100  19401417
2019-04-24 00:00:00-04:00  207.3600  208.4800  207.0500  207.1800  14914939
2019-04-25 00:00:00-04:00  206.8300  207.7600  205.1200  205.2400  15908807
2019-04-26 00:00:00-04:00  204.9000  205.0000  202.1200  204.2900  16315669
2019-04-29 00:00:00-04:00  204.4000  205.9700  203.8600  204.6100  19641066
2019-04-30 00:00:00-04:00  203.0600  203.4000  199.1100  200.5700  35362106
2019-05-01 00:00:00-04:00  209.8800  215.3100  209.2300  210.5200  57751414
2019-05-02 00:00:00-04:00  209.8400  212.6500  208.1300  209.1700  29014844
2019-05-03 00:00:00-04:00  210.7400  211.8400  210.2300  211.7800  17987793
2019-05-06 00:00:00-04:00  204.2900  208.8400  203.5000  208.6000  28949691
2019-05-07 00:00:00-04:00  205.8800  207.4175  200.8250  202.8600  34328425
2019-05-08 00:00:00-04:00  201.9000  205.3400  201.7500  202.9000  22729670
...                             ...       ...       ...       ...       ...

Add dry-run mode

submit_order() and cancel_order() are two main write operations and as a user I sometimes tempted to mock those to test the code logic without actually placing orders. Would be nice for this library to have this capability.

No data with Polygon

import alpaca_trade_api as tradeapi
api = tradeapi.REST(API_KEY, API_SECRET_KEY, API_URL)
data = api.polygon.historic_agg('minute', 'CYBR', limit=1000).df

Of course, I set the constants before. But it doesn't work. I get the following error:

requests.exceptions.HTTPError: 401 Client Error: Unauthorized for url: https://api.polygon.io/v1/historic/agg/minute/CYBR?limit=1000&apiKey=XXXXXXXXX

Is there a possibility to solve that?
Maybe it's because I have no data subscription from Polygon? But how to get the data from IEX over Alpaca?
Thank you very much!

Add df() method to Bars

As a python algo writer, I want a df() method that returns pandas.DataFrame from Bars entity. It should not be hard since pandas are already part of the dependency

Make thread safer

Session object from requests is not meant to be thread safe, but the SDK client code can use REST objects in multithread. It happens to be ok for now since it is not mutating anything yet, but things will happen. We should use ThreadLocal to separate session objects.

Can't seem to create a stream to get trade updates. (RuntimeError: This event loop is already running)

So I am trying to get a stream of trade updates from the alpaca api, I run the following command.

import alpaca_trade_api as tradeapi
import time
import datetime

api = tradeapi.REST('xxx','https://paper-api.alpaca.markets')
conn = tradeapi.StreamConn('xxx','xxx','https://paper-api.alpaca.markets')
account = api.get_account()

def run():
    @conn.on(r'trade_updates')
    async def on_msg(conn, channel, data):
        datasymbol = data.order['symbol']
        event = data.event
        print('Order executed for',datasymbol, data.order['side'], event, data.order['filled_qty'])
        
conn.run(['trade_updates'])

This is the error I get.

---------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
D:\Users\user\Anaconda3\envs\ml\lib\site-packages\alpaca_trade_api\stream2.py in run(self, initial_channels)
    158         try:
--> 159             loop.run_until_complete(self.subscribe(initial_channels))
    160             loop.run_forever()

D:\Users\user\Anaconda3\envs\ml\lib\asyncio\base_events.py in run_until_complete(self, future)
    565         try:
--> 566             self.run_forever()
    567         except:

D:\Users\user\Anaconda3\envs\ml\lib\asyncio\base_events.py in run_forever(self)
    520         if self.is_running():
--> 521             raise RuntimeError('This event loop is already running')
    522         if events._get_running_loop() is not None:

RuntimeError: This event loop is already running

During handling of the above exception, another exception occurred:

RuntimeError                              Traceback (most recent call last)
<ipython-input-2-8a009c05ab30> in <module>
      6         print('Order executed for',datasymbol, data.order['side'], event, data.order['filled_qty'])
      7 
----> 8 conn.run(['trade_updates'])

D:\Users\user\Anaconda3\envs\ml\lib\site-packages\alpaca_trade_api\stream2.py in run(self, initial_channels)
    162             logging.info("Exiting on Interrupt")
    163         finally:
--> 164             loop.run_until_complete(self.close())
    165             loop.close()
    166 

D:\Users\user\Anaconda3\envs\ml\lib\asyncio\base_events.py in run_until_complete(self, future)
    564         future.add_done_callback(_run_until_complete_cb)
    565         try:
--> 566             self.run_forever()
    567         except:
    568             if new_task and future.done() and not future.cancelled():

D:\Users\user\Anaconda3\envs\ml\lib\asyncio\base_events.py in run_forever(self)
    519         self._check_closed()
    520         if self.is_running():
--> 521             raise RuntimeError('This event loop is already running')
    522         if events._get_running_loop() is not None:
    523             raise RuntimeError(

RuntimeError: This event loop is already running

Is there something wrong with my code?

How do we submit an order?

I am kind of new to alpaca and algo trading itself. How do we submit an order in alpaca?

An example; its placing an after market hour trade by shorting one AAPL stock for an intraday trade.

api = tradeapi.REST(
    key_id='key',
    secret_key='secret',
    base_url='https://paper-api.alpaca.markets'
)
account = api.get_account()
print(account.status)

order=api.submit_order(
                symbol='AAPL',
                qty='1',
                side='sell',
                type='stop_limit',
                limit_price='176',
                stop_price='177',
                time_in_force='day',
            )

But I am getting this error

  raise APIError(error, http_error)
alpaca_trade_api.rest.APIError: insufficient qty (0 < 1)

Polygon API outage causes API requests to hang?

This is my first time trying the polygon API, so I may be doing something wrong, but I think perhaps the API is under maintenance this evening, as https://api.polygon.io is returning:

Error
Application not found or under maintenance.

While in this state, attempting to use api.polygon appears to just hang, haven't dug into why:

import alpaca_trade_api as tradeapi
api = tradeapi.REST()
aapl = api.polygon.historic_agg('day', 'AAPL', limit=10).df

print(aapl)

(never returns)

positions and orders by lot number

How to manage positions and orders by lot number? Have not found it by web gui and APIs

Guess not all algo go by all-or-none type of transactions.

Thanks

How to parse api.submit_order() response

The response after submitting api.submit_order() returns a data type 'entity.Order'.

I can't figure out how to parse this object to extract information, such as, 'client_order_id'.

api.list_orders() has a similar issue in that it puts these objects into a list.

Is there some other method I should be using to obtain order information? Or perhaps you could provide a snippet of code for helping to parse the 'entity.Order' types.

Thanks

Still do not understand

how to set paper trading, python have small problem in accessing external env variables, any way to set the url in the code ?

401 Client Error: Unauthorized for url: https://api.polygon.io

I'm going through the tutorial, and I'm getting an exception:

DEBUG:urllib3.connectionpool:https://api.polygon.io:443 "GET /v1/historic/agg/day/ATVI?from=2015-8-25&to=2018-12-6&apiKey=abcd HTTP/1.1" 401 None
WARNING:__main__:ATVI generated an exception: 401 Client Error: Unauthorized for url: https://api.polygon.io/v1/historic/agg/day/ATVI?from=2015-8-25&to=2018-12-6&apiKey=abcd

Previously I was getting an exception:
alpaca_trade_api.rest.APIError: access key verification failed : request is unauthorized (generate APCA-API-KEY-ID and APCA-API-ACCESS-SECRET-KEY from dashboard and include in HTTP header) (Code = 40110000) (Code = 40110000)
but I regenerated the key, and now the above exception is being returned.

I creating the REST api client like this:
api = tradeapi.REST(key, skey, base_url='https://paper-api.alpaca.markets')

Websocket exception

The websocket sometimes gives an exception but it is not clear if it reconnects...

Task exception was never retrieved
future: <Task finished coro=<StreamConn._consume_msg() done, defined at /opt/conda/lib/python3.6/site-packages/alpaca_trade_api/stream2.py:46> exception=ConnectionClosed('WebSocket connection is closed: code = 1006 (connection closed abnormally [internal]), no reason',)>
Traceback (most recent call last):
File "/opt/conda/lib/python3.6/site-packages/websockets/protocol.py", line 674, in transfer_data
message = yield from self.read_message()
File "/opt/conda/lib/python3.6/site-packages/websockets/protocol.py", line 742, in read_message
frame = yield from self.read_data_frame(max_size=self.max_size)
File "/opt/conda/lib/python3.6/site-packages/websockets/protocol.py", line 815, in read_data_frame
frame = yield from self.read_frame(max_size)
File "/opt/conda/lib/python3.6/site-packages/websockets/protocol.py", line 884, in read_frame
extensions=self.extensions,
File "/opt/conda/lib/python3.6/site-packages/websockets/framing.py", line 99, in read
data = yield from reader(2)
File "/opt/conda/lib/python3.6/asyncio/streams.py", line 674, in readexactly
yield from self._wait_for_data('readexactly')
File "/opt/conda/lib/python3.6/asyncio/streams.py", line 464, in _wait_for_data
yield from self._waiter
concurrent.futures._base.CancelledError

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
File "/opt/conda/lib/python3.6/site-packages/alpaca_trade_api/stream2.py", line 50, in _consume_msg
r = await ws.recv()
File "/opt/conda/lib/python3.6/site-packages/websockets/protocol.py", line 434, in recv
yield from self.ensure_open()
File "/opt/conda/lib/python3.6/site-packages/websockets/protocol.py", line 658, in ensure_open
) from self.transfer_data_exc
websockets.exceptions.ConnectionClosed: WebSocket connection is closed: code = 1006 (connection closed abnormally [internal]), no reason

Access key verification failed

I'm new to the API and am starting to build my trading algorithms. I'm having troubles getting access to any of the asset data. I keep getting the error that my get request has failed because my access key code was not found. I've looked through the issues and found a similar one that was resolved by requesting a new key code. This didn't help either.

The relevant sections of my code (at least I think) are as follows:

api = tradeapi.REST('key', 'secret_key', 'https://api.alpaca.markets')
account = api.get_account()

response = requests.api.get(
"https://api.alpaca.markets/v2/assets/AAPL?apiKey=key",

I've tried the url with and without the ?apiKey= included at the end and also with and without the ticker symbol with the same result. I've also tried other requests with the same result.

Thanks for any help!

get_barset doesn't respect start and end date

The following code returns the data not in the provided time interval. It will return data for 2018 and 2019 while I set the end date to be 20150615.

api = tradeapi.REST(
    key_id='xxx',
    secret_key='xxx',
    base_url='https://paper-api.alpaca.markets'
)

api.get_barset(['AAPL', 'IBM'], timeframe='1D', end=pd.datetime(year=2015, month=6, day=15)).df.index.max()

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.