{ "cells": [ { "cell_type": "markdown", "id": "c9dc167c", "metadata": { "deletable": false, "editable": false }, "source": [ "# How to create a simple stock trading bot in Python (in 10-lines of code) with Alpaca and Anaconda? For complete beginners (non-programmers / non-traders)." ] }, { "cell_type": "markdown", "id": "8ef06019", "metadata": { "deletable": false, "editable": false }, "source": [ "## The trading bot - only code version" ] }, { "cell_type": "code", "execution_count": null, "id": "548167e5", "metadata": {}, "outputs": [], "source": [ "import sys\n", "\n", "!$sys.executable -m pip install alpaca-trade-api" ] }, { "cell_type": "code", "execution_count": null, "id": "5b67f10c", "metadata": {}, "outputs": [], "source": [ "import alpaca_trade_api as tradeapi\n", "import time" ] }, { "cell_type": "code", "execution_count": null, "id": "761abe4c", "metadata": {}, "outputs": [], "source": [ "import time, alpaca_trade_api as tradeapi" ] }, { "cell_type": "code", "execution_count": null, "id": "4d6a5735", "metadata": {}, "outputs": [], "source": [ "api = tradeapi.REST(\"paste your API Key ID here\", \"paste your SECRET_KEY here\", \"https://paper-api.alpaca.markets\", \"v2\")" ] }, { "cell_type": "code", "execution_count": null, "id": "fc591a75", "metadata": {}, "outputs": [], "source": [ "for x in range(10):\n", " try:\n", " api.get_position(\"AAPL\") \n", " time.sleep(11)\n", " except:\n", " api.submit_order(symbol=\"AAPL\",qty=1,side='buy',type='market',time_in_force='gtc')\n", " time.sleep(10)\n", " api.submit_order(symbol=\"AAPL\",qty=1,side='sell',type='trailing_stop',trail_percent=1,time_in_force='gtc')" ] }, { "cell_type": "markdown", "id": "644a18c3", "metadata": { "deletable": false, "editable": false }, "source": [ "## Improved trading bot" ] }, { "cell_type": "code", "execution_count": null, "id": "9a90ebfb", "metadata": {}, "outputs": [], "source": [ "import time, alpaca_trade_api as tradeapi\n", "api = tradeapi.REST(\"paste your API Key ID here\", \"paste your SECRET_KEY here\", \"https://paper-api.alpaca.markets\", \"v2\")\n", "while True:\n", " try:\n", " api.get_position(\"AAPL\")\n", " time.sleep(11)\n", " except:\n", " api.submit_order(symbol=\"AAPL\",qty=500,side='buy',type='market',time_in_force='gtc')\n", " time.sleep(10)\n", " api.submit_order(symbol=\"AAPL\",qty=500,side='sell',type='trailing_stop',trail_percent=0.1,time_in_force='gtc')" ] }, { "cell_type": "code", "execution_count": null, "id": "65b2b035", "metadata": {}, "outputs": [], "source": [] } ], "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.9.7" } }, "nbformat": 4, "nbformat_minor": 5 }