Package: alpaca-trade-api-fixed
alpaca-trade-api-pythonalpaca-trade-api-pythonis a python library for the Alpaca trade API.
It allows rapid trading algo development easily, with support for the
both REST and streaming interfaces. For details of each API behavior,
please see the online API document.Note this module supports only python version 3.5 and above, due to
the async/await keyword use.Install$pip3installalpaca-trade-apiExampleIn order to call Alpaca's trade API, you need to obtain API key pairs.
Replace <key_id> and <secret_key> with what you get from the web console.REST exampleimportalpaca_trade_apiastradeapiapi=tradeapi.REST('<key_id>','<secret_key>')account=api.get_account()api.list_positions()API DocumentThe HTTP API document is located inhttps://docs.alpaca.markets/AuthenticationThe Alpaca API requires API key ID and secret key, which you can obtain from the
web console after you sign in.  You can passkey_idandsecret_keyto the initializers ofRESTorStreamConnas arguments, or set up environment variables as
follows.APCA_API_KEY_ID: key IDAPCA_API_SECRET_KEY: secret keyBase URLThe base URL for API calls defaults tohttps://api.alpaca.markets/. This endpoint
is for live trading, and for paper trading and other purposes, you can to change
the base URL. You can passbase_urlkwarg toREST(), or using the environment
variable,APCA_API_BASE_URL.The environment variableAPCA_API_DATA_URLcan also be changed to configure the
endpoint for returning data from the/barsendpoint. By default, it will usehttps://data.alpaca.markets.RESTTheRESTclass 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 ofEntityclass (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_rawfield.
It also converts certain types to the appropriate python object.importalpaca_trade_apiastradeapiapi=tradeapi.REST()account=api.get_account()account.status=>'ACTIVE'TheEntityclass also converts timestamp string field to a pandas.Timestamp
object.  Its_rawproperty returns the original raw primitive data unmarshaled
from the response JSON text.When a REST API call sees the 429 or 504 status code, this library retries 3 times
by default, with 3 seconds apart between each call. These are configurable with
the following environment variables.APCA_RETRY_MAX: the number of subsequent API calls to retry, defaults to 3APCA_RETRY_WAIT: seconds to wait between each call, defaults to 3APCA_RETRY_CODES: comma-separated HTTP status code for which retry is attemptedIf the retry exceeds, or other API error is returned,alpaca_trade_api.rest.APIErroris raised.
You can access the following information through this object.the API error code:.codepropertythe API error message:str(error)the original request object:.requestpropertythe original response objecgt:.responsepropertythe HTTP status code:.status_codepropertyREST.get_account()CallsGET /accountand returns anAccountentity.REST.list_orders(status=None, limit=None, after=None, until=None, direction=None)CallsGET /ordersand returns a list ofOrderentities.afteranduntilneed to be string format, which you can obtain bypd.Timestamp().isoformat()REST.submit_order(symbol, qty, side, type, time_in_force, limit_price=None, stop_price=None, client_order_id=None)CallsPOST /ordersand returns anOrderentity.REST.get_order_by_client_order_id(client_order_id)CallsGET /orderswith client_order_id and returns anOrderentity.REST.get_order(order_id)CallsGET /orders/{order_id}and returns anOrderentity.REST.cancel_order(order_id)CallsDELETE /orders/{order_id}.REST.list_positions()CallsGET /positionsand returns a list ofPositionentities.REST.get_position(symbol)CallsGET /positions/{symbol}and returns aPositionentity.REST.list_assets(status=None, asset_class=None)CallsGET /assetsand returns a list ofAssetentities.REST.get_asset(symbol)CallsGET /assets/{symbol}and returns anAssetentity.REST.get_barset(symbols, timeframe, limit, start=None, end=None, after=None, until=None)CallsGET /bars/{timeframe}for the given symbols, and returns a Barset withlimitBar objects
for each of the the requested symbols.timeframecan be one ofminute,1Min,5Min,15Min,dayor1D.minuteis an alias
of1Min. Similarly,dayis an alias of1D.start,end,after, anduntilneed to be string format, which you can obtain withpd.Timestamp().isoformat()aftercannot be used withstartanduntilcannot be used withend.REST.get_clock()CallsGET /clockand returns aClockentity.REST.get_calendar(start=None, end=None)CallsGET /calendarand returns aCalendarentity.StreamConnTheStreamConnclass provides WebSocket/NATS-based event-driven
interfaces.  Using theondecorator of the instance, you can
define custom event handlers that are called when the pattern
is matched on the channel name.  Once event handlers are set up,
call therunmethod which runs forever until a critical exception
is raised. This module itself does not provide any threading
capability, so if you need to consume the messages pushed from the
server, you need to run it in a background thread.This class provides a unique interface to the two interfaces, both
Alpaca's account/trade updates events and Polygon's price updates.
One connection is established when thesubscribe()is called with
the corresponding channel names.  For example, if you subscribe toaccount_updates, a WebSocket connects to Alpaca stream API, and
ifAM.*given to thesubscribe()method, a NATS connection is
established to Polygon's interface.Therunmethod is a short-cut to start subscribing to channels and
runnnig forever.  The call will be blocked forever until a critical
exception is raised, and each event handler is called asynchronously
upon the message arrivals.Therunmethod tries to reconnect to the server in the event of
connection failure.  In this case you may want to reset your state
which is best in theconnectevent.  The method still raises
exception in the case any other unknown error happens inside the
event loop.Themsgobject passed to each handler is wrapped by the entity
helper class if the message is from the server.Each event handler has to be a marked asasync.  Otherwise,
aValueErroris raised when registering it as an event handler.conn=StreamConn()@conn.on(r'account_updates')asyncdefon_account_updates(conn,channel,account):print('account',account)@conn.on(r'^AM.')defon_bars(conn,channel,bar):print('bars',bar)# blocks foreverconn.run(['account_updates','AM.*'])You will likely call therunmethod in a thread since it will keep running
unless an exception is raised.StreamConn.subscribe(channels)Request "listen" to the server.channelsmust be a list of string channel names.StreamConn.run(channels)Goes into an infinite loop and awaits for messages from the server.  You should
set up event listeners using theonorregistermethod before callingrun.StreamConn.on(channel_pat)As in the above example, this is a decorator method to add an event handler function.channel_patis used as a regular expression pattern to filter stream names.StreamConn.register(channel_pat, func)Registers a function as an event handler that is triggered by the stream events
that match withchannel_pathregular expression. Calling this method with the
samechannel_patwill overwrite the old handler.StreamConn.deregister(channel_pat)Deregisters the event handler function that was previously registered viaonorregistermethod.Polygon API ServiceAlpaca's API key ID can be used to access Polygon API whose document is foundhere.
This python SDK wraps their API service and seamlessly integrates with Alpaca API.alpaca_trade_api.REST.polygonwill be theRESTobject for Polygon.The example below gives AAPL daily OHLCV data in a DataFrame format.importalpaca_trade_apiastradeapiapi=tradeapi.REST()aapl=api.polygon.historic_agg('day','AAPL',limit=1000).dfpolygon/RESTIt is initialized through alpacaRESTobject.polygon/REST.exchanges()Returns a list ofExchangeentity.polygon/REST.symbol_type_map()Returns aSymbolTypeMapobject.polygon/REST.historic_trades(symbol, date, offset=None, limit=None)Returns aTradeswhich is a list ofTradeentities.dateis a date string such as '2018-2-2'.  The returned quotes are from this day onyl.offsetis an integer in Unix Epoch millisecond as the lower bound filter, inclusive.limitis an integer for the number of ticks to return.  Default and max is 30000.polygon/Trades.dfReturns a pandas DataFrame object with the ticks returned by thehistoric_trades.polygon/REST.historic_quotes(symbol, date, offset=None, limit=None)Returns aQuoteswhich is a list ofQuoteentities.dateis a date string such as '2018-2-2'. The returned quotes are from this day only.offsetis an integer in Unix Epoch millisecond as the lower bound filter, inclusive.limitis an integer for the number of ticks to return.  Default and max is 30000.polygon/Quotes.dfReturns a pandas DataFrame object with the ticks returned by thehistoric_quotes.polygon/REST.historic_agg(size, symbol, _from=None, to=None, limit=None)Returns anAggswhich is a list ofAggentities.Aggs.dfgives you the DataFrame
object._fromis an Eastern Time timestamp string that filters the result for the lower bound, inclusive.tois an Eastern Time timestamp string that filters the result for the upper bound, inclusive.limitis an integer to limit the number of results.  3000 is the default and max value.Specify the_fromparameter if you specify thetoparameter since whentois
specified_fromis assumed to be the beginning of history.  Otherwise, when you
use only thelimitor no parameters, the result is returned from the latest point.The returned entities have fields relabeled with the longer name instead of shorter ones.
For example, theofield is renamed toopen.polygon/Aggs.dfReturns a pandas DataFrame object with the ticks returned by thehitoric_agg.poylgon/REST.last_trade(symbol)Returns aTradeentity representing the last trade for the symbol.polygon/REST.last_quote(symbol)Returns aQuoteentity representing the last quote for the symbol.polygon/REST.condition_map(ticktype='trades')Returns aConditionMapentity.polygon/REST.company(symbol)Returns aCompanyentity ifsymbolis string, or a
dict[symbol ->Company] ifsymbolis a list of string.polygon/REST.dividends(symbol)Returns aDividendsentity ifsymbolis string, or a
dict[symbol ->Dividends] if `symbol is a list of string.polygon/REST.splits(symbol)Returns aSplitsentity for the symbol.polygon/REST.earnings(symbol)Returns anEarningsentity ifsymbolis string, or a
dict[symbol ->Earnings] ifsymbolis a list of string.polygon/REST.financials(symbol)Returns anFinancialsentity ifsymbolis string, or a
dict[symbol ->Financials] ifsymbolis a list of string.polygon/REST.news(symbol)Returns aNewsListentity for the symbol.Support and ContributionFor 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 pull request is always
welcomed.