### Setup Python Virtual Environment Source: https://github.com/alpacahq/alpaca-py/blob/master/examples/stocks/build_trading_bot_with_ChatGPT/README.md Install and activate a virtual environment to manage project dependencies. ```bash sudo apt update sudo apt install python3-venv -y python3 -m venv venv source venv/bin/activate ``` -------------------------------- ### Install and Import Alpaca-py Library Source: https://github.com/alpacahq/alpaca-py/blob/master/examples/options/options-zero-dte.ipynb Installs the alpaca-py package and imports necessary modules for trading and data access. Ensure you are using a paper account for this example. ```python # Install or upgrade the package `alpaca-py` and import it !python3 -m pip install --upgrade alpaca-py import pandas as pd import numpy as np from scipy.stats import norm import alpaca from scipy.optimize import brentq from datetime import datetime, time from zoneinfo import ZoneInfo from alpaca.trading.client import TradingClient from alpaca.trading.requests import ( MarketOrderRequest, GetOptionContractsRequest, MarketOrderRequest, OptionLegRequest, ClosePositionRequest, ) from alpaca.data.historical.option import OptionHistoricalDataClient from alpaca.data.historical.stock import StockHistoricalDataClient, StockLatestTradeRequest from alpaca.data.requests import OptionLatestQuoteRequest from alpaca.trading.enums import ( AssetStatus, # ExerciseStyle, OrderSide, OrderClass, OrderType, TimeInForce, # QueryOrderStatus, ContractType ) ``` -------------------------------- ### Example .env file for Local Development Source: https://github.com/alpacahq/alpaca-py/blob/master/examples/options/options-zero-dte-backtesting/README.md This is an example of how to structure your .env file to store API keys and other configuration settings for local development. Ensure this file is added to your .gitignore to prevent accidental commits. ```bash # Edit .env with your API keys ALPACA_API_KEY=your_alpaca_api_key ALPACA_SECRET_KEY=your_alpaca_secret_key ALPACA_PAPER_TRADE=True DATABENTO_API_KEY=your_databento_api_key ``` -------------------------------- ### Install Alpaca-py Library Source: https://github.com/alpacahq/alpaca-py/blob/master/examples/options/options-trading-basic.ipynb Check for the library installation and install it if missing. ```python # install alpaca-py if it is not available try: import alpaca except ImportError: !python3 -m pip install alpaca-py import alpaca ``` -------------------------------- ### Install Dependencies Source: https://github.com/alpacahq/alpaca-py/blob/master/examples/options/options-zero-dte-backtesting/options-zero-dte-backtesting.ipynb Install the required Python packages for the backtesting environment. ```bash !uv pip install databento alpaca-py python-dotenv pandas numpy scipy matplotlib jupyter ipykernel ``` -------------------------------- ### Install Serverless Framework and Login Source: https://github.com/alpacahq/alpaca-py/blob/master/examples/stocks/lbr-anti-setup-trading-bot/docs/PRE-DEPLOYMENT.md Install the Serverless Framework and log in to your account. This is necessary for deploying and managing serverless applications, including the trading bot. ```bash # 4. Install Serverless and log in npm ci && npx serverless login ``` -------------------------------- ### Install Dependencies Source: https://github.com/alpacahq/alpaca-py/blob/master/examples/stocks/build_trading_bot_with_ChatGPT/README.md Install the required Python packages listed in requirements.txt. ```bash pip install -r requirements.txt ``` -------------------------------- ### Install Dependencies using uv Source: https://github.com/alpacahq/alpaca-py/blob/master/examples/options/options-zero-dte-backtesting/README.md This command installs project dependencies using uv, a modern and faster package installer, creating a virtual environment named 'myvenv'. Ensure uv is installed separately before running this command. ```bash uv venv myvenv source myvenv/bin/activate # On Windows: myvenv\Scripts\activate uv pip install databento alpaca-py python-dotenv pandas numpy scipy matplotlib jupyter ipykernel ``` -------------------------------- ### Install and Import Libraries Source: https://github.com/alpacahq/alpaca-py/blob/master/examples/options/options-polygon-alpaca.ipynb Installs and imports necessary Python libraries for data analysis and API interaction. Ensure you have the correct Python version installed. ```python # Install or upgrade the package `polygon-api-client` and `plotly` and import them !python3 -m pip install --upgrade polygon-api-client !python3 -m pip install --upgrade plotly #import modules from polygon import RESTClient import datetime as dt import pandas as pd import numpy as np import plotly.graph_objects as go from plotly.offline import plot from datetime import datetime, timedelta ``` -------------------------------- ### Install and Import alpaca-py Source: https://github.com/alpacahq/alpaca-py/blob/master/examples/options/options-wheel-strategy.ipynb Install the required library and import necessary modules for trading and data retrieval. ```python !python3 -m pip install --upgrade alpaca-py import pandas as pd import numpy as np from scipy.stats import norm import alpaca import time from scipy.optimize import brentq from datetime import datetime, timedelta from zoneinfo import ZoneInfo from alpaca.data.timeframe import TimeFrame, TimeFrameUnit from alpaca.trading.client import TradingClient from alpaca.data.historical.option import OptionHistoricalDataClient from alpaca.data.historical.stock import StockHistoricalDataClient, StockLatestTradeRequest from alpaca.data.requests import StockBarsRequest, OptionLatestQuoteRequest, OptionChainRequest from alpaca.trading.requests import GetOptionContractsRequest, MarketOrderRequest from alpaca.trading.enums import AssetStatus, ContractType ``` -------------------------------- ### Install Dependencies using pip Source: https://github.com/alpacahq/alpaca-py/blob/master/examples/options/options-zero-dte-backtesting/README.md This command installs project dependencies using pip, creating a virtual environment named 'myvenv'. It includes essential libraries for Alpaca trading, data handling, and development. ```bash python3 -m venv myvenv source myvenv/bin/activate # On Windows: myvenv\Scripts\activate pip install databento alpaca-py python-dotenv pandas numpy scipy matplotlib jupyter ipykernel ``` -------------------------------- ### Install and Import Dependencies Source: https://github.com/alpacahq/alpaca-py/blob/master/examples/crypto/crypto-trading-basic.ipynb Ensure the alpaca-py library is installed and import necessary modules for trading and data operations. ```python # install alpaca-py if it is not available try: import alpaca except ImportError: !python3 -m pip install alpaca-py import alpaca ``` ```python import json from datetime import datetime, timedelta from zoneinfo import ZoneInfo from alpaca.trading.client import TradingClient from alpaca.data.timeframe import TimeFrame, TimeFrameUnit from alpaca.data.historical.crypto import CryptoHistoricalDataClient from alpaca.trading.stream import TradingStream from alpaca.data.live.crypto import CryptoDataStream from alpaca.data.requests import ( CryptoBarsRequest, CryptoQuoteRequest, CryptoTradesRequest, CryptoLatestQuoteRequest ) from alpaca.trading.requests import ( GetAssetsRequest, MarketOrderRequest, LimitOrderRequest, StopLimitOrderRequest, GetOrdersRequest, ClosePositionRequest ) from alpaca.trading.enums import ( AssetClass, AssetStatus, OrderSide, OrderType, TimeInForce, QueryOrderStatus ) from alpaca.common.exceptions import APIError ``` -------------------------------- ### Install and Import Alpaca-py Library Source: https://github.com/alpacahq/alpaca-py/blob/master/examples/options/options-iron-butterfly.ipynb Installs and imports necessary libraries for Alpaca trading and data analysis. Ensure you have the `alpaca-py` package installed or upgraded. ```python # Install or upgrade the package `alpaca-py` and import it # !python3 -m pip install --upgrade alpaca-py import pandas as pd import numpy as np import alpaca import time from datetime import datetime, timedelta from zoneinfo import ZoneInfo from alpaca.data.timeframe import TimeFrame, TimeFrameUnit from dotenv import load_dotenv import os from typing import Any, Dict, List, Optional, Tuple from alpaca.data.historical.option import OptionHistoricalDataClient from alpaca.data.historical.stock import StockHistoricalDataClient, StockLatestTradeRequest from alpaca.data.requests import StockBarsRequest, OptionSnapshotRequest, OptionBarsRequest from alpaca.trading.client import TradingClient from alpaca.trading.requests import ( MarketOrderRequest, GetOptionContractsRequest, OptionLegRequest, ClosePositionRequest, ) from alpaca.trading.enums import ( AssetStatus, ExerciseStyle, OrderSide, OrderClass, OrderStatus, OrderType, TimeInForce, QueryOrderStatus, ContractType, ) ``` -------------------------------- ### Install alpaca-py Source: https://github.com/alpacahq/alpaca-py/blob/master/README.md Install the alpaca-py library using pip. Ensure you are using Python 3.8+. ```shell pip install alpaca-py ``` -------------------------------- ### Verify Virtual Environment Installation Source: https://github.com/alpacahq/alpaca-py/blob/master/examples/options/options-zero-dte-backtesting/README.md This command lists the contents of the virtual environment's bin directory, useful for verifying that the installation was successful and to locate the Python interpreter path. ```bash ls -la /path/to/your/project/myvenv/bin/ ``` -------------------------------- ### 0DTE Bull Put Spread Algorithm Setup Source: https://github.com/alpacahq/alpaca-py/blob/master/examples/options/options-zero-dte-backtesting/options-zero-dte-backtesting.ipynb This comment block outlines the setup and core functionalities of the 0DTE bull put spread algorithm. It highlights the selection of option contracts based on delta criteria and spread width, and the minute-by-minute monitoring of the position for exit conditions. ```python # Complete 0DTE bull put spread algorithm demonstration: # - Selects option contracts based on delta criteria and spread width # - Monitors position every minute for exit conditions ``` -------------------------------- ### Install and Import Alpaca Trading Libraries Source: https://github.com/alpacahq/alpaca-py/blob/master/examples/options/options-polygon-alpaca.ipynb Installs and imports the necessary `alpaca-py` modules for trading operations, including clients for trading, options, and historical data. ```python # Install or upgrade the package `alpaca-py` and import it !python3 -m pip install --upgrade alpaca-py import alpaca from alpaca.trading.client import TradingClient from alpaca.trading.requests import GetOptionContractsRequest, MarketOrderRequest from alpaca.data.requests import OptionLatestQuoteRequest, OptionSnapshotRequest from alpaca.data.historical.option import OptionHistoricalDataClient from alpaca.data.historical.stock import StockHistoricalDataClient, StockLatestTradeRequest ``` -------------------------------- ### Install and Import Alpaca SDK Source: https://github.com/alpacahq/alpaca-py/blob/master/examples/options/options-calendar-spread.ipynb Installs the latest version of the Alpaca Python SDK and imports necessary modules for data retrieval, trading, and statistical calculations. ```python !python3 -m pip install --upgrade alpaca-py import pandas as pd import numpy as np from scipy.stats import norm import alpaca import time from scipy.optimize import brentq from datetime import datetime, timedelta from zoneinfo import ZoneInfo from alpaca.data.timeframe import TimeFrame, TimeFrameUnit from alpaca.data.historical.option import OptionHistoricalDataClient from alpaca.data.historical.stock import StockHistoricalDataClient, StockLatestTradeRequest from alpaca.data.requests import StockBarsRequest, OptionLatestQuoteRequest, OptionChainRequest, OptionBarsRequest from alpaca.trading.client import TradingClient from alpaca.trading.requests import ( MarketOrderRequest, GetOptionContractsRequest, MarketOrderRequest, OptionLegRequest, ClosePositionRequest, ) from alpaca.trading.enums import ( AssetStatus, ExerciseStyle, OrderSide, OrderClass, OrderStatus, OrderType, TimeInForce, QueryOrderStatus, ContractType ) ``` -------------------------------- ### Install and Import Alpaca-py Library Source: https://github.com/alpacahq/alpaca-py/blob/master/examples/options/options-iron-condor.ipynb Installs or upgrades the alpaca-py package and imports necessary libraries for data analysis and trading. ```python # Install or upgrade the package `alpaca-py` and import it !python3 -m pip install --upgrade alpaca-py import pandas as pd import numpy as np from scipy.stats import norm import alpaca import time from scipy.optimize import brentq from datetime import datetime, timedelta from zoneinfo import ZoneInfo from alpaca.data.timeframe import TimeFrame, TimeFrameUnit from alpaca.data.historical.option import OptionHistoricalDataClient from alpaca.data.historical.stock import StockHistoricalDataClient, StockLatestTradeRequest from alpaca.data.requests import StockBarsRequest, OptionLatestQuoteRequest, OptionChainRequest, OptionBarsRequest from alpaca.trading.client import TradingClient from alpaca.trading.requests import ( MarketOrderRequest, GetOptionContractsRequest, MarketOrderRequest, OptionLegRequest, ClosePositionRequest, ) from alpaca.trading.enums import ( AssetStatus, ExerciseStyle, OrderSide, OrderClass, OrderStatus, OrderType, TimeInForce, QueryOrderStatus, ContractType, ) ``` -------------------------------- ### Install Alpaca-py and Dependencies Source: https://github.com/alpacahq/alpaca-py/blob/master/examples/stocks/lbr-anti-setup-trading-bot/notebooks/ibr_algorithm_walkthrough.ipynb Installs the necessary Python libraries for interacting with Alpaca's API, handling data, and plotting. This command is typically run in a notebook environment. ```bash !uv pip install alpaca-py python-dotenv pandas matplotlib pytz ``` -------------------------------- ### Run Educational Notebook Locally Source: https://github.com/alpacahq/alpaca-py/blob/master/examples/stocks/lbr-anti-setup-trading-bot/README.md Launch the Jupyter Notebook for a step-by-step walkthrough of the LBR signal logic. Setup instructions are provided within the notebook. ```bash jupyter notebook notebooks/ibr_algorithm_walkthrough.ipynb ``` -------------------------------- ### Get Corporate Actions Source: https://github.com/alpacahq/alpaca-py/blob/master/examples/stocks/stocks-trading-basic.ipynb Fetches corporate actions data for a given symbol starting from a specified date. Requires `CorporateActionsClient` and `CorporateActionsRequest`. ```python from alpaca.trading.client import CorporateActionsClient from alpaca.trading.requests import CorporateActionsRequest from datetime import datetime corporate_actions_client = CorporateActionsClient(api_key, secret_key) corporate_actions_client.get_corporate_actions(CorporateActionsRequest( start=datetime(2020, 1, 1), symbols=[symbol] )).df ``` -------------------------------- ### Get Options Historical Trades Source: https://github.com/alpacahq/alpaca-py/blob/master/examples/options/options-trading-basic.ipynb Retrieve historical options trades for a specified symbol. You can set the start and end times, and a limit for the results. ```python # get options historical trades by symbol req = OptionTradesRequest( symbol_or_symbols = high_open_interest_contract.symbol, start = now - timedelta(days = 5), # specify start datetime, default=the beginning of the current day. # end=None, # specify end datetime, default=now limit = 2, # specify limit ) option_historical_data_client.get_option_trades(req).df ``` -------------------------------- ### Set Up Strategy Inputs and Parameters Source: https://github.com/alpacahq/alpaca-py/blob/master/examples/options/options-bull-call-spread.ipynb Initializes strategy parameters including underlying symbol, timezone, date range, strike price range, buying power limits, risk-free rate, and option expiration. ```python # Select the underlying stock underlying_symbol = 'WMT' # Set the timezone timezone = ZoneInfo('America/New_York') # Get current date in US/Eastern timezone today = datetime.now(timezone).date() # Define a 6% range around the underlying price STRIKE_RANGE = 0.06 # Buying power percentage to use for the trade BUY_POWER_LIMIT = 0.05 # Risk free rate for the options greeks and IV calculations risk_free_rate = 0.01 # Check account buying power # buying_power = float(trade_client.get_account().buying_power) # Set the open interest volume threshold OI_THRESHOLD = 50 # Calculate the limit amount of buying power to use for the trade # buying_power_limit = buying_power * BUY_POWER_LIMIT # Set the expiration date range for the options min_expiration = today + timedelta(days=21) max_expiration = today + timedelta(days=60) # Get the latest price of the underlying stock def get_underlying_price(symbol): # Get the latest trade for the underlying stock # underlying_trade_request = StockLatestTradeRequest(symbol_or_symbols=symbol) # underlying_trade_response = stock_data_client.get_stock_latest_trade(underlying_trade_request) # return underlying_trade_response[symbol].price pass # Placeholder for actual implementation # Get the latest price of the underlying stock # underlying_price = get_underlying_price(underlying_symbol) # Set the minimum and maximum strike prices based on the underlying price # min_strike = str(underlying_price * (1 - STRIKE_RANGE)) # max_strike = str(underlying_price * (1 + STRIKE_RANGE)) # Define the criteria for selecting the options ``` -------------------------------- ### Initialize Environment and Clients Source: https://github.com/alpacahq/alpaca-py/blob/master/examples/crypto/crypto-trading-basic.ipynb Setup the trading client and environment for Jupyter notebook execution. ```python # to run async code in jupyter notebook import nest_asyncio nest_asyncio.apply() ``` ```python # check version of alpaca-py alpaca.__version__ ``` ```python # setup clients trade_client = TradingClient(api_key=api_key, secret_key=secret_key, paper=paper, url_override=trade_api_url) ``` -------------------------------- ### Get Options Historical Bars Source: https://github.com/alpacahq/alpaca-py/blob/master/examples/options/options-trading-basic.ipynb Retrieve historical options bars for a given symbol. You can specify the timeframe, start and end dates, and a limit. ```python # get options historical bars by symbol req = OptionBarsRequest( symbol_or_symbols = high_open_interest_contract.symbol, timeframe = TimeFrame(amount = 1, unit = TimeFrameUnit.Hour), # specify timeframe start = now - timedelta(days = 5), # specify start datetime, default=the beginning of the current day. # end_date=None, # specify end datetime, default=now limit = 2, # specify limit ) option_historical_data_client.get_option_bars(req).df ``` -------------------------------- ### Get Put Options Contracts for SPY Source: https://github.com/alpacahq/alpaca-py/blob/master/examples/options/options-trade-options-with-alpaca.ipynb Retrieves a list of put options contracts for the SPY underlying symbol. Note that this example is for demonstration and not investment advice. ```python # Get put options contracts # Please note that the stock SPY is used as an example and should not be considered investment advice. req = GetOptionContractsRequest( underlying_symbol=['SPY'], type=ContractType.PUT ) res = trade_client.get_option_contracts(req) res ``` -------------------------------- ### Setup Historical Data Client Source: https://github.com/alpacahq/alpaca-py/blob/master/examples/stocks/stocks-trading-basic.ipynb Initializes the client for fetching historical stock data. ```python # setup stock historical data client stock_historical_data_client = StockHistoricalDataClient(api_key, secret_key, url_override = data_api_url) ``` -------------------------------- ### Create Project Directory Source: https://github.com/alpacahq/alpaca-py/blob/master/examples/stocks/build_trading_bot_with_ChatGPT/README.md Initialize a new directory for the trading bot project. ```bash mkdir new_folder_name cd ./new_folder_name ``` -------------------------------- ### Get Positions Filtered by Option Contract Symbol Source: https://github.com/alpacahq/alpaca-py/blob/master/examples/options/options-trading-basic.ipynb Fetches all open positions and filters them to show only those matching the specified option contract symbol. This example is best run during market hours as positions may not be visible otherwise. ```python positions = trade_client.get_all_positions() [pos for pos in positions if pos.symbol == high_open_interest_contract.symbol] ``` -------------------------------- ### Initialize Trading Client Source: https://github.com/alpacahq/alpaca-py/blob/master/examples/options/options-trading-mleg.ipynb Create a TradingClient instance using the configured credentials. ```python # setup client trade_client = TradingClient(api_key=api_key, secret_key=secret_key, paper=paper, url_override=trade_api_url) ``` -------------------------------- ### Install Alpaca-py and Pandas-ta Source: https://github.com/alpacahq/alpaca-py/blob/master/examples/crypto/crypto-btc-usd-swing-trade.ipynb Installs or upgrades the `alpaca-py` and `pandas-ta` Python packages. Ensure you have Python 3 installed. ```python # Install or upgrade the package `alpaca-py` and import it # !python3 -m pip install --upgrade alpaca-py # Install or upgrade the package `pandas-ta` # !python3 -m pip install -U git+https://github.com/twopirllc/pandas-ta ``` -------------------------------- ### Initialize Trading Client Source: https://github.com/alpacahq/alpaca-py/blob/master/examples/options/options-trading-basic.ipynb Create a TradingClient instance using the configured credentials. ```python # setup clients trade_client = TradingClient(api_key=api_key, secret_key=secret_key, paper=paper, url_override=trade_api_url) ``` -------------------------------- ### Install Node.js Dependencies Source: https://github.com/alpacahq/alpaca-py/blob/master/examples/stocks/lbr-anti-setup-trading-bot/docs/PRE-DEPLOYMENT.md Install Node.js dependencies using `npm ci`. This command installs exact versions from `package-lock.json`, ensuring consistency. ```bash npm ci ``` -------------------------------- ### Setup Crypto Historical Data Client Source: https://github.com/alpacahq/alpaca-py/blob/master/examples/crypto/crypto-trading-basic.ipynb Initializes the client for fetching historical crypto market data. ```python # setup crypto historical data client crypto_historical_data_client = CryptoHistoricalDataClient() symbol="BTC/USD" ``` -------------------------------- ### Main Trading Loop Setup and Logic Source: https://github.com/alpacahq/alpaca-py/blob/master/examples/stocks/build_trading_bot_with_ChatGPT/trading_bot_chatgpt.ipynb Sets up logging, initializes strategy variables, and enters a continuous loop to monitor market status, fetch data, compute indicators, and determine trading actions. Handles market open/close transitions and fetches historical bars for analysis. ```python def main(): """Main trading loop and setup.""" # Configure logging logging.basicConfig( filename="trade_log.txt", # file to write level=logging.INFO, # log INFO and above format="%(asctime)s %(levelname)s: %(message)s", datefmt="%Y-%m-%d %H:%M:%S" ) logging.info("=== Strategy started ===") # remembers whether the market was open in the previous iteration market_open = False # Set tracking signal flags over a predefined window global rsi_bounce_bar, macd_cross_bar, rsi_retreat_bar, macd_death_cross_bar, macd_centerline_bar, current_bar_index rsi_bounce_bar = None macd_cross_bar = None rsi_retreat_bar = None macd_death_cross_bar = None macd_centerline_bar = None current_bar_index = 0 while True: clock = trade_client.get_clock() # The following code is commented out for running in the notebook. To run in `strategy.py`, uncomment the following code to use the market open/close logic # # Detect if the market has just transitioned from open to closed. # if market_open and not clock.is_open: # logging.info("Market closed. Sleeping until next open at %s", clock.next_open) # market_open = False # sleep_until(clock.next_open) # continue # skip the rest of the loop while the market is shut # Detect if the market has just transitioned from closed to open. if (not market_open) and clock.is_open: logging.info("Market opened. Resuming trading") market_open = True # fall through and run the trading logic # Detect if the market is closed (e.g., at script start or unexpected state), exit to prevent trading. if not clock.is_open: logging.info("Market is closed. Exiting.") exit(0) # Fetch data df_main = fetch_bars(stock_data_client, underlying_symbol, TIMEFRAME_MAIN, days=300) df_trend = fetch_bars(stock_data_client, underlying_symbol, TIMEFRAME_TREND, days=MA_SLOW + 10) logging.info("Fetched %d main bars and %d trend bars", len(df_main), len(df_trend)) # Update current bar index current_bar_index = len(df_main) - 1 # Check if we currently hold the underlying_symbol try: position = trade_client.get_open_position(underlying_symbol) position_open = True current_qty = int(position.qty) except Exception as e: position_open = False current_qty = 0 # Compute indicators using helper functions prices = df_main.close rsi_series = compute_rsi(prices, RSI_PERIOD) macd_line, signal_line = compute_macd(prices, MACD_FAST, MACD_SLOW, MACD_SIGNAL) # Get latest values rsi_now = rsi_series.iloc[-1] rsi_prev = rsi_series.iloc[-2] macd_now = macd_line.iloc[-1] macd_prev = macd_line.iloc[-2] sig_now = signal_line.iloc[-1] sig_prev = signal_line.iloc[-2] # Trend filter on higher timeframe with NaN check ma_fast = df_trend.close.rolling(MA_FAST).mean() ma_mid = df_trend.close.rolling(MA_MID).mean() ma_slow = df_trend.close.rolling(MA_SLOW).mean() # Check if we have enough data for all MAs if not (ma_fast.isna().any() or ma_mid.isna().any() or ma_slow.isna().any()): in_uptrend = (ma_fast.iloc[-1] > ma_mid.iloc[-1]) and (ma_mid.iloc[-1] > ma_slow.iloc[-1]) else: in_uptrend = False # Calculate position size based on buying power buying_power_limit = calculate_buying_power_limit(BUY_POWER_LIMIT) current_price = get_underlying_price(underlying_symbol) position_size = int(buying_power_limit / current_price) # Detect RSI oversold bounce if (rsi_prev < 30) and (rsi_now > 30): rsi_bounce_bar = current_bar_index # Detect MACD golden cross if (macd_prev < sig_prev) and (macd_now > sig_now): macd_cross_bar = current_bar_index # Entry logic if not position_open and in_uptrend and position_size > 0: ``` -------------------------------- ### Initialize BrokerClient Source: https://github.com/alpacahq/alpaca-py/blob/master/docs/broker.rst Instantiate the BrokerClient using API keys. Set the sandbox parameter to True to use the sandbox environment. ```python from alpaca.broker import BrokerClient BROKER_API_KEY = "api-key" BROKER_SECRET_KEY = "secret-key" broker_client = BrokerClient( api_key=Broker_API_KEY, secret_key=BROKER_SECRET_KEY, sandbox=True, ) ``` -------------------------------- ### Install and Import Alpaca-Py Source: https://github.com/alpacahq/alpaca-py/blob/master/examples/options/options-bull-call-spread.ipynb Installs or upgrades the alpaca-py package and imports necessary libraries for trading and data analysis. Ensure you have Python 3 installed. ```python # Install or upgrade the package `alpaca-py` and import it !python3 -m pip install --upgrade alpaca-py import pandas as pd import numpy as np from scipy.stats import norm import time from scipy.optimize import brentq from datetime import datetime, timedelta from zoneinfo import ZoneInfo from typing import Any, Dict, List, Optional, Tuple import alpaca from alpaca.data.timeframe import TimeFrame, TimeFrameUnit from alpaca.data.historical.option import OptionHistoricalDataClient from alpaca.data.historical.stock import StockHistoricalDataClient, StockLatestTradeRequest from alpaca.data.requests import StockBarsRequest, OptionLatestQuoteRequest, OptionSnapshotRequest from alpaca.trading.client import TradingClient from alpaca.trading.requests import ( MarketOrderRequest, GetOptionContractsRequest, MarketOrderRequest, OptionLegRequest, ClosePositionRequest, ) from alpaca.trading.enums import ( AssetStatus, OrderSide, OrderClass, OrderStatus, TimeInForce, ContractType, ) ``` -------------------------------- ### Initialize Trading Clients Source: https://github.com/alpacahq/alpaca-py/blob/master/examples/stocks/build_trading_bot_with_ChatGPT/trading_bot_chatgpt.ipynb Creates instances of the TradingClient and StockHistoricalDataClient using the loaded credentials. ```python # setup trading clients trade_client = TradingClient(api_key=API_KEY, secret_key=API_SECRET, paper=ALPACA_PAPER_TRADE, url_override=trade_api_url) stock_data_client = StockHistoricalDataClient(api_key=API_KEY, secret_key=API_SECRET) ``` -------------------------------- ### Initialize Live Data Stream Clients Source: https://github.com/alpacahq/alpaca-py/blob/master/docs/market_data.rst Initializes clients for subscribing to real-time data streams for crypto, stocks, and options. API keys are required for live data. ```python from alpaca.data.live import CryptoDataStream, OptionDataStream, StockDataStream # keys are required for live data crypto_stream = CryptoDataStream("api-key", "secret-key") # keys required stock_stream = StockDataStream("api-key", "secret-key") option_stream = OptionDataStream("api-key", "secret-key") ``` -------------------------------- ### Install and Import Alpaca-Py and Libraries Source: https://github.com/alpacahq/alpaca-py/blob/master/examples/options/options-long-straddle.ipynb Installs the alpaca-py package and imports essential libraries for data manipulation, calculations, and Alpaca API interaction. Ensure you have Python 3 and pip installed. ```python # Install or upgrade the package `alpaca-py` and import it !python3 -m pip install --upgrade alpaca-py import pandas as pd import numpy as np from scipy.stats import norm import alpaca import time from scipy.optimize import brentq from datetime import datetime, timedelta from zoneinfo import ZoneInfo from alpaca.data.timeframe import TimeFrame, TimeFrameUnit from alpaca.data.historical.option import OptionHistoricalDataClient from alpaca.data.historical.stock import StockHistoricalDataClient, StockLatestTradeRequest from alpaca.data.requests import StockBarsRequest, OptionLatestQuoteRequest, OptionChainRequest, OptionBarsRequest from alpaca.trading.client import TradingClient from alpaca.trading.requests import ( MarketOrderRequest, LimitOrderRequest, GetOptionContractsRequest, MarketOrderRequest, OptionLegRequest, ClosePositionRequest, CreateWatchlistRequest ) from alpaca.trading.enums import ( AssetStatus, ExerciseStyle, OrderSide, OrderClass, OrderStatus, OrderType, TimeInForce, QueryOrderStatus, ContractType, ) ``` -------------------------------- ### Initialize Alpaca Trading and Data Clients Source: https://github.com/alpacahq/alpaca-py/blob/master/examples/options/options-polygon-alpaca.ipynb Sets up the TradingClient and StockHistoricalDataClient using API keys and paper trading environment. Ensure your API keys are securely stored and accessible. ```python from google.colab import userdata API_KEY = userdata.get('ALPACA_API_KEY') API_SECRET = userdata.get('ALPACA_SECRET_KEY') BASE_URL = None ## We use paper environment for this example PAPER = True # Please do not modify this. This example is for paper trading only. trade_client = TradingClient(api_key=API_KEY, secret_key=API_SECRET, paper=PAPER, url_override=BASE_URL) stock_data_client = StockHistoricalDataClient(api_key=API_KEY, secret_key=API_SECRET) option_historical_data_client = OptionHistoricalDataClient(api_key=API_KEY, secret_key=API_SECRET, url_override=BASE_URL) ``` -------------------------------- ### Initialize Trading Client for Paper Trading Source: https://github.com/alpacahq/alpaca-py/blob/master/docs/trading.rst Instantiate the TradingClient with paper=True to enable the paper trading sandbox environment. Ensure your API keys correspond to a paper account. ```python from alpaca.trading.client import TradingClient # paper=True enables paper trading trading_client = TradingClient('api-key', 'secret-key', paper=True) ``` -------------------------------- ### Install and Import Alpaca-py Libraries Source: https://github.com/alpacahq/alpaca-py/blob/master/examples/options/options-bull-put-spread.ipynb Installs and imports essential libraries for Alpaca trading and data access, including pandas, numpy, and various Alpaca-specific modules for historical data, trading, and request formatting. Ensure you have the latest version of alpaca-py installed. ```python # Install or upgrade the package `alpaca-py` and import it # !python3 -m pip install --upgrade alpaca-py import pandas as pd import numpy as np from scipy.stats import norm import time from scipy.optimize import brentq from datetime import datetime, timedelta from zoneinfo import ZoneInfo from dotenv import load_dotenv import os from typing import Any, Dict, List, Optional, Tuple import alpaca from alpaca.data.timeframe import TimeFrame, TimeFrameUnit from alpaca.data.historical.option import OptionHistoricalDataClient from alpaca.data.historical.stock import StockHistoricalDataClient, StockLatestTradeRequest from alpaca.data.requests import StockBarsRequest, OptionLatestQuoteRequest, OptionSnapshotRequest from alpaca.trading.client import TradingClient from alpaca.trading.requests import ( MarketOrderRequest, GetOptionContractsRequest, MarketOrderRequest, OptionLegRequest, ClosePositionRequest, ) from alpaca.trading.enums import ( AssetStatus, OrderSide, OrderClass, OrderStatus, TimeInForce, ContractType, ) ``` -------------------------------- ### Install and Update Alpaca-py Source: https://github.com/alpacahq/alpaca-py/blob/master/examples/options/options-trade-options-with-alpaca.ipynb Installs or upgrades the alpaca-py library to the latest version. This is a prerequisite for using the library's functionalities. ```python # 1.1 Install / Update Alpaca-py !pip install --upgrade alpaca-py ``` -------------------------------- ### Check Serverless Framework Version Source: https://github.com/alpacahq/alpaca-py/blob/master/examples/stocks/lbr-anti-setup-trading-bot/docs/PRE-DEPLOYMENT.md Verify that the installed Serverless Framework version matches the one specified in `package.json`. Use `npx` to ensure the correct version is used. ```bash npx serverless --version ``` -------------------------------- ### BrokerClient Initialization Source: https://github.com/alpacahq/alpaca-py/blob/master/docs/api_reference/broker/broker-client.rst Information about initializing the BrokerClient. ```APIDOC ## BrokerClient Initialization ### Description Initializes the BrokerClient with API keys and base URLs. ### Method __init__ ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) None #### Response Example None ``` -------------------------------- ### Download or Upload Project Files Source: https://github.com/alpacahq/alpaca-py/blob/master/examples/stocks/build_trading_bot_with_ChatGPT/README.md Retrieve the project files from the repository or transfer them from a local machine. ```bash sudo apt update sudo apt install subversion -y svn export https://github.com/alpacahq/alpaca-py/trunk/examples/stocks/build_trading_bot_with_chatgpt ``` ```bash scp -i your-key.pem strategy.py secret.py requirements.txt ubuntu@your-ec2-ip:/home/ubuntu/new_folder_name ``` -------------------------------- ### Initialize Alpaca Clients Source: https://github.com/alpacahq/alpaca-py/blob/master/examples/options/options-zero-dte-backtesting/options-zero-dte-backtesting.ipynb Instantiate the signed Alpaca clients for trading and historical data. ```python # Initialize Alpaca clients trade_client = TradingClientSigned(api_key=ALPACA_API_KEY, secret_key=ALPACA_SECRET_KEY, paper=ALPACA_PAPER_TRADE) option_historical_data_client = OptionHistoricalDataClientSigned(api_key=ALPACA_API_KEY, secret_key=ALPACA_SECRET_KEY) stock_data_client = StockHistoricalDataClientSigned(api_key=ALPACA_API_KEY, secret_key=ALPACA_SECRET_KEY) ``` -------------------------------- ### Install Alpaca-py via Poetry Source: https://github.com/alpacahq/alpaca-py/blob/master/docs/getting_started.rst Command to add the library to a project managed by Poetry. ```shell-session poetry add alpaca-py ``` -------------------------------- ### Get Latest Stock Quote Source: https://github.com/alpacahq/alpaca-py/blob/master/examples/stocks/stocks-trading-basic.ipynb Retrieves the most recent stock quote for a given symbol. Initializes `StockQuotesRequest` without start/end times to get the latest data. ```python from alpaca.data.requests import StockQuotesRequest req = StockQuotesRequest( symbol_or_symbols = [symbol], ) res = stock_historical_data_client.get_stock_latest_quote(req) res ``` -------------------------------- ### Initialize Databento Client Source: https://github.com/alpacahq/alpaca-py/blob/master/examples/options/options-zero-dte-backtesting/options-zero-dte-backtesting.ipynb Instantiate the Databento historical data client. ```python # Initialize Databento client databento_client = db.Historical(DATABENTO_API_KEY) ``` -------------------------------- ### Calculate LBR Signal and Detect Anti Setup Source: https://github.com/alpacahq/alpaca-py/blob/master/examples/stocks/lbr-anti-setup-trading-bot/notebooks/ibr_algorithm_walkthrough.ipynb Computes the LBR 3/10 oscillator and detects the Anti setup by evaluating multiple trading rules. Returns a result dictionary indicating if a symbol is selected and the reasons for skipping. ```python import pandas as pd # Assume LBR_MIN_BARS, LBR_FAST, LBR_SLOW, LBR_SIGNAL are defined elsewhere # Assume calculate_adx, calculate_ema20, calculate_atr are defined elsewhere def calculate_lbr_signal(symbol: str, price_data: list[dict]) -> dict: """ Computes the LBR 3/10 oscillator and detects the Anti setup. Returns a result dict with all rule evaluations. """ result = { "score": 0.0, "selected": False, "adx": 0.0, "adx_rising": False, "ema20": 0.0, "last_close": 0.0, "atr": 0.0, "signal_crossed": False, "pullback": False, "skip_reason": "", } # ── Rule 1: Sufficient data ──────────────────────────────────────────── if len(price_data) < LBR_MIN_BARS: result["skip_reason"] = f"insufficient bars ({len(price_data)} < {LBR_MIN_BARS})" return result closes = pd.Series([d["close"] for d in price_data]) sma_fast = closes.rolling(LBR_FAST).mean() sma_slow = closes.rolling(LBR_SLOW).mean() macd_line = sma_fast - sma_slow signal_line = macd_line.rolling(LBR_SIGNAL).mean() histogram = macd_line - signal_line result["score"] = float(macd_line.iloc[-1] - signal_line.iloc[-1]) # ── Rule 2: ADX filter ───────────────────────────────────────────────── adx, adx_rising = calculate_adx(price_data) result["adx"] = adx result["adx_rising"] = adx_rising if adx > 32 and adx_rising: result["skip_reason"] = f"ADX {adx:.1f} > 32 and rising — strong trend filter" return result # ── Rule 3: Trend context ────────────────────────────────────────────── ema20 = calculate_ema20(price_data) last_close = float(closes.iloc[-1]) result["ema20"] = ema20 result["last_close"] = last_close if last_close <= ema20: result["skip_reason"] = f"price {last_close:.2f} below EMA20 {ema20:.2f} — no long Anti" return result # ── ATR (needed for proximity check in Rule 5) ────────────────────────── atr = calculate_atr(price_data) result["atr"] = atr # ── Rule 4: Signal line crossed zero from below ──────────────────────── recent_signal = signal_line.iloc[-LBR_SIGNAL:] currently_above_zero = float(signal_line.iloc[-1]) >= 0 was_below_zero = bool((recent_signal < 0).any()) crossed_zero = currently_above_zero and was_below_zero result["signal_crossed"] = crossed_zero if not crossed_zero: result["skip_reason"] = ( "signal line currently below zero — no active uptrend" if not currently_above_zero else "signal line has not crossed zero from below — no trend change" ) return result # ── Rule 5: Pullback ─────────────────────────────────────────────────── macd_now = float(macd_line.iloc[-1]) signal_now = float(signal_line.iloc[-1]) proximity = 0.5 * atr if atr > 0 else abs(signal_now) * 0.1 recent_macd = macd_line.iloc[-LBR_SIGNAL:] macd_made_high = float(recent_macd.max()) > macd_now near_signal = macd_now <= signal_now + proximity pulled_back = macd_made_high and near_signal result["pullback"] = pulled_back if not pulled_back: result["skip_reason"] = ( "MACD line has not made a new high — no impulse to pull back from" if not macd_made_high else "MACD line has not pulled back to signal line yet" ) return result # ── Rule 6: Hook ────────────────────────────────────────────────────── hist_now = float(histogram.iloc[-1]) hist_prev = float(histogram.iloc[-2]) if hist_now <= hist_prev: result["skip_reason"] = "MACD histogram not yet hooking up — waiting for entry" return result # ── All rules passed ─────────────────────────────────────────────────── result["selected"] = True return result print("✅ LBR signal function loaded") ``` -------------------------------- ### Get all Journals Source: https://github.com/alpacahq/alpaca-py/blob/master/docs/api_reference/broker/journals.rst Retrieves a list of all journals. ```APIDOC ## GET /journals ### Description Retrieves all journal entries. ### Method GET ### Endpoint /journals ``` -------------------------------- ### Initialize Market Data Clients Source: https://github.com/alpacahq/alpaca-py/blob/master/docs/market_data.rst Instantiate historical data clients for stocks, crypto, and options. Crypto clients do not require API keys. ```python from alpaca.data import CryptoHistoricalDataClient, StockHistoricalDataClient, OptionHistoricalDataClient # no keys required. crypto_client = CryptoHistoricalDataClient() # keys required stock_client = StockHistoricalDataClient("api-key", "secret-key") option_client = OptionHistoricalDataClient("api-key", "secret-key") ``` -------------------------------- ### Initialize Option Historical Data Client Source: https://github.com/alpacahq/alpaca-py/blob/master/examples/options/options-trading-basic.ipynb Set up the client for retrieving historical options data. Ensure you have your API keys and secret. ```python # setup option historical data client option_historical_data_client = OptionHistoricalDataClient(api_key, secret_key, url_override = data_api_url) ``` -------------------------------- ### Get Option Chain Source: https://github.com/alpacahq/alpaca-py/blob/master/docs/api_reference/data/option/historical.rst Retrieves an option chain. ```APIDOC ## Get Option Chain ### Description Retrieves an option chain for a given underlying symbol. ### Method get_option_chain ### Endpoint This information is not available in the provided text. ### Parameters This method does not have any explicitly documented parameters in the provided text. ### Request Example This information is not available in the provided text. ### Response This information is not available in the provided text. ``` -------------------------------- ### GET /v2/watchlists Source: https://github.com/alpacahq/alpaca-py/blob/master/docs/api_reference/trading/watchlists.rst Retrieve all watchlists associated with the account. ```APIDOC ## GET /v2/watchlists ### Description Retrieves a list of all watchlists created by the user. ### Method GET ### Endpoint /v2/watchlists ``` -------------------------------- ### Initialize Amplitude SDK Source: https://github.com/alpacahq/alpaca-py/blob/master/docs/_templates/base.html Initializes the Amplitude SDK with an API key. The key is determined by the hostname, using a production key for 'alpaca.markets' and a development key otherwise. Configuration includes using 'beacon' transport, and including UTM and referrer information. ```javascript const key = window.location.hostname === "alpaca.markets" ? "555479bdc8d2d0e70d7398de4521c8aa" : "d6814239bfb8d784ac22aa90be251d77"; amplitude.getInstance().init(key, null, { transport: "beacon", includeUtm: true, includeReferrer: true, }); ``` -------------------------------- ### GET /v2/orders Source: https://github.com/alpacahq/alpaca-py/blob/master/docs/api_reference/trading/orders.rst Retrieve a list of orders for the account. ```APIDOC ## GET /v2/orders ### Description Retrieve a list of orders associated with the account. ### Method GET ### Endpoint /v2/orders ``` -------------------------------- ### Display Configuration Values Source: https://github.com/alpacahq/alpaca-py/blob/master/examples/options/options-calendar-spread.ipynb Prints various strategy configuration parameters to the console. ```python print(f"Underlying Symbol: {underlying_symbol}") print(f"{underlying_symbol} price: {underlying_price}") print(f"Strike Range: {STRIKE_RANGE}") print(f"Buying Power Limit Percentage: {BUY_POWER_LIMIT}") print(f"Risk Free Rate: {risk_free_rate}") print(f"Account Buying Power: {buying_power}") print(f"Buying Power Limit: {buying_power_limit}") print(f"Open Interest Threshold: {OI_THRESHOLD}") print(f"Minimum Expiration Date: {min_expiration}") print(f"Maximum Expiration Date: {max_expiration}") print(f"Minimum Strike Price: {min_strike}") print(f"Maximum Strike Price: {max_strike}") print(f"Expiry date range for options: {EXPIRY_RANGE}") print(f"Implied Volatility range for options: {IV_RANGE}") print(f"Delta range for options: {DELTA_RANGE}") print(f"Theta range for options: {THETA_RANGE}") ``` -------------------------------- ### Configure Environment and API Clients Source: https://github.com/alpacahq/alpaca-py/blob/master/examples/options/options-zero-dte-backtesting/options-zero-dte-backtesting.ipynb Set up API credentials and define custom client classes for Alpaca services. ```python if "google.colab" in sys.modules: # In Google Colab environment, we will fetch API keys from Secrets. # Please set ALPACA_API_KEY, ALPACA_SECRET_KEY, DATABENTO_API_KEY in Google Colab's Secrets from the left sidebar from google.colab import userdata ALPACA_API_KEY = userdata.get("ALPACA_API_KEY") ALPACA_SECRET_KEY = userdata.get("ALPACA_SECRET_KEY") DATABENTO_API_KEY = userdata.get("DATABENTO_API_KEY") else: # Please safely store your API keys and never commit them to the repository (use .gitignore) # Load environment variables from environment file (e.g., .env) load_dotenv() # API credentials for Alpaca's Trading API and Databento API ALPACA_API_KEY = os.environ.get("ALPACA_API_KEY") ALPACA_SECRET_KEY = os.environ.get("ALPACA_SECRET_KEY") DATABENTO_API_KEY = os.getenv("DATABENTO_API_KEY") ## We use paper environment for this example ALPACA_PAPER_TRADE = True # Please do not modify this. This example is for paper trading only. # Below are the variables for development this documents (Please do not change these variables) TRADE_API_URL = None TRADE_API_WSS = None DATA_API_URL = None OPTION_STREAM_DATA_WSS = None # Signed Alpaca clients from alpaca import __version__ as alpacapy_version class _ClientMixin: def _get_default_headers(self): headers = self._get_auth_headers() headers["User-Agent"] = "APCA-PY/" + alpacapy_version + "-ZERO-DTE-NOTEBOOK" return headers class TradingClientSigned(_ClientMixin, TradingClient): pass class OptionHistoricalDataClientSigned(_ClientMixin, OptionHistoricalDataClient): pass class StockHistoricalDataClientSigned(_ClientMixin, StockHistoricalDataClient): pass ``` -------------------------------- ### GET /corporate_announcements Source: https://github.com/alpacahq/alpaca-py/blob/master/docs/api_reference/broker/corporate-actions.rst Retrieves a list of corporate announcements. ```APIDOC ## GET /corporate_announcements ### Description Retrieves a list of corporate announcements for splits, mergers, and other corporate events. ### Method GET ### Endpoint /corporate_announcements ``` -------------------------------- ### Get Option Snapshot Source: https://github.com/alpacahq/alpaca-py/blob/master/docs/api_reference/data/option/historical.rst Retrieves a snapshot of option data. ```APIDOC ## Get Option Snapshot ### Description Retrieves a snapshot of option data for a given symbol. ### Method get_option_snapshot ### Endpoint This information is not available in the provided text. ### Parameters This method does not have any explicitly documented parameters in the provided text. ### Request Example This information is not available in the provided text. ### Response This information is not available in the provided text. ```