alpaca-trade-api-python is a python library for the Alpaca Commission Free Trading API.

Overview

PyPI version CircleCI Updates Python 3

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.6 and above, due to the async/await and websockets module dependency.

Install

We support python>=3.6. 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 package before installing alpaca-trade-api. e.g:

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

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= Your API Key
APCA_API_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 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
api = REST()

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

                               open    high      low     close    volume
timestamp                                                               
2021-02-08 09:00:00+00:00  136.6800  137.15  136.450  136.9600     38707
2021-02-08 10:00:00+00:00  136.9600  137.08  136.800  136.8300     22334
2021-02-08 11:00:00+00:00  136.8300  136.97  136.710  136.9100     19546
2021-02-08 12:00:00+00:00  136.9000  136.97  136.050  136.2200    483167
2021-02-08 13:00:00+00:00  136.2200  136.25  136.010  136.1700    307755
2021-02-08 14:00:00+00:00  136.1525  136.35  134.920  135.6900  12159693
2021-02-08 15:00:00+00:00  135.6800  136.68  135.595  136.6100   8076122
2021-02-08 16:00:00+00:00  136.6800  136.91  135.040  136.2350   8484923
2021-02-08 17:00:00+00:00  136.2400  136.54  135.030  135.9745   4610247
2021-02-08 18:00:00+00:00  135.9799  136.30  135.800  135.9330   3375300

option 2: iterate over bars

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

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

Quotes

option 1: wait for the data

from alpaca_trade_api.rest import REST
api = REST()

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

                                    ask_exchange  ask_price  ask_size bid_exchange  bid_price  bid_size conditions
timestamp                                                                                                         
2021-02-08 09:02:07.697204555+00:00            Q     136.80         1            P     136.52         1        [R]
2021-02-08 09:02:07.706401536+00:00            Q     136.80         1            P     136.56         2        [R]
2021-02-08 09:02:07.837365238+00:00            P     136.81         1            P     136.56         2        [R]
2021-02-08 09:02:07.838885705+00:00            Q     136.79         1            P     136.56         2        [R]
2021-02-08 09:02:30.946732544+00:00            P     136.64         1            P     136.50         1        [R]
2021-02-08 09:02:32.558048512+00:00            P     136.64         1            P     136.37         1        [R]
2021-02-08 09:02:32.794415360+00:00            Q     136.69         1            P     136.37         1        [R]
2021-02-08 09:02:32.795173632+00:00            P     136.62         1            P     136.37         1        [R]
2021-02-08 09:02:33.969686528+00:00            Q     136.69         1            P     136.37         1        [R]
2021-02-08 09:02:34.069692672+00:00            P     136.55         1            P     136.37         1        [R]

option 2: iterate over quotes

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

quote_iter = api.get_quotes_iter("AAPL", "2021-02-08", "2021-02-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-02-08", "2021-02-08", limit=10).df

                                    exchange   price  size conditions  id tape
timestamp                                                                     
2021-02-08 09:00:11.764828160+00:00        P  136.68     1  [@, T, I]  46    C
2021-02-08 09:00:13.885322240+00:00        P  136.75    35  [@, T, I]  49    C
2021-02-08 09:00:13.885322240+00:00        P  136.75    10  [@, T, I]  48    C
2021-02-08 09:00:13.885322240+00:00        P  136.68    28  [@, T, I]  47    C
2021-02-08 09:00:17.024569856+00:00        P  136.61    16  [@, T, I]  50    C
2021-02-08 09:00:17.810107904+00:00        P  136.66     1  [@, T, I]  51    C
2021-02-08 09:00:19.932405248+00:00        P  136.68    25  [@, T, I]  55    C
2021-02-08 09:00:19.932405248+00:00        P  136.75    18  [@, T, I]  56    C
2021-02-08 09:00:19.932405248+00:00        P  136.68    11  [@, T, I]  54    C
2021-02-08 09:00:19.932405248+00:00        P  136.67    10  [@, T, I]  53    C

option 2: iterate over trades

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

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

Live Stream 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 could subscribe to bars, trades or quotes and accoutn updates as well.
Under the example folder you could find different code samples to achieve different goals. Let's see the basic example
We present a new Streamer class under alpaca_trade_api.stream for API V2.

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

Acount & 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 StreamConn 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 objecgt: .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, nested=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_barset(symbols, timeframe, limit, start=None, end=None, after=None, until=None) GET /bars/{timeframe} Barset with limit Bar objects for each of the the requested symbols. timeframe can be one of minute, 1Min, 5Min, 15Min, day or 1D. minute is an alias of 1Min. Similarly, day is an alias of 1D. start, end, after, and until need to be string format, which you can obtain with pd.Timestamp().isoformat() after cannot be used with start and until cannot be used with end.
get_aggs(symbol, timespan, multiplier, _from, to) GET /aggs/ticker/{symbol}/range/{multiplier}/{timespan}/{from}/{to} Aggs entity. multiplier is the size of the timespan multiplier. timespan is the size of the time window, can be one of minute, hour, day, week, month, quarter or year. _from and to must be in YYYY-MM-DD format, e.g. 2020-01-15.
get_last_trade(symbol) GET /last/stocks/{symbol} Trade entity
get_last_quote(symbol) GET /last_quote/stocks/{symbol} Quote 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 instace, 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',
)
Using get_barset() (Deprecated. use get_bars() instead)
import pandas as pd
NY = 'America/New_York'
start=pd.Timestamp('2020-08-01', tz=NY).isoformat()
end=pd.Timestamp('2020-08-30', tz=NY).isoformat()
print(api.get_barset(['AAPL', 'GOOG'], 'day', start=start, end=end).df)

# Minute data example
start=pd.Timestamp('2020-08-28 9:30', tz=NY).isoformat()
end=pd.Timestamp('2020-08-28 16:00', tz=NY).isoformat()
print(api.get_barset(['AAPL', 'GOOG'], 'minute', start=start, end=end).df)

please note that if you are using limit, it is calculated from the end date. and if end date is not specified, "now" is used.
Take that under consideration when using start date with a limit.


Debugging

Websocket exceptions may occur during execution. It will usually happen during the consume() method, which basically is the websocket steady-state.
exceptions during the consume method may occur due to:

  • server disconnections
  • error while handling the response data

We handle the first issue by reconnecting the websocket every time there's a disconnection. The second issue, is usually a user's code issue. To help you find it, we added a flag to the StreamConn object called debug. It is set to False by default, but you can turn it on to get a more verbose logs when this exception happens. Turn it on like so StreamConn(debug=True)

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

There's a way to execute more than one algorithm at once.
The websocket connection is limited to 1 connection per account.
For that exact purpose this project was created
The steps to execute this are:

  • Run the Alpaca Proxy Agent as described in the project's README
  • Define this env variable: DATA_PROXY_WS to be 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 you you initiate the StreamConn object with the container's url, like so: data_url='http://127.0.0.1:8765'
  • execute your algorithm. it will connect to the 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 StreamConn is wrapped with an Entity object for ease of use.
Some users may prefer working with raw 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 StreamConn() 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.

Issues
  • Alpaca historical data to support weekly, monthly data

    Alpaca historical data to support weekly, monthly data

    Is there an existing issue for this?

    • [X] I have searched the existing issues

    Is your feature request related to a problem? Please describe.

    I'm trying to get historical data for other TimeFrames like weekly, monthly. When I look at the TimeFrameUnit, there's support only for Minute, Hour, Day - but not for Weekly or Monthly

    Weekly may not just be querying for 5 days or Monthly can't be 30 days as some months can have more than 30 days or less than that.

    Am I missing something in terms of an existing feature?

    Describe the solution you'd like.

    TimeFrameUnit must include Week, Month, Year as a valid units and the data can be queried based on multiples of these new units

    Describe an alternate solution.

    No response

    Anything else? (Additional Context)

    No response

    opened by akarun2405 15
  • TimeFrame.Hours

    TimeFrame.Hours

    Code from documentation:

    api = REST()
    
    api.get_bars("AAPL", TimeFrame.Hour, "2021-02-08", "2021-02-08", limit=10, adjustment='raw').df ```
    
    
    Returns the Error:
    
    Traceback (most recent call last):
      File "trade_bot.py", line 18, in <module>
        api.get_bars("AAPL", TimeFrame.Hour, "2021-02-08", "2021-02-08", limit=10, adjustment='raw').df
    AttributeError: type object 'TimeFrame' has no attribute 'Hour'
    opened by FarhanQ7 15
  •  certificate verify failed: certificate has expired

    certificate verify failed: certificate has expired

    self._sslobj.do_handshake() ssl.SSLCertVerificationError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: certificate has expired (_ssl.c:1129)

    error during websocket communication: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: certificate has expired (_ssl.c:1129)

    opened by Oke-Harridon 13
  • get_barset() still ignores start and end date

    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
    ...                             ...       ...       ...       ...       ...
    
    opened by edwardyu 13
  • Loosen up the requirements

    Loosen up the requirements

    Related to: https://github.com/alpacahq/alpaca-trade-api-python/issues/230

    Specifying exact versions for a 3rd party package is not a very friendly practice. Locking to exact versions is critical for a production application, but for libraries that will be consumed by others, you generally want version specifications as wide as possible (without breakage).

    Python has its warts with dependency management, but locking to specific versions is going to magnify those by an order of magnitude and virtually guarantee version incompatibilities as an app grows (along with its dependencies).

    opened by mLewisLogic 12
  • [Question]: list_orders() Quantity

    [Question]: list_orders() Quantity

    Is there an existing issue for this?

    • [X] I have searched the existing issues

    Current Behavior

    This is not a bug, it is a question. I can't find any documentation or example about this.

    I know how to show a list of orders:

    api = alpaca.REST(api_key, api_secret, base_url, api_version='v2')  
    ORDERS = api.list_orders()
    

    But what I don't know, is how to get the quantity of orders I have open right now. I don't have the order id, I just have the symbol

    For example: I want to know the exact qty of open orders I have to sell TSLA to avoid submitting another order.

    Thanks in advance for your response.

    Expected Behavior

    Get orders qty

    SDK Version I encountered this issue in

    Alpaca-trade-api- == 2.0.0

    Steps To Reproduce

    Try to get the quantity of open orders for a given symbol (Ex: TSLA)
    

    Filled out the Steps to Reproduce section?

    • [X] I have entered valid steps to reproduce my issue or have attached a minimally reproducible case in code that shows my issue happening; and understand that without this my issue will be flagged as invalid and closed after 30 days.

    Anything else?

    No response

    question 
    opened by sshcli 9
  • WARNING:root:code = 1009 (message too big), no reason

    WARNING:root:code = 1009 (message too big), no reason

    I'm simply trying to stream the data of all NASDAQ aggregate minute bar data. and I'm getting the above error. @shlomikushchi would be very thankful if you can help me with this issue :)

    ERROR

    3610
    authorized
    Entity({'action': 'authenticate', 'status': 'authorized'})
    listening
    Entity({'streams': ['trade_updates']})
    authorized
    Entity({'action': 'authenticate', 'status': 'authorized'})
    WARNING:root:code = 1009 (message too big), no reason
    Traceback (most recent call last):
      File "paper.py", line 34, in <module>
        conn.run(['trade_updates']+symbol_list[:700])
      File "/Users/dinesh/Desktop/muon-capital/lib/python3.8/site-packages/alpaca_trade_api/stream2.py", line 298, in run
        loop.run_until_complete(self.consume())
      File "/usr/local/opt/[email protected]/Frameworks/Python.framework/Versions/3.8/lib/python3.8/asyncio/base_events.py", line 616, in run_until_complete
        return future.result()
    asyncio.exceptions.CancelledError
    
    

    CODE

    conn = StreamConn(key_id=KEY_ID, secret_key=SECRET_KEY, base_url=BASE_URL, data_url=DATA_URL, data_stream='alpacadatav1')
    api = tradeapi.REST(key_id=KEY_ID, secret_key=SECRET_KEY, base_url=BASE_URL)
    account = api.get_account()
    assets = api.list_assets(status="active", asset_class="us_equity")
    assets = filter(lambda a: a.exchange == "NASDAQ", assets)
    
    def get_alpaca_symbol(asset):
    	symbol = asset.symbol
    	return 'alpacadatav1/AM.'+symbol
    
    symbol_list = list(map(get_alpaca_symbol, assets))
    
    print(len(symbol_list))
    
    
    @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(['trade_updates']+symbol_list)
    
    
    opened by dinnu93 8
  • ConnectionResetError: [Errno 54] Connection reset by peer

    ConnectionResetError: [Errno 54] Connection reset by peer

    Hi, I keep getting the 'ConnectionResetError: [Errno 54] Connection reset by peer' error, not quite sure why. I am using the Paper Trading API. Any help would be really appreciated

    opened by ksan01 8
  • says qty is required when submitting an order with a notional value

    says qty is required when submitting an order with a notional value

    order = api.submit_order(symbol=stock.upper(), notional=5000, side='buy', type='market', time_in_force='day')
      File "C:\ProgramData\Anaconda3\lib\site-packages\alpaca_trade_api\rest.py", line 347, in submit_order
        resp = self.post('/orders', params)
      File "C:\ProgramData\Anaconda3\lib\site-packages\alpaca_trade_api\rest.py", line 179, in post
        return self._request('POST', path, data)
      File "C:\ProgramData\Anaconda3\lib\site-packages\alpaca_trade_api\rest.py", line 139, in _request
        return self._one_request(method, url, opts, retry)
      File "C:\ProgramData\Anaconda3\lib\site-packages\alpaca_trade_api\rest.py", line 168, in _one_request
        raise APIError(error, http_error)
    alpaca_trade_api.rest.APIError: qty is required
    

    says qty is required when submitting an order with a notional value and then when I try to submit an order with both it says I shouldn't have qty, which is true, but why isn't notional working by itself?

    bug 
    opened by JESIII 7
  • Invalid TimeFrame in getbars for hourly

    Invalid TimeFrame in getbars for hourly

    Hello when I try to use the example, I get an error:

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

    """
    Traceback (most recent call last):
      File "/home/kyle/.virtualenv/lib/python3.8/site-packages/alpaca_trade_api/rest.py", line 160, in _one_request
        resp.raise_for_status()
      File "/home/kyle/.virtualenv/lib/python3.8/site-packages/requests/models.py", line 943, in raise_for_status
        raise HTTPError(http_error_msg, response=self)
    requests.exceptions.HTTPError: 422 Client Error: Unprocessable Entity for url: https://data.alpaca.markets/v2/stocks/AAPL/bars?timeframe=1Hour&adjustment=raw&start=2021-02-08&end=2021-02-08&limit=10
    
    During handling of the above exception, another exception occurred:
    
    Traceback (most recent call last):
      File "run_hourly.py", line 231, in make_df
        tdf = api.get_bars("AAPL", TimeFrame.Hour, "2021-02-08", "2021-02-08", limit=10, adjustment='raw').df
      File "/home/kyle/.virtualenv/lib/python3.8/site-packages/alpaca_trade_api/rest.py", line 625, in get_bars
        bars = list(self.get_bars_iter(symbol,
      File "/home/kyle/.virtualenv/lib/python3.8/site-packages/alpaca_trade_api/rest.py", line 611, in get_bars_iter
        for bar in bars:
      File "/home/kyle/.virtualenv/lib/python3.8/site-packages/alpaca_trade_api/rest.py", line 535, in _data_get_v2
        resp = self.data_get('/stocks/{}/{}'.format(symbol, endpoint),
      File "/home/kyle/.virtualenv/lib/python3.8/site-packages/alpaca_trade_api/rest.py", line 192, in data_get
        return self._request(
      File "/home/kyle/.virtualenv/lib/python3.8/site-packages/alpaca_trade_api/rest.py", line 139, in _request
        return self._one_request(method, url, opts, retry)
      File "/home/kyle/.virtualenv/lib/python3.8/site-packages/alpaca_trade_api/rest.py", line 168, in _one_request
        raise APIError(error, http_error)
    alpaca_trade_api.rest.APIError: invalid timeframe
    

    Minute data seems to work.

    opened by hansonkd 7
  • run_forever()'s restart condition never met

    run_forever()'s restart condition never met

    in this loop on line 208 of stream.py, self._running is never set to false in the exception. retries starts at 0, then incremented in the exception. This has it compare 1>3 which is false. This means that self._running is never set to false. Then in finally block on line 226, the break statement on line 228 will never be reached. Wouldn't this stop it from restarting on the next pass of the loop?

            while True: # stream.py - line 208
                try:
                    if not self._running:
                        await self._start_ws()
                        self._running = True
                        retries = 0
                        await self._consume()
                except websockets.WebSocketException as wse:
                    retries += 1
                    if retries > int(os.environ.get('APCA_RETRY_MAX', 3)):
                        await self.close()
                        self._running = False
                        raise ConnectionError("max retries exceeded")
                    if retries > 1:
                        await asyncio.sleep(
                            int(os.environ.get('APCA_RETRY_WAIT', 3)))
                    log.warn('websocket error, restarting connection: ' +
                             str(wse))
                finally:
                    print(retries)
                    if not self._running:
                        break
                    await asyncio.sleep(0.01)```
    opened by Chrisrdouglas 7
  • [Feature Request] api.list_orders(side='Buy or Sell')`

    [Feature Request] api.list_orders(side='Buy or Sell')`

    Is there an existing issue for this?

    • [X] I have searched the existing issues

    Is your feature request related to a problem? Please describe.

    Is your feature request related to a problem?

    Yes, we need an easy way to get the list of orders by side (Buy or Sell)

    Describe the solution you'd like.

    According to documentation here: https://alpaca.markets/docs/api-references/trading-api/orders/

    To Get a list of orders: list_orders()

    The only available query parameters attributes are:

    status
    limit
    after
    until
    direction
    nested
    symbols
    

    My suggestion is that we also need this one: side

    For example: api.list_orders(side='sell')

    Describe an alternate solution.

    As a workaround you could try to get this information by adding extra Python code to your program. But IMHO, simple is better than complex

    Anything else? (Additional Context)

    No response

    bug enhancement 
    opened by sshcli 2
  • [Bug]: cancel_all_orders method does not work

    [Bug]: cancel_all_orders method does not work

    Is there an existing issue for this?

    • [X] I have searched the existing issues

    Current Behavior

    When I call api.cancel_all_orders() I check my account from the UI and open orders remain open.

    Expected Behavior

    All orders should be closed.

    Steps To Reproduce

    No response

    Anything else?

    No response

    opened by albertsalgueda 0
  • [Bug]: calling get_barse that call the method _data_get_v2 throw error TypeError: 'NoneType' object is not iterable

    [Bug]: calling get_barse that call the method _data_get_v2 throw error TypeError: 'NoneType' object is not iterable

    Is there an existing issue for this?

    • [X] I have searched the existing issues

    Current Behavior

    Hi all,

    I'm trying to load data using the method get_barse and I'm getting an error TypeError: 'NoneType' object is not iterable that thrown in method _data_get_v2

    [/usr/local/lib/python3.7/dist-packages/alpaca_trade_api/rest.py](https://localhost:8080/#) in _data_get_v2(self, endpoint, symbol, **kwargs)
        562                                  data=data, api_version='v2')
        563             items = resp.get(endpoint, [])
    --> 564             for item in items:
        565                 yield item
        566             total_items += len(items)
    
    TypeError: 'NoneType' object is not iterable
    

    Expected Behavior

    No response

    Steps To Reproduce

    1. import alpaca-trade-api in google colab
    2. Load the method download_data
    3. Execute the method download_data
    
    
    
    data = download_data(API_KEY, API_SECRET, start_date = '2021-02-01', end_date = '2021-10-05', 
                         ticker_list = ['AAPL', 'GOOG', 'AMZN'], 
                         time_interval= '1Min')
    
    def download_data(API_KEY, API_SECRET, ticker_list, start_date, end_date, time_interval
    ) -> pd.DataFrame:
        start = start_date
        end = end_date
        time_interval = time_interval
        API_DATA_URL = 'https://data.alpaca.markets/v2/stocks'
        api = REST(API_KEY, API_SECRET, API_DATA_URL)
    
        NY = "America/New_York"
        start_date = pd.Timestamp(start_date, tz=NY)
        end_date = pd.Timestamp(end_date, tz=NY) + pd.Timedelta(days=1)
        date = start_date
        data_df = pd.DataFrame()
        while date != end_date:
            start_time = (date + pd.Timedelta("09:30:00")).isoformat()
            end_time = (date + pd.Timedelta("15:59:00")).isoformat()
            for tic in ticker_list:
                barset = api.get_bars(tic, TimeFrame.Minute, start=start_time, end=end_time, limit=500, adjustment='raw').df
    
                barset['tic'] = tic
                barset = barset.reset_index()
                data_df = data_df.append(barset)
    
            print(("Data before ") + end_time + " is successfully fetched")
    
            date = date + pd.Timedelta(days=1)
            
            if date.isoformat()[-14:-6] == "01:00:00":
                date = date - pd.Timedelta("01:00:00")
            elif date.isoformat()[-14:-6] == "23:00:00":
                date = date + pd.Timedelta("01:00:00")
            if date.isoformat()[-14:-6] != "00:00:00":
                raise ValueError("Timezone Error")
        """times = data_df['time'].values
        for i in range(len(times)):
            times[i] = str(times[i])
        data_df['time'] = times"""
    
        return data_df
    
    
    
    
    ### Anything else?
    
    _No response_
    opened by ObaidaAlhaasan 0
  • [WARNING] data websocket error, restarting connection: no close frame received or sent

    [WARNING] data websocket error, restarting connection: no close frame received or sent

    Is there an existing issue for this?

    • [X] I have searched the existing issues

    Current Behavior

    websocket connection on sip is unusable for me, a connection lost every 10 seconds, one of tow errors

    • [WARNING] data websocket error, restarting connection: no close frame received or sent
    • [WARNING] data websocket error, restarting connection: sent 1011 (unexpected error) keepalive ping timeout; no close frame received simple subscribtion to bars for all symbols attempts:
    • tested versions 1.5.0 1.5.1
    • changed host (local machine, friend's machine, personal laptop, 2 vps servers) exact same behaviour
    • changed websocket versions i can't even remember how many log websocket shows ping timeout sometimes

    some suggested that api already reconnect automatically, that's not a solution because you're missing 5sec of timeout before the connection actually drop plus reconnection+subscription time, that leaves gaps in 1minute bars by the time you start receiving again. for 24h run i got a total of 290 candles on AAPL (because of this error) out of possible 960 candles that 70% lost data.

    my guess:

    • Alpaca servers websocket timeout ping interval is too short for such high traffic.
    • Alpaca servers deliberately drop random connections at saturation to prevent service failure (problem happens at peak hours)

    Expected Behavior

    Expected to work

    Steps To Reproduce

    simple 1minute barse subscription for all symbols
    

    Anything else?

    No response

    opened by kimboox44 10
  • [Bug]: Cannot import TimeFrameUnit

    [Bug]: Cannot import TimeFrameUnit

    Is there an existing issue for this?

    • [X] I have searched the existing issues

    Current Behavior

    based on the documentation:

    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
    

    I got the error:

    ImportError: cannot import name 'TimeFrameUnit' from 'alpaca_trade_api.rest'
    

    Tried: uninstalling and reinstalling alpaca_trade_api through pip

    Expected Behavior

    No errors

    Steps To Reproduce

    conda env for python 3.8
    
    pip install alpaca_trade_api
    
    put that code into a python file
    
    python main.py    (you can do this because in conda env, python3 can be written as just python)
    

    Anything else?

    No response

    opened by darrenzou2000 1
  • Cannot access/print any bars

    Cannot access/print any bars

    Hi,

    I am able to setup my connection but I have never seen any bar data being displayed in my console. Occasionally when I run without nest_asyncio, it gives a runtime error of Cannot close loop while still running/ This loop is still running and if I try to stop it, it says stream object has no attribute stop. Tried numerous solutions, nothing seems to work. Cannot even print or see the data stream on the console. Please help

    invalid Missing Reproducible Case 
    opened by hriday2771 1
Releases(v2.0.0)
  • v2.0.0(Mar 25, 2022)

    :warning: Note this release is a Breaking Change due to the removal of Market Data V1 capabilities

    • Adds a param to the stream classes to allow overriding of websocket defaults (#596)
    • Scheduled weekly dependency update for week 12 (#592)
    • Increase ping timeout (#591)
    • Send subscription requests in parts (#586)
    • Remove marketdata v1 functions (#590)
    • Updating overnight-hold to use the new data api (async get bars) (#562)
    • Add Week and Month timeframe units (#583)
    • Multi symbol support for the latest crypto endpoints (#580)

    You can view this release on PyPi here

    Source code(tar.gz)
    Source code(zip)
  • v1.5.1(Feb 28, 2022)

    • Move updated bars to their own subscription by @gnvk #574
    • empty handler check when unregister cancel errors + corrections by @ccnlui #577
    • Adds support for Python 3.10 by @ccnlui #561
    • Fixes Incorrect Access Issue on Long-Short Example by @haxdds #560
    Source code(tar.gz)
    Source code(zip)
  • v1.5.0(Jan 26, 2022)

    What's Changed

    • Add news api by @ccnlui in https://github.com/alpacahq/alpaca-trade-api-python/pull/555
    • Drops Support For Python 3.6 by @haxdds in https://github.com/alpacahq/alpaca-trade-api-python/pull/544
    • Mark v1 marketdata endpoints deprecated by @gnvk in https://github.com/alpacahq/alpaca-trade-api-python/pull/558
    • Adds Raw Data Support for TradingStream by @haxdds in https://github.com/alpacahq/alpaca-trade-api-python/pull/556

    Full Changelog: https://github.com/alpacahq/alpaca-trade-api-python/compare/v1.4.3...v1.5.0

    Source code(tar.gz)
    Source code(zip)
  • v1.4.3(Dec 10, 2021)

    • Adds Crypto Snapshot Endpoint

    • Handle new messages as implicit subscriptions messages that come with subscribing to trades - The biggest change is letting user pass in handler_cancel_errors and handler_corrections into subscribe_trades()

    Source code(tar.gz)
    Source code(zip)
  • v1.4.2(Nov 30, 2021)

    In this release:

    • Fixed error handling syntax within rest.py
    • Fixed named parameter syntax in code package in __main__.py
    • Update Python 3.7 CI dependencies to support numpy and pandas
      • pandas==1.3.4 and numpy===1.21.4
    Source code(tar.gz)
    Source code(zip)
  • v1.4.1(Nov 2, 2021)

  • v.1.4.0(Sep 28, 2021)

    In this release we:

    • add support for crypto market data
    • add support for the multiple symbols endpoint data queries

    fixes:

    • data ws disconnections resolved.
    • removed polygon old code refereces
    Source code(tar.gz)
    Source code(zip)
  • v1.3.0(Sep 7, 2021)

    In this release we add asyncio support for the historic endpoints

    • Bars
    • Quotes
    • Trades

    We also support the latest endpoints:

    • latest quote
    • latest trade

    We also add

    • LULDs to stream.
    Source code(tar.gz)
    Source code(zip)
  • v1.2.2(Jun 18, 2021)

    In this release we:

    • Add daily bars to data stream (f826e5bfd00419db5fcad45dae15afb6fdf917d9)
    • Add support for closing partial position (253bd6d7aa4854235bcc5773ca7116f85e67e62e)
    • Fix a data v2 websocket reconnection issue (b649fb4066a423877c1cf378a63edf752d8f9ebe)
    • extend list_order() to be able to filter by symbol list (e203f38840d5e396154bf30aafb6adf8888e3551)
    • update the websockets package and the websocket-client package (d5b5e26326cfc6397ef28aa022abfecbe9b57a10, 59b4fb86a0272eb666f5bb7323c9f2a5b9faee21)
    • fix example code - overnight_hold.py (797d508a339536694f29c3717598af21c77c207b)
    Source code(tar.gz)
    Source code(zip)
  • v1.2.1(May 7, 2021)

  • v1.2.0(Apr 19, 2021)

    In this release, we add support for fractional amounts (qty) and notional values (notional) in POST/v2/orders requests, via submit_order():

    • qty is now an optional float kwarg
    • notional has been added as an optional float kwarg
    • side is now a kwarg (default is "buy")
    • type is now a kwarg (default is "market")
    • time_in_force is now a kwarg (default is "day")

    With these changes, we encourage users to call submit_order() with named arguments instead of positional ones.

    For examples, please refer to the docs.

    Source code(tar.gz)
    Source code(zip)
  • v1.1.0(Mar 19, 2021)

    • Added ability to stop the ws connection (d214cbf50d39f85426c74fb6a3721a5195b3493c)
    • updated the websocket examples for v2 (a77bc6b099e63b7deb71ad037869790246126e29)
    • removed old, unsupported example code
    • only support 'raw' adjustment for get_bars() for now (aa748d717c40505966a396dfca75db2ca565658b)
    Source code(tar.gz)
    Source code(zip)
  • v1.0.0(Mar 2, 2021)

    In this release we upgrade our service to Alpaca Data V2 as described here. (1391436dbba635efb56615739d91fdbb2f23cd9c) We dropped support for the Polygon stream data and Rest APIs.
    To learn how to use the new functionality:

    • refer to the docs
    • check out the readme file examples
    • check out the sample code
    Source code(tar.gz)
    Source code(zip)
  • v0.53.0(Feb 15, 2021)

    In this release we add the ability to stop the websocket connection when using the data streams. Allowing the users to "pause/resume" their data stream.(d7e10ec51824947a010b7340b2162578844d4879) We also add advanced usage example to help tackle the most common usage issues:

    • pause/resume websocket connection (fc61ca97ac6d06d3aad6a79d39b1672c03634508)
    • change the channels the websocket is subscribed to (85abc5874b0c3b4ce5d608b5f28cfba4e1ab4c72)
    • websocket re-connection pattern, making sure we reconnect on ws diconnection (2902cb4a15816074da1374553faeb35b77cbc63a)
    • different channels subscriptions for alpaca and polygon data streams.
    Source code(tar.gz)
    Source code(zip)
  • v0.52.0(Jan 17, 2021)

    In this release we enable raw data responses from REST and Stream APIs. (de0fc4f5dbc37ad1fada7624d2a68a9f27d63983) It is achieved by passing raw_data=True to API instances and it returns the data without wrapping it with Entity objects. Default is using Entities, exactly as before. Also:

    • Support for polygon financials V2 (200f667d7779ddb0674aa1bb1190442ce1ef0f7c)
    • Update the example code for websocket usage (a02e694faec15bb358aaa1c8daf3fde2be932e8d)
    • Add oauth support for StreamConn (05f3a78ab12f9f06cdb5e9d7d1f1aa45c4b1b33b)
    • Add CI pipelines for python 3.6-3.9 (be040630fb851edac27d09bbe0ea052c74ee0282)
    • Make sure there are no issues with pandas 1.2.0+ and numpy 1.20.0+ which dropped support for python 3.6 (e2eb54d0efc3c4d522012e867ded4a181571a5d8)

    Fixes

    • handle better aggs empty response (e2c9b74edc1bdb817f46018d428d24ba66ed7f27)
    • fixing dates for polygon queries (d84675eb490201dfe932f42283293f72398bfa81)
    • fix should use asyncio.sleep inside async methods (c329fbae6f8fdb9696432a6e803e6f8160118e32)
    • Calendar Entity dates (f848bdd46e1e31b8a37913302e4f9cd8e545f205)
    • polygon grouped_daily() url (013cb801bf810f4b2d7452500bd28bfbee0cd9ea)
    • update polygon trade mapping for Entity (8dbb10966353206842ba818fa8c574be97ba408c)
    Source code(tar.gz)
    Source code(zip)
  • v0.51.0(Oct 8, 2020)

    In this release we add support for the alpaca-proxy-agent which allows users to run multiple strategies in parallel.

    also:

    • Add a new simple stream example to demonstrate how to use the streaming service. It's under examples/websocket_example.py
    • Cleaner look for the documentation (README file)
    • Explain exactly how to use get_barset()
    Source code(tar.gz)
    Source code(zip)
  • v0.50.1(Aug 24, 2020)

  • v0.50.0(Aug 18, 2020)

    In this release we add support for the new added feature - trailing stop:

    • submit_order now supports a new type trailing_stop.
    • 2 new optional args to submit_order: trail_price, trail_percent.

    Bugs

    • Fix functions related to the Watchlist endpoint.
    Source code(tar.gz)
    Source code(zip)
  • v0.49.1(Aug 4, 2020)

    In this release we add small changes to help the user debug issues easily:

    • Indicate that websocket is connected and to which endpoint
    • add a debug flag to make websocket exceptions more verbose
    • explain in the docs, how to define a logger to see these changes

    Other changes

    • We also removed the Alpha Vantage Integration. it will be moved to a stand alone package
    • We now allow working with all versions of pandas (required for Pylivetrader)

    Bugs

    • fix bug with polygons' historic_aggs_v2 (https://github.com/alpacahq/alpaca-trade-api-python/issues/280)
    • 'NoneType' object is not iterable (https://github.com/alpacahq/alpaca-trade-api-python/issues/270)
    Source code(tar.gz)
    Source code(zip)
  • v0.49.0(Jul 14, 2020)

    In this release we:

    • reconnect when the data websocket disconnects
    • add type hints for the rest and stream modules
    • add some input validators for URLs, price floats and dates
    • remove deprecated polygon api wrappers: historic_trades, historic_quotes, splits
    • add integration with pyup
    • change the package requirements to be less strict
    • update the README documentation

    fixes:

    • historic_agg_v2 now accepts different date formats
    • adjust the sample code: martingale.py to work with the new data api
    Source code(tar.gz)
    Source code(zip)
  • v0.48(May 11, 2020)

    Alpaca Data API's new endpoints are supported as of this version.

    • get_last_trade()
    • get_last_quote()
    • StreamConn() can now connect to streams of trade, quotes and minute bars provided by Alpaca streaming endpoint

    Now all users (with or without live brokerage account) can access realtime quotes/trades both in REST and streaming.

    As part of these changes, this release defaults streaming connection to the Alpaca streaming endpoint. If you want to keep using Polygon streaming endpoint, you will need to specify data_stream in the StreamConn() initializer, as

    conn = StreamConn(data_stream="polygon")
    
    Source code(tar.gz)
    Source code(zip)
  • v0.47rc5(May 6, 2020)

  • v0.47rc4(May 6, 2020)

    This is another pre-release for 0.47. In this release we:

    • removed the polyfeed prefix
    • better exception handling for stream2
    • support the new data schema:
      • trade in WS: rename “sym” to “T”, “t” to be nanoseconds (from milliseconds)
      • quote in WS: no change
      • bars in WS: rename “sym” to “T”
      • trade in REST: timestamp resolution is now nanoseconds
      • quote in REST: timestamp resolution is now nanoseconds
      • bars in REST: no change
    Source code(tar.gz)
    Source code(zip)
  • v0.47rc3(Apr 28, 2020)

    This is another pre-release for the upcoming Alpaca Data API upgrade. This release notably changes the default streaming connection from polygon to alpaca. The caller can still choose polygon with data_stream='polygon' in StreamConn initializer.

    Source code(tar.gz)
    Source code(zip)
  • v0.47rc2(Apr 28, 2020)

    This is the first RC release to support new Alpaca Data API.

    • get_last_trade()
    • get_last_quote()
    • StreamConn() can now connect to streams of trade, quotes and minute bars
    Source code(tar.gz)
    Source code(zip)
  • v0.46(Mar 5, 2020)

    The API specification changed after the release of v0.45 - timestamps are now provided in milliseconds rather than seconds. This update fixes the dataframe's index.

    Source code(tar.gz)
    Source code(zip)
  • v0.45(Mar 2, 2020)

    As it says in the title, support has been added for a couple new endpoints.

    Polygon open/close: https://polygon.io/docs/#!/Stocks--Equities/get_v1_open_close_symbol_date Documentation for Alpaca portfolio history is forthcoming, but is documented as such in the readme for the moment:

    REST.get_portfolio_history(date_start=None, date_end=None, period=None, timeframe=None, extended_hours=None)
    Calls GET /account/portfolio/history and returns a PortfolioHistory entity. PortfolioHistory.df can be used to get the results as a dataframe.
    
    Source code(tar.gz)
    Source code(zip)
  • v0.44(Feb 6, 2020)

    The Alpha Vantage package added in the last release was not declared in setup.py, leading to some installation issues. We've added it now, so it should be picked up when you try to run the SDK.

    Source code(tar.gz)
    Source code(zip)
  • v0.43(Feb 6, 2020)

    In this release, support for advanced order types - bracket orders - is added. You can now submit bracket orders like so:

    {
      "side": "buy",
      "symbol": "SPY",
      "type": "market",
      "qty": "100",
      "time_in_force": "gtc",
      "class": "bracket",
      "take_profit": {
        "limit_price": "301"
      },
      "stop_loss": {
        "stop_price": "299",
        "limit_price": "298.5"
      }
    }
    

    Please note the inclusion of the new nested parameter in the order list call. Specifying nested=true will make it so that bracket orders have legs fields which will contain their child orders. Child orders will be in this nested field rather than the main array of orders. For more information about using bracket orders with Alpaca, please refer to https://docs.alpaca.markets.

    Watchlist endpoint support was also added - learn more about using it here: https://docs.alpaca.markets/api-documentation/api-v2/watchlist/.

    Additionally, support for Alpha Vantage has been added for those looking for more data sources akin to our Polygon integration. Please see the updated README.md for information about using the Alpha Vantage API. We also corrected an issue where Position-closing endpoints were not returning the created Order objects.

    Source code(tar.gz)
    Source code(zip)
  • v0.42(Dec 3, 2019)

    In this release, support has been added for the following Polygon endpoints:

    Historic Trades v2: https://polygon.io/docs/#!/Stocks--Equities/get_v2_ticks_stocks_trades_ticker_date Historic Quotes v2: https://polygon.io/docs/#!/Stocks--Equities/get_v2_ticks_stocks_nbbo_ticker_date

    The methods using the v1 endpoints have been marked as deprecated and will be removed from the library in a future release, as Polygon intends to remove them from the API.

    Source code(tar.gz)
    Source code(zip)
Owner
Alpaca
Alpaca builds an API for free stock trading
Alpaca
Get informed when your DeFI Earn CRO Validator is jailed or changes the commission rate.

CRO-DeFi-Warner Intro CRO-DeFi-Warner can be used to notify you when a validator changes the commission rate or gets jailed. It can also notify you wh

null 4 Apr 11, 2022
Cryptocurrency Trading Bot - A trading bot to automate cryptocurrency trading strategies using Python, equipped with a basic GUI

Cryptocurrency Trading Bot - A trading bot to automate cryptocurrency trading strategies using Python, equipped with a basic GUI. Used REST and WebSocket API to connect to two of the most popular crypto exchanges in the world.

Francis 6 Apr 8, 2022
Trading bot - A Trading bot With Python

Trading_bot Trading bot intended for 1) Tracking current prices of tokens 2) Set

Tymur Kotkov 31 Apr 8, 2022
Crypto-trading-simulator - Cryptocurrency trading simulator using Python, Streamlit

Crypto Trading Simulator Run streamlit run main.py Dependency Python 3 streamli

Brad 11 Apr 12, 2022
Utilizing the freqtrade high-frequency cryptocurrency trading framework to build and optimize trading strategies. The bot runs nonstop on a Rasberry Pi.

Freqtrade Strategy Repository Please test all scripts and dry run them before using them in live mode Contact me on discord if you have any questions!

Michael Fourie 82 Apr 11, 2022
This program is an automated trading bot that uses TDAmeritrades Thinkorswim trading platform's scanners and alerts system.

Python Trading Bot w/ Thinkorswim Description This program is an automated trading bot that uses TDAmeritrades Thinkorswim trading platform's scanners

Trey Thomas 167 Apr 18, 2022
Intelligent Trading Bot: Automatically generating signals and trading based on machine learning and feature engineering

Intelligent Trading Bot: Automatically generating signals and trading based on machine learning and feature engineering

Alexandr Savinov 159 Apr 24, 2022
Terminal-Trade(Panel API) For Binance

Binance-Trade-Project Binance Futures Terminal-Trade(API) & Binance This Project Worth Around 500 Bucks. **I Did This Project For SomeOne And He

Cyber 9 Dec 30, 2021
Freqtrade is a free and open source crypto trading bot written in Python.

Freqtrade is a free and open source crypto trading bot written in Python. It is designed to support all major exchanges and be controlled via Telegram. It contains backtesting, plotting and money management tools as well as strategy optimization by machine learning.

Kazune Takeda 5 Dec 30, 2021
Free python/telegram bot for easy execution and surveillance of crypto trading plans on multiple exchanges.

EazeBot Introduction Have you ever traded cryptocurrencies and lost overview of your planned buys/sells? Have you encountered the experience that your

Marcel Beining 93 Apr 18, 2022
A Telegram bot for remotely managing Binance Trade Bot

Binance Trade Bot Manager Telegram A Telegram bot for remotely managing Binance Trade Bot. If you have feature requests please open an issue on this r

Lorenzo Callegari 乐子睿 320 Apr 20, 2022
This tool helps users selecting items from the Gwennen gambling trade (based on prices of the uniques).

Gwennen Gambler This small program will check each item in the Gwennen shop (item gamble) according and show small stats according to poe.ninja. Shoul

null 9 Apr 10, 2022
Most Simple & Powefull web3 Trade Bot (WINDOWS LINUX) Suport BSC ETH

Most Simple & Powefull Trade Bot (WINDOWS LINUX) What Are Some Pros And Cons Of Owning A Sniper Bot? While having a sniper bot is typically an advanta

GUI BOT 4 Jan 25, 2022
Tsar-Bot - Crypto auto trade bot that use sentiment analysis from twitter

Tsar Bot - Crypto Sentiment Bot Tsar Bot is a Twitter Crypto Sentiment Bot that

Hilmi Azizi 15 Apr 21, 2022
(unofficial) Googletrans: Free and Unlimited Google translate API for Python. Translates totally free of charge.

Googletrans Googletrans is a free and unlimited python library that implemented Google Translate API. This uses the Google Translate Ajax API to make

Suhun Han 2.9k Apr 21, 2022
Stock trading bot made using the Robinhood API / Python library...

High-Low Stock trading bot made using the Robinhood API / Python library... Index Installation Use Development Notes Installation To Install and run t

Reed Graff 1 Jan 7, 2022
The official Python client library for the Kite Connect trading APIs

The Kite Connect API Python client - v3 The official Python client for communicating with the Kite Connect API. Kite Connect is a set of REST-like API

Zerodha Technology 665 Apr 13, 2022
Leveraged grid-trading bot using CCXT/CCXT Pro library in FTX exchange.

Leveraged-grid-trading-bot The code is designed to perform infinity grid trading strategy in FTX exchange. The basic trader named Gridtrader.py contro

Hao-Liang Wen 25 Oct 7, 2021
A library for demo trading | backtest and forward test simulation

Trade Engine a library for demo trading | backtest and forward test simulation Features Limit/Market orders: you can place a Limit or Market order in

Ali Moradi 4 Feb 21, 2022