### Run pylivetrader example with backend config Source: https://github.com/alpacahq/pylivetrader/blob/master/examples/README.md Execute an example algorithm when API credentials are stored in a config.yaml file. Requires the config file to contain base_url, key_id, and secret parameters. Omit --backend-config config.yaml if credentials are set via environment variables (APCA_API_BASE_URL, APCA_API_KEY_ID, APCA_API_SECRET_KEY). ```bash pylivetrader run path/to/example.py --backend-config config.yaml ``` -------------------------------- ### order() usage example Source: https://github.com/alpacahq/pylivetrader/blob/master/_autodocs/api-reference/algorithm.md Shows placing a market buy and a sell limit order in handle_data. Uses symbol() to get an Asset. ```python from pylivetrader.api import symbol, order def handle_data(context, data): aapl = symbol('AAPL') order_id = order(aapl, 10) # market buy 10 order_id = order(aapl, -10, limit_price=150) # sell limit ``` -------------------------------- ### Install redis-py for Redis Storage Engine Source: https://github.com/alpacahq/pylivetrader/blob/master/README.md Install the `redis-py` library, required to use the redis storage engine for persisting context across restarts in ephemeral file store environments. ```sh $ pip install redis ``` -------------------------------- ### pylivetrader run Source: https://github.com/alpacahq/pylivetrader/blob/master/README.md Starts live trading using your algorithm script. It initializes the algorithm, calls before_trading_start and handle_data functions according to the market schedule, and supports various options for configuration. ```APIDOC ## [CLI] pylivetrader run ### Description Starts live trading using your algorithm script. It calls the `initialize()` function if any, waits until the market opens, calls `before_trading_start` at 8:45 ET (or if started after), and calls `handle_data()` every minute during the session, or any functions registered by `schedule_function`. ### Method CLI command ### Endpoint `pylivetrader run` ### Parameters #### Options - `-f` or `--file` (string) - Required - The file path to the algorithm source - `-b` or `--backend` (string) - Optional - The name of backend to use - `--backend-config` (string) - Optional - The yaml file for backend parameters - `--storage-engine` (string) - Optional - The storage engine to use for persisting the context. ('file' or 'redis') - `-s` or `--statefile` (string) - Optional - The file path to the persisted state file - `-r` or `--retry` (flag) - Optional - The algorithm runner continues execution in the event a general exception is raised - `-l` or `--log-level` (string) - Optional - The minimum level of log which will be written ('DEBUG', 'INFO', 'WARNING', 'ERROR', or 'CRITICAL') ### Request Example ``` pylivetrader run -f algo.py -b my_backend --backend-config config.yaml --storage-engine file -s state.json -r -l INFO ``` ### Response No explicit response documented. ``` -------------------------------- ### Example Backend Configuration File Source: https://github.com/alpacahq/pylivetrader/blob/master/README.md A simple YAML configuration file for the backend, specifying broker API credentials and the data feed. The `feed` can be changed to 'pro' if you have a paid account. ```yaml $ cat config.yaml key_id: BROKER_API_KEY secret: BROKER_SECRET base_url: https://paper-api.alpaca.markets feed: iex # <== change to pro if you have a paid account ``` -------------------------------- ### Order usage example Source: https://github.com/alpacahq/pylivetrader/blob/master/_autodocs/api-reference/finance-execution.md Shows how to create an Order instance and access its status, open flag, and open_amount. Also demonstrates to_dict() which includes 'sid' and 'status' keys. ```python from pylivetrader.finance.order import Order, ORDER_STATUS o = Order(dt=pd.Timestamp.utcnow(), asset=aapl, amount=10, limit=150.0) print(o.status, o.open, o.open_amount) # ORDER_STATUS.OPEN True 10 d = o.to_dict() # includes 'sid' and 'status' keys ``` -------------------------------- ### Run command usage example Source: https://github.com/alpacahq/pylivetrader/blob/master/_autodocs/api-reference/cli.md Shows the basic invocation of the run command with an algorithm file and backend config. ```sh pylivetrader run -f algo.py --backend-config config.yaml ``` -------------------------------- ### Run pylivetrader Algorithm from CLI Source: https://github.com/alpacahq/pylivetrader/blob/master/README.md Command to run an algorithm using the `pylivetrader` CLI tool. It starts the algorithm with the broker API and does not require a data bundle file in advance, unlike zipline. ```sh $ pylivetrader run -f algo.py --backend-config config.yaml ``` -------------------------------- ### order_target() usage example Source: https://github.com/alpacahq/pylivetrader/blob/master/_autodocs/api-reference/algorithm.md Shows ordering to hold exactly 100 shares and liquidating to 0 shares. ```python from pylivetrader.api import order_target, symbol order_target(symbol('AAPL'), 100) # hold exactly 100 shares order_target(symbol('AAPL'), 0) # liquidate ``` -------------------------------- ### Install pylivetrader in a Python 3.6 virtual environment Source: https://github.com/alpacahq/pylivetrader/blob/master/README.md Creates a Python 3.6 virtual environment, activates it, and installs pylivetrader via pip. pylivetrader currently supports only Python 3.6. ```bash $ python3.6 -m venv venv $ source venv/bin/activate (venv)$ pip install pylivetrader ``` -------------------------------- ### Usage example: loading an algorithm and creating an Algorithm instance Source: https://github.com/alpacahq/pylivetrader/blob/master/_autodocs/api-reference/loader.md This shows the typical workflow for loading an algorithm script and constructing a pylivetrader Algorithm. It mirrors the CLI's internal paths: load the module namespace from a file, extract the API functions, then pass them to the Algorithm constructor. ```python from pylivetrader.loader import get_algomodule_by_path, get_api_functions module_ns = get_algomodule_by_path('algo.py') functions = get_api_functions(module_ns) from pylivetrader import Algorithm algo = Algorithm(**functions) ``` -------------------------------- ### initialize(self, *args, **kwargs) Source: https://github.com/alpacahq/pylivetrader/blob/master/_autodocs/api-reference/algorithm.md Initializes the algorithm by loading persisted state, calling the user-defined initialize callback, and saving state. This method is called automatically before trading starts. ```APIDOC ## initialize(self, *args, **kwargs) ### Description Initializes the algorithm by loading persisted state, calling the user-defined initialize callback, and saving state. This method is called automatically before trading starts. ### Method initialize ### Signature `def initialize(self, *args, **kwargs)` ### Parameters - `*args, **kwargs` (any) - Optional - Forwarded to the user `initialize` callback. ### Behavior - Captures the current `__dict__` (plus `'executor'`) as the persistence-exclusion list. - Loads persisted state via `StateStore.load`. - Calls the user `initialize` inside a `LiveTraderAPI` context. - Saves state and sets `initialized = True`. ### Errors - Raises `ValueError` from `StateStore.load` on checksum mismatch (state file produced by a different algorithm name). ``` -------------------------------- ### order() error handling example Source: https://github.com/alpacahq/pylivetrader/blob/master/_autodocs/api-reference/algorithm.md Catches UnsupportedOrderParameters when both limit_price and style are provided. Shows importing errors from pylivetrader.errors. ```python from pylivetrader.api import order, symbol from pylivetrader.errors import OrderInBeforeTradingStart, UnsupportedOrderParameters def handle_data(context, data): try: order(symbol('AAPL'), 5, limit_price=120, style=None) except UnsupportedOrderParameters: print('use limit_price or style, not both') ``` -------------------------------- ### can_trade usage example Source: https://github.com/alpacahq/pylivetrader/blob/master/_autodocs/api-reference/data.md Shows how to use can_trade to conditionally order an asset. ```python if data.can_trade(symbol('AAPL')): order_target(symbol('AAPL'), 10) ``` -------------------------------- ### Usage example with order() and execution styles Source: https://github.com/alpacahq/pylivetrader/blob/master/_autodocs/api-reference/finance-execution.md Shows how to place limit and stop-limit orders using the pylivetrader API. The order() function accepts a style parameter; LimitOrder(150.0) sets a limit buy at <=150, StopLimitOrder(145.0, 140.0) sets a stop-limit. ```python from pylivetrader.api import order, symbol from pylivetrader.finance.execution import LimitOrder, StopLimitOrder def handle_data(context, data): aapl = symbol('AAPL') order(aapl, 10, style=LimitOrder(150.0)) # limit buy at <=150 order(aapl, 10, style=StopLimitOrder(145.0, 140.0)) # stop-limit ``` -------------------------------- ### Basic order and asset lookup (macd_example.py) Source: https://github.com/alpacahq/pylivetrader/blob/master/_autodocs/api-reference/api.md Example from examples/MACD/macd_example.py showing how to use order_target, record, and symbol. It computes a MACD from 1-minute price history and places an order if the MACD is positive, recording the current price. ```python from pylivetrader.api import order_target, record, symbol def initialize(context): context.asset = symbol('AA') def handle_data(context, data): short_data = data.history( context.asset, 'price', bar_count=12, frequency="1m") macd = short_data.mean() if macd > 0: order_id = order_target(context.asset, 100) if order_id: print("bought", order_id) record(AA=data.current(context.asset, 'price')) ``` -------------------------------- ### run(self, retry=True) Source: https://github.com/alpacahq/pylivetrader/blob/master/_autodocs/api-reference/algorithm.md Starts the algorithm execution loop. This method initializes the algorithm if needed, creates an executor, and runs it indefinitely until interrupted. ```APIDOC ## run(self, retry=True) ### Description Starts the algorithm execution loop. This method initializes the algorithm if needed, creates an executor, and runs it indefinitely until interrupted. ### Method run ### Signature `def run(self, retry=True)` ### Parameters - `retry` (bool) - Optional - Default: `True`. When `True`, per-bar callbacks that raise are logged and execution continues; `False` re-raises. ### Returns - The result of `AlgorithmExecutor.run(retry)` (an infinite iteration over the realtime clock; effectively runs forever until interrupted). ### Behavior - Logs start. - Preloads the asset universe (`_assets_from_source`). - Calls `initialize()` if not yet initialized. - Creates `AlgorithmExecutor(self, self.data_portal)` and returns `self.executor.run(retry=retry)`. ``` -------------------------------- ### Configuration file for Alpaca API credentials Source: https://github.com/alpacahq/pylivetrader/blob/master/examples/MACD/README.md YAML configuration file containing Alpaca API credentials and settings. Required when environment variables are not set. Replace placeholders with your actual API key and secret. ```yaml key_id: secret: base_url: https://paper-api.alpaca.markets feed: iex ``` -------------------------------- ### Error handling example with BadOrderParameters Source: https://github.com/alpacahq/pylivetrader/blob/master/_autodocs/api-reference/finance-execution.md Demonstrates catching BadOrderParameters when creating a LimitOrder with a non-finite price. The error message is "Attempted to place an order with a limit price of nan." ```python from pylivetrader.finance.execution import LimitOrder from pylivetrader.errors import BadOrderParameters try: LimitOrder(float('nan')) except BadOrderParameters as e: print(e) # "Attempted to place an order with a limit price of nan." ``` -------------------------------- ### history method usage example Source: https://github.com/alpacahq/pylivetrader/blob/master/_autodocs/api-reference/data.md Shows how to call history to get mean of price over 100 and 300 bars. ```python short = data.history(context.asset, 'price', bar_count=100, frequency="1m").mean() long = data.history(context.asset, 'price', bar_count=300, frequency="1m").mean() ``` -------------------------------- ### Configure Alpaca backend via environment variables and run pylivetrader Source: https://github.com/alpacahq/pylivetrader/blob/master/README.md Sets the Alpaca API credentials and base URL as environment variables, then runs the algorithm with `pylivetrader run -f algo.py`. The base URL must be either the live or paper trading endpoint. ```bash $ export APCA_API_KEY_ID={your api key id} $ export APCA_API_SECRET_KEY={your api secret key} $ export APCA_API_BASE_URL={https://api.alpaca.markets/ or https://paper-api.alpaca.markets} $ pylivetrader run -f algo.py ``` -------------------------------- ### Run pylivetrader shell with an algorithm file Source: https://github.com/alpacahq/pylivetrader/blob/master/README.md Starts an IPython interactive shell in the algorithm script namespace, allowing calls to Algorithm API functions like symbol() and data.history(). The -f option specifies the algorithm source file. ```bash $ pylivetrader shell algo.py ``` -------------------------------- ### Configure Alpaca backend via config file (YAML) and run pylivetrader Source: https://github.com/alpacahq/pylivetrader/blob/master/README.md Shows a YAML config file with `key_id`, `secret`, and `base_url` keys, then runs the algorithm with `--backend-config config.yaml`. The config file can be YAML or JSON. ```bash $ cat config.yaml key_id: {your api key id} secret: {your api secret key} base_url: {https://api.alpaca.markets/ or https://paper-api.alpaca.markets} $ pylivetrader run -f algo.py --backend-config config.yaml ``` -------------------------------- ### Using run_smoke with before_run_hook Source: https://github.com/alpacahq/pylivetrader/blob/master/_autodocs/api-reference/testing.md Example from the README showing how to call run_smoke with a before_run_hook that sets a position on the backend before the algorithm runs. ```python from pylivetrader.testing.smoke import harness def before_run(context, backend): backend.set_position('A', 10, 200) def test_algo(): harness.run_smoke(algo, before_run_hook=before_run) ``` -------------------------------- ### shell command implementation in __main__.py Source: https://github.com/alpacahq/pylivetrader/blob/master/_autodocs/api-reference/cli.md Click command that opens an interactive shell. It processes shell parameters, builds an Algorithm with defaults, and starts the shell with LiveTraderAPI. ```py @click.command(help="opens an interactive shell for the user to try the interface") @shell_parameters @click.pass_context def shell(ctx, **kwargs): # __main__.py:284 ctx = process_shell_params(ctx, **kwargs) algorithm = ctx.algorithm algomodule = ctx.algomodule with LiveTraderAPI(algorithm): start_shell(algorithm, algomodule) ``` -------------------------------- ### Dual Moving Average Algorithm with pylivetrader API Source: https://github.com/alpacahq/pylivetrader/blob/master/README.md Example algorithm using the pylivetrader API, which provides zipline-compatible interfaces. It computes short and long moving averages from price history and places orders based on their crossover. The `data.history()` method must be called with the same parameters and returns a pandas dataframe. ```python from pylivetrader.api import order_target, symbol def initialize(context): context.i = 0 context.asset = symbol('AAPL') def handle_data(context, data): # Compute averages # data.history() has to be called with the same params # from above and returns a pandas dataframe. short_mavg = data.history(context.asset, 'price', bar_count=100, frequency="1m").mean() long_mavg = data.history(context.asset, 'price', bar_count=300, frequency="1m").mean() # Trading logic if short_mavg > long_mavg: # order_target orders as many shares as needed to # achieve the desired number of shares. order_target(context.asset, 100) elif short_mavg < long_mavg: order_target(context.asset, 0) ``` -------------------------------- ### pylivetrader shell Source: https://github.com/alpacahq/pylivetrader/blob/master/_autodocs/configuration.md CLI command to start an interactive shell with the specified backend and configuration. ```APIDOC ## pylivetrader shell ### Description CLI command to start an interactive shell with the specified backend and configuration. ### Options - `-f`, `--file` (path) - Required - algorithm script path - `-b`, `--backend` (str) - Optional - backend name (default `'alpaca'`) - `--backend-config` (path) - Optional - yaml/json backend config ``` -------------------------------- ### Using DefaultPipelineHooker with run_smoke Source: https://github.com/alpacahq/pylivetrader/blob/master/_autodocs/api-reference/testing.md Example from the README showing how to pass a DefaultPipelineHooker instance as the pipeline_hook to run_smoke. ```python pipeline = harness.DefaultPipelineHooker() harness.run_smoke(algo, before_run_hook=before_run, pipeline_hook=pipeline) ``` -------------------------------- ### Build pylivetrader Docker image from source Source: https://github.com/alpacahq/pylivetrader/blob/master/README.md Builds a development Docker image from the `dockerfiles/Dockerfile-dev` file. This allows running locally and editing or debugging the code. ```bash docker build -t alpaca/pylivetrader-dev -f dockerfiles/Dockerfile-dev . ``` -------------------------------- ### Asset usage example Source: https://github.com/alpacahq/pylivetrader/blob/master/_autodocs/api-reference/assets.md Shows creating an Equity asset, checking sid-based equality, converting to dict, and printing with exchange-open check. Requires pandas for the timestamp. ```python from pylivetrader.assets import Asset, Equity a = Equity('7124', 'NYSE', symbol='AAPL', asset_name='AAPL') assert a.sid == Equity('7125', 'NYSE', symbol='GOOG').sid or True # equality is sid-based d = a.to_dict() print(a, a.is_exchange_open(__import__('pandas').Timestamp('now', tz='UTC'))) ``` -------------------------------- ### current method usage example Source: https://github.com/alpacahq/pylivetrader/blob/master/_autodocs/api-reference/data.md Shows how to call current with a single asset and a list of assets. The first returns a scalar, the second returns a Series indexed by asset. ```python def handle_data(context, data): price = data.current(context.asset, 'price') # scalar px = data.current([context.asset], 'price') # Series indexed by asset ``` -------------------------------- ### Example: accessing a position by asset Source: https://github.com/alpacahq/pylivetrader/blob/master/_autodocs/api-reference/protocol.md Shows how to access a position from the portfolio's positions using an asset symbol. Returns a real or all-zero Position. ```python pos = context.portfolio.positions[symbol('AAPL')] # real or all-zero Position ``` -------------------------------- ### Run pylivetrader with Redis Storage Engine Source: https://github.com/alpacahq/pylivetrader/blob/master/README.md Command to run pylivetrader with the redis storage engine, which serializes the context object to and from redis. Assumes redis is running. ```sh $ pylivetrader run -f algo.py --backend-config config.yaml --storage-engine redis ``` -------------------------------- ### Advanced usage example Source: https://github.com/alpacahq/pylivetrader/blob/master/_autodocs/api-reference/executor.md Shows how to run the algorithm without the CLI. Creates an Algorithm instance with initialize, handle_data, backend, and data_frequency, then calls run with retry=False to propagate algorithm exceptions. ```python from pylivetrader import Algorithm from pylivetrader.executor.executor import AlgorithmExecutor algo = Algorithm( initialize=initialize, handle_data=handle_data, backend=my_backend, data_frequency='minute', ) algo.run(retry=False) # propagates algorithm exceptions ``` -------------------------------- ### pylivetrader migrate Source: https://github.com/alpacahq/pylivetrader/blob/master/README.md Migrates quantopian/zipline code to pylivetrader compatible code. It takes an input file and outputs a compatible file that can be executed with the run command. ```APIDOC ## [CLI] pylivetrader migrate ### Description Allows you to easily migrate your quantopian/zipline code to pylivetrader compatible code. The output file can be executed with the `run` command. ### Method CLI command ### Endpoint `pylivetrader migrate` ### Parameters #### Options - `-i` (string) - Required - The input file path (zipline code) - `-o` (string) - Required - The output file path (pylivetrader compatible code) ### Request Example ``` pylivetrader migrate -i zipline_code.py -o pylivetrader_compatible.py ``` ### Response No explicit response documented. ``` -------------------------------- ### Run pylivetrader algorithm in Docker container Source: https://github.com/alpacahq/pylivetrader/blob/master/README.md Runs the `alpacamarkets/pylivetrader` Docker image, mounting the current directory and setting the working directory to `/work`. The algorithm file must be named `algo.py`; backend environment variables must be set with `-e KEY=VAL`. ```sh docker run -v $PWD:/work -w /work alpacamarkets/pylivetrader pylivetrader run -f algo.py ``` -------------------------------- ### pipeline_output(name) Source: https://github.com/alpacahq/pylivetrader/blob/master/_autodocs/api-reference/algorithm.md Returns the output of a previously attached pipeline as a pandas DataFrame. If a pipeline hook is set, it delegates to that hook; otherwise it requires the `pipeline_live` engine and raises an error if not installed. ```APIDOC ## pipeline_output(name) ### Description Returns the output of a previously attached pipeline as a pandas DataFrame. If a pipeline hook is set, it delegates to that hook; otherwise it requires the `pipeline_live` engine and raises an error if not installed. ### Method Function call ### Endpoint `pipeline_output(name)` ### Parameters - **name** (str) - Required - Name of the attached pipeline. ### Returns - **pd.DataFrame** - The pipeline output. ### Errors - **RuntimeError** - Raised if `pipeline_live` is not installed. ``` -------------------------------- ### Instantiate and run Algorithm with pylivetrader Source: https://github.com/alpacahq/pylivetrader/blob/master/_autodocs/api-reference/algorithm.md Creates an Algorithm instance with Alpaca backend, minute data frequency, and custom callbacks, then runs it. Requires initialize, handle_data, and optionally before_trading_start functions to be defined. Uses paper trading base URL and IEX feed. ```python from pylivetrader import Algorithm algo = Algorithm( backend='alpaca', backend_options={'key_id': 'KEY', 'secret': 'SECRET', 'base_url': 'https://paper-api.alpaca.markets', 'feed': 'iex'}, data_frequency='minute', initialize=initialize, handle_data=handle_data, before_trading_start=before_trading_start, statefile='algo-state.pkl', log_level='INFO', ) algo.run() ``` -------------------------------- ### Algorithm constructor signature Source: https://github.com/alpacahq/pylivetrader/blob/master/_autodocs/api-reference/algorithm.md Constructor accepts all configuration via **kwargs. Parameters include data_frequency, algoname, backend, backend_options, trading_calendar, initialize, handle_data, before_trading_start, log_level, storage_engine, statefile, quantopian_compatible, and pipeline_hook. Building the instance also constructs StateStore, AssetFinder, DataPortal, EventManager, and registers the handle_data event. ```python def __init__(self, *args, **kwargs): ``` -------------------------------- ### Smoke test an algorithm with pylivetrader.testing.smoke Source: https://github.com/alpacahq/pylivetrader/blob/master/README.md Defines a `before_run` hook that sets an existing position and wraps `initialize` to modify context fields, then runs the algorithm with `harness.run_smoke`. The `DefaultPipelineHooker` provides synthetic pipeline results. The backend creates a universe of 50 stocks ('A'..'AX') and simulates a market day; works with pytest and supports line coverage. ```py import algo from pylivetrader.testing.smoke import harness def before_run(context, backend): '''This hook is called before algorithm starts.''' # Populate existing position backend.set_position( 'A', 10, 200, ) # modify some fields of context after `initialize(context)` is called _init = context._initialize def wrapper(ctx): _init(ctx) ctx.age[ctx.symbol('A')] = 3 ctx.age[ctx.symbol('B')] = 2 context._initialize = wrapper def test_algo(): pipeline = harness.DefaultPipelineHooker() # run the algorithm under the simulation environment harness.run_smoke(algo, before_run_hook=before_run, pipeline_hook=pipeline, ) if __name__ == '__main__': import logging logging.basicConfig(level=logging.DEBUG) test_algo() ``` -------------------------------- ### before_trading_start(self, data) Source: https://github.com/alpacahq/pylivetrader/blob/master/_autodocs/api-reference/algorithm.md Prepares the algorithm for the trading day by calling the user-defined before_trading_start callback and saving state. This method is called before market open. ```APIDOC ## before_trading_start(self, data) ### Description Prepares the algorithm for the trading day by calling the user-defined before_trading_start callback and saving state. This method is called before market open. ### Method before_trading_start ### Signature `def before_trading_start(self, data)` ### Parameters - `data` (BarData) - Required - The current bar data. ### Behavior - Sets `_in_before_trading_start = True`. - Wraps the call with `handle_non_market_minutes(data)` when in minute mode (so spot lookups resolve to the previous market minute). - Calls the user callback. - Saves state and resets the flag. ``` -------------------------------- ### AssetFinder usage example Source: https://github.com/alpacahq/pylivetrader/blob/master/_autodocs/api-reference/assets.md Example of using AssetFinder to look up a symbol and retrieve the asset. The symbol is upper-cased by Algorithm.symbol() before lookup. ```python from pylivetrader.assets import AssetFinder finder = AssetFinder(alpaca_backend) aapl = finder.lookup_symbol('aapl') # 'aapl' is upper-cased by Algorithm.symbol() before this assert finder.retrieve_asset(aapl.sid) == aapl ``` -------------------------------- ### Backend.__init__ options Source: https://github.com/alpacahq/pylivetrader/blob/master/_autodocs/configuration.md Configuration options for the Alpaca backend constructor. These parameters can be passed directly or set via environment variables. ```APIDOC ## Backend.__init__ options ### Description Configuration options for the Alpaca backend constructor. These parameters can be passed directly or set via environment variables. ### Parameters - `key_id` (str) - Optional - API key id (else `APCA_API_KEY_ID`) - `secret` (str) - Optional - API secret (else `APCA_API_SECRET_KEY`) - `base_url` (str) - Optional - REST base URL (else `APCA_API_BASE_URL`); e.g. `https://paper-api.alpaca.markets` - `api_version` (str) - Optional - broker API version (default `'v2'`) - `feed` (str) - Optional - websocket data feed; `'iex'` or `'pro'` (paid account) (default `'iex'`) ``` -------------------------------- ### run_smoke Source: https://github.com/alpacahq/pylivetrader/blob/master/_autodocs/configuration.md Runs a smoke test for a given algorithm. It accepts optional hooks for before-run and pipeline setup. ```APIDOC ## run_smoke ### Description Runs a smoke test for a given algorithm. It accepts optional hooks for before-run and pipeline setup. ### Method run_smoke ### Endpoint pylivetrader.testing.smoke.harness.run_smoke ### Parameters - **algo** (object) - Required - The algorithm to test. - **before_run_hook** (callable) - Optional - Hook called before the run. - **pipeline_hook** (callable) - Optional - Hook for pipeline setup. ``` -------------------------------- ### schedule_function Usage Source: https://github.com/alpacahq/pylivetrader/blob/master/_autodocs/api-reference/misc-events.md Example usage of schedule_function with time_rules and date_rules to schedule functions in a trading algorithm. ```APIDOC ## schedule_function Usage ### Description Example usage of schedule_function with time_rules and date_rules to schedule functions in a trading algorithm. ### Example ```py from pylivetrader.api import schedule_function, time_rules, date_rules def initialize(context): # every minute (default when called from handle_data context) schedule_function(my_func) # 30 minutes after market open schedule_function(my_func, time_rule=time_rules.market_open(minutes=30)) # on the last trading day of the month at market close schedule_function(my_func, date_rule=date_rules.month_end(), time_rule=time_rules.market_close()) ``` ``` -------------------------------- ### Instantiate Alpaca Backend from configuration Source: https://github.com/alpacahq/pylivetrader/blob/master/_autodocs/api-reference/backend.md Shows how to create a Backend instance directly with Alpaca credentials. The Algorithm builds backends by module name via importlib, falling back to a global import path, then instantiates backendmod.Backend(**backend_options). A missing module raises RuntimeError("Could not find backend package `{name}`."). ```python from pylivetrader.backend.alpaca import Backend be = Backend( key_id='KEY', secret='SECRET', base_url='https://paper-api.alpaca.markets', api_version='v2', feed='iex', ) print(be.portfolio.portfolio_value) ``` -------------------------------- ### continuous_future Source: https://github.com/alpacahq/pylivetrader/blob/master/_autodocs/api-reference/api.md Gets a continuous future contract. Must be called within an active LiveTraderAPI context. ```APIDOC ## continuous_future ### Description Gets a continuous future contract. Must be called within an active LiveTraderAPI context. ### Method Function call ### Endpoint `continuous_future(symbol, offset=None, roll=None)` ### Parameters - **symbol** (string) - Required - The symbol of the future. - **offset** (int) - Optional - The offset from the current contract. - **roll** (string) - Optional - The rollover rule. ### Response Returns the continuous future object. ``` -------------------------------- ### Backend.__init__ Source: https://github.com/alpacahq/pylivetrader/blob/master/_autodocs/api-reference/backend.md Initializes the Alpaca backend with API credentials and configuration. This constructor sets up the REST client, calendar, and internal order tracking. ```APIDOC ## Backend.__init__ ### Description Initializes the Alpaca backend with API credentials and configuration. This constructor sets up the REST client, calendar, and internal order tracking. ### Method Constructor ### Signature ```py Backend( key_id=None, secret=None, base_url=None, api_version='v2', feed='iex' ) ``` ### Parameters - **key_id** (str) - Optional - Alpaca API key id (falls back to `APCA_API_KEY_ID` inside `alpaca_trade_api.REST`) - **secret** (str) - Optional - API secret (`APCA_API_SECRET_KEY`) - **base_url** (str) - Optional - REST base URL (`APCA_API_BASE_URL`); `https://paper-api.alpaca.markets` for paper trading - **api_version** (str) - Optional - broker API version (default `'v2'`) - **feed** (str) - Optional - data feed; `'iex'` or `'pro'` (paid) — used for the websocket `Stream` data_feed (default `'iex'`) ### Notes - Constants: `ALPACA_MAX_SYMBOLS_PER_REQUEST = 199`, `NY = 'America/New_York'`, `end_offset = pd.Timedelta('1000 days')`, `one_day_offset = pd.Timedelta('1 day')` ``` -------------------------------- ### start_shell function in pylivetrader/shell.py Source: https://github.com/alpacahq/pylivetrader/blob/master/_autodocs/api-reference/cli.md Injects context and data (a fresh BarData) into the algorithm module namespace, calls initialize(algorithm), and embeds an IPython shell with the given banner. ```py def start_shell(algorithm, algomodule): algomodule['context'] = algorithm algomodule['data'] = BarData(algorithm.data_portal, algorithm.data_frequency) algorithm.on_dt_changed(pd.Timestamp.utcnow().floor('1min')) algomodule['data'].datetime = algorithm.datetime algomodule['initialize'](algorithm) InteractiveShellEmbed()('*** pylivetrader shell ***', local_ns=algomodule) ``` -------------------------------- ### Asset.is_alive_for_session(session_label) Source: https://github.com/alpacahq/pylivetrader/blob/master/_autodocs/api-reference/assets.md Checks whether the asset is alive for the given trading session, based on its start and end dates. ```APIDOC ## Asset.is_alive_for_session(session_label) ### Description Checks whether the asset is alive for the given trading session, based on its start and end dates. ### Parameters - **session_label** (pd.Timestamp) - The trading session label. ### Returns - **bool** - True if `start_date.value <= session_label.value <= end_date.value`, False otherwise. ### Example ```py from pylivetrader.assets import Equity a = Equity('7124', 'NYSE', symbol='AAPL', start_date=pd.Timestamp('2020-01-01'), end_date=pd.Timestamp('2021-01-01')) print(a.is_alive_for_session(pd.Timestamp('2020-06-01'))) ``` ``` -------------------------------- ### Run command with config file and redis persistence Source: https://github.com/alpacahq/pylivetrader/blob/master/_autodocs/api-reference/cli.md Shows how to run the algorithm using a config file and redis storage engine. ```sh # or via a config file, with redis persistence pylivetrader run -f algo.py --backend-config config.yaml --storage-engine redis ``` -------------------------------- ### pylivetrader shell Source: https://github.com/alpacahq/pylivetrader/blob/master/README.md Enters an IPython interactive shell mode as if you are in the algorithm script namespace, allowing you to call Algorithm API such as symbol() and data.history() to check behavior. ```APIDOC ## [CLI] pylivetrader shell ### Description Goes into the IPython interactive shell mode as if you are in the algorithm script namespace. You can call Algorithm API such as `symbol()` and `data.history()` to check the behavior of each operation. ### Method CLI command ### Endpoint `pylivetrader shell` ### Parameters #### Options - `-f` or `--file` (string) - Required - The file path to the algorithm source - `-b` or `--backend` (string) - Optional - The name of backend to use - `--backend-config` (string) - Optional - The yaml file for backend parameters ### Request Example ``` pylivetrader shell algo.py ``` ### Response No explicit response documented. ``` -------------------------------- ### Convert Python 2 script to Python 3 with 2to3 Source: https://github.com/alpacahq/pylivetrader/blob/master/migration.md Run the 2to3 command to convert your Python 2 algorithm script to Python 3. The original file is saved as algo.py.bak. ```sh $ 2to3 -w algo.py ``` -------------------------------- ### pylivetrader migrate command Source: https://github.com/alpacahq/pylivetrader/blob/master/_autodocs/api-reference/cli.md Migrates a Quantopian/Zipline algorithm to pylivetrader. Requires -i/--in-file (must exist) and -o/--out-file (must not exist yet). Runs the migration pipeline from pylivetrader.misc.migration_tool with animated progress output; exceptions are re-raised as click.ClickException. ```sh pylivetrader migrate -i zipline_code.py -o pylivetrader_compatible.py ``` -------------------------------- ### Run command with environment variables Source: https://github.com/alpacahq/pylivetrader/blob/master/_autodocs/api-reference/cli.md Shows how to run the algorithm using broker credentials from environment variables. ```sh # broker credentials via environment export APCA_API_KEY_ID=... export APCA_API_SECRET_KEY=... export APCA_API_BASE_URL=https://paper-api.alpaca.markets pylivetrader run -f algo.py ``` -------------------------------- ### before_run hook to set existing positions and initialize context Source: https://github.com/alpacahq/pylivetrader/blob/master/_autodocs/api-reference/testing.md Exercises the algorithm code path that accepts existing positions, as shown in the README pattern. Sets position 'A' with amount 10 and cost basis 200, then wraps the context's _initialize to set age values for symbols 'A' and 'B'. ```py def before_run(context, backend): backend.set_position('A', 10, 200) _init = context._initialize def wrapper(ctx): _init(ctx) ctx.age[ctx.symbol('A')] = 3 ctx.age[ctx.symbol('B')] = 2 context._initialize = wrapper ``` -------------------------------- ### AssetFinder error handling Source: https://github.com/alpacahq/pylivetrader/blob/master/_autodocs/api-reference/assets.md Example of handling SymbolNotFound error when looking up a non-existent symbol. The error message is "Symbol 'ZZZZ' was not found". ```python from pylivetrader.errors import SymbolNotFound, SidsNotFound try: finder.lookup_symbol('ZZZZ') except SymbolNotFound as e: print(e) # "Symbol 'ZZZZ' was not found" ``` -------------------------------- ### order() API method signature Source: https://github.com/alpacahq/pylivetrader/blob/master/_autodocs/api-reference/algorithm.md Core method to place market, limit, or stop orders. Requires an Asset; positive amount buys, negative sells. Returns order id or None on failure. Throws OrderDuringInitialize, UnsupportedOrderParameters, OrderInBeforeTradingStart, or TradingControlViolation. ```python @api_method @disallowed_in_before_trading_start(OrderInBeforeTradingStart()) def order( self, asset, amount, limit_price=None, stop_price=None, style=None): ``` -------------------------------- ### register_account_control(control) Source: https://github.com/alpacahq/pylivetrader/blob/master/_autodocs/api-reference/algorithm.md Registers an account control. Raises RegisterAccountControlPostInit if called after initialize. ```APIDOC ## register_account_control(control) ### Description Registers an account control. Raises RegisterAccountControlPostInit if called after initialize. ### Parameters - **control** - The account control object to register. ### Returns - None ``` -------------------------------- ### Run pylivetrader with state store from CLI Source: https://github.com/alpacahq/pylivetrader/blob/master/_autodocs/api-reference/statestore.md Commands to run a pylivetrader algorithm with file-based or Redis persistence. Use --storage-engine redis for Redis persistence. ```sh $ pylivetrader run -f algo.py --backend-config config.yaml # or with redis persistence: $ pylivetrader run -f algo.py --backend-config config.yaml --storage-engine redis ``` -------------------------------- ### Iterate open orders from context.get_open_orders() Source: https://github.com/alpacahq/pylivetrader/blob/master/_autodocs/api-reference/protocol.md Shows how to iterate over the open orders returned by context.get_open_orders(). For each asset and order, prints order.id, order.amount, order.dt, and order.status. ```python orders = context.get_open_orders() for asset, order_list in orders.items(): for order in order_list: print(order.id, order.amount, order.dt, order.status) ``` -------------------------------- ### order(asset, amount, limit_price=None, stop_price=None, style=None) Source: https://github.com/alpacahq/pylivetrader/blob/master/_autodocs/api-reference/algorithm.md Places an order for the given asset and amount. Supports market, limit, stop, and stop-limit orders via optional parameters. ```APIDOC ## order(asset, amount, limit_price=None, stop_price=None, style=None) ### Description Places an order for the given asset and amount. Supports market, limit, stop, and stop-limit orders via optional parameters. ### Method Function call ### Endpoint `order(asset, amount, limit_price=None, stop_price=None, style=None)` ### Parameters - `asset` (Asset) - Required - Must be an `Asset`; pass `symbol()`/`sid()` results. - `amount` (int/float) - Required - Positive = buy, negative = sell; rounded via `round_order`. - `limit_price` (float) - Optional - Converts to a `LimitOrder`/`StopLimitOrder` style. - `stop_price` (float) - Optional - Converts to a `StopOrder`/`StopLimitOrder` style. - `style` (ExecutionStyle) - Optional - Explicit style; mutually exclusive with `limit_price`/`stop_price`. ### Returns Order id (`str`) on success, or `None` when the asset cannot be ordered, the rounded amount is 0, the backend rejects the order, or `amount > self._max_shares` is impossible. ### Throws - `OrderDuringInitialize` — before initialization completes. - `UnsupportedOrderParameters` — non-`Asset` argument, or `style` combined with `limit_price`/`stop_price`. - `OrderInBeforeTradingStart` — inside `before_trading_start`. - `TradingControlViolation` — a registered trading control fails with `on_error='fail'`. ### Example ```py from pylivetrader.api import symbol, order def handle_data(context, data): aapl = symbol('AAPL') order_id = order(aapl, 10) # market buy 10 order_id = order(aapl, -10, limit_price=150) # sell limit ``` ### Error Handling Example ```py from pylivetrader.api import order, symbol from pylivetrader.errors import OrderInBeforeTradingStart, UnsupportedOrderParameters def handle_data(context, data): try: order(symbol('AAPL'), 5, limit_price=120, style=None) except UnsupportedOrderParameters: print('use limit_price or style, not both') ``` ``` -------------------------------- ### record(*args, **kwargs) Source: https://github.com/alpacahq/pylivetrader/blob/master/_autodocs/api-reference/algorithm.md Records name/value pairs into `_recorded_vars`, accessible via `context.recorded_vars`. Supports both positional pairs and keyword arguments. ```APIDOC ## record(*args, **kwargs) ### Description Records name/value pairs into `_recorded_vars`, accessible via `context.recorded_vars`. Supports both positional pairs and keyword arguments. ### Method record(*args, **kwargs) ### Parameters - **args** - Required - Alternating name and value pairs, e.g., `record('a', 1, 'b', 2)`. - **kwargs** - Optional - Keyword arguments representing name/value pairs, e.g., `record(a=1, b=2)`. ### Returns None ``` -------------------------------- ### Backend Source: https://github.com/alpacahq/pylivetrader/blob/master/_autodocs/configuration.md Creates a backend instance for the smoke test with configurable cash, size, and clock. ```APIDOC ## Backend ### Description Creates a backend instance for the smoke test with configurable cash, size, and clock. ### Method Backend ### Endpoint backend.Backend ### Parameters - **cash** (float) - Optional - Initial cash amount. Default is 1e6. - **size** (int) - Optional - Size parameter. Default is 50. - **clock** (object) - Optional - Clock object for time simulation. ``` -------------------------------- ### Shorthand trading control API methods Source: https://github.com/alpacahq/pylivetrader/blob/master/_autodocs/api-reference/algorithm.md Defines shorthand methods for registering trading controls, all usable only before initialize. Each method maps to a specific control class and accepts parameters like max_leverage, max_shares, max_notional, on_error, etc. ```python def set_max_leverage(self, max_leverage): # algorithm.py:911 -> MaxLeverage account control def set_max_position_size(self, asset=None, max_shares=None, max_notional=None, on_error='fail'): # algorithm.py:935 -> MaxPositionSize def set_max_order_size(self, asset=None, max_shares=None, max_notional=None, on_error='fail'): # algorithm.py:969 -> MaxOrderSize def set_max_order_count(self, max_count, on_error='fail'): # algorithm.py:998 -> MaxOrderCount def set_do_not_order_list(self, restricted_list, on_error='fail'): # algorithm.py:1011 (deprecated) def set_asset_restrictions(self, restrictions, on_error='fail'): # algorithm.py:1047 -> RestrictedListOrder def set_long_only(self, on_error='fail'): # algorithm.py:1064 -> LongOnly ``` -------------------------------- ### RealtimeClock iteration loop Source: https://github.com/alpacahq/pylivetrader/blob/master/_autodocs/api-reference/executor.md Infinite loop that yields events synchronized to wall time. Handles non-session days, session start, before-trading-start, minute bars, minute end, and session end. Raises RuntimeError on invalid state. ```python while True: current_time = pd.to_datetime('now', utc=True) server_time = (current_time + self.time_skew).floor('1 min') ... ``` -------------------------------- ### batch_order() implementation Source: https://github.com/alpacahq/pylivetrader/blob/master/_autodocs/api-reference/algorithm.md Places multiple orders from a list of positional-argument tuples for order(). Returns a list of order ids or Nones. ```python @api_method def batch_order(self, order_arg_list): return [self.order(*order_args) for order_args in order_arg_list] ``` -------------------------------- ### Backend class constructor with cash, size, clock parameters Source: https://github.com/alpacahq/pylivetrader/blob/master/_autodocs/api-reference/testing.md Minimal simulator backend for smoke testing with naive order filling and synthetic price data. Constructor accepts initial cash (default 1e6), number of synthetic stocks (default 50), and an optional FaketimeClock for fill simulation. ```py class Backend(BaseBackend): '''This backend is a minimal simulator with naive order filling for mainly smoke testing. The price data is supplied by fake data generator.''' def __init__(self, cash=1e6, size=50, clock=None): ``` -------------------------------- ### Using StaticRestrictions and HistoricalRestrictions Source: https://github.com/alpacahq/pylivetrader/blob/master/_autodocs/api-reference/finance-controls.md Example usage of StaticRestrictions and HistoricalRestrictions. StaticRestrictions checks membership in a frozenset regardless of date; HistoricalRestrictions checks state as of a given date based on effective dates. Combining with | returns a _UnionRestrictions. ```python from pylivetrader.finance.asset_restrictions import ( Restriction, RESTRICTION_STATES, StaticRestrictions, HistoricalRestrictions, ) s = StaticRestrictions([aapl, msft]) assert s.is_restricted(aapl, pd.Timestamp('2020-01-01')) h = HistoricalRestrictions([ Restriction(aapl, pd.Timestamp('2020-01-01'), RESTRICTION_STATES.ALLOWED), Restriction(aapl, pd.Timestamp('2020-06-01'), RESTRICTION_STATES.FROZEN), ]) assert h.is_restricted(aapl, pd.Timestamp('2020-07-01')) assert not h.is_restricted(aapl, pd.Timestamp('2020-03-01')) combined = s | h # _UnionRestrictions ``` -------------------------------- ### RedisStore class for Redis-based state persistence Source: https://github.com/alpacahq/pylivetrader/blob/master/_autodocs/api-reference/statestore.md Persists algorithm context to Redis using pickle. Uses REDIS_URL env var (default redis://localhost:6379) and key 'pylivetrader_redis_state'. Raises ValueError if redis module not installed or on corrupt state. ```python class RedisStore(object): REDIS_STATE_KEY = 'pylivetrader_redis_state' def __init__(self): try: redis except NameError: raise ValueError( "Redis was not installed, please install the redis module." ) self.redis = redis.from_url( os.getenv('REDIS_URL', 'redis://localhost:6379') ) def save(self, state): self.redis.set(self.REDIS_STATE_KEY, pickle.dumps(state)) def load(self): try: loaded_state = pickle.loads(self.redis.get(self.REDIS_STATE_KEY)) return loaded_state except pickle.UnpicklingError: raise ValueError("Corrupt state file in redis") def can_load(self): return self.redis.exists(self.REDIS_STATE_KEY) ``` -------------------------------- ### validate_account_controls() Source: https://github.com/alpacahq/pylivetrader/blob/master/_autodocs/api-reference/algorithm.md Runs control.validate(portfolio, account, datetime, current_data) for each account control. ```APIDOC ## validate_account_controls() ### Description Runs control.validate(portfolio, account, datetime, current_data) for each account control. ### Parameters - None ### Returns - None ```