Git Product home page Git Product logo

alpaca-trade-api-python's Introduction

PyPI version CircleCI Updates Python 3

Deprecation Notice

A new python SDK, Alpaca-py, is available. This SDK will be the primary python SDK starting in 2023. We recommend moving over your code to use the new SDK. Keep in mind, we will be maintaining this repo as usual until the end of 2022.

alpaca-trade-api-python

alpaca-trade-api-python is a python library for the Alpaca Commission Free Trading API. It allows rapid trading algo development easily, with support for both REST and streaming data interfaces. For details of each API behavior, please see the online API document.

Note that this package supports only python version 3.7 and above.

Install

We support python>=3.7. If you want to work with python 3.6, please note that these package dropped support for python <3.7 for the following versions:

pandas >= 1.2.0
numpy >= 1.20.0
scipy >= 1.6.0

The solution - manually install these packages before installing alpaca-trade-api. e.g:

pip install pandas==1.1.5 numpy==1.19.4 scipy==1.5.4

Also note that we do not limit the version of the websockets library, but we advise using

websockets>=9.0

Installing using pip

$ pip3 install alpaca-trade-api

API Keys

To use this package you first need to obtain an API key. Go here to signup

Services

These services are provided by Alpaca:

The free services are limited, please check the docs to see the differences between paid/free services.

Alpaca Environment Variables

The Alpaca SDK will check the environment for a number of variables that can be used rather than hard-coding these into your scripts.
Alternatively you could pass the credentials directly to the SDK instances.

Environment default Description
APCA_API_KEY_ID=<key_id> Your API Key
APCA_API_SECRET_KEY=<secret_key> Your API Secret Key
APCA_API_BASE_URL=url https://api.alpaca.markets (for live) Specify the URL for API calls, Default is live, you must specify
https://paper-api.alpaca.markets to switch to paper endpoint!
APCA_API_DATA_URL=url https://data.alpaca.markets Endpoint for data API
APCA_RETRY_MAX=3 3 The number of subsequent API calls to retry on timeouts
APCA_RETRY_WAIT=3 3 seconds to wait between each retry attempt
APCA_RETRY_CODES=429,504 429,504 comma-separated HTTP status code for which retry is attempted
DATA_PROXY_WS When using the alpaca-proxy-agent you need to set this environment variable as described here

Working with Data

Historic Data

You could get one of these historic data types:

  • Bars
  • Quotes
  • Trades

You now have 2 pythonic ways to retrieve historical data.
One using the traditional rest module and the other is to use the experimental asyncio module added lately.
Let's have a look at both:

The first thing to understand is the new data polling mechanism. You could query up to 10000 items, and the API is using a pagination mechanism to provide you with the data.
You now have 2 options:

  • Working with data as it is received with a generator. (meaning it's faster but you need to process each item alone)
  • Wait for the entire data to be received, and then work with it as a list or dataframe. We provide you with both options to choose from.

Bars

option 1: wait for the data

from alpaca_trade_api.rest import REST, TimeFrame
api = REST()

api.get_bars("AAPL", TimeFrame.Hour, "2021-06-08", "2021-06-08", adjustment='raw').df

                              open      high       low     close    volume
timestamp
2021-06-08 08:00:00+00:00  126.100  126.3000  125.9600  126.3000     42107
2021-06-08 09:00:00+00:00  126.270  126.4000  126.2200  126.3800     21095
2021-06-08 10:00:00+00:00  126.380  126.6000  125.8400  126.4900     54743
2021-06-08 11:00:00+00:00  126.440  126.8700  126.4000  126.8500    206460
2021-06-08 12:00:00+00:00  126.821  126.9500  126.7000  126.9300    385164
2021-06-08 13:00:00+00:00  126.920  128.4600  126.4485  127.0250  18407398
2021-06-08 14:00:00+00:00  127.020  127.6400  126.7800  127.1350  13446961
2021-06-08 15:00:00+00:00  127.140  127.4700  126.2101  126.6100  10444099
2021-06-08 16:00:00+00:00  126.610  126.8400  126.5300  126.8250   5289556
2021-06-08 17:00:00+00:00  126.820  126.9300  126.4300  126.7072   4813459
2021-06-08 18:00:00+00:00  126.709  127.3183  126.6700  127.2850   5338455
2021-06-08 19:00:00+00:00  127.290  127.4200  126.6800  126.7400   9817083
2021-06-08 20:00:00+00:00  126.740  126.8500  126.5400  126.6600   5525520
2021-06-08 21:00:00+00:00  126.690  126.8500  126.6500  126.6600    156333
2021-06-08 22:00:00+00:00  126.690  126.7400  126.6600  126.7300     49252
2021-06-08 23:00:00+00:00  126.725  126.7600  126.6400  126.6400     41430

option 2: iterate over bars

def process_bar(bar):
    # process bar
    print(bar)

bar_iter = api.get_bars_iter("AAPL", TimeFrame.Hour, "2021-06-08", "2021-06-08", adjustment='raw')
for bar in bar_iter:
    process_bar(bar)

Alternatively, you can decide on your custom timeframes by using the TimeFrame constructor:

from alpaca_trade_api.rest import REST, TimeFrame, TimeFrameUnit

api = REST()
api.get_bars("AAPL", TimeFrame(45, TimeFrameUnit.Minute), "2021-06-08", "2021-06-08", adjustment='raw').df

                               open      high       low     close    volume  trade_count        vwap
timestamp
2021-06-08 07:30:00+00:00  126.1000  126.1600  125.9600  126.0600     20951          304  126.049447
2021-06-08 08:15:00+00:00  126.0500  126.3000  126.0500  126.3000     21181          349  126.231904
2021-06-08 09:00:00+00:00  126.2700  126.3200  126.2200  126.2800     15955          308  126.284120
2021-06-08 09:45:00+00:00  126.2900  126.4000  125.9000  125.9000     30179          582  126.196877
2021-06-08 10:30:00+00:00  125.9000  126.7500  125.8400  126.7500    105380         1376  126.530863
2021-06-08 11:15:00+00:00  126.7300  126.8500  126.5600  126.8300    129721         1760  126.738041
2021-06-08 12:00:00+00:00  126.4101  126.9500  126.3999  126.8300    418107         3615  126.771889
2021-06-08 12:45:00+00:00  126.8500  126.9400  126.6000  126.6200    428614         5526  126.802825
2021-06-08 13:30:00+00:00  126.6200  128.4600  126.4485  127.4150  23065023       171263  127.425797
2021-06-08 14:15:00+00:00  127.4177  127.6400  126.9300  127.1350   8535068        65753  127.342337
2021-06-08 15:00:00+00:00  127.1400  127.4700  126.2101  126.7101   8447696        64616  126.789316
2021-06-08 15:45:00+00:00  126.7200  126.8200  126.5300  126.6788   5084147        38366  126.712110
2021-06-08 16:30:00+00:00  126.6799  126.8400  126.5950  126.5950   3205870        26614  126.718837
2021-06-08 17:15:00+00:00  126.5950  126.9300  126.4300  126.7010   3908283        31922  126.665727
2021-06-08 18:00:00+00:00  126.7072  127.0900  126.6700  127.0600   3923056        29114  126.939887
2021-06-08 18:45:00+00:00  127.0500  127.4200  127.0000  127.0050   5051682        38235  127.214157
2021-06-08 19:30:00+00:00  127.0150  127.0782  126.6800  126.7800  11665598        47146  126.813182
2021-06-08 20:15:00+00:00  126.7700  126.7900  126.5400  126.6600     83725         1973  126.679259
2021-06-08 21:00:00+00:00  126.6900  126.8500  126.6700  126.7200    145153          769  126.746457
2021-06-08 21:45:00+00:00  126.7000  126.7400  126.6500  126.7100     38455          406  126.699544
2021-06-08 22:30:00+00:00  126.7100  126.7600  126.6700  126.7100     30822          222  126.713892
2021-06-08 23:15:00+00:00  126.7200  126.7600  126.6400  126.6400     32585          340  126.704131

Quotes

option 1: wait for the data

from alpaca_trade_api.rest import REST
api = REST()

api.get_quotes("AAPL", "2021-06-08", "2021-06-08", limit=10).df

                                    ask_exchange  ask_price  ask_size bid_exchange  bid_price  bid_size conditions
timestamp
2021-06-08 08:00:00.070928640+00:00            P     143.00         1                    0.00         0        [Y]
2021-06-08 08:00:00.070929408+00:00            P     143.00         1            P     102.51         1        [R]
2021-06-08 08:00:00.070976768+00:00            P     143.00         1            P     116.50         1        [R]
2021-06-08 08:00:00.070978816+00:00            P     143.00         1            P     118.18         1        [R]
2021-06-08 08:00:00.071020288+00:00            P     143.00         1            P     120.00         1        [R]
2021-06-08 08:00:00.071020544+00:00            P     134.18         1            P     120.00         1        [R]
2021-06-08 08:00:00.071021312+00:00            P     134.18         1            P     123.36         1        [R]
2021-06-08 08:00:00.071209984+00:00            P     131.11         1            P     123.36         1        [R]
2021-06-08 08:00:00.071248640+00:00            P     130.13         1            P     123.36         1        [R]
2021-06-08 08:00:00.071286016+00:00            P     129.80         1            P     123.36         1        [R]

option 2: iterate over quotes

def process_quote(quote):
    # process quote
    print(quote)

quote_iter = api.get_quotes_iter("AAPL", "2021-06-08", "2021-06-08", limit=10)
for quote in quote_iter:
    process_quote(quote)

Trades

option 1: wait for the data

from alpaca_trade_api.rest import REST
api = REST()

api.get_trades("AAPL", "2021-06-08", "2021-06-08", limit=10).df

                                    exchange   price  size conditions  id tape
timestamp
2021-06-08 08:00:00.069956608+00:00        P  126.10   179     [@, T]   1    C
2021-06-08 08:00:00.207859+00:00           K  125.97     1  [@, T, I]   1    C
2021-06-08 08:00:00.207859+00:00           K  125.97    12  [@, T, I]   2    C
2021-06-08 08:00:00.207859+00:00           K  125.97     4  [@, T, I]   3    C
2021-06-08 08:00:00.207859+00:00           K  125.97     4  [@, T, I]   4    C
2021-06-08 08:00:00.207859+00:00           K  125.97     8  [@, T, I]   5    C
2021-06-08 08:00:00.207859+00:00           K  125.97     1  [@, T, I]   6    C
2021-06-08 08:00:00.207859+00:00           K  126.00    30  [@, T, I]   7    C
2021-06-08 08:00:00.207859+00:00           K  126.00    10  [@, T, I]   8    C
2021-06-08 08:00:00.207859+00:00           K  125.97    70  [@, T, I]   9    C

option 2: iterate over trades

def process_trade(trade):
    # process trade
    print(trade)

trades_iter = api.get_trades_iter("AAPL", "2021-06-08", "2021-06-08", limit=10)
for trade in trades_iter:
    process_trade(trade)

Asyncio Rest module

The rest_async.py module now provides an asyncion approach to retrieving the historic data.
This module is, and thus may have expansions in the near future to support more endpoints.
It provides a much faster way to retrieve the historic data for multiple symbols.
Under the hood we use the aiohttp library.
We provide a code sample to get you started with this new approach and it is located here.
Follow along with the example code to learn more, and utilize it for your own needs.

Live Stream Market Data

There are 2 streams available as described here.

The free plan is using the iex stream, while the paid subscription is using the sip stream.

You can subscribe to bars, trades, quotes, and trade updates for your account as well. Under the example folder you can find different code samples to achieve different goals.

Here in this basic example, We use the Stream class under alpaca_trade_api.stream for API V2 to subscribe to trade updates for AAPL and quote updates for IBM.

from alpaca_trade_api.common import URL
from alpaca_trade_api.stream import Stream

async def trade_callback(t):
    print('trade', t)


async def quote_callback(q):
    print('quote', q)


# Initiate Class Instance
stream = Stream(<ALPACA_API_KEY>,
                <ALPACA_SECRET_KEY>,
                base_url=URL('https://paper-api.alpaca.markets'),
                data_feed='iex')  # <- replace to 'sip' if you have PRO subscription

# subscribing to event
stream.subscribe_trades(trade_callback, 'AAPL')
stream.subscribe_quotes(quote_callback, 'IBM')

stream.run()

Websockets Config For Live Data

Under the hood our SDK uses the Websockets library to handle our websocket connections. Since different environments can have wildly differing requirements for resources we allow you to pass your own config options to the websockets lib via the websocket_params kwarg found on the Stream class.

ie:

# Initiate Class Instance
stream = Stream(<ALPACA_API_KEY>,
                <ALPACA_SECRET_KEY>,
                base_url=URL('https://paper-api.alpaca.markets'),
                data_feed='iex', # <- replace to 'sip' if you have PRO subscription
                websocket_params =  {'ping_interval': 5}, #here we set ping_interval to 5 seconds 
                )

If you're curious this link to their docs shows the values that websockets uses by default as well as any parameters they allow changing. Additionally, if you don't specify any we set the following defaults on top of the ones the websockets library uses:

{
    "ping_interval": 10,
    "ping_timeout": 180,
    "max_queue": 1024,
}

Account & Portfolio Management

The HTTP API document is located at https://docs.alpaca.markets/

API Version

API Version now defaults to 'v2', however, if you still have a 'v1' account, you may need to specify api_version='v1' to properly use the API until you migrate.

Authentication

The Alpaca API requires API key ID and secret key, which you can obtain from the web console after you sign in. You can pass key_id and secret_key to the initializers of REST or Stream as arguments, or set up environment variables as outlined below.

REST

The REST class is the entry point for the API request. The instance of this class provides all REST API calls such as account, orders, positions, and bars.

Each returned object is wrapped by a subclass of the Entity class (or a list of it). This helper class provides property access (the "dot notation") to the json object, backed by the original object stored in the _raw field. It also converts certain types to the appropriate python object.

import alpaca_trade_api as tradeapi

api = tradeapi.REST()
account = api.get_account()
account.status
=> 'ACTIVE'

The Entity class also converts the timestamp string field to a pandas.Timestamp object. Its _raw property returns the original raw primitive data unmarshaled from the response JSON text.

Please note that the API is throttled, currently 200 requests per minute, per account. If your client exceeds this number, a 429 Too many requests status will be returned and this library will retry according to the retry environment variables as configured.

If the retries are exceeded, or other API error is returned, alpaca_trade_api.rest.APIError is raised. You can access the following information through this object.

  • the API error code: .code property
  • the API error message: str(error)
  • the original request object: .request property
  • the original response object: .response property
  • the HTTP status code: .status_code property

API REST Methods

Rest Method End Point Result
get_account() GET /account and Account entity.
get_order_by_client_order_id(client_order_id) GET /orders with client_order_id Order entity.
list_orders(status=None, limit=None, after=None, until=None, direction=None, params=None,nested=None, symbols=None, side=None) GET /orders list of Order entities. after and until need to be string format, which you can obtain by pd.Timestamp().isoformat()
submit_order(symbol, qty=None, side="buy", type="market", time_in_force="day", limit_price=None, stop_price=None, client_order_id=None, order_class=None, take_profit=None, stop_loss=None, trail_price=None, trail_percent=None, notional=None) POST /orders Order entity.
get_order(order_id) GET /orders/{order_id} Order entity.
cancel_order(order_id) DELETE /orders/{order_id}
cancel_all_orders() DELETE /orders
list_positions() GET /positions list of Position entities
get_position(symbol) GET /positions/{symbol} Position entity.
list_assets(status=None, asset_class=None) GET /assets list of Asset entities
get_asset(symbol) GET /assets/{symbol} Asset entity
get_clock() GET /clock Clock entity
get_calendar(start=None, end=None) GET /calendar Calendar entity
get_portfolio_history(date_start=None, date_end=None, period=None, timeframe=None, extended_hours=None) GET /account/portfolio/history PortfolioHistory entity. PortfolioHistory.df can be used to get the results as a dataframe

Rest Examples

Please see the examples/ folder for some example scripts that make use of this API

Using submit_order()

Below is an example of submitting a bracket order.

api.submit_order(
    symbol='SPY',
    side='buy',
    type='market',
    qty='100',
    time_in_force='day',
    order_class='bracket',
    take_profit=dict(
        limit_price='305.0',
    ),
    stop_loss=dict(
        stop_price='295.5',
        limit_price='295.5',
    )
)

For simple orders with type='market' and time_in_force='day', you can pass a fractional amount (qty) or a notional amount (but not both). For instance, if the current market price for SPY is $300, the following calls are equivalent:

api.submit_order(
    symbol='SPY',
    qty=1.5,  # fractional shares
    side='buy',
    type='market',
    time_in_force='day',
)
api.submit_order(
    symbol='SPY',
    notional=450,  # notional value of 1.5 shares of SPY at $300
    side='buy',
    type='market',
    time_in_force='day',
)

Logging

You should define a logger in your app in order to make sure you get all the messages from the different components.
It will help you debug, and make sure you don't miss issues when they occur.
The simplest way to define a logger, if you have no experience with the python logger - will be something like this:

import logging
logging.basicConfig(format='%(asctime)s %(message)s', level=logging.INFO)

Websocket best practices

Under the examples folder you could find several examples to do the following:

  • Different subscriptions(channels) usage with the alpaca streams
  • pause / resume connection
  • change subscriptions/channels of existing connection
  • ws disconnections handler (make sure we reconnect when the internal mechanism fails)

Running Multiple Strategies

The base version of this library only allows running a single algorithm due to Alpaca's limit of one websocket connection per account. For those looking to run multiple strategies, there is alpaca-proxy-agent project.

The steps to execute this are:

  • Run the Alpaca Proxy Agent as described in the project's README
  • Define a new environment variable: DATA_PROXY_WS set to the address of the proxy agent. (e.g: DATA_PROXY_WS=ws://127.0.0.1:8765)
  • If you are using the Alpaca data stream, make sure to initiate the Stream object with the container's url: data_url='http://127.0.0.1:8765'
  • Execute your algorithm. It will connect to the Alpaca servers through the proxy agent, allowing you to execute multiple strategies

Raw Data vs Entity Data

By default the data returned from the api or streamed via Stream is wrapped with an Entity object for ease of use. Some users may prefer working with vanilla python objects (lists, dicts, ...). You have 2 options to get the raw data:

  • Each Entity object as a _raw property that extract the raw data from the object.
  • If you only want to work with raw data, and avoid casting to Entity (which may take more time, casting back and forth) you could pass raw_data argument to Rest() object or the Stream() object.

Support and Contribution

For technical issues particular to this module, please report the issue on this GitHub repository. Any API issues can be reported through Alpaca's customer support.

New features, as well as bug fixes, by sending a pull request is always welcomed.

alpaca-trade-api-python's People

Contributors

abpwrs avatar andrewkim316 avatar bbeale avatar bdowling avatar camelpac avatar ccnlui avatar devination avatar drew887 avatar ducille avatar ekovacs avatar erikreed avatar fumoboy007 avatar gnvk avatar h55nick avatar hackengineer avatar haxdds avatar hiohiohio avatar jrenk avatar julio-santiesteban avatar jwesleye avatar k-kristof avatar kalmant avatar patrickalphac avatar raymond-devries avatar sebrollen avatar shlomiku avatar t-shah avatar ttt733 avatar umitanuki avatar yoshiso avatar

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

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

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?

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

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.

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

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?

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

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 ?

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

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

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.

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

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'])

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)

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.

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/

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!

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!

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.

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.

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()

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

[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?

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

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)

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.

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!

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

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

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.

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.

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.

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

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.

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')

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

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.