<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Irving Derin on Medium]]></title>
        <description><![CDATA[Stories by Irving Derin on Medium]]></description>
        <link>https://medium.com/@scarzer?source=rss-9aea5ad7f7d3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*aQlfdOnd4qt-DfOO.</url>
            <title>Stories by Irving Derin on Medium</title>
            <link>https://medium.com/@scarzer?source=rss-9aea5ad7f7d3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 22:05:42 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@scarzer/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Make a Discord Bot for you and your friends to trade stocks]]></title>
            <link>https://scarzer.medium.com/make-a-discord-bot-for-you-and-your-friends-to-trade-stocks-bde681ad38e2?source=rss-9aea5ad7f7d3------2</link>
            <guid isPermaLink="false">https://medium.com/p/bde681ad38e2</guid>
            <category><![CDATA[finance]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[discord]]></category>
            <category><![CDATA[trading]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Irving Derin]]></dc:creator>
            <pubDate>Fri, 26 Mar 2021 16:59:10 GMT</pubDate>
            <atom:updated>2021-03-26T16:59:10.824Z</atom:updated>
            <content:encoded><![CDATA[<p>Sitting at home for a year, one starts to explore a variety of new and different hobbies to try and keep their sanity. Me personally, I decided to help my friends find financial ruin with a stock trading Discord bot!</p><p>Along this journey I’ve decided to build my new discord friend, Dispaca the Alpaca!</p><figure><img alt="What a cutie!" src="https://cdn-images-1.medium.com/max/1024/0*qh4nN85LOkmP8tDz" /><figcaption>Alpaca Photo by <a href="https://unsplash.com/@carlos_ruizh?utm_source=medium&amp;utm_medium=referral">Carlos Ruiz Huaman</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>I’ll walk through my steps of building this potentially horrible idea so that others can also share their wealth amongst their friends, with no accountability (yet… Stay tuned for part 2).</p><h3>⚠️ <strong>WARNINGS AND DISCLOSURES </strong>⚠️</h3><p>This tutorial will be using a paper account on <a href="https://app.alpaca.markets/">https://app.alpaca.markets/</a>, so there is no real money involved.</p><p>IF YOU DECIDE TO USE REAL MONEY, be very mindful that there could be legal and tax ramifications for allowing other people trading securities in your name. I do not know what those ramifications are; the knowledge that they exist is enough to keep me away from giving other people that sort of control. My recommendation is that you too don’t give other people control over your money. Any actions you take outside of that recommendation is your own damn decision.</p><p>Here are some useful resources in general:</p><ul><li><a href="https://www.finra.org/#/">https://www.finra.org/</a></li><li><a href="https://www.investor.gov/">https://www.investor.gov/</a></li><li><a href="https://analyzingalpha.com/trade-stocks-for-others">https://analyzingalpha.com/trade-stocks-for-others</a></li></ul><h3>Step 0 — Setting up an environment</h3><p>This tutorial won’t go into the knitty-gritty details of my development setup, but I will discuss how I’m hosting this bot and my process in getting changes out into ‘production’.</p><p><strong>Caprover on DigitalOcean<br></strong><a href="https://caprover.com/">Caprover</a> is a deployment platform that I’ve found myself using over the last couple of months to simplifying self hosting some of the open source software I use (bitwarden, ect) as well small personal projects.</p><p>I found Caprover since I use DigitalOcean(<a href="https://m.do.co/c/29aa0a75081d">referral link</a> 💛) as my hosting provider. Their marketplace has an easy to deploy image that gets you started pretty quickly. Just make sure that you’ve got a domain name ready to go.</p><p>We’ll be deploying Dockerfiles to Caprover in this tutorial, so any other hosting options or local docker runs will work just as well.</p><p><strong>Initial File Structure<br></strong>We’ll be starting this project off with the following file structure.</p><pre>.<br>├── Dockerfile<br>├── README.md<br>├── requirements.txt<br>└── src<br>    └── bot.py</pre><p>This corresponds to our Docker looking like this.</p><pre>FROM gorialis/discord.py</pre><pre>WORKDIR /bot</pre><pre>COPY requirements.txt ./<br>RUN pip install -r requirements.txt</pre><pre>COPY /src .</pre><pre>ENV DISCORD_TOKEN=[WE WILL GET THIS SOON]<br>ENV ALPACA_KEY_ID=[WE WILL GET THIS SOON]<br>ENV ALPACA_KEY_SECRET=[WE WILL GET THIS SOON]</pre><pre>CMD [&quot;python&quot;, &quot;./bot.py&quot;]</pre><p>The <a href="https://hub.docker.com/r/gorialis/discord.py/">base image</a> for this Dockerfile was built with the discord.py library in mind.</p><p>With this file structure and docker installed, all we need to do to get up and running is just run the following command.</p><pre>$ docker build -t dispacapy .<br>$ docker run dispacapy</pre><p>Any time we add a change, we just rerun docker build and docker run and we’ll be able to see our changes deployed live!</p><h3>Step 1 — Setting up your Discord Bot</h3><p>At the end of this step we’ll have a Discord bot user that we can invite to our server, as well as an application token to add to our Dockerfile.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bOfcfPf3OWd8hLMx" /><figcaption>Photo by <a href="https://unsplash.com/@alexbemore?utm_source=medium&amp;utm_medium=referral">Alexander Shatov</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>First thing we need to do is get our discord bot set up and ready to go.</p><p><em>Note that I’m writing this tutorial after slash commands were introduced, but before I really explored how to use them.</em></p><p>Since we’re only making a chat bot without any special kinds of permission, we don’t need to worry about messy OAuth stuff.</p><p>We start off by going to <a href="https://discord.com/developers">https://discord.com/developers</a>. I’m assuming that you, the reader, have a discord account. If not go ahead and make one!</p><p>Once you’re logged in you should find a page that looks similar to this screenshot:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vi-Wmezi52VXCVP-CtU3Bw.png" /><figcaption>Taken from my own developers homepage</figcaption></figure><p>From here we’ll click on New Application and name our wonderful new application. This will bring us to the General Information page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X9AWW8hrROdjDIoEttDqVQ.png" /><figcaption>General Information page for our bot</figcaption></figure><p>To make our application an actual bot, we need to click on the Bot sidebar option and then Build-A-Bot.<strong> YOU HAVE TO DO THIS TO CREATE A BOT USER.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iSRCr_DdEqfhzi7QqeqaPg.png" /><figcaption>Before we made our bot.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wd50DLUnsWlAIHVZWcgjTQ.png" /><figcaption>After we added a bot. That token is long deleted ;)</figcaption></figure><p>This is an irreversible action and Discord will make sure to tell you that. Once our bot is created, we can grab our DISCORD_TOKEN for our Dockerfile.</p><p><strong>DO. NOT. PUSH. YOUR. DISCORD. TOKEN. TO. GITHUB.</strong></p><p>They will find it. They will tell you about it. They will revoke it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iviEYHPXVGDtCUxT1spTcg.png" /><figcaption>I’m speaking from experience</figcaption></figure><p>Finally the last step is to invite your bot to your server. This is done by going to the OAuth2 side menu option. We can get our bot going without requiring us to setup user authentication and redirects. This greatly simplifies our lives.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SyV-gdh84ZAGKMGliRSM3Q.png" /><figcaption>Permissions and scopes we’ll need for this project</figcaption></figure><p>We’ll select the bot OAuth scope, which will generate an invite link that we can use to add our bot to a server. Before we add our bot, we want to make sure we’ve got our permissions selected as well.</p><p>For this project we’ll only need Send Messages, Attach Files, and Add Reactions. Once you’re all set, go to the link you’ve generated and you’ll find yourself able to add your bot to any server that gives you the permission to do so.</p><pre><a href="https://discord.com/api/oauth2/authorize?client_id=824427896240209963&amp;permissions=34880&amp;scope=bot">https://discord.com/api/oauth2/authorize?client_id=myclientid12345&amp;permissions=34880&amp;scope=bot</a> -- THIS IS NOT A REAL URL</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/877/1*fwf_tcoWLOYN_EO-6HbHkA.png" /><figcaption>Selection screen for where to add your bot.</figcaption></figure><h3><strong>Step 2 — Setting up your Alpaca accoun</strong>t</h3><p>At the end of this step we’ll have an Alpaca paper account that will allow us to trade stocks, as well as get historical data. Their <a href="https://alpaca.markets/docs/">API documentation</a> is pretty fantastic.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/815/0*oHpMSksXzRN-MC2H" /><figcaption><a href="https://app.alpaca.markets/">https://app.alpaca.markets</a> is the first Commission Free API Stock Broker</figcaption></figure><p>I like Alpaca. It’s easy to get up and running. It gives you a paper account to practice your algorithms and then makes it easy to switch over to real money.</p><h3>⚠️<strong> BE VERY CAREFUL WHEN TRADING YOUR OWN MONEY. </strong>⚠️</h3><p>When you make your account and verify your email address, you’ll find yourself in a potentially intimidating screen. We can completely ignore it by switching over to our paper account. We do that by clicking on Live Trading and selecting the paper trading account in the dropdown.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lpXlLBdis5vLPPfdFCJMAA.png" /><figcaption>Intimidating signup page</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ya5YdGaYnoBPkJljJXm5AQ.png" /><figcaption>Our safe paper trading account</figcaption></figure><p>Once we’re on our paper trading account, we can generate our API Key and add them to our Dockerfile above. This is done by clicking on the View button in the Your API Keys box.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/549/1*nJZhi0iH3dJEjl_HUX9Yvw.png" /><figcaption>Another set of long deleted credentials.</figcaption></figure><h3>Step 3 —Relaying data from Alpaca to you</h3><p>We have a Discord bot account. We have an Alpaca trading account. Lets start building a bot getting data from it. At the end of this step we will have the early workings of a bot that will respond to commands and give us information about an individual stock. It’s always important to be informed when trading.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bpHPRAnKOCCdck5RpJxKsA.png" /><figcaption>At the end of this step we’ll have charts on demand</figcaption></figure><p>This tutorial won’t touch upon how to do any kind of financial analysis. That’s a complicated topic that I’m not qualified to talk about. There are plenty of other sources on Medium, YouTube and what have you that will teach you about markets.</p><p>If we open up bot.py we can get started on returning some information when we ask for it.</p><pre>## Discord.py is a well supported wrapper for the Discord API<br>import discord<br>from discord.ext import commands</pre><pre>## alpaca_trade_api wraps the Alpaca API<br>import alpaca_trade_api as tradeapi</pre><pre>## We&#39;ll be using matplotlib to generate simple line graphs<br>import matplotlib.pyplot as plt</pre><pre>## Useful imports to have<br>import io, os</pre><pre>## Environmental Consts<br>## These are set in the Dockerfile<br>DISCORD_TOKEN = os.environ.get(&quot;DISCORD_TOKEN&quot;)<br>ALPACA_KEY_ID = os.environ.get(&quot;ALPACA_KEY_ID&quot;)<br>ALPACA_KEY_SECRET = os.environ.get(&quot;ALPACA_KEY_SECRET&quot;)<br>ALPACA_BASE_URL = &#39;https://paper-api.alpaca.markets&#39;</pre><pre>## These are parameters to make our future charts prettier <br>plt.rcParams.update({&#39;xtick.labelsize&#39; : &#39;small&#39;,<br>                     &#39;ytick.labelsize&#39; : &#39;small&#39;,<br>                     &#39;figure.figsize&#39; : [16,9]})</pre><pre>## Connect to your Alpaca account</pre><pre>alpaca_api = tradeapi.REST(ALPACA_KEY_ID,<br>                           ALPACA_KEY_SECRET,<br>                           base_url=ALPACA_BASE_URL, <br>                           api_version=&#39;v2&#39;)</pre><pre>## Initialize our Discord bot<br>## Using a command prefix helps find issued commands <br>bot = commands.Bot(command_prefix=&#39;&gt;&#39;)</pre><pre>## Create our first command<br>@bot.command()<br>async def hello_world(context):<br>    await context.send(&quot;Hello Dispaca!&quot;)</pre><pre>## Any other commands we want to add should be added here</pre><pre>## Start our bot<br>bot.run(DISCORD_TOKEN)</pre><p>If we deploy our bot.py from above, we’ll be able to get our first bot communications!</p><p>Type in &gt;hello_world into a server that you share with your bot, and you’ll get a response back!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/751/1*tthOp0aqUewI4JFDLy-PHg.png" /><figcaption>Our first command to Dispaca!</figcaption></figure><p>Every subsequent command that we add is going to follow the same structure that the async def hello_world() follows. We use the @bot.command() decorator to designate functions as commands. Be sure to check out the <a href="https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#decorators">documentation</a> to see what more you can do with the decorators.</p><p>Now that we can have a conversation with Dispaca, lets start making it a useful conversation.</p><pre>@bot.command()<br>async def account(context):<br>    print(&quot;Checking account&quot;)</pre><pre>. ## Retrieve your Alpaca paper account info<br>    account_info = alpaca_api.get_account()<br>    await context.send(f&quot;{account_info}&quot;)</pre><p>Adding async def account(context) to your bot will allow you to use the &gt;account command.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b2ns44fnzeuxQ7S5kOGm_Q.png" /><figcaption>Retrieving your account info yields a JSON object</figcaption></figure><p>When called, your bot will reach out to the Alpaca API and retrieve your account information. It’ll be ugly but cleaning it up will be for another section. Before we move on, it’s important to note that this will be where we can retrieve our buying power, cash and other important values.</p><pre>@bot.command()<br>async def last_price(context, ticker):<br>    print(f&quot;Checking the last price of {ticker}&quot;)<br>    <br>    last_price = alpaca_api.get_last_trade(ticker)<br>    await context.send(f&quot;Last price for {ticker} was {last_price}&quot;)</pre><p>Here we’ve added &gt;last_price that will do exactly what it says- grab the last price of some stock. As an example we can send &gt;last_price GOOG and get the last price!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*61JlMtdlG8MhvwW9YGLafA.png" /><figcaption>Getting useful stock data!</figcaption></figure><p>Let us take this moment to talk about exceptions. Discord.py will ignore exceptions in commands. The code as written above can easily fail when getting a command, and the user might never know.</p><p>Here’s what happens when you send &gt;last_price goog.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cCRzHwwOhPMks8_jez8yJg.png" /><figcaption>We didn’t get our price data again. goog is different from GOOG</figcaption></figure><p>Looking at the output logs from Docker will reveal exactly what went wrong.</p><pre><strong>Ignoring exception in command last_price:</strong><br><strong>...</strong><br><strong>requests.exceptions.HTTPError: 404 Client Error: Not Found for url: </strong><a href="https://data.alpaca.markets/v1/last/stocks/goog"><strong>https://data.alpaca.markets/v1/last/stocks/goog</strong></a></pre><pre>The above exception was the direct cause of the following exception:<br><strong>...<br>discord.ext.commands.errors.CommandInvokeError: Command raised an exception: HTTPError: 404 Client Error: Not Found for url: </strong><a href="https://data.alpaca.markets/v1/last/stocks/goog"><strong>https://data.alpaca.markets/v1/last/stocks/goog</strong></a></pre><p>Alpaca’s market data is case sensitive, so searching for goog will not yield the same results as GOOG.</p><pre>@bot.command()<br>async def last_price(context, ticker):<br>    if isinstance(ticker, str):<br>        ticker = ticker.upper()</pre><pre>    print(f&quot;Checking the last price of {ticker}&quot;)<br>    try:<br>        last_price = alpaca_api.get_last_trade(ticker)<br>        await context.send(f&quot;{ticker} -- ${last_price.price}&quot;)</pre><pre>except Exception as e:<br>    await context.send(f&quot;Error getting the last price: {e}&quot;)</pre><p>For a quick mitigation, lets set all inputs to upper case. Also we should add an exception so that we can send back notice of a failure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sSIQjPFFvFo6ytIdM2ES7g.png" /></figure><p>Now we’re handling some errors.</p><p>Finally, lets make a chart and send it to the user. What good is the last price without some context. While there are several different ways to share a chart, I decided to generate a .png with Matplotlib and send it to Discord. This way we don’t have to worry about any other services or hosting.</p><pre>@bot.command()<br>async def check(context, ticker):<br>    print(f&quot;Checking the history of a stock&quot;)<br>    <br>    ## Make sure the symbol is upper case<br>    if isinstance(ticker, str):<br>        ticker = ticker.upper()</pre><pre>    try:</pre><pre>        ## Retrieve the last 100 days of trading data<br>        bars = alpaca_api.get_barset(ticker, &#39;day&#39;, limit=100)<br>        bars = bars.df[ticker]<br>        <br>        ## This bytes buffer will hole the image we send back<br>        fig = io.BytesIO()</pre><pre>        ## Grab the last closing price<br>        last_price = bars.tail(1)[&#39;close&#39;].values[0]</pre><pre>        ## Make a chart from the data we retrieved<br>        plt.title(f&quot;{ticker} -- Last Price ${last_price:.02f}&quot;)<br>        plt.xlabel(&quot;Last 100 days&quot;)<br>        plt.plot(bars[&quot;close&quot;])</pre><pre>        ## Save the image to the buffer we created earlier<br>        plt.savefig(fig, format=&quot;png&quot;)<br>        fig.seek(0)</pre><pre>## Sending back the image to the user.<br>        await context.send(file=discord.File(fig, f&quot;{ticker}.png&quot;))</pre><pre>        plt.close()</pre><pre>    except Exception as e:<br>      await context.send(f&quot;Error getting the stock&#39;s data: {e}&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ql5-9fqhbQiuk50yhuYsoQ.png" /><figcaption>We’ve got a graph!!</figcaption></figure><p>Since this is an image being uploaded to Discord, we can share a public link to anyone.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*sYxpOyO7AXzLTBQs.png" /><figcaption><a href="https://media.discordapp.net/attachments/824442560540835890/824491703192649748/GOOG.png?width=1258&amp;height=707">https://media.discordapp.net/attachments/824442560540835890/824491703192649748/GOOG.png?width=1258&amp;height=707</a></figcaption></figure><h3>Step 4 — Generating Embeds for general user friendliness</h3><p>Now we can access a lot of data and make simple graphs of that data. Lets start making some of that data easier to look at in discord. In this step we’ll be designing an Embed, populating it with only the information we care about, and return it back to the user.</p><p>I used <a href="https://cog-creators.github.io/discord-embed-sandbox/">Discord Embed Sandbox</a> to design my embeds. Other tools also exist</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/1*N6qQm2CGTnHXoEOGjfDZKA.png" /><figcaption>Mocking an Embed with <a href="https://cog-creators.github.io/discord-embed-sandbox/">https://cog-creators.github.io/discord-embed-sandbox/</a></figcaption></figure><p>Lets look back at what the account JSON looked like. <a href="https://alpaca.markets/docs/api-documentation/api-v2/account/">(Documentation on accounts</a>).</p><pre>Account({   <br>    &#39;account_blocked&#39;: False,<br>    &#39;account_number&#39;: &#39;PA0T4EI00TV0&#39;,<br>    &#39;buying_power&#39;: &#39;400000&#39;,<br>    &#39;cash&#39;: &#39;100000&#39;,<br>    &#39;created_at&#39;: &#39;2021-03-25T00:17:25.566381Z&#39;,<br>    &#39;currency&#39;: &#39;USD&#39;,<br>    &#39;daytrade_count&#39;: 0,<br>    &#39;daytrading_buying_power&#39;: &#39;400000&#39;,<br>    &#39;equity&#39;: &#39;100000&#39;,<br>    &#39;id&#39;: &#39;246a152e-a15d-433a-b5dc-0abcaca6d656&#39;,<br>    &#39;initial_margin&#39;: &#39;0&#39;,<br>    &#39;last_equity&#39;: &#39;100000&#39;,<br>    &#39;last_maintenance_margin&#39;: &#39;0&#39;,<br>    &#39;long_market_value&#39;: &#39;0&#39;,<br>    &#39;maintenance_margin&#39;: &#39;0&#39;,<br>    &#39;multiplier&#39;: &#39;4&#39;,<br>    &#39;pattern_day_trader&#39;: False,<br>    &#39;portfolio_value&#39;: &#39;100000&#39;,<br>    &#39;regt_buying_power&#39;: &#39;200000&#39;,<br>    &#39;short_market_value&#39;: &#39;0&#39;,<br>    &#39;shorting_enabled&#39;: True,<br>    &#39;sma&#39;: &#39;0&#39;,<br>    &#39;status&#39;: &#39;ACTIVE&#39;,<br>    &#39;trade_suspended_by_user&#39;: False,<br>    &#39;trading_blocked&#39;: False,<br>    &#39;transfers_blocked&#39;: False})</pre><p>Feels like we can confidently grab:</p><ul><li>cash</li><li>buying_power</li><li>equity</li><li>portfolio_value</li></ul><p>If we find that we need other values, we’ll add them later.</p><pre>def generate_account_embed(account):<br>    embed=discord.Embed(title=&quot;Account Status&quot;, <br>                       description=&quot;Alpaca Markets Account Status&quot;, <br>                       color=0x47c02c)<br>    <br>    embed.add_field(name=&quot;Cash&quot;, value=f&quot;${account.cash}&quot;)<br>    embed.add_field(name=&quot;Buying Power&quot;,<br>                    value=f&quot;${account.buying_power}&quot;)<br>    embed.add_field(name=&quot;Portfolio Value&quot;,<br>                    value=f&quot;${account.portfolio_value}&quot;)<br>    embed.add_field(name=&quot;Equity&quot;, value=f&quot;${account.equity}&quot;)<br>    <br>    return embed</pre><p>Here we’re using the generated python code as a template for our embed. We populate it with all of the variables that we’re passing in.</p><pre>## Replace the previous instance of this function in bot.py<br>@bot.command()<br>async def account(context):<br>    print(f&quot;Checking account&quot;)<br>    account_info = alpaca_api.get_account()<br>    account_embed = generate_account_embed(account_info)<br>    await context.send(embed=account_embed)</pre><p>Don’t forget to replace your account function in your bot.py before reruning.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/742/1*F2R3WyEAEKcYc8y-ioEx2Q.png" /><figcaption>Account values embed</figcaption></figure><p>Look at how much cleaner and easier it is to see your current account status.</p><h3>Step 5 — Reactions for trade confirmations</h3><p>It’s been a long journey, but we’re finally ready to ask Dispaca to go buy some securities for us. At the end of this step we’ll be able to ask Dispaca to make a trade for us, as well as confirm with us before it issues that trade. We wouldn’t want to accidentally buy 100 shares of GameStop… right? 🚀</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/651/1*6GcLbf-neWcxq4lCNneyxQ.png" /><figcaption>That could have been a mistake</figcaption></figure><p>In the case of our bot, lets see what the simplest buy command could look like.</p><pre>@bot.command()<br>async def buy(context, ticker, quantity):<br>    print(f&quot;Ordering {quantity} shares of {ticker}&quot;)</pre><pre>    buy_order = alpaca_api.submit_order(ticker, quantity,&#39;buy&#39;, <br>                                        &#39;market&#39;, &#39;day&#39;)<br>    await context.send(f&quot;{buy_order}&quot;)</pre><p>Issuing a &gt;buy GME 100 will just tell Alpaca that we want 100 shares of GameStop and to go buy them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Twj5cpnLOJFI0ylTK0AYBQ.png" /><figcaption>We don’t want this at all..</figcaption></figure><p>No confirmation, no checking of account value, nothing. All we would get back is an order confirmation. An ugly JSON blob at that.</p><pre>Order({   <br>        &#39;asset_class&#39;: &#39;us_equity&#39;,     <br>        &#39;asset_id&#39;: &#39;9eae922d-8d67-4c40-b6ea-faca9b092b89&#39;,<br>        &#39;canceled_at&#39;: None,     <br>        &#39;client_order_id&#39;: &#39;6ff64956-0123-4567-887a-632086981208&#39;,<br>        &#39;created_at&#39;: &#39;2021-03-24T21:07:28.551801Z&#39;,     <br>        &#39;expired_at&#39;: None,<br>        &#39;extended_hours&#39;: False,<br>        &#39;failed_at&#39;: None,<br>        &#39;filled_at&#39;: None,<br>        &#39;filled_avg_price&#39;: None,<br>        &#39;filled_qty&#39;: &#39;0&#39;,<br>        &#39;hwm&#39;: None,<br>        &#39;id&#39;: &#39;d1d08f71-a4a5-45f7-8508-64a86918b74e&#39;,     <br>        &#39;legs&#39;: None,     <br>        &#39;limit_price&#39;: None,     <br>        &#39;notional&#39;: None,     <br>        &#39;order_class&#39;: &#39;&#39;,     <br>        &#39;order_type&#39;: &#39;market&#39;,     <br>        &#39;qty&#39;: &#39;100&#39;,     <br>        &#39;replaced_at&#39;: None,     <br>        &#39;replaced_by&#39;: None,     <br>        &#39;replaces&#39;: None,     <br>        &#39;side&#39;: &#39;buy&#39;,     <br>        &#39;status&#39;: &#39;accepted&#39;,     <br>        &#39;stop_price&#39;: None,     <br>        &#39;submitted_at&#39;: &#39;2021-03-24T21:07:28.54462Z&#39;,     <br>        &#39;symbol&#39;: &#39;GME&#39;,     <br>        &#39;time_in_force&#39;: &#39;day&#39;,     <br>        &#39;trail_percent&#39;: None,     <br>        &#39;trail_price&#39;: None,     <br>        &#39;type&#39;: &#39;market&#39;,     <br>        &#39;updated_at&#39;: &#39;2021-03-24T21:07:28.551801Z&#39;})</pre><p>Buying securities shouldn’t be easy, it’s a lot of responsibility! How about instead we build an embed that we can use to show what our order is going to look like. Then we wait for an order confirmation via a reaction on that embed. If we get the right reaction we make the order, otherwise we just time out and pretend that nothing ever never happened.</p><pre>def generate_buy_embed(ticker, quantity, market_price):<br>    embed = discord.Embed()<br>    total_cost = int(quantity) * market_price<br>    embed=discord.Embed(title=f&quot;Buying {ticker}&quot;, <br>                    description=&quot;Review your buy order below.\<br>                    React with 👍 to confirm in the next 30 seconds&quot;)</pre><pre>    embed.add_field(name=&quot;Quantity&quot;, <br>                    value=f&quot;{quantity}&quot;, inline=False)<br>    embed.add_field(name=&quot;Per Share Cost&quot;, <br>                    value=f&quot;${market_price}&quot;, inline=False)<br>    embed.add_field(name=&quot;Estimated Cost&quot;, <br>                    value=f&quot;${total_cost}&quot;, inline=False)<br>    embed.add_field(name=&quot;In Force&quot;, <br>                    value=&quot;Good Until Cancelled&quot;, inline=False )</pre><pre>    return embed</pre><p>Above we’re starting to build up what we want our embed to look like. We want to make the information quick to digest, as well as simple to react to.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/531/1*OFusjtCwyIRqv1OBjXPZfA.png" /><figcaption>What our embed will look like when rendered in Discord</figcaption></figure><pre>@bot.command()<br>async def buy(context, ticker, quantity):<br>    if isinstance(ticker, str):<br>        ticker = ticker.upper()</pre><pre>    ## Lets get some supporting information about this stock<br>    try:<br>        last_trade = alpaca_api.get_last_trade(ticker)<br>        last_price = last_trade.price</pre><pre>    except Exception as e:<br>        await context.send(f&quot;Error getting the last price: {e}&quot;)<br>        return</pre><pre>    ## This is the embed we set up earlier<br>    buy_embed = generate_buy_embed(ticker, quantity, last_price)</pre><pre>    await context.send(embed=buy_embed)</pre><pre>    ## We only care about the user who started the trade<br>    def check(reaction, user):<br>        return user == context.message.author</pre><pre>    try:<br>        ## Wait for a reaction event. 30 second timeout.<br>        reaction, user = await bot.wait_for(&quot;reaction_add&quot;, <br>                         timeout=30.0, check=check)<br>    except TimeoutError:<br>        await context.send(&quot;Cancelling the trade. No activity&quot;)</pre><pre>    else:<br>        if str(reaction.emoji) == &#39;👍&#39;:<br>            await context.send(&quot;Executing on the trade&quot;)<br>            ## Placing the actual order <br>            placed_order = alpaca_api.submit_order(symbol=ticker, <br>                           qty=quantity,<br>                           side=&#39;buy&#39;, <br>                           type=&#39;market&#39;, <br>                           time_in_force=&#39;gtc&#39;)</pre><pre>            await context.send(f&quot;Order ID: {placed_order.id}&quot;)<br>        else:<br>            await context.send(&quot;Cancelling Order&quot;)</pre><p>This is a bit more complex of a command, but it’s super cool!</p><p>When Dispaca sees a &gt;buy GME 100, it’ll go out and grab the last trade price. We will use that price to estimate the cost of our order.</p><p>await bot.wait_for(&quot;reaction_add&quot;, timeout=30.0, check=check)</p><p>Here we’re telling our bot to listen for reactions for 30 seconds. If the user who started the order responds with 👍, then the order will proceed! We send a buy order at the current market price. On the other hand if the user reacts with any other emoji, or 30 seconds pass, then the order will be cancelled.</p><p>This gives us at least a sense of how much we’ll be spending and the added benefit of avoiding a catastrophic mistake =].</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/652/1*sbKAKaTtA5M0Ikob9-9hfQ.png" /><figcaption>A successful trade being issued</figcaption></figure><p>I strongly recommend checking out Alpaca’s O<a href="https://alpaca.markets/docs/api-documentation/api-v2/orders">rder API</a> to see how you can make different types of market orders. For this tutorial we went with the simplest option.</p><h3>Conclusion</h3><p>Thank you for following this tutorial till the end. At this point you should have been able to deploy a discord bot that can buy, with confirmation, stocks on your behalf.</p><p>There’s still A LOT that can be done such as selling the securities you’ve just bought, and more advanced order types and analysis. Stay tuned for Part 2 where I explore more topics in building out Dispaca, the Discord Alpaca.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bde681ad38e2" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>