{ "cells": [ { "cell_type": "markdown", "id": "66be0f9b-942f-421c-882b-5cf6a8d225ef", "metadata": {}, "source": [ "# Creating an AI Trading Bot using Machine Learning with help of AI" ] }, { "cell_type": "markdown", "id": "f70ecd95-f883-40e1-a73d-1ade318c8783", "metadata": {}, "source": [ "## Used tools" ] }, { "cell_type": "markdown", "id": "314ddf94-059a-452a-8098-22b1ec78d5b1", "metadata": {}, "source": [ "- https://aistudio.google.com\n", "- https://alpaca.markets/\n", "- https://jupyter.org/\n", "- https://superai.pl/courses.html" ] }, { "cell_type": "markdown", "id": "2b8e5201-a668-4b6a-9be0-5172b5e67b95", "metadata": {}, "source": [ "## Creating AI Trading Bot with AI" ] }, { "cell_type": "markdown", "id": "9d07ca5d-c625-496a-bd5c-5efa72b3e404", "metadata": {}, "source": [ "### 1st Prompt" ] }, { "cell_type": "markdown", "id": "bccd6bdd-6e98-4f76-bd50-eb0f13f5636c", "metadata": {}, "source": [ "1. \"I would like to create a trading bot. It should be using machine learning to trade BTCUSD in one minute intervals and Alpaca Markets. Can you help me with that?\"\n", "\n", "(Remember: At the moment Alpaca uses different symbols for executing orders such as “BTC/USD” and checking portfolio positions such as “BTCUSD”.)\n" ] }, { "cell_type": "markdown", "id": "6cf0ec94-cdb3-47e5-918e-5ba2cfd6f16e", "metadata": {}, "source": [ "#### Keys to Alpaca" ] }, { "cell_type": "code", "execution_count": null, "id": "7d232c4b-7f4a-4f9d-b557-1abe46047672", "metadata": {}, "outputs": [], "source": [ "KEY_ID = \"your API KEY\" #replace it with your own KEY_ID from Alpaca: https://alpaca.markets/\n", "SECRET_KEY = \"your SECRET KEY\" #replace it with your own SECRET_KEY from Alpaca" ] }, { "cell_type": "markdown", "id": "ea5c66d3-6c54-49a0-800e-7dd663fec83c", "metadata": {}, "source": [ "### 1st Attempt" ] }, { "cell_type": "code", "execution_count": null, "id": "56fce22c-c529-40c1-ae46-3576bcb75475", "metadata": {}, "outputs": [], "source": [ "import warnings\n", "warnings.filterwarnings('ignore')" ] }, { "cell_type": "markdown", "id": "86801639-ce2c-4bac-bf23-94ab71cf70b7", "metadata": {}, "source": [ "Step 1: Alpaca Setup & Python Environment\n", "\n", " Sign up for an Alpaca account: https://alpaca.markets/\n", "\n", " Get your API Key ID and Secret Key from your paper trading account dashboard.\n", "\n", " Install necessary Python libraries:" ] }, { "cell_type": "code", "execution_count": null, "id": "91850edf-7220-407e-a577-7a8cf4ee6ca9", "metadata": {}, "outputs": [], "source": [ "pip install alpaca-trade-api pandas scikit-learn xgboost numpy pandas-ta" ] }, { "cell_type": "markdown", "id": "41adbca4-5621-4491-8541-3dd4f52eed2b", "metadata": {}, "source": [ "Set up API credentials (environment variables are best):" ] }, { "cell_type": "code", "execution_count": null, "id": "bc5e6181-d205-476d-8c17-8cecda0c01ed", "metadata": {}, "outputs": [], "source": [ "import os\n", "import alpaca_trade_api as tradeapi\n", "import pandas as pd\n", "from datetime import datetime, timedelta\n", "import time\n", "\n", "# For Paper Trading\n", "os.environ['APCA_API_BASE_URL'] = 'https://paper-api.alpaca.markets'\n", "# Replace with your actual keys or set them as environment variables\n", "os.environ['APCA_API_KEY_ID'] = \"your API KEY\" #replace it with your own KEY_ID from Alpaca: https://alpaca.markets/\n", "os.environ['APCA_API_SECRET_KEY'] = \"your SECRET KEY\" #replace it with your own SECRET_KEY from Alpaca\n", "\n", "API_KEY = os.getenv('APCA_API_KEY_ID')\n", "API_SECRET = os.getenv('APCA_API_SECRET_KEY')\n", "BASE_URL = os.getenv('APCA_API_BASE_URL')\n", "\n", "api = tradeapi.REST(API_KEY, API_SECRET, BASE_URL, api_version='v2')\n", "\n", "print(\"Connected to Alpaca Paper Trading.\")\n", "# Check account\n", "# account = api.get_account()\n", "# print(f\"Account status: {account.status}\")" ] }, { "cell_type": "markdown", "id": "45682be7-b549-422b-8a7d-1d9dbd8f2672", "metadata": {}, "source": [ "Step 2: Data Acquisition" ] }, { "cell_type": "code", "execution_count": null, "id": "923fea7c-910e-45cb-b19f-3b7a3002322c", "metadata": {}, "outputs": [], "source": [ "def fetch_data(symbol, timeframe, start_date_str, end_date_str=None):\n", " \"\"\"Fetches historical crypto data from Alpaca.\"\"\"\n", " if end_date_str is None:\n", " end_date_str = datetime.now().strftime('%Y-%m-%d')\n", "\n", " # Alpaca API expects ISO 8601 format for start/end times\n", " # And it has a limit on how many bars can be fetched per request (e.g., 10000 for crypto)\n", " # So we may need to fetch in chunks if requesting a long period.\n", "\n", " all_bars = []\n", " start_dt = pd.to_datetime(start_date_str, utc=True)\n", " end_dt = pd.to_datetime(end_date_str, utc=True)\n", "\n", " # Fetch data in chunks to avoid hitting API limits for very long periods\n", " # For 1-minute data, 10000 bars is about 7 days.\n", " # Let's fetch data in smaller chunks, e.g., 5 days at a time.\n", " current_start = start_dt\n", " while current_start < end_dt:\n", " chunk_end = min(current_start + timedelta(days=5), end_dt) # Adjust chunk size as needed\n", " print(f\"Fetching data from {current_start.isoformat()} to {chunk_end.isoformat()}\")\n", "\n", " # Alpaca's get_crypto_bars expects start and end in ISO format\n", " bars = api.get_crypto_bars(\n", " symbol,\n", " timeframe,\n", " start=current_start.isoformat(),\n", " end=chunk_end.isoformat(),\n", " limit=10000 # Max limit per request\n", " ).df\n", "\n", " if bars.empty:\n", " print(f\"No data found for chunk starting {current_start.isoformat()}\")\n", " if current_start + timedelta(days=5) > end_dt and not all_bars: # if first chunk and no data\n", " break\n", " current_start += timedelta(days=5) # Move to next chunk period\n", " time.sleep(1) # Be nice to the API\n", " continue\n", "\n", " all_bars.append(bars)\n", " # Update current_start to the timestamp of the last bar fetched + 1 minute\n", " # to avoid overlap and to ensure we move forward.\n", " if not bars.index.empty:\n", " current_start = bars.index[-1] + pd.Timedelta(minutes=1)\n", " else: # Should not happen if bars is not empty, but as a safeguard\n", " current_start += timedelta(days=5)\n", "\n", " time.sleep(1) # Respect API rate limits\n", "\n", " if not all_bars:\n", " print(\"No data fetched. Check your date range or symbol.\")\n", " return pd.DataFrame()\n", "\n", " df = pd.concat(all_bars)\n", " df = df[~df.index.duplicated(keep='first')] # Remove potential duplicates from chunking\n", " df = df.sort_index() # Ensure chronological order\n", " df = df[df.index <= end_dt] # Ensure we don't go past the requested end_dt\n", " return df\n", "\n", "# Example usage:\n", "symbol = \"BTC/USD\" # Alpaca uses \"BTC/USD\" for crypto pairs\n", "timeframe = tradeapi. টাইমফ্রেম.মিনিট # or \"1Min\" for older SDK versions\n", "# Fetch last 30 days of data for example\n", "start_date = (datetime.now() - timedelta(days=30)).strftime('%Y-%m-%d')\n", "# end_date = datetime.now().strftime('%Y-%m-%d') # Fetches up to now\n", "\n", "btc_data = fetch_data(symbol, timeframe, start_date)\n", "if not btc_data.empty:\n", " print(f\"Fetched {len(btc_data)} rows of {symbol} data.\")\n", " print(btc_data.head())\n", " print(btc_data.tail())\n", "else:\n", " print(\"Failed to fetch data.\")" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.12.3" } }, "nbformat": 4, "nbformat_minor": 5 }