Code For Sale

Alpaca Trading Script - Buy V3

It authenticates with the Alpaca API using the given API keys.
It reads a list of stock symbols from a text file named "symbols.txt".
Then, it enters into a loop that continues indefinitely until the account is restricted from trading.
a. It retrieves the last 60 days' worth of trading data, excluding the last 2 days, for the stock.
b. From the retrieved data, it calculates the average closing price over the past days.
c. It retrieves the last trade data for the stock.
d. If the last trade price is less than 90% of the 60-day average price, it considers buying the stock. The buy price is set at 90% of the average price.
e. Before buying, it checks if there is enough cash in the account to purchase the stock. It uses a strategy where it invests only 90% of the available cash, spread across 10% of the total number of stocks (both calculated as integers). The script will place a limit order to buy as many shares as can be afforded with this allocated amount.
f. The script prints out various details such as average price, last trade, buy price, amount to invest, and shares to buy.
g. If the account has enough money to buy at least one share, it places a limit order to buy the shares.
h. After attempting to purchase shares for all the stock symbols, the script pauses for a period (in this case, 1000 seconds) before starting the next iteration of the loop.

  • This script is a Python program that interfaces with the Alpaca Trading API to automate buying stocks based on specific criteria. The basic flow of the script is
  • Inside this loop, for each stock symbol in the list
Alpaca Trading Script - Get All Symbols v1

The provided Python code connects to Alpaca's trading platform API and gets a list of all tradable assets. Alpaca is a platform that provides an API for stock trading. The API key and secret key are used to authenticate the user's session.
It first sets up constants for the API key, secret key, and the base URL of the Alpaca API. The API key and secret key would be provided by Alpaca when you sign up for their API. Note that the base URL points to Alpaca's paper trading API, which is a sandbox environment for testing, not live trading.
The code then creates an instance of Alpaca's REST API client by providing the API key, secret key, base URL, and specifying the API version.
It calls the list_assets method from the Alpaca API, which returns a list of assets (stocks) available on the platform.
The code then opens a file called 'symbols.txt' in write mode.
It iterates over each asset in the list of assets. If an asset is tradable, it writes the symbol of the asset (the stock ticker) to the file, followed by a newline character.

  • Here is a step-by-step breakdown of what the code does