<?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 Steve Mayo on Medium]]></title>
        <description><![CDATA[Stories by Steve Mayo on Medium]]></description>
        <link>https://medium.com/@stevenwmayo?source=rss-310758628d4------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*yfGhvYWKDE3VQPsnREZpfg.png</url>
            <title>Stories by Steve Mayo on Medium</title>
            <link>https://medium.com/@stevenwmayo?source=rss-310758628d4------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 13:27:10 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@stevenwmayo/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[TRADEnosis™ — My Quest to Build a Mythical Stock Trading Platform]]></title>
            <link>https://medium.com/@stevenwmayo/tradenosis-my-quest-to-build-a-mythical-stock-trading-platform-1771245c54a2?source=rss-310758628d4------2</link>
            <guid isPermaLink="false">https://medium.com/p/1771245c54a2</guid>
            <category><![CDATA[dash-plotly]]></category>
            <category><![CDATA[alpaca-markets]]></category>
            <category><![CDATA[tradenosis]]></category>
            <category><![CDATA[stock-trading]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Steve Mayo]]></dc:creator>
            <pubDate>Wed, 23 Aug 2023 00:18:50 GMT</pubDate>
            <atom:updated>2023-08-23T00:26:34.546Z</atom:updated>
            <content:encoded><![CDATA[<h3>TRADEnosis™ — My Quest to Build a Mythical Stock Trading Platform</h3><h4>Chapter 6: Displaying Orders and Positions</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cffucWmKLkq_dd3ALLGsdg.png" /></figure><p>Alpaca provides a website as well as mobile apps that list orders and positions (but, surprisingly, not an app that handles advanced orders!) so adding this functionality to our trading app is optional. It will require another set of functions and callbacks, which can slow our app, so I’ll try to keep the amount of data retrieved to a minimum.</p><h4>Retrieving Orders</h4><p>Here’s a function to retrieve orders from Alpaca. Put this code near the top of our script in the “Functions” section. First, it configures the TradingClient with the required access keys and then configures the GetOrdersRequest object with the set of configuration passed into the function.</p><p>The get_orders call to Alpaca returns a nested <em>key:value</em> object that then get’s parsed to extract and configure the data we need. Notice in the request, I set nested=True which embeds the exit legs of Advanced orders within the opening-order record. Setting that parameter to False would put each leg into its own “row” in the structure, but I wanted to maintain a linkage between the entry order and its exit legs, which is the purpose of that second loop. Finally, the extracted data is returned as a Pandas dataFrame.</p><pre>def retrieve_orders(key: str, secret: str, paper: bool, status: str = &#39;all&#39;,<br>                    limit: int = 50, symbols: list = [], side: str = None,<br>                    until: Union[None, datetime] = None, after: Union[None, datetime] = None,<br>                    ) -&gt; pd.DataFrame:<br>    &quot;&quot;&quot; Get Alpaca Orders as a dataFrame<br><br>    :param paper        [Reqired] True if &#39;paper&#39; (default) or &#39;live&#39;.<br>    :param key:         [Required] The Alpaca.Markets access key for either paper or live acct.<br>    :param secret:      [Required] The Alpaca secret key for either paper or live acct. Required<br>    :param status:      Str convertible to QueryOrderStatus:  open, closed, all (default).<br>    :param limit:       Default is 50, max is 500 records retrieved<br>    :param side:        &#39;Buy&#39; or &#39;Sell&#39; or &#39;None&#39; (default)<br>    :param symbols:     One or more tickers as a list, ex. [&#39;AAPL&#39;]. defaults to [].<br>    :param until:       Exclusive filter as timestamp in ISO8601 with NO TIMEZONE OR MILLISECONDS!!<br>    :param after:       Exclusive filter as imestamp in ISO8601 with NO TIMEZONE OR MILLISECONDS!!<br><br>    :return:            Dataframe with selected columns from Orders records. Each<br>                        leg of multi-leg order will have separate row and the opening<br>                        order will have ids of its advanced closing legs, if any, in the &#39;leg&#39; column.<br>    &quot;&quot;&quot;<br><br>    trading_client = TradingClient(key, secret, paper=paper)<br>    request_params = GetOrdersRequest(<br>        status=status,<br>        limit=limit,<br>        nested=True,  # roll-up multileg<br>        symbols=symbols,  # must be a [list]<br>        side=side,<br>        until=until,<br>        after=after,<br>        # direction=&#39;desc&#39;,  # or &#39;asc&#39; but not implemented<br>    )<br><br>    # Get requested orders<br>    orders_data = trading_client.get_orders(filter=request_params)<br><br>    # Process opening orders<br>    data = []<br>    for order in orders_data:<br>        main_order_leg = order.id if order.legs else &#39;&#39;  # Set to main order ID if legs exist, else empty<br>        order_data = [<br>            order.id,  # ID of this specific order<br>            order.client_order_id,<br>            order.symbol,<br>            order.side,<br>            order.time_in_force,<br>            order.created_at.strftime(&#39;%Y-%m-%d %H:%M:%S&#39;) if order.created_at else None,<br>            order.filled_at.strftime(&#39;%Y-%m-%d %H:%M:%S&#39;) if order.filled_at else None,<br>            order.limit_price,<br>            order.stop_price,<br>            order.qty,<br>            order.filled_qty,<br>            order.filled_avg_price,<br>            order.notional,<br>            order.trail_percent,<br>            order.trail_price,<br>            order.extended_hours,<br>            order.hwm,<br>            order.order_class,<br>            order.order_type.value if order.order_type else None,<br>            order.status.value if order.status else None,<br>            main_order_leg,  # Empty if no legs, main order ID if it&#39;s a leg<br>        ]<br>        data.append(order_data)<br><br>        for leg in order.legs or []:<br>            leg_data = [<br>                leg.id,  # Reference to THIS closing leg<br>                leg.client_order_id,<br>                leg.symbol,<br>                leg.side,<br>                leg.time_in_force,<br>                leg.created_at.strftime(&#39;%Y-%m-%d %H:%M:%S&#39;) if leg.created_at else None,<br>                leg.filled_at.strftime(&#39;%Y-%m-%d %H:%M:%S&#39;) if leg.filled_at else None,<br>                leg.limit_price,<br>                leg.stop_price,<br>                leg.qty,<br>                leg.filled_qty,<br>                leg.filled_avg_price,<br>                leg.notional,<br>                leg.trail_percent,<br>                leg.trail_price,<br>                leg.extended_hours,<br>                leg.hwm,<br>                leg.order_class,<br>                leg.order_type.value if leg.order_type else None,<br>                leg.status.value if leg.status else None,<br>                order.id,  # Main order ID for legs<br>            ]<br>            data.append(leg_data)<br><br>    # Create a dataFrame with the extracted orders and matched column names<br>    columns = [<br>        &#39;id&#39;, &#39;client_id&#39;, &#39;symbol&#39;, &#39;side&#39;, &#39;tif&#39;, &#39;created_at&#39;, &#39;filled_at&#39;, &#39;limit_price&#39;, &#39;stop_price&#39;,<br>        &#39;qty&#39;, &#39;filled_qty&#39;, &#39;filled_price&#39;, &#39;notional&#39;, &#39;trail_perc&#39;, &#39;trail_price&#39;, &#39;ext_hours&#39;, &#39;hwm&#39;,<br>        &#39;order_class&#39;, &#39;order_type&#39;, &#39;status&#39;, &#39;leg&#39;<br>    ]<br>    df_orders = pd.DataFrame(data, columns=columns)  # .drop_duplicates()<br><br>    return df_orders</pre><p>As it is similar, let’s go ahead and look at the function for retrieving positions. Alpaca actually provide two calls, one for retrieving all positions and another for retrieving the positions for a specific symbol. Rather than writing two separate functions with identical parsing code, I combined the two requests here, using a simple if ticker: conditional. I also put the try/except blocks here, rather than in the callback, as the responses differ: a single object versus a nested object for get_all_positions.</p><pre>def retrieve_positions(ticker: str, key: str, secret: str, paper: bool):<br>    &quot;&quot;&quot; Get Alpaca positions as a list of dicts. (Closed positions only available in account activities!)<br>    If supplied, get only the positions for a specific ticker otherwise retrieve all open positions.<br>    &quot;&quot;&quot;<br><br>    # Retrieve positions as list-of-dicts: [{&#39;key&#39;: &#39;value&#39;, &#39;key2&#39;: &#39;value2&#39;}, {&#39;key&#39;: &#39;value&#39;}]<br>    trading_client = TradingClient(key, secret, paper=paper)<br>    if ticker:<br>        try:<br>            position = trading_client.get_open_position(ticker)<br>            positions = [position] if position else []  # Convert single object to a list, so can handle the same way.<br>        except APIError as e:<br>            return None<br>    else:<br>        try:<br>            positions = trading_client.get_all_positions()<br>        except APIError as e:<br>            return None<br><br>    # Process positions<br>    data = []<br>    for p in positions:<br>        positions_data = [<br>            # p.asset_id,<br>            p.symbol if p.symbol else &quot;&quot;,<br>            # p.exchange,  # NASDAQ<br>            # p.asset_class,  # us_equity<br>            p.side,  # long/short<br>            p.qty,<br>            p.qty_available,  # qty after allowing for open orders<br>            p.avg_entry_price,  # Alpaca consolidates fills, individual retrievable only through Orders.<br>            p.cost_basis,  # qty * entry_price<br><br>            p.current_price,  # stock price at time of run<br>            p.market_value,  # qty * current_price<br><br>            p.unrealized_pl,  # extrapolated $pnl<br>            p.unrealized_plpc,  # extrapolated pnl as ratio (multiply x 100 to get percent)<br>            p.unrealized_intraday_pl,  # today&#39;s change in $pnl<br>            p.unrealized_intraday_plpc,  # today&#39;s change in pnl ratio<br>            # p.lastday_price,  # prior day&#39;s price (as used for calculating intraday change<br>            # p.change_today,  # Seems to be same as unrealized_intraday_pl?<br>        ]<br>        data.append(positions_data)<br><br>    # Create a dataFrame with the extracted positions and matched column names<br>    columns = [<br>        &#39;symbol&#39;, &#39;side&#39;, &#39;qty&#39;, &#39;q_avail&#39;, &#39;avg_entry_price&#39;, &#39;cost_basis&#39;, &#39;current_price&#39;,<br>        &#39;mkt_value&#39;, &#39;unrealized_pl&#39;, &#39;unrealized_plp&#39;, &#39;today_pl&#39;, &#39;today_plp&#39;<br>    ]<br>    df_positions = pd.DataFrame(data, columns=columns)  # .drop_duplicates()<br><br>    return df_positions</pre><p>Here’s the callback needed to process and post the orders to the front-end. In an attempt to squeeze all this data into a table format, I consolidated the fields into a small number of summary columns.</p><pre># region CALLBACK LOAD ORDERS<br>@callback(<br>    Output(&#39;orders_table&#39;, &#39;data&#39;),<br>    # Input(&#39;refresh-orders&#39;, &#39;n_clicks&#39;),<br>    Input(&#39;order-account-radios&#39;, &#39;value&#39;),<br>    Input(&#39;order-type-select&#39;, &#39;value&#39;),<br>    Input(&#39;order-limit-select&#39;, &#39;value&#39;),<br>    Input(&#39;after-input&#39;, &#39;date&#39;),  # &#39;value&#39; if using html date input<br>    Input(&#39;until-input&#39;, &#39;date&#39;),  # &#39;value&#39; if using html date input<br>    Input(&#39;selected-symbol-store&#39;, &#39;data&#39;),<br>    State(&#39;alpaca-key-paper&#39;, &#39;value&#39;),<br>    State(&#39;alpaca-secret-paper&#39;, &#39;value&#39;),<br>    State(&#39;alpaca-key-live&#39;, &#39;value&#39;),<br>    State(&#39;alpaca-secret-live&#39;, &#39;value&#39;),<br>)<br>def display_orders(<br>        # refresh_btn,<br>        acct, ord_filter, show, after, until,<br>        symbol, key_paper, secret_paper, key_live, secret_live):<br>    if acct == &#39;live&#39;:<br>        key = key_live<br>        secret = secret_live<br>        paper = False<br>    elif acct == &#39;paper&#39;:<br>        key = key_paper<br>        secret = secret_paper<br>        paper = True<br>    else:<br>        raise PreventUpdate<br><br>    # Determine filter, if symbol then set to current symbol, if selected in watchlist<br>    if ord_filter == &#39;symbol&#39;:<br>        symbols = [symbol] if symbol else []  # Ignore filter if no symbol selected yet<br>        status = &quot;all&quot;<br>    else:<br>        status = ord_filter  # all, open, closed<br>        symbols = []<br><br>    # Format and adjust After/Until dates<br>    after = pd.to_datetime(after)  # + timedelta(days=1) if after else None<br>    until = pd.to_datetime(until)  # - timedelta(days=1) if until else None<br><br>    limit = show if show else 500<br>    side = None<br>    df_orders = retrieve_orders(key=key, secret=secret, paper=paper, status=status,<br>                                limit=limit, symbols=symbols, side=side, until=until, after=after)<br>    if df_orders.empty:<br>        raise PreventUpdate<br><br>    # Make the id columns serializable, so they can be passed to the dataTable<br>    df_orders[&#39;id&#39;] = df_orders[&#39;id&#39;].apply(str)<br>    df_orders[&#39;leg&#39;] = df_orders[&#39;leg&#39;].apply(str)<br><br>    def create_columns(row):<br>        type_at_price = &quot;&quot;<br>        if row[&#39;order_type&#39;] == &#39;limit&#39;:<br>            type_at_price = f&quot;LIMIT @${row[&#39;limit_price&#39;]}&quot;<br>        elif row[&#39;order_type&#39;] == &#39;stop&#39;:<br>            type_at_price = f&quot;STOP @${row[&#39;stop_price&#39;]}&quot;<br>        elif row[&#39;order_type&#39;] == &#39;stop_limit&#39;:<br>            type_at_price = f&quot;STOP-LIMIT @${row[&#39;stop_price&#39;]}|${row[&#39;limit_price&#39;]}&quot;<br>        elif row[&#39;order_type&#39;] == &#39;trailing_stop&#39;:<br>            if row[&#39;trail_perc&#39;]:<br>                type_at_price = f&quot;TRAIL @{row[&#39;trail_perc&#39;]}%&quot;<br>            elif row[&#39;trail_price&#39;]:<br>                type_at_price = f&quot;TRAIL @${row[&#39;trail_price&#39;]}&quot;<br>        elif row[&#39;order_type&#39;] == &#39;market&#39;:<br>            type_at_price = &quot;MARKET&quot;<br>        else:<br>            type_at_price = &quot;******&quot;<br><br>        if row[&#39;notional&#39;]:<br>            qty_or_notional = f&quot;${row[&#39;notional&#39;]}&quot;<br>        else:<br>            qty_or_notional = f&quot;{row[&#39;qty&#39;]}&quot;<br><br>        ext = &#39;EXT&#39; if row[&#39;ext_hours&#39;] else &quot;&quot;<br><br>        instructions = f&quot;{row[&#39;side&#39;].capitalize()} {qty_or_notional} {ext} {row[&#39;tif&#39;]} {type_at_price}&quot;<br>        fill_info = f&quot;{row[&#39;filled_qty&#39;]} @${row[&#39;filled_price&#39;]} on {row[&#39;filled_at&#39;]}&quot; if row[&#39;filled_at&#39;] else &#39;&#39;<br><br>        return instructions, fill_info<br><br>    # Calc instructions by row<br>    df_orders[[&#39;instructions&#39;, &#39;filled_info&#39;]] = df_orders.apply(lambda row: create_columns(row),<br>                                                                 axis=1, result_type=&#39;expand&#39;)<br><br>    return df_orders.to_dict(&#39;records&#39;)<br># endregion /load orders cb</pre><p>And, here’s the similar callback for handing positions.</p><pre># region CALLBACK LOAD POSITIONS<br>@callback(<br>    Output(&#39;positions_table&#39;, &#39;data&#39;),<br>    Input(&#39;selected-symbol-store&#39;, &#39;data&#39;),<br>    Input(&#39;position-filter&#39;, &#39;value&#39;),<br>    Input(&#39;position-account-radios&#39;, &#39;value&#39;),<br>    State(&#39;alpaca-key-paper&#39;, &#39;value&#39;),<br>    State(&#39;alpaca-secret-paper&#39;, &#39;value&#39;),<br>    State(&#39;alpaca-key-live&#39;, &#39;value&#39;),<br>    State(&#39;alpaca-secret-live&#39;, &#39;value&#39;),<br>)<br>def display_positions(<br>        symbol, pos_filter, acct, key_paper, secret_paper, key_live, secret_live):<br>    if acct == &#39;live&#39;:<br>        key = key_live<br>        secret = secret_live<br>        paper = False<br>    elif acct == &#39;paper&#39;:<br>        key = key_paper<br>        secret = secret_paper<br>        paper = True<br>    else:<br>        raise PreventUpdate<br><br>    if pos_filter == &quot;all&quot;:<br>        df_positions = retrieve_positions(&quot;&quot;, key, secret, paper)<br>        if df_positions is None or df_positions.empty:<br>            return []<br>    elif pos_filter == &quot;symbol&quot; and symbol:<br>        df_positions = retrieve_positions(symbol, key, secret, paper)<br>        if df_positions is None or df_positions.empty:<br>            return []<br>    else:<br>        raise PreventUpdate<br><br>    # Calc Table Columns<br>    def create_columns(row):<br>        pos_text = f&quot;{row[&#39;qty&#39;]} {row[&#39;side&#39;]} @ ${float(row[&#39;avg_entry_price&#39;]):,.3f} &quot; \<br>                   f&quot;(${float(row[&#39;cost_basis&#39;]):.2f})&quot;<br>        curr_text = f&quot;${float(row[&#39;current_price&#39;]):.3f} (${float(row[&#39;mkt_value&#39;]):,.2f})&quot;<br><br>        pnl_text = f&quot;{float(row[&#39;unrealized_plp&#39;]):.2%} ({format_dollar(float(row[&#39;unrealized_pl&#39;]))})&quot;<br>        return pos_text, curr_text, pnl_text<br><br>    df_positions[[&#39;position&#39;, &#39;current&#39;, &#39;pnl&#39;]] = df_positions.apply(lambda row: create_columns(row),<br>                                                                      axis=1, result_type=&#39;expand&#39;)<br><br>    return df_positions.to_dict(&#39;records&#39;)<br><br><br># endregion /cb load positions</pre><p>For both of these callbacks, you’ll notice in the Inputs several new id’s for fields that I added to the tab layouts. These inputs are intended to limit the amount of data that the user routinely loads (to reduce overhead), but still allow the listings to be expanded when needed.</p><p>Here’s the updated Positions Card. Notice that the position-filter radio has a value of ‘symbol’, meaning only the one (if any) position will get loaded as the default.</p><pre># region LAYOUT - POSITIONS CARD<br>positions_card = dbc.Card(<br>    [<br>        dbc.CardBody(<br>            [<br>                dbc.Row(<br>                    [<br>                        dbc.Col(<br>                            dbc.RadioItems(<br>                                options=[<br>                                    {&quot;label&quot;: &quot;Symbol&quot;, &quot;value&quot;: &#39;symbol&#39;},<br>                                    {&quot;label&quot;: &quot;All&quot;, &quot;value&quot;: &#39;all&#39;},<br>                                ],<br>                                value=&#39;symbol&#39;,<br>                                inline=True,<br>                                className=&quot;rfs-small&quot;,<br>                                id=&quot;position-filter&quot;,<br>                            ),<br>                            xs=6, md=3<br>                        ),<br>                        dbc.Col(<br>                            dbc.RadioItems(<br>                                options=[<br>                                    {&quot;label&quot;: &quot;Paper&quot;, &quot;value&quot;: &#39;paper&#39;},<br>                                    {&quot;label&quot;: &quot;Live&quot;, &quot;value&quot;: &#39;live&#39;},<br>                                ],<br>                                value=&#39;paper&#39;,<br>                                inline=True,<br>                                className=&quot;rfs-small&quot;,<br>                                id=&quot;position-account-radios&quot;,<br>                            ),<br>                            xs=6, md=3<br>                        ),<br>                    ]<br>                ),<br>                dbc.Row(<br>                    [<br>                        dash_table.DataTable(<br>                            id=&quot;positions_table&quot;,<br>                            data=[],<br>                            columns=[<br>                                {&quot;name&quot;: &#39;Ticker&#39;, &quot;id&quot;: &#39;symbol&#39;, &#39;type&#39;: &quot;text&quot;},<br>                                {&quot;name&quot;: &#39;Position&#39;, &quot;id&quot;: &#39;position&#39;, &#39;type&#39;: &quot;text&quot;},<br>                                {&quot;name&quot;: &#39;Current Value&#39;, &quot;id&quot;: &#39;current&#39;, &#39;type&#39;: &quot;text&quot;},<br>                                {&quot;name&quot;: &#39;Profit/Loss&#39;, &quot;id&quot;: &#39;pnl&#39;, &#39;type&#39;: &quot;text&quot;},<br>                            ],<br>                            style_cell={<br>                                &#39;textAlign&#39;: &#39;left&#39;,<br>                                &#39;height&#39;: &#39;auto&#39;,<br>                                &#39;minWidth&#39;: &#39;50px&#39;,<br>                                &#39;whiteSpace&#39;: &#39;normal&#39;<br>                            },<br>                            style_as_list_view=True,<br>                            style_header={&#39;font-weight&#39;: &#39;600&#39;, &#39;font-size&#39;: &#39;12px&#39;},<br>                            style_data={&#39;font-size&#39;: &#39;12px&#39;},<br>                            style_table={&#39;height&#39;: &#39;20vh&#39;, &#39;overflow&#39;: &#39;auto&#39;}<br>                        )<br>                    ]<br>                ),<br><br>            ]<br>        )<br>    ]<br>)<br># endregion /positions card</pre><p>Here’s the updated Orders layout. Similarly here, the default is to load only two“rows”, which may get expanded up to six rows if those two orders have exit legs. Although the default again is to load only the orders for the specified symbol, given the differences in how Alpaca implemented these calls, the callback doesn’t blank the table when it initially loads orders for all symbols. I liked this, so I decided to keep it knowing that it wouldn’t significantly impact performance since no graph would be showing yet.</p><pre># region LAYOUT - ORDERS CARD<br>orders_card = dbc.Card(<br>    [<br>        dbc.CardBody(<br>            [<br>                dbc.Row(<br>                    [<br><br>                    ],<br>                    align=&quot;center&quot;, justify=&quot;evenly&quot;<br>                ),<br>                dbc.Row(<br>                    [<br>                        dbc.Col(<br>                            dbc.RadioItems(<br>                                options=[<br>                                    {&quot;label&quot;: &quot;Paper&quot;, &quot;value&quot;: &#39;paper&#39;},<br>                                    {&quot;label&quot;: &quot;Live&quot;, &quot;value&quot;: &#39;live&#39;},<br>                                ],<br>                                value=&#39;paper&#39;,<br>                                inline=True,<br>                                className=&quot;rfs-small&quot;,<br>                                id=&quot;order-account-radios&quot;,<br>                            ),<br>                            # xs=6, md=3<br>                        ),<br>                        dbc.Col(<br>                            [<br>                                html.Div([<br>                                    html.Div(&quot;Filter: &quot;, className=&quot;rfs-tiny&quot;),<br>                                    dbc.Select(<br>                                        id=&#39;order-type-select&#39;,<br>                                        options=[<br>                                            {&quot;label&quot;: &quot;All&quot;, &quot;value&quot;: &quot;all&quot;},<br>                                            {&quot;label&quot;: &quot;Open&quot;, &quot;value&quot;: &quot;open&quot;},<br>                                            {&quot;label&quot;: &quot;Closed&quot;, &quot;value&quot;: &quot;closed&quot;},<br>                                            {&quot;label&quot;: &quot;Symbol&quot;, &quot;value&quot;: &quot;symbol&quot;},<br>                                        ],<br>                                        value=&#39;symbol&#39;, size=&quot;sm&quot;<br>                                    )<br>                                ],<br>                                ),<br>                            ],<br>                            # xs=6, md=3, lg=2<br>                        ),<br>                        dbc.Col(<br>                            [<br>                                html.Div([<br>                                    html.Div(&quot;Show: &quot;, className=&quot;rfs-tiny&quot;),<br>                                    dbc.Select(<br>                                        id=&#39;order-limit-select&#39;,<br>                                        options=[<br>                                            {&quot;label&quot;: &quot;3&quot;, &quot;value&quot;: 2},<br>                                            {&quot;label&quot;: &quot;20&quot;, &quot;value&quot;: 20},<br>                                            {&quot;label&quot;: &quot;50&quot;, &quot;value&quot;: 50},<br>                                            {&quot;label&quot;: &quot;100&quot;, &quot;value&quot;: 100},<br>                                            {&quot;label&quot;: &quot;500 Max&quot;, &quot;value&quot;: 500},<br>                                        ],<br>                                        value=2, size=&quot;sm&quot;<br>                                    )<br>                                ],<br>                                ),<br>                            ],<br>                            # xs=6, md=3, lg=2<br>                        ),<br>                        dbc.Col(<br>                            [<br>                                html.Div(&quot;After:&quot;, className=&quot;rfs-tiny&quot;),<br>                                # dbc.Input(id=&quot;after-input&quot;, type=&quot;date&quot;, debounce=True, size=&quot;sm&quot;)<br>                                dcc.DatePickerSingle(<br>                                    id=&#39;after-input&#39;,<br>                                    clearable=True,<br>                                    day_size=24,<br>                                    month_format=&quot;MMM YYYY&quot;,<br><br>                                )<br>                            ],<br>                            # xs=6, md=3, lg=2<br>                        ),<br>                        dbc.Col(<br>                            [<br>                                html.Div(&quot;Before:&quot;, className=&quot;rfs-tiny&quot;),<br>                                # dbc.Input(id=&quot;until-input&quot;, type=&quot;date&quot;, debounce=True, size=&quot;sm&quot;),<br>                                dcc.DatePickerSingle(<br>                                    id=&#39;until-input&#39;,<br>                                    className=&quot;&quot;,<br>                                    style={},<br>                                    clearable=True,<br>                                    day_size=24,<br>                                    month_format=&quot;MMM YYYY&quot;,<br>                                )<br>                            ],<br>                            # xs=6, md=3, lg=2<br>                        )<br>                    ],<br>                    align=&quot;center&quot;, justify=&quot;evenly&quot;, className=&quot;my-2&quot;<br>                ),<br>                dbc.Row(<br>                    dash_table.DataTable(<br>                        id=&#39;orders_table&#39;,<br>                        data=[],<br>                        columns=[<br>                            {&quot;name&quot;: &#39;Ticker&#39;, &quot;id&quot;: &#39;symbol&#39;, &#39;type&#39;: &quot;text&quot;},<br>                            {&quot;name&quot;: &#39;Order&#39;, &quot;id&quot;: &#39;instructions&#39;, &#39;type&#39;: &quot;text&quot;},<br>                            {&quot;name&quot;: &#39;Filled?&#39;, &quot;id&quot;: &#39;filled_info&#39;, &#39;type&#39;: &quot;text&quot;},<br>                            {&quot;name&quot;: &#39;Type&#39;, &quot;id&quot;: &#39;order_class&#39;, &#39;type&#39;: &quot;text&quot;},<br>                            {&quot;name&quot;: &#39;Created&#39;, &quot;id&quot;: &#39;created_at&#39;, &#39;type&#39;: &quot;text&quot;},<br>                            {&quot;name&quot;: &#39;Status&#39;, &quot;id&quot;: &#39;status&#39;, &#39;type&#39;: &quot;text&quot;},<br>                        ],<br>                        style_cell={<br>                            &#39;textAlign&#39;: &#39;left&#39;,<br>                            &#39;height&#39;: &#39;auto&#39;,<br>                            &#39;minWidth&#39;: &#39;50px&#39;,<br>                            &#39;whiteSpace&#39;: &#39;normal&#39;<br>                        },<br>                        style_as_list_view=True,<br>                        style_header={&#39;font-weight&#39;: &#39;600&#39;, &#39;font-size&#39;: &#39;12px&#39;},<br>                        style_data={&#39;font-size&#39;: &#39;12px&#39;},<br>                        style_table={&#39;width&#39;: &#39;100%&#39;, &#39;height&#39;: &#39;20vh&#39;, &#39;overflow&#39;: &#39;auto&#39;}<br>                    ),<br>                )<br>            ],<br>        )<br>    ], className=&quot;mb-3&quot;<br>)<br># endregion / orders card</pre><p>Orders can be retrieved within a specified date range, so I added “Before” and “After” inputs. Initially, I used the “date” type in a standard input. That works, but I decided to try the Dash dcc.DatePickerSingle component. The problem with it is that it’s very tall, so I had to add some code to the styles.css external stylesheet as Dash doesn’t provide an interface to adjust it. Here’s that style code:</p><pre>/*Adjust the Before/After DatePickerSingle spacing */<br>.SingleDatePicker #date {<br>  padding-top: 1px;<br>  padding-bottom: 1px;<br>  font-size: 14px;<br>}</pre><p>Finally, we’ve completed our quest and we can head back to Camelot. Here’s our now fully-functional trading platform on initial load. Notice it is showing multiple stocks but only four rows, three of which are part of a single bracket order.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rJK1N9sm5uHTNilngQ8ZTA.png" /></figure><p>And here’s how the Orders tab looks after selecting a ticker. Now, the listing is filtered to show only those orders pertaining to the selected stock.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7pVL_nDcmpQqYZ7w5WuTnQ.png" /></figure><p>Finally, here’s the Positions tab showing the composite position for the selected stock (it is blank until then). Seems it wasn’t a great time to buy fruit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5b71RfmMzVfjDCtTasaI8w.png" /></figure><p>And, just to prove that it is responsive, here’s that same view as simulated for an iPhone 8 screen. I’m still not 100% happy with the spacing, but as I mentioned at the start of this series, one could easily spend a lifetime trying to get the perfect layout across all screen widths!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/792/1*5m-obt_HQWNMcGWrNfeqWQ.png" /></figure><h4>Back at Camelot</h4><p>We’ve reached the end of our journey. I think you now understand why I called this a quest. It’s almost 2000 lines of code and dealing with our limited armament (Python and Dash may not be the best choice) and the lack of a map (or at least, good documentation) were challenges. But we prevailed. Thank you for joining me on this quest and I hope you will give me feedback, maybe even a nice hand clap. Until we meet again, my friends!</p><h4>Where should you go from here?</h4><p>This is the only example of a fully functional Alpaca trading app that I’ve seen; even Alpaca’s examples don’t support advance orders and most code snippets you will find use the (now obsolete?) older version of the Python SDK. Don’t even bother asking ChatGPT for help, as it doesn’t know about this new version at all.</p><p>Anyway, this should therefore be a good working prototype for you to now start adding additional functionality. Consider:</p><ul><li>Minimally, adding a way to select symbols, perhaps using Alpaca’s Assets request.</li><li>Adding technical analysis studies — implemented as additional series in the chart component.</li><li>Displaying an equity curve — using Alpaca’s Account Activities functionality, albeit that doesn’t seem to be in their Python SDK yet.</li><li>Implementing algorithmic trading, buy/sell signals on the chart and backtesting functionality, perhaps using machine learning algorithms. This is where sticking with Python seems like the right choice!</li><li>Modify the code to support crypto — Alpaca uses different requests and there are different trading rules for that.</li></ul><p>As for me, I decided to focus my time on building a API-based web services platform to support running complex machine learning algorithms on thousands of stocks. After showing my results to a commercial vendor, I was able to strike a deal where they would connect my API to their desktop software, providing the robust graphing, symbol management, technical analysis and trade management functionality needed for a commercial platform. <strong>That’s what became the commercial </strong><a href="https://www.nirvanasystems.com/tradenosis/"><strong>TRADEnosis Trading Platform</strong></a><strong>!</strong></p><h3>A Summary of our Adventure:</h3><ul><li>In <a href="https://medium.com/@stevenwmayo/tradenosis-my-quest-to-build-a-mythical-stock-trading-platform-chapter-1-90924cd09f3f"><strong>Chapter 1</strong></a>, we developed the user interface for a basic trading webpage using Plotly Dash.</li><li>In <a href="https://medium.com/@stevenwmayo/tradenosis-my-quest-to-build-a-mythical-stock-trading-platform-e2c62f10e67b"><strong>Chapter 2</strong></a>, we created an Alpaca Settings dialog and wrote code to load candlestick price data into a stock chart.</li><li>In <a href="https://medium.com/@stevenwmayo/tradenosis-my-quest-to-build-a-mythical-stock-trading-platform-c1bf56372d7c"><strong>Chapter 3</strong></a>, we reviewed Alpaca’s trading rules.</li><li>In <a href="https://medium.com/@stevenwmayo/tradenosis-my-quest-to-build-a-mythical-stock-trading-platform-31d452683b6"><strong>Chapter 4</strong></a>, we created the order form and associated code to compile trade instructions.</li><li>In <a href="https://medium.com/@stevenwmayo/tradenosis-my-quest-to-build-a-mythical-stock-trading-platform-65a46823c606"><strong>Chapter 5</strong></a>, we wrote the callback needed to submit an order to Alpaca.</li><li>In this final chapter,<strong> </strong>we compiled data to the Orders and Positions tabs.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1771245c54a2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[TRADEnosis™ — My Quest to Build a Mythical Stock Trading Platform]]></title>
            <link>https://medium.com/@stevenwmayo/tradenosis-my-quest-to-build-a-mythical-stock-trading-platform-65a46823c606?source=rss-310758628d4------2</link>
            <guid isPermaLink="false">https://medium.com/p/65a46823c606</guid>
            <category><![CDATA[tradenosis]]></category>
            <category><![CDATA[dash]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[alpacafinance]]></category>
            <category><![CDATA[trading]]></category>
            <dc:creator><![CDATA[Steve Mayo]]></dc:creator>
            <pubDate>Tue, 22 Aug 2023 22:15:19 GMT</pubDate>
            <atom:updated>2023-08-23T00:29:22.391Z</atom:updated>
            <content:encoded><![CDATA[<h3>TRADEnosis™ — My Quest to Build a Mythical Stock Trading Platform</h3><h4>Chapter 5: Submitting a Trade Order to Alpaca</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cffucWmKLkq_dd3ALLGsdg.png" /></figure><p>As our journey has been long and you, my brave fellow knight, are sure to be weary, I’ll catapult right into our next challenge of writing the callback in <strong>Plotly Dash</strong> to submit a trade order to <strong>Alpaca Markets</strong> using their <strong>Python SDK version 2</strong>. If you are new to our quest to build a <strong>stock trading platform</strong>, or ponder my medieval parlance, start with <a href="https://medium.com/@stevenwmayo/tradenosis-my-quest-to-build-a-mythical-stock-trading-platform-chapter-1-90924cd09f3f"><strong>Chapter 1</strong></a>.</p><p>During our exploits so far, we learned that Alpaca expects us to submit a minimum set of instructions for a basic trade, plus even more instructions for advanced multi-leg orders. Further, we learned of a complex set of rules that must be followed when submitting orders to a broker.</p><p>As a quick starting point, let’s add the imports that we’ll need in this chapter. I also removed the ones we won’t be using.</p><pre>from typing import Union<br>import pandas as pd<br>import json<br>import pytz<br>from dash import Dash, dcc, html, callback, Input, Output, State, dash_table, no_update, ctx<br>from dash.exceptions import PreventUpdate<br>import dash_bootstrap_components as dbc<br>import dash_tvlwc<br>from datetime import datetime<br>from alpaca.data.historical import StockHistoricalDataClient<br>from alpaca.data.requests import StockBarsRequest, StockSnapshotRequest<br>from alpaca.data.timeframe import TimeFrame<br>from alpaca.trading.client import TradingClient<br>from alpaca.trading.requests import (<br>    MarketOrderRequest,<br>    StopOrderRequest,<br>    LimitOrderRequest,<br>    StopLimitOrderRequest,<br>    TrailingStopOrderRequest,<br>    TakeProfitRequest,<br>    StopLossRequest,<br>    GetOrdersRequest,<br>)<br>from alpaca.trading import (<br>    OrderType,<br>    OrderSide,<br>    OrderClass,<br>)<br>from alpaca.common.exceptions import APIError<br>from pydantic import ValidationError</pre><p>We’ve already created a layout to collect the necessary instructions, so let’s start by adding those fields to a new “COMPILE ORDERS” callback as our Input arguments. For the Output arguments (which must come first), we will reference an order-summary html component (where we will display compiled instructions for user review), the submit button, and an argument that will close the modal after submission. Additionally, as State arguments, we must reference the Alpaca keys and our stored data being passed from other callbacks. As you can see, this is going to be a long and complex callback!</p><pre># region CALLBACK - COMPILE ORDERS<br>@callback(<br>    # TODO: Add &quot;disable_n_clicks=True&quot; to non-btns in layout -- helps screen readers and reduces traffic<br>    Output(&#39;order-summary&#39;, &#39;children&#39;),<br>    Output(&#39;submit-button&#39;, &#39;disabled&#39;),  # True or False<br>    Output(&#39;order-status-store&#39;, &#39;data&#39;),  # &quot;submitted&quot; or &quot;&quot;<br>    Output(&#39;orders-modal&#39;, &#39;is_open&#39;, allow_duplicate=True),  # True or False<br>    Output(&#39;order-toast&#39;, &#39;is_open&#39;),  # True or False<br>    Output(&#39;order-toast&#39;, &#39;children&#39;),<br><br>    Input(&#39;account&#39;, &#39;value&#39;),  # &#39;paper&#39; or &#39;live&#39;<br>    Input(&#39;order-side&#39;, &#39;value&#39;),  # &#39;buy&#39; or &#39;sell&#39;<br>    Input(&#39;qty&#39;, &#39;value&#39;),<br>    Input(&#39;qty-icon&#39;, &#39;children&#39;),  # &#39;$&#39; or &#39;%&#39;<br>    Input(&#39;tif&#39;, &#39;value&#39;),<br>    Input(&#39;limit-entry&#39;, &#39;value&#39;),<br>    Input(&#39;stop-entry&#39;, &#39;value&#39;),<br>    Input(&#39;trailing-stop&#39;, &#39;value&#39;),<br>    Input(&#39;trailing-icon&#39;, &#39;children&#39;),  # &#39;$&#39; or &#39;%&#39;<br>    Input(&#39;profit-leg-limit&#39;, &#39;value&#39;),<br>    Input(&#39;loss-leg-limit&#39;, &#39;value&#39;),<br>    Input(&#39;loss-leg-stop&#39;, &#39;value&#39;),<br>    Input(&#39;oco_checked&#39;, &#39;value&#39;),<br>    Input(&#39;submit-button&#39;, &#39;n_clicks&#39;),<br><br>    State(&#39;selected-symbol-store&#39;, &#39;data&#39;),<br>    State(&quot;alpaca-key-paper&quot;, &quot;value&quot;),<br>    State(&quot;alpaca-secret-paper&quot;, &quot;value&quot;),<br>    State(&quot;alpaca-key-live&quot;, &quot;value&quot;),<br>    State(&quot;alpaca-secret-live&quot;, &quot;value&quot;),<br>    State(&#39;order-status-store&#39;, &#39;data&#39;),<br>    State(&#39;bid-price-store&#39;, &#39;data&#39;),<br>    State(&#39;ask-price-store&#39;, &#39;data&#39;),<br>    State(&#39;last-price-store&#39;, &#39;data&#39;),<br>    prevent_initial_call=True<br>)<br>def compile_order(<br>        account, side, qty, qty_icon, tif, limit, stop, trailing_stop, trailing_icon,<br>        profit_leg_limit, loss_leg_limit, loss_leg_stop, oco_checked, n_submit,<br>        symbol, paper_key, paper_secret, live_key, live_secret, order_status, equity, buy_power,<br>        cash, bid, ask, last):<br>    &quot;&quot;&quot; Compile and validate parameters for a trade order, submit to Alpaca brokerage if user confirms. &quot;&quot;&quot;<br><br>    ...</pre><p>Next, we need to validate our inputs and enforce the trading rules. For that, we’ll use a series of conditional tests. If any test fails, our script will return a message to the order-summary html component of our modal.</p><pre>invalid = None<br>    if not symbol:  # Just in case, but shouldn&#39;t happen as Trade btn hidden until symbol selected<br>        invalid = html.P(&quot;Symbol must be selected.&quot;, className=&quot;text-info&quot;)<br>    if not account:<br>        invalid = html.P(&quot;Account must be selected.&quot;, className=&quot;text-info&quot;)<br>    if not side:<br>        invalid = html.P(&quot;Side must be selected.&quot;, className=&quot;text-info&quot;)<br>    # If you will be trading penny stocks (or modifying code for crypto), modify this to allow 4 digits if &lt;$1<br>    if limit is not None and (not isinstance(limit, (float, int)) or (limit * 100) % 1 != 0):<br>        invalid = html.P(&quot;Limit price must have no more than two decimal places.&quot;, className=&quot;text-info&quot;)<br>    if stop is not None and (not isinstance(stop, (float, int)) or (stop * 100) % 1 != 0):<br>        invalid = html.P(&quot;Stop price must have no more than two decimal places.&quot;, className=&quot;text-info&quot;)<br>    if not qty or not isinstance(qty, (float, int)):<br>        invalid = html.P(&quot;Qty must be a non-blank number &gt; zero.&quot;, className=&quot;text-info&quot;)<br>    if tif == &quot;ext&quot; and not limit:<br>        invalid = html.P(&quot;Extended-hours orders must be Limit.&quot;, className=&quot;text-info&quot;)<br>    if tif == &quot;ext&quot; and (stop or trailing_stop or profit_leg_limit or loss_leg_stop or loss_leg_limit):<br>        invalid = html.P(&quot;Only Limit orders are allowed to use Extended Hours.&quot;, className=&quot;text-info&quot;)<br>    if tif == &quot;opg&quot; and (stop or trailing_stop or profit_leg_limit or loss_leg_stop or loss_leg_limit):<br>        invalid = html.P(&quot;OPG orders must be Limit or Market.&quot;, className=&quot;text-info&quot;)<br>    if tif == &quot;cls&quot; and (stop or trailing_stop or profit_leg_limit or loss_leg_stop or loss_leg_limit):<br>        invalid = html.P(&quot;CLS orders must be Limit or Market.&quot;, className=&quot;text-info&quot;)<br>    if qty and tif == &quot;day&quot; and qty_icon == &quot;$&quot; and \<br>            (limit or stop or trailing_stop or profit_leg_limit or loss_leg_stop or loss_leg_limit):<br>        invalid = html.P(&quot;Notional-Day orders can only be Market.&quot;, className=&quot;text-info&quot;)<br>    if trailing_stop and (limit or stop):<br>        invalid = html.P(&quot;Trailing-stop orders cannot have limit or stop entries.&quot;, className=&quot;text-info&quot;)<br>    if oco_checked and (limit or stop or trailing_stop):<br>        invalid = html.P(&quot;An OCO order cannot open a new entry position.&quot;, className=&quot;text-info&quot;)<br>    if oco_checked and not qty:<br>        invalid = html.P(&quot;An OCO order must have a qty (&lt;= qty in an open position).&quot;, className=&quot;text-info&quot;)<br>    if oco_checked and not profit_leg_limit:<br>        invalid = html.P(&quot;An OCO order must have both legs, missing Take-Profit Limit.&quot;, className=&quot;text-info&quot;)<br>    if oco_checked and not (loss_leg_limit or loss_leg_stop):<br>        invalid = html.P(&quot;An OCO order must have both legs, missing Stop-Loss Limit and/or Stop.&quot;,<br>                         className=&quot;text-info&quot;)<br>    if loss_leg_limit and not loss_leg_stop:<br>        invalid = html.P(&quot;For the Stop-Loss leg, Alpaca only supports Stop or Stop-Limit, &quot;<br>                         &quot;not Limit alone, orders.&quot;, className=&quot;text-info&quot;)<br>    if loss_leg_limit and loss_leg_stop and (side == &quot;buy&quot;) and not (loss_leg_stop &gt;= (loss_leg_limit + 0.01)):<br>        invalid = html.P(&quot;In a sell-to-close Stop-Loss leg, the Stop Price must be at least $0.01 above&quot;<br>                         &quot; the Limit Price for that leg.&quot;, className=&quot;text-info&quot;)<br>    if limit and loss_leg_stop and (side == &quot;buy&quot;) and not (loss_leg_stop &lt;= (limit + 0.01)):<br>        invalid = html.P(&quot;In a sell-to-close Stop-Loss leg, the Stop Price must be at least $0.01 below&quot;<br>                         &quot; the Limit price for the entry order.&quot;, className=&quot;text-info&quot;)<br>    if (bid != 0) and loss_leg_stop and (side == &quot;buy&quot;) and not (loss_leg_stop &lt;= (bid + 0.01)):<br>        invalid = html.P(&quot;In a sell-to-close Stop-Loss leg, the Stop Price must be at least $0.01 below&quot;<br>                         &quot; the current Bid price for the entry order.&quot;, className=&quot;text-info&quot;)<br>    if loss_leg_limit and loss_leg_stop and (side == &quot;sell&quot;) and not (loss_leg_stop &lt;= (loss_leg_limit + 0.01)):<br>        invalid = html.P(&quot;In a buy-to-close Stop-Loss leg, the Stop Price must be at least $0.01 below&quot;<br>                         &quot; the Limit Price for that leg.&quot;, className=&quot;text-info&quot;)<br>    if limit and loss_leg_stop and (side == &quot;sell&quot;) and not (loss_leg_stop &gt;= (limit + 0.01)):<br>        invalid = html.P(&quot;In a buy-to-close Stop-Loss leg, the Stop Price must be at least $0.01 above &quot;<br>                         &quot;the Limit price for the entry order.&quot;, className=&quot;text-info&quot;)<br>    if (ask != 0) and loss_leg_stop and (side == &quot;sell&quot;) and not (loss_leg_stop &lt;= (ask + 0.01)):<br>        invalid = html.P(&quot;In a buy-to-close Stop-Loss leg, the Stop Price must be at least $0.01 below&quot;<br>                         &quot; the current Ask price.&quot;, className=&quot;text-info&quot;)<br>    if profit_leg_limit and (side == &quot;buy&quot;) and loss_leg_stop and not (profit_leg_limit &gt;= (loss_leg_stop + 0.01)):<br>        invalid = html.P(&quot;In a sell-to-close Take-Profit leg, the Limit Price must be at least $0.01 above&quot;<br>                         &quot; the Stop-Loss for Stop-Loss leg.&quot;, className=&quot;text-info&quot;)<br>    if profit_leg_limit and (side == &quot;buy&quot;) and stop and not (profit_leg_limit &lt;= (stop + 0.01)):<br>        invalid = html.P(&quot;In a sell-to-close Take-Profit leg, the Limit Price must be at least $0.01 below&quot;<br>                         &quot; the Stop Price for the entry leg.&quot;, className=&quot;text-info&quot;)<br>    if profit_leg_limit and (side == &quot;buy&quot;) and limit and not (profit_leg_limit &gt;= (limit + 0.01)):<br>        invalid = html.P(&quot;In a sell-to-close Take-Profit leg, the Limit Price must be at least $0.01 above&quot;<br>                         &quot; the Limit Price for the entry leg.&quot;, className=&quot;text-info&quot;)<br>    if profit_leg_limit and (side == &quot;buy&quot;) and (bid != 0) and not (profit_leg_limit &gt;= (bid + 0.01)):<br>        invalid = html.P(&quot;In a sell-to-close Take-Profit leg, the Limit Price must be at least $0.01 above&quot;<br>                         &quot; the current Bid price.&quot;, className=&quot;text-info&quot;)<br>    if profit_leg_limit and (side == &quot;sell&quot;) and loss_leg_stop and not (profit_leg_limit &lt;= (loss_leg_stop + 0.01)):<br>        invalid = html.P(&quot;In a buy-to-close Take-Profit leg, the Limit Price must be at least $0.01 below&quot;<br>                         &quot; the Stop Price for the Stop-Loss leg.&quot;, className=&quot;text-info&quot;)<br>    if profit_leg_limit and (side == &quot;sell&quot;) and stop and not (profit_leg_limit &lt;= (stop + 0.01)):<br>        invalid = html.P(&quot;In a buy-to-close Take-Profit leg, the Limit Price must be at least $0.01 below&quot;<br>                         &quot; the Stop Price for the entry leg.&quot;, className=&quot;text-info&quot;)<br>    if profit_leg_limit and (side == &quot;sell&quot;) and limit and not (profit_leg_limit &lt;= (limit + 0.01)):<br>        invalid = html.P(&quot;In a buy-to-close Take-Profit leg, the Limit Price must be at least $0.01 below&quot;<br>                         &quot; the Limit Price for the entry leg.&quot;, className=&quot;text-info&quot;)<br>    if profit_leg_limit and (side == &quot;sell&quot;) and (ask != 0) and not (profit_leg_limit &lt;= (ask + 0.01)):<br>        invalid = html.P(&quot;In a buy-to-close Take-Profit leg, the Limit Price must be at least $0.01 below&quot;<br>                         &quot; the current Ask price.&quot;, className=&quot;text-info&quot;)<br>    if invalid:<br>        # ord-summary, submit-btn (disabled), order-status, modal (is_open)<br>        return invalid, True, &quot;&quot;, True<br><br>...</pre><p>Shortly, we will march down our list of input fields to compile a set of order instructions to append to this starting list, an order_params dictionary.</p><pre>order_params = {<br>    &#39;symbol&#39;: symbol,<br>    &#39;side&#39;: OrderSide.BUY if side == &#39;buy&#39; else OrderSide.SELL,<br>    &#39;time_in_force&#39;: tif,<br>    &#39;order_id&#39;: None,<br>}</pre><p>But first, Alpaca allows either qty (#shares) or a nominal ($USD) entry. Our qty input from Chapter 4 had the option of selecting either # or $ so we need to handle those options. Also, from our rules discussion in Chapter 3, we learned that fractional shares (as well as notional values) are only allowed for Market-Day orders. We partially handle that here and then finish when we get to the Market-Day type.</p><pre><br> # Set Qty Param<br>    if qty_icon == &quot;$&quot;:  # notional, will confirm mkt-day below and override if not<br>        order_params[&#39;notional&#39;] = qty<br>        num_shares = 0<br>        num_shares_fractional = 0<br>        qty_text = f&quot;${qty:,.2f} of&quot;<br><br>    else:  # qty_icon = &#39;#&#39; so entered as shares, possibly fractional which is handled below<br>        num_shares = int(qty)<br>        order_params[&#39;qty&#39;] = num_shares<br>        num_shares_fractional = qty  # handing fractional-qty for mkt-day below, limited digits unless crypto<br>        qty_text = f&quot;{str(qty)} shares of&quot;</pre><p>Now, we can work through the 5 basic order types, adding to our order_params as needed for each type. Notice we are also deriving a how_traded variable that we will use later in compiling order_summary.</p><pre> # Limit Order<br>    if limit and not stop and not trailing_stop:<br>        order_type = &#39;limit&#39;<br>        order_params[&#39;type&#39;] = OrderType.LIMIT<br>        order_params[&#39;limit_price&#39;] = limit<br>        order_params[&#39;extended_hours&#39;] = True if tif == &quot;ext&quot; else False<br>        order_params[&#39;time_in_force&#39;] = &quot;day&quot; if tif == &quot;ext&quot; else tif<br>        how_traded = f&quot;at LIMIT ${limit:.2f} or better&quot;<br><br>    # Stop Order<br>    elif stop and not limit and not trailing_stop:<br>        order_type = &#39;stop&#39;<br>        order_params[&#39;type&#39;] = OrderType.STOP<br>        order_params[&#39;stop_price&#39;] = stop<br>        how_traded = f&quot;at MARKET after ${stop:.2f} STOP crossed&quot;<br><br>    # Stop-Limit Order<br>    elif stop and limit:<br>        order_type = &#39;stop_limit&#39;<br>        order_params[&#39;type&#39;] = OrderType.STOP_LIMIT<br>        order_params[&#39;stop_price&#39;] = stop<br>        order_params[&#39;limit_price&#39;] = limit<br>        how_traded = f&quot;at LIMIT ${limit:.2f} or better after ${stop:.2f} STOP crossed&quot;<br><br>    # Trailing-Stop Order<br>    elif trailing_stop and not limit and not stop:<br>        order_type = &#39;trailing_stop&#39;<br>        order_params[&#39;type&#39;] = OrderType.TRAILING_STOP<br>        if trailing_icon == &quot;%&quot;:<br>            order_params[&#39;trail_percent&#39;] = trailing_stop<br>            trailing_text = f&quot;{trailing_stop}%&quot;<br>        else:  # default $<br>            order_params[&#39;trail_price&#39;] = trailing_stop<br>            trailing_text = f&quot;${trailing_stop:,.2f}&quot;<br>        how_traded = f&quot;at MARKET after a reversion of {trailing_text} &quot; \<br>                     f&quot;{&#39;below peak price&#39; if side == &#39;buy&#39; else &#39;above trough price&#39;} &quot; \<br>                     f&quot;as a TRAILING-STOP&quot;<br><br>    # Market Order - with potential notional<br>    else:<br>        order_type = &#39;market&#39;<br>        order_params[&#39;order_type&#39;] = OrderType.MARKET<br>        if tif == &#39;day&#39; and qty_icon == &quot;#&quot;:  # Fractional entry allowed so over-write param<br>            order_params[&#39;qty&#39;] = num_shares_fractional  # Float limited to 6 digits albeit Alpaca allows 9<br>        how_traded = &#39;at MARKET&#39;</pre><p>Now we’ll handle the Advanced Order classes, which add exit legs to the basic-entry order types. Note that these are within a new if-else loop as they are optional. Also note where I’m using the oco_checked variable to distinguish this close-legs-only class from the others.</p><pre># Profit-Leg OTO<br>if profit_leg_limit and not (loss_leg_limit or loss_leg_stop) and not oco_checked:<br>    order_params[&#39;order_class&#39;] = OrderClass.OTO<br>    order_described = &#39;Take-Profit closing order once opening order is filled (OTO)&#39;<br>    profit_line = f&quot;{&#39;SELL&#39; if side == &#39;buy&#39; else &#39;BUY&#39;} {num_shares} shares of {symbol} &quot; \<br>                  f&quot;to TAKE PROFIT at ${profit_leg_limit:.2f} LIMIT or {&#39;above&#39; if side == &#39;buy&#39; else &#39;below&#39;}.&quot;<br>    loss_line = &quot;&quot;<br>    try:<br>        order_params[&#39;take_profit&#39;] = TakeProfitRequest(limit_price=profit_leg_limit)<br>    except ValidationError as e:<br>        return f&quot;Invalid Order: {e}&quot;, True, &quot;&quot;, True<br><br># Loss-Leg OTO<br>if (loss_leg_limit or loss_leg_stop) and not profit_leg_limit and not oco_checked:<br>    order_params[&#39;order_class&#39;] = OrderClass.OTO<br>    order_described = &#39;Stop-Loss closing order once opening order is filled (OTO)&#39;<br>    profit_line = &quot;&quot;<br>    try:<br>        if loss_leg_stop and not loss_leg_limit:<br>            order_params[&#39;stop_loss&#39;] = StopLossRequest(stop_price=loss_leg_stop)<br>            loss_line = f&quot;{&#39;SELL&#39; if side == &#39;buy&#39; else &#39;BUY&#39;} {num_shares} shares of {symbol} &quot; \<br>                        f&quot;to STOP LOSS if ${loss_leg_stop:.2f} STOP &quot; \<br>                        f&quot;crossed {&#39;below&#39; if side == &#39;buy&#39; else &#39;above&#39;}.&quot;<br>        else:  # both limit and stop, Alpaca doesn&#39;t support stop_loss.limit_price alone!<br>            order_params[&#39;stop_loss&#39;] = StopLossRequest(limit_price=loss_leg_limit, stop_price=loss_leg_stop)<br>            loss_line = f&quot;{&#39;SELL&#39; if side == &#39;buy&#39; else &#39;BUY&#39;} {num_shares} shares of {symbol} &quot; \<br>                        f&quot;at ${loss_leg_limit} LIMIT or better &quot; \<br>                        f&quot;to STOP LOSS if ${loss_leg_stop:.2f} STOP &quot; \<br>                        f&quot;crossed {&#39;below&#39; if side == &#39;buy&#39; else &#39;above&#39;}.&quot;<br>    except ValidationError as e:<br>        return f&quot;Invalid Order: {e}&quot;, True, &quot;&quot;, True<br><br># Bracket Order (OTOCO) - opening order + 2 closing legs<br>if (loss_leg_limit or loss_leg_stop) and profit_leg_limit and not oco_checked:<br>    order_params[&#39;order_class&#39;] = OrderClass.BRACKET<br>    order_described = &quot;Closing orders once opening order is filled (Bracket OTO+OCO):&quot;<br>    profit_line = f&quot;{&#39;SELL&#39; if side == &#39;buy&#39; else &#39;BUY&#39;} {num_shares} shares of {symbol} &quot; \<br>                  f&quot;to TAKE PROFIT at ${profit_leg_limit:.2f} LIMIT or {&#39;above&#39; if side == &#39;buy&#39; else &#39;below&#39;}.&quot;<br>    try:<br>        order_params[&#39;take_profit&#39;] = TakeProfitRequest(limit_price=profit_leg_limit)<br>        if loss_leg_stop and not loss_leg_limit:<br>            order_params[&#39;stop_loss&#39;] = StopLossRequest(stop_price=loss_leg_stop)<br>            loss_line = f&quot;{&#39;SELL&#39; if side == &#39;buy&#39; else &#39;BUY&#39;} {num_shares} shares of {symbol} &quot; \<br>                        f&quot;to STOP LOSS if ${loss_leg_stop:.2f} STOP &quot; \<br>                        f&quot;crossed {&#39;below&#39; if side == &#39;buy&#39; else &#39;above&#39;}.&quot;<br>        else:  # both limit and stop, Alpaca doesn&#39;t support stop_loss.limit_price alone!<br>            order_params[&#39;stop_loss&#39;] = StopLossRequest(limit_price=loss_leg_limit, stop_price=loss_leg_stop)<br>            loss_line = f&quot;{&#39;SELL&#39; if side == &#39;buy&#39; else &#39;BUY&#39;} {num_shares} shares of {symbol} &quot; \<br>                        f&quot;at ${loss_leg_limit} LIMIT or better &quot; \<br>                        f&quot;to STOP LOSS if ${loss_leg_stop:.2f} STOP &quot; \<br>                        f&quot;crossed {&#39;below&#39; if side == &#39;buy&#39; else &#39;above&#39;}.&quot;<br>    except ValidationError as e:<br>        return f&quot;Invalid Order: {e}&quot;, True, &quot;&quot;, True<br><br># OCO Order - closing legs only, no opening order. Side should be for the CLOSING order!!!<br>if (loss_leg_limit or loss_leg_stop) and profit_leg_limit and oco_checked:<br>    order_params[&#39;order_class&#39;] = OrderClass.OCO<br>    try:  # Note the change in side relative to other order types<br>        profit_line = f&quot;{&#39;BUY&#39; if side == &#39;buy&#39; else &#39;SELL&#39;} {num_shares} shares of {symbol} &quot; \<br>                      f&quot;to TAKE PROFIT at ${profit_leg_limit:.2f} LIMIT &quot; \<br>                      f&quot;or {&#39;above&#39; if side == &#39;sell&#39; else &#39;below&#39;}.&quot;<br>        order_params[&#39;take_profit&#39;] = TakeProfitRequest(limit_price=profit_leg_limit)<br>        if loss_leg_stop and not loss_leg_limit:<br>            order_params[&#39;stop_loss&#39;] = StopLossRequest(stop_price=loss_leg_stop)<br>            loss_line = f&quot;{&#39;BUY&#39; if side == &#39;buy&#39; else &#39;SELL&#39;} {num_shares} shares of {symbol} &quot; \<br>                        f&quot;to STOP LOSS if ${loss_leg_stop:.2f} STOP &quot; \<br>                        f&quot;crossed {&#39;above&#39; if side == &#39;sell&#39; else &#39;below&#39;}.&quot;<br>        else:  # both limit and stop, Alpaca doesn&#39;t support stop_loss.limit_price alone!<br>            order_params[&#39;stop_loss&#39;] = StopLossRequest(limit_price=loss_leg_limit, stop_price=loss_leg_stop)<br>            loss_line = f&quot;{&#39;SELL&#39; if side == &#39;buy&#39; else &#39;BUY&#39;} {num_shares} shares of {symbol} &quot; \<br>                        f&quot;at ${loss_leg_limit} or better &quot; \<br>                        f&quot;to STOP LOSS if ${loss_leg_stop:.2f} &quot; \<br>                        f&quot;STOP crossed {&#39;above&#39; if side == &#39;sell&#39; else &#39;below&#39;}.&quot;<br>    except ValidationError as e:<br>        return f&quot;Invalid Order: {e}&quot;, True, &quot;&quot;, True</pre><p>The new Version 2 of the Alpaca Python SDK Version 2 uses a Python package called Pydantic to validate order parameters. This means there is a unique class for each order type and you will get immediate feedback (in the console) if your parameters are incorrect. Notice that I said “parameters” but above we’ve been compiling a dictionary. That was so we can use Python’s <em>iterable unpacking </em>functionality<em> </em>in this next section to convert key:value pairs in our dictionary into the key=value parameters needed for the Pydantic classes. Notice the **order_params argument which is what unpacks the dictionaries we’ve been customizing for each order type.</p><p>As an aside, there is a generic OrderRequest() class that one can use but doing so would reduce the benefit of this pre-submission validation. I worked on how best to configure the orders for quite a while! Logically, one might think it would be easier to just configure each type separately, maybe using the generic class, but the complication is in dealing with the OPTIONAL advanced classes; the Pydantic classes often don’t allow setting a parameter to None so I used this unpacking approach to overcome that. An alternative might be to just require the user to stipulate the order type in the interface then only build that set of params but I wanted to remove that complexity from the user interface.</p><pre># Create Order object using the unpacked order parameters<br>try:<br>    if order_type == &#39;market&#39;:<br>        order_obj = MarketOrderRequest(**order_params)<br>    if order_type == &#39;limit&#39;:<br>        order_obj = LimitOrderRequest(**order_params)<br>    if order_type == &quot;stop&quot;:<br>        order_obj = StopOrderRequest(**order_params)<br>    if order_type == &#39;stop-limit&#39;:<br>        order_obj = StopLimitOrderRequest(**order_params)<br>    if order_type == &#39;trailing_stop&#39;:<br>        order_obj = TrailingStopOrderRequest(**order_params)<br>except ValidationError as e:<br>    return f&quot;Invalid Order: {e}&quot;, True, &quot;&quot;, True</pre><p>Now, let’s compile our order_summary, to give the user feedback on what they are about to submit to the broker. If desired, you could certainly make this less verbose, say by just listing the order components, but I wanted to provide as much helpful information as possible to my users who might not be familiar with advanced order types.</p><pre>entry_line = f&quot;{side.upper()} {tif.upper() if tif != &#39;ext&#39; else &#39;during EXTENDED HOURS&#39;} &quot; \<br>             f&quot;{qty_text} {symbol} {how_traded}.&quot;<br>if not oco_checked and account == &#39;live&#39; and qty and symbol and side:<br>    account_html = html.Span([<br>        html.Small(&quot;Opening order for &quot;, style={&#39;color&#39;: &#39;darkgray&#39;}),<br>        html.Small(f&quot;{account.capitalize()}:&quot;, className=&quot;bg-warning&quot;)<br>    ])<br>elif not oco_checked and account == &#39;paper&#39; and qty and symbol and side:<br>    account_html = html.Span([<br>        html.Small(&quot;Opening order for &quot;, style={&#39;color&#39;: &#39;darkgray&#39;}),<br>        html.Small(&quot;PAPER ACCOUNT:&quot;, style={&#39;color&#39;: &#39;darkgray&#39;})<br>    ])<br>elif oco_checked and account == &#39;live&#39; and qty and symbol and side:<br>    entry_line = &quot;&quot;<br>    order_described = &quot;&quot;<br>    account_html = html.Div([<br>        html.Small(&quot;Closing orders for current position (OCO) in &quot;, style={&#39;color&#39;: &#39;darkgray&#39;}),<br>        html.Small(&quot;LIVE ACCOUNT:&quot;, className=&quot;bg-warning&quot;)<br>    ])<br>elif oco_checked and account == &#39;paper&#39; and qty and symbol and side:<br>    entry_line = &quot;&quot;<br>    order_described = &quot;&quot;<br>    account_html = html.Div([<br>        html.Small(&quot;Closing order for open position (OCO) in &quot;, style={&#39;color&#39;: &#39;darkgray&#39;}),<br>        html.Small(&quot;PAPER ACCOUNT:&quot;, style={&#39;color&#39;: &#39;darkgray&#39;})<br>    ])<br>else:<br>    account_html = &quot;&quot;</pre><p>Once the user reviews the order summary, they will click the submit button to send the order to Alpaca. We need to handle that next as the first part of an if statement which will submit the order to Alpaca and return the submission_details. As the model is also closed you will not actually see the submission_details but I send them through to support testing (by changing the True to False for the modal’s is_open argument). For the else clause, we’ll return the order_summary with some styling.</p><pre>if ctx.triggered_id == &quot;submit-button&quot; and order_status != &quot;submitted&quot;:<br>    print(&quot;Submit Clicks:&quot;, n_submit)<br>    key = live_key if account == &quot;live&quot; else paper_key<br>    secret = live_secret if account == &quot;live&quot; else paper_secret<br>    try:<br>        order_details = submit_order_to_Alpaca(order_obj, account, key, secret)<br>    except APIError as e:<br>        error_data = json.loads(e.args[0])<br>        msg = html.Div(<br>            [<br>                html.H4(&quot;Alpaca rejected the order!&quot;, className=&quot;bg-warning text-danger&quot;),<br>                html.P(error_data[&quot;message&quot;].capitalize(), className=&quot;text-info&quot;)<br>            ]<br>        )<br>        return msg, True, &quot;submitted&quot;, True<br><br>    else:  # order accepted<br>        submission_details = html.Div(<br>            [<br>                html.P(&quot;Order Submitted&quot;, className=&quot;text-info&quot;),<br>                html.Table(<br>                    [<br>                        html.Tr([html.Td(f&quot;{property_name}:&quot;), html.Td(f&quot;{value}&quot;)], className=&quot;text-info&quot;)<br>                        for property_name, value in order_details<br>                    ]<br>                )<br>            ]<br>        )<br>        order_status = order_details.status.value if order_details.status else &quot;N/A&quot;<br><br>        return submission_details, True, &quot;submitted&quot;, False<br><br>else:  # Not yet submitted, so just return the summary<br>    summary_text = html.Div(<br>        [<br>            html.Small(account_html),<br>            html.P(entry_line),<br>            html.Small(order_described, style={&#39;color&#39;: &#39;darkgray&#39;}),<br>            html.P(profit_line, style={&#39;color&#39;: &#39;green&#39;}),<br>            html.P(loss_line, style={&#39;color&#39;: &#39;red&#39;}),<br>        ]<br>    )<br>    return summary_text, False, &quot;&quot;, True</pre><p>Notice the submit_order_to_Alpaca function call, wrapped within a try/except block. Even though we are validating our instructions both at the field level and again with the Pydantic classes implemented by Alpaca, there is still the chance that an order submission can fail. For example, Alpaca will reject a “reversing” order, meaning one that flips from, say, a long to a short position in a single order. Or, as another example, an order can get rejected for insufficient funds. In such obscure situations we just need to capture Alpaca’s rejection and display it on the frontend.</p><p>With the error handing in the callback, the function is rather simple. Here’s that code.</p><pre>def submit_order_to_Alpaca(the_order, the_acct, the_key, the_secret):<br>    if the_acct == &#39;paper&#39;:<br>        trading_client = TradingClient(the_key, the_secret, paper=True)<br>    else:<br>        trading_client = TradingClient(the_key, the_secret, paper=False)<br>    order_details = trading_client.submit_order(the_order)<br>    return order_details</pre><p>With this function plus our callback we can now submit orders to Alpaca! As I’ve said repeatedly, run lots of tests using the paper account before ever considering setting up a live account.</p><h4>BID/ASK/LAST</h4><p>We have a few more tasks to complete this chapter. Our Order model has fields for bid/ask and last price, plus the day’s change in price. We need another callback to update those. Unfortunately, all three values are in different Alpaca datasets, so let’s use the Snapshot request to load everything we need in one step.</p><p>Here’s the function we’ll use. Of course, we need the Alpaca access keys and the current stock from the selected-symbol-store. Quotes are updated in realtime, and Alpaca does provide a webSocket interface. However, Dash doesn’t provide an easy way to get a“push” data stream into a callback; it can be done with what’s called a ClientSide callback but it requires writing Javascript code. For our end-of-day trading application, we don’t need sub-second accuracy in our bid/ask/last prices. Besides, unless you pay for an expensive realtime SIP account, the free IEX data doesn’t change that fast anyway!</p><pre>def retrieve_snapshot_for_single_stock(ticker: str, key: str, secret: str) -&gt; object:<br>    &quot;&quot;&quot; Get historical snapshot from Alpaca for specified ticker<br><br>        Retrieves a dictionary-like (keyed by ticker) nested object with datasets: &#39;latest_trade&#39;,<br>        &#39;latest_quote&#39;, latest &#39;minute_bar&#39;, latest &#39;daily_bar&#39; and previous &#39;daily_bar&#39;.<br>        Get keys using: snapshot.keys(). Get datasets and attributes using:  snapshot.items().<br>        Example for accessing attributes: snapshot[ticker].latest_quote.ask_price.<br>    &quot;&quot;&quot;<br><br>    try:<br>        historical_client = StockHistoricalDataClient(key, secret)<br>        request = StockSnapshotRequest(symbol_or_symbols=[ticker])  # multiple allowed but not supported<br>        return historical_client.get_stock_snapshot(request)<br>    except Exception as e:<br>        print(e)<br>        return None</pre><p>Remember, awhile back, we set up the dcc.Interval component in our main layout. We will use that now as an input to a new callback that will trigger data collection at one second intervals. Snapshot retrieves several data objects as a list, so parsing to get the values we want is a bit harder but still relatively straightforward.</p><pre>@callback(<br>    Output(&#39;bid-text&#39;, &#39;children&#39;),  # $0.00 &amp; exchange code<br>    Output(&#39;bid-size&#39;, &#39;children&#39;),  # x 000<br>    Output(&#39;ask-text&#39;, &#39;children&#39;),  # $0.00<br>    Output(&#39;ask-size&#39;, &#39;children&#39;),  # x 000 &amp; exchange code<br>    Output(&#39;spread-text&#39;, &#39;children&#39;),  # $0.00 &amp; time<br>    Output(&#39;last-text&#39;, &#39;children&#39;),  # $0.00<br>    Output(&#39;last-change&#39;, &#39;children&#39;),  # $0.00 (0.00%)<br>    Output(&#39;bid-price-store&#39;, &#39;data&#39;),<br>    Output(&#39;ask-price-store&#39;, &#39;data&#39;),<br>    Output(&#39;last-price-store&#39;, &#39;data&#39;),<br>    Input(&#39;interval-quotes&#39;, &#39;n_intervals&#39;),<br>    Input(&#39;alpaca-key-paper&#39;, &#39;value&#39;),<br>    Input(&#39;alpaca-secret-paper&#39;, &#39;value&#39;),<br>    Input(&#39;alpaca-key-live&#39;, &#39;value&#39;),<br>    Input(&#39;alpaca-key-live&#39;, &#39;value&#39;),<br>    Input(&#39;account&#39;, &#39;value&#39;),<br>    State(&#39;selected-symbol-store&#39;, &#39;data&#39;),<br>)<br>def update_quotes(interval, paper_key, paper_secret, live_key, live_secret, account, symbol):<br>    &quot;&quot;&quot; Get an Alpaca Snapshot to compile data for the Order Modal&#39;s header.<br>        Note: Snapshot uses IEX (unless a paid account) whereas historic bars use SIP-15m-delayed.<br>        Small differences will be seen in this data compared to graph!<br>    &quot;&quot;&quot;<br><br>    if not symbol:<br>        raise PreventUpdate<br><br>    # Get Snapshot from Alpaca<br>    key = live_key if account == &quot;live&quot; else paper_key<br>    secret = live_secret if account == &quot;live&quot; else paper_secret<br>    snapshot = retrieve_snapshot_for_single_stock(symbol, paper_key, paper_secret)<br>    if not snapshot:<br>        raise PreventUpdate<br><br>    def convert_exchange(val):<br>        if val == &quot;V&quot;:<br>            return &quot;IEX&quot;<br>        elif val == &quot;A&quot;:<br>            return &quot;AMEX&quot;<br>        elif val == &quot;N&quot;:<br>            return &quot;NYSE&quot;<br>        elif val in [&#39;Q&#39;, &#39;S&#39;, &#39;X&#39;]:<br>            # Q is OMX (formerly Nordic), S is smallcap, X is OMX PSX (formerly Pacific). B is OMX-BX options exch.<br>            return &quot;NDQ&quot;<br>        else:<br>            return val<br><br>    # Get Bid/Ask/Spread data from Latest Quote<br>    quote = snapshot[symbol].latest_quote<br>    ask = quote.ask_price<br>    ask_str = f&quot;${float(ask):.2f}&quot;<br>    ask_size = f&quot;{quote.ask_size * 100:.0f} {convert_exchange(quote.ask_exchange)}&quot;<br>    bid = quote.bid_price<br>    bid_str = f&quot;${float(bid):.2f}&quot;<br>    bid_size = f&quot;{quote.bid_size * 100:.0f} {convert_exchange(quote.bid_exchange)}&quot;<br>    quote_time = quote.timestamp.astimezone(pytz.timezone(&quot;US/Eastern&quot;)).strftime(&quot;%H:%M:%S&quot;)<br>    spread_val = float(bid) - float(ask)<br>    spread = html.Div([html.Div(f&quot;{spread_val:.2f}&quot;), html.Div(quote_time)])<br><br>    # Get Last-Trade from the latest minute bar<br>    latest_minute_bar = snapshot[symbol].minute_bar<br>    last = float(latest_minute_bar.close)<br>    last_str = f&quot;${last:.2f}&quot;<br><br>    # Get previous-day data to calculate change<br>    prev_high = float(snapshot[symbol].previous_daily_bar.high)<br>    prev_low = float(snapshot[symbol].previous_daily_bar.low)<br>    prev_close = snapshot[symbol].previous_daily_bar.close<br>    day_chg = last - prev_close<br>    day_perc = day_chg / prev_close<br>    if day_chg &lt; 0:<br>        last_change = html.Div(f&quot;{format_dollar(day_chg)} ({day_perc:.2%})&quot;, className=&quot;text-warning&quot;)<br>    else:<br>        last_change = html.Div(f&quot;${day_chg:.2f} ({day_perc:.2%})&quot;, className=&quot;&quot;)<br><br>    return bid_str, bid_size, ask_str, ask_size, spread, last_str, last_change, bid, ask, last</pre><p>There’s a useful little utility function, format_dollar, in this code that I found on StackOverflow. This will put the negative sign ahead of the dollar sign when formatting negative dollar amounts, -$100 instead of $-100.</p><pre>def format_dollar(amount):<br>    # From https://stackoverflow.com/questions/30258593/python-format-negative-currency<br>    formatted_absolute_amount = &#39;${:,.2f}&#39;.format(abs(amount))<br>    if round(amount, 2) &lt; 0:<br>        return f&#39;-{formatted_absolute_amount}&#39;<br>    return formatted_absolute_amount</pre><h3>A Summary of our Adventure:</h3><ul><li>In <a href="https://medium.com/@stevenwmayo/tradenosis-my-quest-to-build-a-mythical-stock-trading-platform-chapter-1-90924cd09f3f"><strong>Chapter 1</strong></a>, we created the UI for a basic trading webpage using Dash.</li><li>In <a href="https://medium.com/@stevenwmayo/tradenosis-my-quest-to-build-a-mythical-stock-trading-platform-e2c62f10e67b"><strong>Chapter 2</strong></a>, created an Alpaca Settings dialog and added code to load candlestick price data into a stock chart.</li><li>In <a href="https://medium.com/@stevenwmayo/tradenosis-my-quest-to-build-a-mythical-stock-trading-platform-c1bf56372d7c"><strong>Chapter 3</strong></a>, we reviewed Alpaca’s trading rules.</li><li>In <a href="https://medium.com/@stevenwmayo/tradenosis-my-quest-to-build-a-mythical-stock-trading-platform-31d452683b6"><strong>Chapter 4</strong></a>, we created the order form and associated code to compile trade instructions.</li><li>In this chapter, we wrote the callback needed to submit an order to Alpaca.</li><li>In <a href="https://medium.com/@stevenwmayo/tradenosis-my-quest-to-build-a-mythical-stock-trading-platform-1771245c54a2"><strong>Chapter 6</strong></a>, we’ll use the Alpaca account data to fill the Orders and Positions tabs.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=65a46823c606" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[TRADEnosis™ — My Quest to Build a Mythical Stock Trading Platform]]></title>
            <link>https://medium.com/@stevenwmayo/tradenosis-my-quest-to-build-a-mythical-stock-trading-platform-31d452683b6?source=rss-310758628d4------2</link>
            <guid isPermaLink="false">https://medium.com/p/31d452683b6</guid>
            <category><![CDATA[tradenosis]]></category>
            <category><![CDATA[alpacafinance]]></category>
            <category><![CDATA[dash]]></category>
            <category><![CDATA[trading]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Steve Mayo]]></dc:creator>
            <pubDate>Tue, 15 Aug 2023 18:25:14 GMT</pubDate>
            <atom:updated>2023-08-23T00:28:15.201Z</atom:updated>
            <content:encoded><![CDATA[<h3>TRADEnosis™ — My Quest to Build a Mythical Stock Trading Platform</h3><h4>Chapter 4: An Alpaca Python SDK v2 Order Modal in Plotly Dash</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cffucWmKLkq_dd3ALLGsdg.png" /></figure><p>On our <a href="https://medium.com/@stevenwmayo/tradenosis-my-quest-to-build-a-mythical-stock-trading-platform-chapter-1-90924cd09f3f">quest to build a stock trading applicatio</a>n, we have imported a number of Python packages, configured <strong>Plotly Dash</strong> to use <strong>Dash Bootstrap Components</strong> (dbc) and some stylesheets, wrote a function to retrieve historic candlestick price data from the <strong>Alpaca Markets Python SDK</strong>, created a number of layout components within a Bootstrap-like container structure, and wrote our first Dash callbacks to collect API keys and update the stock graph. We also reviewed the many rules and requirements for submitting trades to a brokerage. We want to use Alpaca for that, but first we need a form to collect the trade instructions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/304/1*QUh0zcNLPF3aZXmHrblkkQ.png" /></figure><h4>Before we break camp</h4><p>Let’s make a few quick refinements to our code. First, let’s add the company name to our test Pandas dataFrame so that we can pass it through to our forthcoming orders form. Again, this is still just example data. Once we have the basic app, I’m expecting you will want to add your own trading algorithm that will include generating a custom ticker list and additional columns with trading signals.</p><pre># region SETUP<br>stock_list = [&quot;AAPL&quot;, &quot;MSFT&quot;, &quot;GOOG&quot;, &quot;TSLA&quot;, &quot;NVDA&quot;, &quot;AMZN&quot;, &quot;META&quot;]<br>companies = [&#39;Apple Inc.&#39;, &#39;Microsoft Inc.&#39;, &#39;Alphabet Inc.&#39;, &#39;Tesla Inc.&#39;,<br>             &#39;NVIDIA Corporation&#39;, &#39;Amazon Inc.&#39;, &#39;Meta Platforms Inc.&#39;]<br>df_watchlist = pd.DataFrame(data={&quot;TICKER&quot;: stock_list, &quot;COMPANY&quot;: companies})</pre><p>As we configured our watchlist to use all columns, the company names will appear there as well. You may now see part of the COMPANY column peeking through and the columns may look a bit crowded. My goal is to support screens widths from the iPhone-8 (375 x 667px) up through a full desktop so we may want to hide this column on smaller screens.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/516/1*-uZbk3hHg2Ijx40EtPlCAg.png" /><figcaption>Time for a quick layout tweak?</figcaption></figure><p>One way to do that is with some style directives, as shown by the watchlist layout code below. Notice, I added a font-size CSS setting to the style_header and a new style_data_conditional parameter that targets just the first column. You may need to tweak the minWidth setting for the devices you intend to support.</p><pre># region LAYOUT - WATCHLIST<br>watchlist = dash_table.DataTable(<br>    id=&#39;watchlist-table&#39;,<br>    data=df_watchlist.to_dict(&#39;records&#39;),<br>    columns=[{&quot;name&quot;: i, &quot;id&quot;: i} for i in df_watchlist.columns],<br>    style_cell={&#39;textAlign&#39;: &#39;left&#39;},<br>    style_as_list_view=True,<br>    style_header={&#39;borderTop&#39;: &#39;0px&#39;, &#39;font-size&#39;: &#39;12px&#39;, &#39;font-weight&#39;: &#39;600&#39;},<br>    style_data={&#39;border&#39;: &#39;0px&#39;},<br>    style_data_conditional=[<br>            {<br>                &#39;if&#39;: {<br>                    &#39;column_id&#39;: &#39;TICKER&#39;,<br>                },<br>                &#39;minWidth&#39;: &#39;100px&#39;, &#39;font-size&#39;: &#39;12px&#39;<br>            }<br>        ]<br>    )<br># endregion /watchlist</pre><p>Another, less fidgety, way is to simply not display company name; it will still be in the data we passed to this component so we can show it elsewhere. In this alternative example, I configured just a single column rather than parsing all records.</p><pre># region LAYOUT - WATCHLIST<br>watchlist = dash_table.DataTable(<br>    id=&#39;watchlist-table&#39;,<br>    data=df_watchlist.to_dict(&#39;records&#39;),<br>    columns=[<br>        {&quot;name&quot;: &#39;Ticker&#39;, &quot;id&quot;: &#39;TICKER&#39;, &#39;type&#39;: &quot;text&quot;},<br>    ],<br>    style_cell={&#39;textAlign&#39;: &#39;left&#39;},<br>    style_as_list_view=True,<br>    style_header={&#39;borderTop&#39;: &#39;0px&#39;, &#39;font-size&#39;: &#39;12px&#39;, &#39;font-weight&#39;: &#39;600&#39;},<br>    style_data={&#39;border&#39;: &#39;0px&#39;, &#39;font-size&#39;: &#39;12px&#39;},<br>)<br># endregion /watchlist</pre><h4>Adding a Order Submission Modal</h4><p>Now we are ready to create our trade order modal. First, we need a button to open a modal. Let’s add one just below the chart. Notice in this code I also added an orders_modal variable at the top of our main container.</p><pre># region LAYOUT - CONTAINER<br>app.layout = dbc.Container(<br>    [<br>        alpaca_modal,<br>        orders_modal,  # Chpt4: New layout variable for the Order modal<br>        navbar,<br>        dbc.Row(<br>            [<br>                dbc.Col(watchlist,<br>                        xs=3, sm=2, md=1, style={&quot;maxHeight&quot;: &quot;375px&quot;, &quot;overflow&quot;: &quot;scroll&quot;}, ),<br>                dbc.Col(chart, xs=9, sm=10, md=11)<br>            ],<br>            className=&quot;mt-1&quot;,<br>        ),<br>        # Chpt4: New row to insert a &#39;TRADE&#39; button below the stock graph<br>        dbc.Row(<br>            [<br>                html.Div(<br>                    [<br>                        dbc.Button(&quot;Trade&quot;, id=&quot;btn-orders-modal&quot;, n_clicks=0,<br>                                   color=&quot;primary&quot;, disabled=True, size=&quot;sm&quot;)<br>                    ], className=&quot;my-1 col-8 col-md-5  d-grid mx-auto&quot;,<br>                )<br>            ]<br>        ),<br> dbc.Row(<br>            [<br>                dbc.Col(<br>                    dbc.Tabs(<br>                        [<br>                            dbc.Tab(orders_card, label=&quot;Orders&quot;,<br>                                    activeLabelClassName=&quot;fw-bold&quot;,<br>                                    ),<br>                            dbc.Tab(positions_card, label=&quot;Positions&quot;, activeLabelClassName=&quot;fw-bold&quot;),<br>                        ],<br>                    ),<br>                    id=&quot;tabs&quot;,<br>                    width=12)<br>            ],<br>        )<br>    ],<br>    fluid=False,<br>)</pre><p>Now, let’s add that new modal layout to collect the specifics of our order. Add this skeleton code below the KEYS MODAL.</p><pre># region LAYOUT - ORDERS MODAL<br>order_header = &quot;&quot;<br>account_radios = &quot;&quot;<br>order_side_buttons = &quot;&quot;<br>tif_input = &quot;&quot;<br>qty_input = &quot;&quot;<br>limit_price_input = &quot;&quot;<br>stop_price_input = &quot;&quot;<br>trailing-stop_input = &quot;&quot;<br>bracket_profit_input = &quot;&quot;<br>bracket_stop_input = &quot;&quot;<br><br>orders_modal = html.Div(<br>    [<br>        dbc.Modal(<br>            [<br>                dbc.ModalHeader(<br>                    [<br>                        order_header,<br><br>                    ], className=&quot;bg-secondary&quot;<br>                ),<br>                dbc.ModalBody(<br>                    [<br>                        dbc.Container(<br>                            [<br>                                account_radios,<br>                                order_side_buttons,<br>                                qty_input,<br>                                tif_input,<br>                                html.H5(<br>                                    &quot;Entry Triggers&quot;,<br>                                    id=&quot;entry-triggers-heading&quot;,<br>                                    className=&quot;text-primary text-center border-bottom border-top &quot;<br>                                              &quot;border-primary rfs-small py-1&quot;<br>                                ),<br>                                limit_price_input,<br>                                stop_price_input,<br>                                trailing_stop_input,<br>                                html.H5(<br>                                    &quot;Advanced Exits&quot;,<br>                                    id=&quot;brackets-heading&quot;,<br>                                    className=&quot;text-primary text-center border-bottom border-top &quot;<br>                                              &quot;border-primary rfs-small py-1&quot;<br>                                ),<br>                                oco_checkbox,<br>                                html.I(&quot;Take-Profit Leg:&quot;, className=&quot;text-muted rfs-tiny&quot;),<br>                                take_profit_leg,<br>                                html.I(&quot;Stop-Loss Leg:&quot;, className=&quot;text-muted rfs-tiny&quot;),<br>                                stop_loss_leg_limit,<br>                                stop_loss_leg_stop,<br>                                html.H5(<br>                                    &quot;Order Summary&quot;,<br>                                    id=&quot;order-summary-heading&quot;,<br>                                    className=&quot;text-primary text-center border-bottom border-top &quot;<br>                                              &quot;border-primary rfs-small py-1&quot;,<br>                                ),<br>                                html.Div(id=&#39;order-summary&#39;),<br><br>                            ]<br>                        )<br>                    ]<br>                ),<br>                dbc.ModalFooter([<br>                    dbc.Row([<br>                        dbc.Button(&#39;Confirm Order&#39;, id=&#39;submit-button&#39;, n_clicks=0, disabled=True),<br>                    ])<br><br>                ])<br>            ],<br>            id=&quot;orders-modal&quot;,<br>            is_open=False,<br>        ),<br>    ]<br>)<br># endregion /order modal</pre><p>We need a Dash callback to trigger displaying this new modal. This code should look familiar as it’s similar to the callback that triggers the Alpaca settings dialog. We’ll modify it later to add additional functionality.</p><pre># region CALLBACK - ORDERS MODAL<br>@app.callback(<br>    Output(&quot;orders-modal&quot;, &quot;is_open&quot;),<br>    Input(&quot;btn-orders-modal&quot;, &quot;n_clicks&quot;),<br>    State(&quot;orders-modal&quot;, &quot;is_open&quot;),<br>)<br>def toggle_orders_modal(n1, is_open):<br>    if n1:<br>        return not is_open<br>    return is_open<br># endregion /orders modal</pre><p>Now, let’s work on the layout for our order modal, starting with the header variable. I’ve configured two rows, wrapped within a div, and each having dbc column components. Our users will want to confirm they are trading the correct stock, so in the first row of this header we will display the symbol and company name. The second row will display the Bid and Ask prices and the spread between them. Remember, we are initially using the free IEX data feed, which can have sporadically-huge spreads, so these prices are a critical feature to include! We’ll get these values to update in the next chapter.</p><pre>order_header = html.Div([<br>    dbc.Row(<br>        [<br>            dbc.Col(<br>                [<br>                    html.Span(id=&quot;symbol&quot;),<br>                    html.Span(&quot; - &quot;),<br>                    html.Span(id=&quot;company&quot;),<br>                ], width=12, className=&quot;rfs-large&quot;),<br>        ],<br>        className=&quot;mb-2&quot;<br>    ),<br>    dbc.Row(<br>        [<br>            dbc.Col(<br>                [<br>                    html.Div(&quot;BID&quot;, className=&quot;rfs-small&quot;),<br>                    html.Div(id=&quot;bid-text&quot;, className=&quot;rfs-small&quot;, n_clicks=0),<br>                    html.Div(id=&quot;bid-size&quot;, className=&quot;rfs-tiny&quot;)<br>                ], width=4,<br>            ),<br>            dbc.Col(<br>                [<br>                    html.Div(id=&quot;spread-text&quot;, className=&quot;rfs-tiny text-muted&quot;, n_clicks=0),<br>                ]<br>            ),<br>            dbc.Col(<br>                [<br>                    html.Div(&quot;ASK&quot;, className=&quot;rfs-small&quot;),<br>                    html.Div(id=&quot;ask-text&quot;, className=&quot;rfs-small&quot;, n_clicks=0),<br>                    html.Div(id=&quot;ask-size&quot;, className=&quot;rfs-tiny&quot;),<br>                ], width=4,<br>            ),<br>])</pre><p>Here’s code to display a set of account radio buttons for specifying whether the order should use a paper or live account. Back when we created the Alpaca Keys Modal, we only created fields for a paper account. I’ll leave it to you to go back and add live-account inputs there.</p><pre>account_radios = dbc.Row(<br>    [<br>        dbc.Label(html.Small(&quot;Account*&quot;, className=&quot;rfs-small&quot;), width=3),<br>        dbc.Col(<br>            [<br>                dbc.RadioItems(<br>                    id=&quot;account&quot;,<br>                    className=&quot;btn-group btn-lg&quot;,<br>                    inputClassName=&quot;btn-check&quot;,<br>                    labelClassName=&quot;btn btn-outline-primary&quot;,<br>                    labelCheckedClassName=&quot;active&quot;,<br>                    persistence_type=&quot;local&quot;, persistence=True,<br>                    options=[<br>                        {&quot;label&quot;: &quot;Paper&quot;, &quot;value&quot;: &#39;paper&#39;},<br>                        {&quot;label&quot;: &quot;Live&quot;, &quot;value&quot;: &#39;live&#39;},<br>                    ],<br>                    value=&#39;paper&#39;,<br>                ),<br>            ],<br>            width=4<br>        ),<br>        dbc.Col(<br>            [<br>                html.Small(id=&#39;account-details&#39;, className=&quot;text-muted rfs-tiny&quot;)<br>            ],<br>            width={&#39;offset&#39;: 3, &#39;size&#39;: 9}<br>        )<br>    ],<br>    className=&quot;radio-buttons&quot;,<br>    style={&#39;marginBottom&#39;: &#39;5px&#39;},  # className not working<br>)</pre><p>The order_side buttons are used to designate whether the order is to buy or sell the security.</p><pre>order_side_buttons = dbc.Row(<br>    [<br>        dbc.Label(html.Small(&quot;Side*&quot;, className=&quot;rfs-small&quot;), width=3),<br>        dbc.Col(<br>            [<br>                dbc.RadioItems(<br>                    id=&quot;order-side&quot;,<br>                    className=&quot;btn-group btn-lg&quot;,<br>                    inputClassName=&quot;btn-check&quot;,<br>                    labelClassName=&quot;btn btn-outline-primary&quot;,<br>                    labelCheckedClassName=&quot;active&quot;,<br>                    options=[<br>                        {&quot;label&quot;: &quot;Buy&quot;, &quot;value&quot;: &#39;buy&#39;},<br>                        {&quot;label&quot;: &quot;Sell&quot;, &quot;value&quot;: &#39;sell&#39;},<br>                    ],<br>                ),<br>            ],<br>            width=9<br>        ),<br>    ],<br>    className=&quot;radio-buttons&quot;,<br>    style={&#39;marginBottom&#39;: &#39;5px&#39;},  # className not working<br>)</pre><p>Both sets of buttons (account and side) use a bit of CSS in the external stylesheet to adjust their borders, alignment, and coloration. Add this to the styles.css file in your assets directory.</p><pre>/* restyle Radio-Type Buttons used for side and account */<br>.radio-buttons .form-check {<br>  padding-left: 0;<br>}<br>.radio-buttons .btn-group &gt; .form-check:not(:last-child) &gt; .btn {<br>  border-top-right-radius: 0;<br>  border-bottom-right-radius: 0;<br>}<br>.radio-buttons .btn-group &gt; .form-check:not(:first-child) &gt; .btn {<br>  border-top-left-radius: 0;<br>  border-bottom-left-radius: 0;<br>  margin-left: -1px;<br>}<br><br>/* CSS rule to color the &#39;live&#39; account button yellow when selected */<br>#account &gt; div:nth-child(2) &gt; input:checked ~ label {<br>  color: rgba(255,69,0,1);<br>  background-color: rgb(255, 193, 7);<br>}</pre><p>For the time-in-force (tif) component, expand the placeholder variable as follows. In the previous chapter, I mentioned that Alpaca uses a separate parameter for signifying extended hours. However, I’m including ‘ext’ as a tif option for reasons you will understand when we work on adding form interactivity in the next chapter. You may also notice that I’m using the Dash Core Component (dcc) rather than the Dash Bootstrap Component (dbc) for the dropdown as the latter does not support labels in the option dictionary; the styling difference is not appreciable in this instance. This code also shows how to use the dbc.Tooltip component for adding a roll-over to the input label.</p><pre>tif_input = dbc.Row(<br>    [<br>        dbc.Label(html.Small(&quot;TIF*&quot;, className=&quot;rfs-small&quot;, id=&quot;tif-label&quot;), width=3),<br>        dbc.Tooltip(html.Div(<br>            [<br>                html.P(&quot;•DAY orders trade during regular hours (9:30AM-4:00PM Eastern) and are &quot;<br>                       &quot;cancelled at the close.&quot;),<br>                html.P(&quot;•EXT orders trade between 4AM-8PM, must be LIMIT, and are cancelled &quot;<br>                       &quot;after extended-hours close.&quot;),<br>                html.P(&quot;•GTC orders are only executed during regular hours and remain &quot;<br>                       &quot;open until filled or cancelled.&quot;),<br>                html.P(&quot;•OPG orders trade at session opening price,   &quot;<br>                       &quot;must be MKT or LIMIT and submitted between 7:00PM and 9:28AM next day.&quot;),<br>                html.P(&quot;•CLS orders trade at session closing price, &quot;<br>                       &quot;must be MKT or LIMIT and submitted between 7:00PM and 3:50PM next day.&quot;),<br>                html.P(&quot;•IOC orders are filled immediately at Market. Any unfilled &quot;<br>                       &quot;portion is cancelled.&quot;),<br>                html.P(&quot;•FOK orders are filled immediately at Market. If it cannot be &quot;<br>                       &quot;fully-executed, it is cancelled &quot;),<br>            ]<br>        ), target=&quot;tif-label&quot;, className=&quot;rfs-tiny my-2&quot;<br>        ),<br>        dbc.Col(<br>            [<br>                dcc.Dropdown(<br>                    options=[<br>                        {&#39;label&#39;: &#39;DAY&#39;, &#39;value&#39;: &#39;day&#39;},<br>                        {&#39;label&#39;: &#39;EXT&#39;, &#39;value&#39;: &#39;ext&#39;},<br>                        {&#39;label&#39;: &#39;GTC&#39;, &#39;value&#39;: &#39;gtc&#39;},<br>                        {&#39;label&#39;: &#39;OPG&#39;, &#39;value&#39;: &#39;opg&#39;},<br>                        {&#39;label&#39;: &#39;CLS&#39;, &#39;value&#39;: &#39;cls&#39;},<br>                        {&#39;label&#39;: &#39;IOC&#39;, &#39;value&#39;: &#39;ioc&#39;},<br>                        {&#39;label&#39;: &#39;FOK&#39;, &#39;value&#39;: &#39;fok&#39;},<br>                    ],<br>                    id=&#39;tif&#39;,<br>                    value=&#39;day&#39;,<br>                    clearable=False,<br>                ),<br>            ], width=9,<br>        )<br>    ],<br>    className=&quot;mb-2&quot;,<br>)</pre><p>For the qty_input component and similar numeric fields, we wrap the input in a dbc.InputGroup() so we can prepend a symbol to specify the data type, a “#” is the default and ending with a dropdown for selecting between # and $ entries. In the browser, Dash server will convert this code to a standard HTML5 input field that limits the entry to numeric values.</p><pre>qty_input = dbc.Row(<br>    [<br>        dbc.Label(html.Small(&quot;Qty*&quot;, className=&quot;rfs-small&quot;, id=&quot;qty-label&quot;), width=3),<br>        dbc.Tooltip(html.Div(<br>            [<br>                html.P(&quot;• Fractional stock shares only allowed for Market-Day orders and with no more than &quot;<br>                       &quot;2 decimal places.),<br>                html.P(&quot;• Notional ($) is only allowed for Market-Day orders.&quot;),<br>            ]<br>        ), target=&quot;qty-label&quot;, className=&quot;rfs-tiny my-2&quot;<br>        ),<br>        dbc.Col(<br>            dbc.InputGroup(<br>                [<br>                    dbc.InputGroupText(&quot;#&quot;)<br>                    dbc.Input(id=&#39;qty&#39;, type=&#39;number&#39;),<br>                    dbc.DropdownMenu([<br>                        dbc.DropdownMenuItem(<br>                            html.Small(&quot;Only Mkt-Day if fractional!&quot;, className=&quot;text-muted rfs-tiny&quot;), header=True),<br>                        dbc.DropdownMenuItem(&quot;# Shares&quot;, id=&quot;qty-shares&quot;),<br>                        dbc.DropdownMenuItem(<br>                            html.Small(&quot;Converted if not Mkt-Day:&quot;, className=&quot;text-muted rfs-tiny&quot;), header=True),<br>                        dbc.DropdownMenuItem(&quot;$ Notional&quot;, id=&quot;qty-dollars&quot;),<br>                        <br>                ]<br>            ),<br>            width=9<br>        ),<br>    ],<br>    id=&#39;qty-input&#39;,<br>    className=&quot;mb-2&quot;,<br>)<br></pre><p>Importantly, we do NOT want to require any of the price fields to be non-blank (using required or min parameters). We will be using blank values in our callback to distinguish the order types. Notice on the Trailing Stop input, I’ve added a dropdown component to the InputGroup for selecting between percent and dollar value formats.</p><pre>limit_price_input = dbc.Row(<br>    [<br>        dbc.Label(html.Small(&quot;Limit&quot;, className=&quot;rfs-small&quot;), width=3),<br>        dbc.Col(<br>            dbc.InputGroup(<br>                [<br>                    dbc.InputGroupText(&quot;$&quot;, id=&#39;limit-icon&#39;),<br>                    dbc.Input(id=&#39;limit-entry&#39;, type=&#39;number&#39; ),<br>                ]<br>            ),<br>            width=9,<br>        ),<br>    ],<br>    id=&#39;limit-price-input&#39;,<br>    className=&quot;mb-2&quot;,<br>)<br><br>stop_price_input = dbc.Row(<br>    [<br>        dbc.Label(html.Small(&quot;Stop&quot;, className=&quot;rfs-small&quot;), width=3),<br>        dbc.Col(<br>            dbc.InputGroup(<br>                [<br>                    dbc.InputGroupText(&quot;$&quot;, id=&#39;stop-icon&#39;),<br>                    dbc.Input(id=&#39;stop-entry&#39;, type=&#39;number&#39;),<br>                ]<br>            ),<br>            width=9,<br>        ),<br>    ],<br>    id=&#39;stop-price-input&#39;,<br>    className=&quot;mb-2&quot;,<br>)<br><br>trailing_stop_input = dbc.Row(<br>    [<br>        dbc.Label(html.Small(&quot;Trailing&quot;, className=&quot;rfs-small&quot;, id=&quot;ts-label&quot;), width=3),<br>        dbc.Tooltip(html.Div(<br>            [<br>                html.P(&quot;• Trailing-stop will only trigger during regular market hours and must be DAY or GTC only.&quot;),<br>                html.P(&quot;• Enter $values as actual trigger price, %values as delta above/below high-water-mark (HWM).&quot;),<br>            ]<br>        ), target=&quot;ts-label&quot;,<br>        ),<br>        dbc.Col(<br>            dbc.InputGroup(<br>                [<br>                    dbc.InputGroupText(&quot;$&quot;, id=&#39;trailing-icon&#39;),<br>                    dbc.Input(id=&#39;trailing-stop&#39;, type=&#39;number&#39;),<br>                    dbc.DropdownMenu([<br>                        dbc.DropdownMenuItem(&quot;% Trigger&quot;, id=&quot;trail-percent&quot;),<br>                        dbc.DropdownMenuItem(&quot;$ Trigger&quot;, id=&quot;trail-dollars&quot;),<br>                    ])<br>                ]<br>            ),<br>            width=9,<br>        ),<br>    ],<br>    id=&#39;trailing-stop-input&#39;,<br>    className=&quot;mb-2&quot;,<br>)<br><br>bracket_profit_input = dbc.Row(<br>    [<br>        dbc.Label(html.Small(&quot;Profit Leg&quot;, className=&quot;rfs-small&quot;), width=3),<br>        dbc.Col(<br>            dbc.InputGroup(<br>                [<br>                    dbc.InputGroupText(&quot;$&quot;, id=&#39;profit-leg-icon&#39;),<br>                    dbc.Input(id=&#39;profit-leg&#39;, type=&#39;number&#39;),<br>                ]<br>            ),<br>            width=9,<br>        ),<br>    ],<br>    id=&#39;profit-leg-input&#39;,<br>    className=&quot;mb-2&quot;,<br>)<br><br>bracket_stop_input = dbc.Row(<br>    [<br>        dbc.Label(html.Small(&quot;Loss Leg&quot;, className=&quot;rfs-small&quot;), width=3),<br>        dbc.Col(<br>            dbc.InputGroup(<br>                [<br>                    dbc.InputGroupText(&quot;$&quot;, id=&#39;loss-leg-icon&#39;),<br>                    dbc.Input(id=&#39;loss-leg&#39;, type=&#39;number&#39;),<br>                ]<br>            ),<br>            width=9,<br>        ),<br>    ],<br>    id=&#39;loss-leg-input&#39;,<br>    className=&quot;mb-2&quot;,<br>)</pre><p>With those changes, our app now looks like this when we click the TRADE button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M1rgUC-RCOHk5QCWYM9ykA.png" /></figure><p>Our order form does not know which stock we are trying to trade! Currently, we can select a ticker in our watchlist and that triggers a callback to load that symbol’s data into the chart. Now, we will need some of that same data in a new callback. Thankfully, Dash has a feature called a Store; a location to where we can easily and temporarily copy the symbol and company name until we need them.</p><p><strong>Implementing Dash Stores to Pass Data to our Order</strong></p><p>In the main app.layout container, add dcc.Store components set to use ‘memory’ as the storage type as we only want data retention to be temporary. Add stores for the symbol, company, order status, bid price and ask price, which we’ll implement later.</p><p>Dash supports three storage types:</p><ul><li><strong>memory</strong> — retains the Store’s data only in memory, so it will not be retained if the browser is refreshed or the server is restarted.</li><li><strong>local</strong> — retains the Store’s data in a file on the local device, similar to a cookie but encrypted. We used something similar when we set persistence_type=local to retain the Alpaca keys across restarts.</li><li><strong>session</strong> — retains the Store’s data in the browser’s session but it is lost if the browser is restarted.</li></ul><p>While there, let’s also add a dcc.Interval component configured to “fire” at, say, 1-second intervals. We will use this later to update bid/ask prices.</p><pre># region LAYOUT - CONTAINER<br>app.layout = dbc.Container(<br>    [<br>        # Stores and Interval added for Chapter 4<br>        dcc.Store(id=&#39;selected-symbol-store&#39;, storage_type=&#39;memory&#39;),<br>        dcc.Store(id=&#39;selected-company-store&#39;, storage_type=&#39;memory&#39;),<br>        dcc.Store(id=&#39;order-status-store&#39;, storage_type=&#39;memory&#39;),<br>        dcc.Store(id=&#39;bid-price-store&#39;, storage_type=&#39;memory&#39;),<br>        dcc.Store(id=&#39;ask-price-store&#39;, storage_type=&#39;memory&#39;),<br>        <br>        dcc.Interval(<br>            id=&#39;interval-quotes&#39;,<br>            interval=1 * 1000,  # in milliseconds<br>            n_intervals=0,<br>            disabled=False,<br>        ),<br><br>        alpaca_modal,<br>        orders_modal,<br>             ...</pre><p>We want to put the symbol and company into their Stores when the user selects a row in the watchlist. Ah! We need to update that callback. Here’s the revised code for the “LOAD CHART DATA” callback. I’ve added Output arguments referencing the stores, a line of code to extract the company from the table, and the symbol and company to the return statement.</p><pre># region CALLBACK - LOAD CHART DATA<br>@callback(<br>    Output(&#39;stock-chart&#39;, &#39;seriesData&#39;),<br>    Output(&#39;selected-symbol-store&#39;, &#39;data&#39;),  # Chpt4 - add this<br>    Output(&#39;selected-company-store&#39;, &#39;data&#39;),  # Chpt4 - add this<br>    Input(&#39;watchlist-table&#39;, &#39;active_cell&#39;),<br>    State(&#39;watchlist-table&#39;, &#39;data&#39;),<br>    State(&#39;alpaca-key-paper&#39;, &#39;value&#39;),<br>    State(&#39;alpaca-secret-paper&#39;, &#39;value&#39;),<br>)<br>def handle_watchlist_selection(active_cell, table_data, paper_key, paper_secret):<br>    # Do nothing if no selection<br>    if active_cell is None:<br>        raise PreventUpdate<br><br>    # Get the ticker using the selected row&#39;s index<br>    selected_row_index = active_cell[&quot;row&quot;]<br>    symbol = table_data[selected_row_index][&#39;TICKER&#39;]<br>    company = table_data[selected_row_index][&#39;COMPANY&#39;]  # Chpt4 - add this<br>    <br><br>    # Call function to retrieve bars data and return as a chart series<br>    return retrieve_eod_bars_for_single_stock_ticker(symbol, paper_key, paper_secret), \<br>        symbol, company  # Chpt4 - add this<br># endregion /load chart cb</pre><p>A logical place to update the header of the order modal with our stored values is in our “Orders Modal” callback. Here’s the revised code where I’ve added references to our Store values as State arguments (instead of Inputs as we just want to read these locations, not have them trigger anything) and also added them as parameters to the function. Then, all that is needed is to pass these values through to our layout locations as children of the html components with the matching ids when if the dialog is being opened.</p><pre># region CALLBACK - ORDERS MODAL<br>@app.callback(<br>    Output(&quot;orders-modal&quot;, &quot;is_open&quot;),<br>    Output(&#39;symbol&#39;, &#39;children&#39;),<br>    Output(&#39;company&#39;, &#39;children&#39;),<br>    Input(&quot;btn-orders-modal&quot;, &quot;n_clicks&quot;),<br>    State(&quot;orders-modal&quot;, &quot;is_open&quot;),<br>    State(&#39;selected-symbol-store&#39;, &#39;data&#39;),<br>    State(&#39;selected-company-store&#39;, &#39;data&#39;),<br>)<br>def toggle_orders_modal(n1, is_open, symbol, company):<br>    if n1:<br>        return not is_open, symbol, company<br>    return is_open, no_update, no_update<br># endregion /settings modal</pre><p>We could use this same callback to add other components to the header, such as the bid/ask price. But, those components must be loaded from Alpaca and for that we need the API keys. We’ll also need the Alpaca access keys to submit orders, so the logical place to load the rest of the header is from the callback that submits the order. We’ll work on that in the next chapter.</p><p>To close out this chapter, let’s add a quick callback to handle the field format toggles. This code shows a nice way to handle multiple toggles in a single callback using a “toggle_map” as an alternative to a long if-else clause. I learned this bit of magic from a wizard called ChatGPT.</p><pre># region CALLBACK - TOGGLE BUTTONS<br>toggle_map = {<br>    &quot;qty-dollars&quot;: (&quot;$&quot;, &quot;bg-warning&quot;, no_update, no_update),<br>    &quot;qty-shares&quot;: (&quot;#&quot;, &quot;&quot;, no_update, no_update),<br>    &quot;trail-percent&quot;: (no_update, no_update, &quot;%&quot;, &quot;bg-warning&quot;),<br>    &quot;trail-dollars&quot;: (no_update, no_update, &quot;$&quot;, &quot;&quot;),<br>}<br>@app.callback(<br>    Output(&quot;qty-icon&quot;, &quot;children&quot;),<br>    Output(&quot;qty-icon&quot;, &quot;className&quot;),<br>    Output(&#39;trailing-icon&#39;, &#39;children&#39;),<br>    Output(&#39;trailing-icon&#39;, &#39;className&#39;),<br>    [Input(button_id, &quot;n_clicks&quot;) for button_id in toggle_map.keys()],<br>)<br>def toggle_icons(*n_clicks):<br>    &quot;&quot;&quot; Use toggle_map to change prepended icons and background colors in input fields of Order modal. &quot;&quot;&quot;<br>    <br>    triggered_id = ctx.triggered_id<br>    if triggered_id in toggle_map:<br>        print(f&quot;{triggered_id} triggered&quot;)<br>        return toggle_map[triggered_id]<br>    else:<br>        raise PreventUpdate<br># endregion CALLBACK - TOGGLE BUTTONS</pre><h3>A Summary of our Adventure:</h3><ul><li>In <a href="https://medium.com/@stevenwmayo/tradenosis-my-quest-to-build-a-mythical-stock-trading-platform-chapter-1-90924cd09f3f"><strong>Chapter 1</strong></a>, we created the UI for a basic trading webpage using Dash.</li><li>In <a href="https://medium.com/@stevenwmayo/tradenosis-my-quest-to-build-a-mythical-stock-trading-platform-e2c62f10e67b"><strong>Chapter 2</strong></a>, we created an Alpaca Settings dialog and added code to load candlestick price data into a stock chart.</li><li>In <a href="https://medium.com/@stevenwmayo/tradenosis-my-quest-to-build-a-mythical-stock-trading-platform-c1bf56372d7c"><strong>Chapter 3</strong></a>, we reviewed Alpaca’s trading rules.</li><li>In this chapter, we created the order form and associated code to compile trade instructions.</li><li>In <a href="https://medium.com/@stevenwmayo/tradenosis-my-quest-to-build-a-mythical-stock-trading-platform-65a46823c606"><strong>Chapter 5</strong></a>, we will write the callback needed to submit an order to Alpaca.</li><li>In <a href="https://medium.com/@stevenwmayo/tradenosis-my-quest-to-build-a-mythical-stock-trading-platform-1771245c54a2"><strong>Chapter 6</strong></a>, we’ll use the Alpaca account data to fill the Orders and Positions tabs.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=31d452683b6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[TRADEnosis™ — My Quest to Build a Mythical Stock Trading Platform]]></title>
            <link>https://medium.com/@stevenwmayo/tradenosis-my-quest-to-build-a-mythical-stock-trading-platform-c1bf56372d7c?source=rss-310758628d4------2</link>
            <guid isPermaLink="false">https://medium.com/p/c1bf56372d7c</guid>
            <category><![CDATA[tradenosis]]></category>
            <category><![CDATA[alpaca-markets]]></category>
            <category><![CDATA[stock-trading]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[dash]]></category>
            <dc:creator><![CDATA[Steve Mayo]]></dc:creator>
            <pubDate>Thu, 03 Aug 2023 17:11:08 GMT</pubDate>
            <atom:updated>2023-08-23T00:26:57.014Z</atom:updated>
            <content:encoded><![CDATA[<h3>TRADEnosis™ — My Quest to Build a Mythical Stock Trading Platform</h3><h4>Chapter 3: Alpaca Market’s Trade Order Submission Rules</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cffucWmKLkq_dd3ALLGsdg.png" /></figure><h4>Where are we, Sire?</h4><p>This is yet another chapter in our ongoing adventure to build a basic, yet functional, web application for viewing stock graphs and entering trades. In <a href="https://medium.com/@stevenwmayo/tradenosis-my-quest-to-build-a-mythical-stock-trading-platform-chapter-1-90924cd09f3f">Chapter 1</a>, we used <strong>Plotly Dash</strong> to write a responsive interface. In <a href="https://medium.com/@stevenwmayo/tradenosis-my-quest-to-build-a-mythical-stock-trading-platform-e2c62f10e67b">Chapter 2</a>, we added interactively with Dash callbacks and used the <strong>Alpaca</strong> V<strong>ersion 2 Python SDK</strong> to load data into our candlestick graph.</p><p><strong>In this chapter we will explore what is needed to generate trade orders. </strong>That’s where things get complicated. There are lots of order parameters and order types and lots of rules we’ll need to follow. So, before we dive into the code, let’s review review what goes into trade orders.</p><h4>Understanding Orders</h4><p>A order is an instruction to your broker to buy or sell a security, essentially to “execute a trade” according to rules established by the US Securities &amp; Exchange Commission (SEC) and the exchanges. Brokers may add additional requirements such as how much margin is required or how much commission is charged. As we discussed earlier, there are multiple markets/exchanges. Your trade many not actually get transacted on a major exchange and often not by your broker directly. In fact, routing orders to various market makers and clearing firms, willing to pay fees for the order flow, is how brokers make money. You didn&#39;t really think brokers were executing trades for free, did you?</p><p>Some brokers use the terms “Buy/Sell to Open” and“Buy/Sell to Close” as a way to distinguish whether a order is intended to establish a new position or to zero-out a previously-entered position. Alpaca does not. For example, you can use an order to buy 10 shares and later enter another order to sell 5 of those shares without having to indicate that it&#39;s to partially close the position. That makes trading easier, but it can make explaining orders a bit harder, especially when we get to the Advanced Order Types.</p><p>First, let’s discuss the 4 basic order types and a fifth that some brokers support. Be aware that orders can be used either to open or close a position. Also, an “entry/opening order” will establish either a <strong>long</strong> (by buying shares) or a <strong>short</strong> (by selling borrowed shares) position, for which you later use a “closing/exiting order” to zero-out your position.</p><ul><li><strong>Market —</strong> an order to buy/sell at the price available at the time the order is executed, specifically at the then-current “ask” price if your are buying and at the “bid” price if selling albeit some brokers will try to get “price improvement” by routing your order to achieve a slightly better price. Provided the market is open and the security is available, market orders execute almost immediately. You won’t know the exact price until the order is transacted and there is a risk there could be an unexpected price deviation from the last quote you saw, especially if your quotes are delayed or not from the major exchanges (e.g., IEX rather than SIP), or if the market is moving quickly.</li><li><strong>Limit</strong> — an order to buy/sell at the specified price OR BETTER. What may be confusing here is that the stock price could exactly hit your limit price, but not be filled if the order could not be immediately executed at that price, say due to insufficient market liquidity. The risk with a limit order is that you can miss a trading opportunity if the price never hits the trigger. Limit orders are viewable in the Level 2 order book. There’s debate whether or not high-frequency trading firms and market makers over a few seconds, move the market by a combination of aggressive selling and placing large sell orders cancelled immediately afterwards, to “take-out” a standing limit order. I don’t know if that really happens, but it sure feels that way when price suddenly moves to my limit and my trade fills only to immediately revert.</li><li><strong>Stop</strong> — this order becomes a market order once the stock price moves past your stop price. It can be used to enter a position, say, when you only want to buy the stock if it breaks above a resistance line on the chart. Conversely, when used to close (as in zero-out your exposure to) an already open position, many think of this as a “protective stop”. But, in a fast moving market, your order could get filled quite far away from the stop price. I remember the Flash Crash of March 2010 when lots of people got “stopped-out” with tremendous loses after the market suddenly dropped hard and the exchanges couldn’t keep up. It hurt all the more when the market fully recovered within just a few minutes, having filled those closing orders near the bottom despite the stops being much higher. I use stops far less often now!</li><li><strong>Stop-Limit — </strong>this order will be executed at a specified limit price, or better, after a given stop price has been reached. Using this order type might have limited losses in the Flash Crash, but in the more serious event of a sudden and sustained price change, say a company suddenly goes under, it might not get you out at all. The triggered order might move beyond the limit before it can be filled.</li><li><strong>Trailing Stop</strong> — Some brokers, including Alpaca, support this order type which will automatically update the stop as the stock price moves in a favorable direction. For a sell order, the order will convert to a market order if the price drops a specified percentage or dollar amount below what is called the “high water mark” (hwm) after reaching a peak high price. For a buy order, say to close a short trade, the opposite is true, but confusingly, Alpaca still labels the trough as hwm just the same. The advantage of this order type is that you don’t have to monitor the market continuously to move up your stop. Another wonderful advantage is that the stop trigger can be entered either as a trailing price or trailing percentage; the latter makes trade management easier!</li></ul><h4>Advanced Order Types</h4><p>Alpaca (and increasingly other brokers) support advanced order types that can be used to add additional “legs” to an order. Some of the legs are not sent to the exchange until after another leg has been filled. This is primarily used to convey your opening and closing instructions within a single order (called a Bracket Order); whereas, normally, you can’t enter contradictory orders. Alpaca supports three types, but unfortunately, in contrast to the trailing stop, they currently support only price targets, not percentage moves.</p><ul><li><strong>One-Cancels-Other (OCO)</strong> —This is a set of two orders with the same side (Buy/Buy or Sell/Sell). When you already have an open position, Alpaca allows this order type to enter both a <strong>Loss-Stop</strong> and a <strong>Take-Profit s</strong>top as conditional closing orders; be aware that you can’t use this order type to enter a new position, only to exit a current position. For example, let’s say last week you bought shares at $10. Using this order type today, you might establish a stop price at $15 to cash-out your position with a profit should the stock move favorably upward, and AT THE SAME TIME, establish a stop at $8 to close-out your position if the stock moves against you. Alpaca will execute whichever target gets hit first, hopefully your “Take-Profit” order, and automatically cancel the other. In a volatile market, especially when your targets are close together, there is a chance that both orders could trigger. It’s rare, but one of the reasons you shouldn’t let trades go totally unattended.</li><li><strong>One-Triggers-Other (OTO)</strong> — This is an opening order, using any of the 5 basic order types, along with a closing leg that has EITHER a stop to prevent the stock from moving against your position ( Loss Stop) <em>OR</em> a stop to extract a profit if the position moves favorably above a predetermined trigger point (Take-Profit stop). This closing leg gets “triggered” only if the opening order was successful.</li><li><strong>Bracket Order (OTOCO)</strong> — This is a combination of the above two advanced types where in a single submission you can establish an opening order (using one of the 5 basic types) plus two OCO closing legs, a Take Profit and a Loss Stop. This is an ideal order type to use in an automated trading system; for discretionary trading, you might want to monitor the trade and “move your stops” manually. The current Alpaca documentation is unclear/inconsistent whether you can adjust stops in advanced orders without first cancelling the current order; I’m still exploring how best to do that.</li></ul><h4>The TIF Order Parameter</h4><p>Time-in-Force (TIF) instructs Alpaca as to when the trade should be executed. There are several available options:</p><ul><li><strong>Day</strong> — A day order is eligible for execution only during REGULAR market hours. In the case of US stocks, that would be 9:30AM to 4:00PM Eastern Time. It can be submitted the evening before, provided it’s submitted after the closing time for regular hours. If it does not get filled (say, if it was an untriggered limit order) or get cancelled by the trader, Alpaca will automatically cancel it at regular market close.</li><li><strong>Good Until Canceled (GTC) </strong>— A GTC order remains active until it is filled, or cancelled by the trader. If there is a stock split while an order is open, the number of shares will get adjusted accordingly.</li><li><strong>Extended Hours</strong> — this is a separate parameter than can be applied to a Day or GTC order; in the user interface we will treat it like a TIF option and distinguish it in the code only. Alpaca allows orders to be submitted “pre-market” between 4:00AM and 9:30AM Eastern Monday to Friday, and “After Hours” between 4:00PM and 8:00PM ET M-F. The number/speed of transactions (called “liquidity”) of a stock is generally much less outside of regular hours, so spreads (between the bid and ask price) can be much higher. As such, Alpaca will only accept Limit-Day orders during extended hours.</li><li><strong>At the Open (OPG) </strong>— Only market and limit orders are allowed to use this TIF option. The order is eligible to be filled at the market’s opening auction price (the “opening price” at 9:30AM) and will be automatically cancelled if not filled. An OPG order must be submitted before 9:28 AM to be valid, and can be submitted any time after 7:00PM for the next session’s opening trade.</li><li><strong>At the Close (CLS)</strong> — Market and limit orders submitted with this TIF parameter are eligible to be filled at the maket’s closing auction price. They will be automatically cancelled if unfilled. CLS orders can be submitted until 3:50PM, or after 7:00PM for the next trading session.</li><li><strong>Immediate or Cancel (IOC)</strong> —This rarely-used TIF parameter requires that the order be executed immediately, either fully or partially, or it will be automatically cancelled. If partially filled, the unfilled portion is cancelled.</li><li><strong>Fill or Kill (FOK) </strong>—A FOK order must be filled for the full requested quantity, otherwise the order is cancelled.</li></ul><h4>Notable Alpaca Trading Rules:</h4><p>On top of the design considerations we’ll be making to implement the order types and parameters discussed above, Alpaca adds certain rule. An order that does not comply will get rejected. In our coding, we may want to handle some of these situations to try and avoid an order being rejected, or to prevent the user getting a “fill” that differs from what was expected.</p><ul><li>You must have sufficient “<strong>buying power</strong>” to execute a trade. Alpaca determines the amount needed to transact the trade by multiplying the limit price by the number of shares. For non-limit orders, they do this calculation using a 2.5% to 4% estimate above/below current price. Buying power takes into account any open orders and whether you are using margin (essentially, agreeing to borrow money); therefore, we may want to show buying power at the time the user is entering a trade.</li><li>A <strong>Limit, Stop or Stop-Limit order</strong> will be rejected if it has a sub-penny increment (ex., $4.026) when the price is over a dollar or if there are more than 4 decimals ($0.50789) when the price is under a dollar.</li><li>A <strong>Stop</strong> order when buying will automatically convert into a Stop-Limit order with the limit price set at 4% higher than a Stop price when the price is under $50, or with a limit set at 2.5% higher than the Stop price when the stock transacts at $50 or more. When selling, this automatic conversion does not occur. I’m sure there a reason, but it evades me!</li><li>The <strong>Take-Profit stop </strong>parameter of advanced order types must be a price, not a percentage; once triggered the order is executed at the market price. The <strong>Stop-Loss</strong> parameter can be either a stop-price, a limit_price or both; again, unfortunately, it must be entered as a price, not a percentage.</li><li>The <strong>Stop-Loss</strong> parameter of an advanced order for exiting a position must be at least $0.01 away (below for a sell, above for a buy) from the price of the entry leg as well as the alternate leg.</li><li><strong>Fractional shares and notional</strong> (dollars instead of qty) orders are only available during regular hours and only as market orders. Only certain higher-volume stocks are “fractionable”. We check for this parameter in the stock’s data, but few people use notional trades and the added step is probably not worth the added complexity and potential delay.</li><li><strong>Shorting</strong> (borrowing to sell) is only allowed with “Easy-to-Borrow” stocks. Additional fees, in some cases substantial, are charged daily. Again, we could check for that parameter in the stock data before submitting the order, but that again adds unnecessary(?) complexity.</li><li>Alpaca will reject an order if it would unintentionally cause a <strong>Pattern Day Trader</strong> (PDT) designation on an account with less than $25,000 in equity. By exchange rules, a PDT designation results if you make four “day trades” (buy &amp; sell the same stock within asingle market session) within 5 days. To actually day trade, you’ll likely need more than $25K to cover the clearing time before funds are returned to your account after a closing transaction. This parameter is in the user’s account data, something well consider displaying in the future.</li></ul><h4>Where do we go next?</h4><p>In the next chapter, we’ll create the order form to handle all these different order parameters. Version 2 of the Alpaca Markets Python API uses a package called Pydantic (on their end, we don’t need to install it) to validate orders. For us, that means we will need to submit orders using a specific API class to match the specific order type. It quickly get’s complex and unfortunately the available documentation is currently incomplete, but we’ll rise to the challenge!</p><h3>A Summary of our Adventure:</h3><ul><li>In <a href="https://medium.com/@stevenwmayo/tradenosis-my-quest-to-build-a-mythical-stock-trading-platform-chapter-1-90924cd09f3f"><strong>Chapter 1</strong></a>, we created the UI for a basic trading webpage using Dash.</li><li>In <a href="https://medium.com/@stevenwmayo/tradenosis-my-quest-to-build-a-mythical-stock-trading-platform-e2c62f10e67b"><strong>Chapter 2</strong></a>, we created an Alpaca Settings dialog and added code to load candlestick price data into a stock chart.</li><li>In this chapter, we reviewed Alpaca’s trading rules.</li><li>In<strong> </strong><a href="https://medium.com/@stevenwmayo/tradenosis-my-quest-to-build-a-mythical-stock-trading-platform-31d452683b6"><strong>Chapter 4</strong></a><strong> </strong>we will create the order form and associated code to compile trade instructions.</li><li>In <a href="https://medium.com/@stevenwmayo/tradenosis-my-quest-to-build-a-mythical-stock-trading-platform-65a46823c606"><strong>Chapter 5</strong></a>, we will write the callback needed to submit an order to Alpaca.</li><li>In <a href="https://medium.com/@stevenwmayo/tradenosis-my-quest-to-build-a-mythical-stock-trading-platform-1771245c54a2"><strong>Chapter 6</strong></a>, we’ll use the Alpaca account data to fill the Orders and Positions tabs.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c1bf56372d7c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[TRADEnosis™ — My Quest to Build a Mythical Stock Trading Platform]]></title>
            <link>https://medium.com/@stevenwmayo/tradenosis-my-quest-to-build-a-mythical-stock-trading-platform-e2c62f10e67b?source=rss-310758628d4------2</link>
            <guid isPermaLink="false">https://medium.com/p/e2c62f10e67b</guid>
            <category><![CDATA[stock-trading]]></category>
            <category><![CDATA[dash]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[tradenosis]]></category>
            <category><![CDATA[alpaca-markets]]></category>
            <dc:creator><![CDATA[Steve Mayo]]></dc:creator>
            <pubDate>Mon, 31 Jul 2023 01:42:42 GMT</pubDate>
            <atom:updated>2023-08-23T00:23:12.808Z</atom:updated>
            <content:encoded><![CDATA[<h3>TRADEnosis™ — My Quest to Build a Mythical Stock Trading Platform</h3><h4><em>Chapter 2: Updating the chart with Alpaca and a little magic</em></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cffucWmKLkq_dd3ALLGsdg.png" /></figure><p>This is the second chapter of a story sharing several of the things I learned while building a stock trading platform in <strong>Python</strong> code using <strong>Plotly Dash</strong> to generate a responsive front-end web app, and the recently released <strong>Alpaca Markets</strong> v2 API for price data and trade executions.</p><p>A seasoned developer would likely have used React or NodeJS. Had I done so, this task might not have felt so much like I was battling dragons on a quest for the Holy Grail. But, I had just spent two years learning Python and machine learning (a/k/a Artificial Intelligence) to implement my idea for a new trading strategy and didn’t want to climb yet another steep learning curve. Sometimes you just have to follow your heart, or that mysterious voice that speaks to you from the heavens. And sometimes you just need to add a little alliterative allegory to a tedious topic!</p><p>In the <a href="https://medium.com/@stevenwmayo/tradenosis-my-quest-to-build-a-mythical-stock-trading-platform-chapter-1-90924cd09f3f">last chapter</a>, we created a basic user interface for our clone of what eventually became a commercial offering, the <a href="http://www.tradenosis.com/">TRADEnosis</a> AI-powered stock trading platform. To help keep us oriented as this script gets longer, here’s a code “rollup” created using PyCharm, my preferred integrated development environment (IDE) for Python, using its handy# region and # endregion comment directives to collapse key code sections. The full code, so far, is in the prior chapter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/706/1*CoxCe9RIzGZgNJ6Flk4_oQ.png" /></figure><h4>Keys to Success</h4><p>Remember that DropDownMenuItem, essentially a button, in the navbar?dbc.DropdownMenuItem(&quot;Alpaca&quot;, id=&quot;btn-alpaca-settings&quot;, n_clicks=0)? Let’s use it to trigger a modal for entering Alpaca API v2 access keys.</p><p>First, between the positions card and the main container, add a new layout variable using the following code. Notice we are dutifully following Bootstrap’s container → row → column structure within the body portion of the surrounding dbc.Modal component. The two columns, each 12 column-widths so they fill an entire line, use an html.Div to group a dbc.Label and dbc.Input component. Importantly, the inputs are configured to use local persistence, meaning the entries will be saved in a browser cookie and thus not need to be re-entered every session. This works well for a paper account. For a funded live account, you might want to use something more secure, like Alpaca OAuth, which is beyond the current scope of this series.</p><pre># region LAYOUT - KEYS MODAL<br>alpaca_modal = html.Div(<br>    [<br>        dbc.Modal(<br>            [<br>                dbc.ModalHeader([<br>                    dbc.ModalTitle(&quot;Alpaca Access Keys&quot;),<br>                ]),<br>                dbc.ModalBody(<br>                    [<br>                        dbc.Container(<br>                            [<br>                                dbc.Row(<br>                                    [<br>                                        dbc.Col(<br>                                            html.Div([<br>                                                dbc.Label(&quot;Paper Account Key&quot;),<br>                                                dbc.Input(<br>                                                    id=&quot;alpaca-key-paper&quot;, type=&quot;text&quot;,<br>                                                    persistence=True, persistence_type=&#39;local&#39;,<br>                                                    className=&quot;mb-2&quot;<br>                                                ),<br>                                            ]),<br>                                            width=12<br>                                        )<br>                                    ]<br>                                ),<br>                                dbc.Row(<br>                                    [<br>                                        dbc.Col(<br>                                            html.Div([<br>                                                dbc.Label(&quot;Paper Secret Key&quot;),<br>                                                dbc.Input(<br>                                                    id=&quot;alpaca-secret-paper&quot;, type=&quot;text&quot;,<br>                                                    persistence=True, persistence_type=&#39;local&#39;,<br>                                                    className=&quot;mb-2&quot;<br>                                                ),<br>                                            ]),<br>                                            width=12<br>                                        )<br>                                    ]<br>                                ),<br>                            ]<br>                        )<br>                    ]<br>                ),<br>            ],<br>            id=&quot;alpaca-modal&quot;,<br>            is_open=False,<br>        ),<br>    ]<br>)<br># endregion /alpaca keys modal</pre><p>Next, add the alpaca_modal variable to the main layout. Put it at the top of the container, as modals can act strangely if embedded deep within a layout. This dialog won’t show up until we take the next step.</p><p># region LAYOUT — CONTAINER<br>app.layout = dbc.Container(<br> [<br> alpaca_modal, # <em>&lt;-- Put the reference to our new modal here</em></p><h4>Callbacks — A Bit of Merlin Magic</h4><p>Now, we need a function to display the modal when we click our settings button. Add this code, called a Dash Callback, near the bottom of our script, below all the layout pieces and just above the “if…main” conditional. By convention, we write variable &amp; property names with underscores and id names with dashes. Within the callback configuration, the part above the function that’s called a decorator, said references must be in quotes.</p><pre># region CALLBACK - ALPACA SETTINGS MODAL<br>@app.callback(<br>    Output(&quot;alpaca-modal&quot;, &quot;is_open&quot;),<br>    Input(&quot;btn-alpaca-settings&quot;, &quot;n_clicks&quot;),<br>    State(&quot;alpaca-modal&quot;, &quot;is_open&quot;),<br>)<br>def toggle_alpaca_modal(n1, is_open):<br>    if n1:<br>        return not is_open<br>    return is_open<br># endregion /settings modal</pre><p>The @app.callback(...) decorator and the function it wraps, in this case def toggle_alpaca_modal(...), is the magic that adds interactivity to our otherwise-static web page. How you may ask? (I’ll assume, oh noble knight, you are are asking in the proper Old Brittonic dialect of King Authur’s time!)</p><p>Well, My Liege, an Output argument specifies the component property that will get changed by the function’s return statement. An Input argument, which gets mapped to a function parameter (in the order in which it occurs), becomes a trigger to run the function. A State argument, like an Input, also gets mapped to a function parameter, but changes to that State argument, say by another callback or a user’s action, won’t trigger the function. Think of State as read-only.</p><p>Virtually any aspect of a Dash component, with a similar bit of Merlin-like callback magic, can be modified interactively. In this example, clicking the button with the id btn-alpaca-settings sends a click message within the browser DOM that will trigger our callback to toggle the is_open parameter and show our new modal.</p><p>Now that we have the layout and callback, try running our app and clicking the Settings button. You should see our new dialog. After creating and logging into your <a href="https://app.alpaca.markets/account/login">Alpaca.markets account</a>, you can generate these keys on the Alpaca Trading Dashboard by following this <a href="https://medium.com/invsto/getting-your-api-key-from-alpaca-f2b786f63222">helpful article</a>. Start with a paper account and go ahead and enter your keys now as we’ll need them for the next step.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CoXMPSLPhGbJlbVo9qqNPA.png" /></figure><p><strong>Enough! Draw forth Excalibur, and let’s get that chart working!</strong></p><p>Finally, we are ready to add Alpaca to our armaments, which we’ll first use to collect stock price data for our chart component. In late 2022, Alpaca updated their Python SDK to version 2. Unfortunately, their documentation for this new version is spare, and you’ll find few working examples elsewhere.</p><p>First, we need to import the packaged Alpaca classes. We might not use all of these, but at least you now have them all in one place; well, there’s a few more in the documentation if you need crypto prices. Add these at the top of our long script.</p><pre>from datetime import datetime, timedelta<br>from alpaca.data.historical import StockHistoricalDataClient<br>from alpaca.data.requests import StockBarsRequest, StockLatestQuoteRequest<br>from alpaca.data.timeframe import TimeFrame<br>from alpaca.trading.client import TradingClient<br>from alpaca.trading.requests import (<br>    MarketOrderRequest,<br>    StopOrderRequest,<br>    LimitOrderRequest,<br>    StopLimitOrderRequest,<br>    TrailingStopOrderRequest,<br>    TakeProfitRequest,<br>    StopLossRequest,<br>    GetOrdersRequest,<br>    GetOrderByIdRequest,<br>    ReplaceOrderRequest,<br>    ClosePositionRequest,<br>    GetAssetsRequest,<br>    GetPortfolioHistoryRequest,<br>    CancelOrderResponse,<br>    GetCalendarRequest<br>)<br>from alpaca.trading.enums import (<br>    OrderSide,<br>    TimeInForce,<br>    AssetClass,<br>    QueryOrderStatus,<br>    OrderClass,<br>)<br>from alpaca.common.exceptions import APIError</pre><p>When a user clicks on a stock ticker, we’ll load the price data (Open, High, Low, Close) into our candlestick chart. But, first we need to assign an id to the table; add the id=’watchlist-table’ to the watchlist layout variable.</p><pre># region LAYOUT - WATCHLIST<br>watchlist = dash_table.DataTable(<br>    id=&#39;watchlist-table&#39;,  # &lt;-- Add this reference<br>    ...<br># endregion /watchlist</pre><p>Now, we need a callback function, triggered by the user selecting a table row. Add this code below the modal callback we added previously. Notice that we have an Output argument directing our callback to return ‘seriesData’ to our chart (id=‘stock-chart’), an Input argument that maps the user’s selection (‘active_cell’) to the first parameter in the function, and three State arguments, which are also sequentially mapped to function parameters. The first is the data parameter from our table of stock symbols, and the other two are the keys that we just entered in our new modal.</p><p>I’m using State arguments here rather than Input as I don’t want the function to run when the keys are entered or when symbols are added to the table’s data, as there would be no table selection yet. Importantly, Dash runs all callbacks when it is first started, which would cause an error if I had not added the if…None statement; PreventUpdate (one of the Dash packages we imported in the last chapter) tells Dash to disregard the callback, in this case, when there has been no user selection yet.</p><pre># region CALLBACK - LOAD CHART DATA<br>@callback(<br>    Output(&#39;stock-chart&#39;, &#39;seriesData&#39;),<br>    Input(&#39;watchlist-table&#39;, &#39;active_cell&#39;),<br>    State(&#39;watchlist-table&#39;, &#39;data&#39;),<br>    State(&#39;alpaca-key-paper&#39;, &#39;value&#39;),<br>    State(&#39;alpaca-secret-paper&#39;, &#39;value&#39;),<br>)<br>def handle_watchlist_selection(active_cell, table_data, paper_key, paper_secret):<br>    <br>    # Do nothing if no selection<br>    if active_cell is None:<br>        raise PreventUpdate<br><br>    # Get the ticker using the selected row&#39;s index<br>    selected_row_index = active_cell[&quot;row&quot;]<br>    symbol = table_data[selected_row_index][&#39;TICKER&#39;]<br><br>    # Call function to retrieve bars data and return as a chart series<br>    return retrieve_eod_bars_for_single_stock_ticker(symbol, paper_key, paper_secret)<br><br># endregion /load chart cb</pre><p>After extracting the symbol from the table’s data object, we call a function to load price-bar data from Alpaca for that symbol, and also provide those all-important keys from our modal. Here’s the code for that function, which you should add between the setup and layout sections.</p><pre># region FUNCTIONS<br>def retrieve_eod_bars_for_single_stock_ticker(ticker: str, key: str, secret: str) -&gt; list[dict]:<br>    &quot;&quot;&quot; Load end-of-data data from Alpaca for a SINGLE STOCK ticker.<br><br><br>        :param ticker           A single stock ticker, ex. &#39;AAPL&#39;<br>        :param key:             Alpaca access key.<br>        :param secret:          Alpaca secret key.<br>        :return:                A list of dictionaries, one per symbol per day, each with the keys:<br>                                &#39;symbol&#39;, &#39;open&#39;, &#39;high&#39;, &#39;low&#39;, close&#39;, &#39;volume&#39;,<br>                                &#39;trade_count&#39;, &#39;vwap&#39; and &#39;time&#39; in ISO-8601 format (YYYY-MM-DD HH:MM:SS).<br>   &quot;&quot;&quot;<br><br>    # Configure the request<br>    alpaca_eod_request = StockBarsRequest(<br>        symbol_or_symbols=[ticker],<br>        timeframe=TimeFrame.Day,<br>        start=datetime(2017, 1, 1),  # IEX bars available from mid-2020, SIP from early-2017<br>        # limit=5000,<br>        feed= &quot;sip&quot;,<br>        adjustment=None,<br>    )<br><br>    # Configure the client and fetch the request<br>    try:<br>        alpaca_historical_client = StockHistoricalDataClient(key, secret)<br>        bars = alpaca_historical_client.get_stock_bars(alpaca_eod_request)<br>        df_ohlc = bars.df  # multi-index by symbol &amp; UTC timestamp<br>        df_ohlc = df_ohlc.reset_index()<br>        # Filter to get only the selected symbol<br>        df_ohlc = df_ohlc[df_ohlc[&#39;symbol&#39;] == ticker].copy()<br>        # Convert to Eastern timezone and ISO-8601<br>        df_ohlc[&#39;timestamp&#39;] = df_ohlc[&#39;timestamp&#39;].dt.tz_convert(&#39;US/Eastern&#39;)<br>        df_ohlc[&#39;time&#39;] = df_ohlc[&#39;timestamp&#39;].dt.strftime(&#39;%Y-%m-%d %H:%M:%S&#39;)<br>        df_ohlc = df_ohlc.drop(columns=&#39;timestamp&#39;)<br>        # print(df_ohlc.head().to_dict(&#39;records&#39;))<br>        return [df_ohlc.to_dict(&#39;records&#39;)]<br>    except APIError as n:<br>        print(&quot;APIError while trying to load EOD data: &quot;, n)<br>        return []<br>    except KeyError as n:<br>        print(f&quot;KeyError while trying to load possibly-invalid {ticker}:&quot;, n)<br>        return []<br>    except ValueError as n:<br>        print(&quot;ValueError while trying to load EOD data:&quot;, n)<br>        return []</pre><p>Remember, we are using the version 2 Python SDK. Be careful that you don’t mix version 2 and the superseded, now-obsolete version 1 code. Version 2 is class-based, so the first thing we have to do is instantiate and configure StockBarsRequest class. The request can be for multiple symbols at one time, so you have to put the ticker/symbol variable into a list.</p><h4>The StockBarsRequest()</h4><p>Alpaca has about 7 years of historic stock data from the Securities Information Processors organization (feed=“sip”) , and about 5 years from Investors Exchange (feed=“iex”). The SIP organization consolidates data from all major exchanges; that’s important as a stock can trade on multiple exchanges at somewhat different prices which SIP somehow reconciles into a single quote. Conversely, IEX is a small exchange that competes with NYSE. Because it has vastly fewer trade executions, the spreads between bid and ask price can be considerably wider than what is on SIP, and even the price bars may vary from SIP as well.</p><p>Given this difference, why would we ever want to use IEX as our data source? Well, the main reason is that IEX data is often available for free, even as a realtime data feed, while SIP realtime data is very expensive. Alpaca charges $99/month for realtime SIP data while other vendors may charge even more, particularly if they have ultralow latency feeds. However, Alpaca will give us 15-minute delayed SIP data for free, and that is fine for daily bars, what we call end-of-day data because it was historically published in newspapers after market hours. All that said, we’ll use the delayed SIP feed to get 7 years of data, as this request will only give us bars through the last market close anyway.</p><p>Alpaca can provide prices, as actually reported by SIP/IEX (adjustment=None), or prices that have been adjusted for each stock split (adjustment=“split”) or dividend (adjustment=“dividend”) or both (adjustment=“all”) since the start date of the request. Which one you should use depends on how you intend to use the data. Use unadjusted prices if you are using the price bars to make a purchase decision on the current bar. If instead, you are using the price bars to evaluate past-performance of a trading system you should use adjusted data. Algorithmic trading, say using a calculated indicator or a machine learning algorithm, is adversely impacted by the non-routine price changes caused by stock splits and dividend payments, potentially resulting in an inaccurate or biased buy/sell signal.</p><h4>The StockHistoricalDataClient and preparing the data</h4><p>The StockHistoricalDataClient class is used to configure a client to execute the request. Here’s where we need those Alpaca keys that we entered in the modal and passed to this function. If one or both keys are missing, we’ll get a ValueError with a “you must supply a method of authentication” message. If the keys are invalid, we will get an APIError with a “forbidden” message. If the stock symbol is invalid, Alpaca will return nothing and, when the code attempts to extract the symbol from the response, we’ll get a KeyError from Pandas with a message that the symbol (or timestamp) is not in the dataFrame. Note where I therefore wrapped the request-response-extraction code in a try/except block to capture these potential errors. I just printed the error messages to the console. Later, you might want to add a layout location and return the messages there as a second output of this callback.</p><p>To execute the request, we use it as a parameter in the client’s get_stock_bars() method. In similar fashion, you can alternatively execute a StockQuotesRequest(), StockTradesRequest(), StockLatestQuoteRequest(), StockLatestTradeRequest(),or aStockSnapshotRequest(). Refer to the <a href="https://alpaca.markets/docs/python-sdk/index.html">Alpaca Python API v2 documentation</a> for the proper parameters and responses, and be sure to import the necessary package.</p><h4>Breaking Camp</h4><p>A few housekeeping tasks remain. In the SETUP code block, you can now delete the test_data variable. Also, correct the symbol for ‘NVDA’ in the stock_list variable as I had entered ‘NVDIA’ to test the try/except block. At least that is what I will tell the King if any of you knaves tell him otherwise!</p><pre># region SETUP<br>stock_list = [&quot;AAPL&quot;, &quot;MSFT&quot;, &quot;GOOG&quot;, &quot;TSLA&quot;, &quot;NVDA&quot;, &quot;AMZN&quot;, &quot;META&quot;]  # Correct NVDIA to NVDA after testing!<br>df_watchlist = pd.DataFrame(data={&quot;TICKER&quot;: stock_list})<br>test_data = [<br>    {&#39;symbol&#39;: &#39;GOOG&#39;, &#39;open&#39;: 37.36, &#39;high&#39;: 38.45, &#39;low&#39;: 37.34, &#39;close&#39;: 38.35, &#39;volume&#39;: 42692420.0,<br>     &#39;trade_count&#39;: 35176.0, &#39;vwap&#39;: 38.09, &#39;time&#39;: &#39;2015-12-01 00:00:00&#39;},<br>    {&#39;symbol&#39;: &#39;GOOG&#39;, &#39;open&#39;: 38.45, &#39;high&#39;: 38.8, &#39;low&#39;: 37.95, &#39;close&#39;: 38.12,<br>     &#39;volume&#39;: 44607460.0, &#39;trade_count&#39;: 34959.0, &#39;vwap&#39;: 38.34, &#39;time&#39;: &#39;2015-12-02 00:00:00&#39;},<br>    {&#39;symbol&#39;: &#39;GOOG&#39;, &#39;open&#39;: 38.3, &#39;high&#39;: 38.45, &#39;low&#39;: 37.28, &#39;close&#39;: 37.63,<br>     &#39;volume&#39;: 51812820.0, &#39;trade_count&#39;: 38195.0, &#39;vwap&#39;: 37.77, &#39;time&#39;: &#39;2015-12-03 00:00:00&#39;},<br>    {&#39;symbol&#39;: &#39;GOOG&#39;, &#39;open&#39;: 37.66, &#39;high&#39;: 38.42, &#39;low&#39;: 37.5, &#39;close&#39;: 38.34, &#39;volume&#39;: 55145660.0,<br>     &#39;trade_count&#39;: 33245.0, &#39;vwap&#39;: 38.2, &#39;time&#39;: &#39;2015-12-04 00:00:00&#39;},<br>    {&#39;symbol&#39;: &#39;GOOG&#39;, &#39;open&#39;: 38.39, &#39;high&#39;: 38.44, &#39;low&#39;: 37.75, &#39;close&#39;: 38.16, &#39;volume&#39;: 36246280.0,<br>     &#39;trade_count&#39;: 23534.0, &#39;vwap&#39;: 38.13, &#39;time&#39;: &#39;2015-12-07 00:00:00&#39;}<br>]</pre><h4>Our Journey So Far</h4><p>With the changes we’ve made in Chapter 2, our app now dynamically loads data from Alpaca.Markets and displays a nice candlestick chart for the selected ticker. With the mouse (or your fingers once we get it hosted and accessible to a phone), one can expand/collapse the date or price axes, Also, on mouse-over, the cursor will show the close price (and corresponding date) of the underlying bar.</p><p>In the next chapter, we’ll face a far more difficult challenge! We’ll explore all the complicated brokerage rules, then create an order form that complies with those rules.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zxqITfEw6pitVDRfSnDkuw.png" /><figcaption>Our stock trading app after the changes made in Chapter 2</figcaption></figure><h3>A Summary of our Adventure:</h3><ul><li>In <a href="https://medium.com/@stevenwmayo/tradenosis-my-quest-to-build-a-mythical-stock-trading-platform-chapter-1-90924cd09f3f"><strong>Chapter 1</strong></a>, we created the UI for a basic trading webpage using Dash.</li><li>In this chapter, we created an Alpaca Settings dialog and added code to load candlestick price data into a stock chart.</li><li>In <a href="https://medium.com/@stevenwmayo/tradenosis-my-quest-to-build-a-mythical-stock-trading-platform-c1bf56372d7c"><strong>Chapter 3</strong></a>, we’ll review Alpaca’s trading rules.</li><li>In <a href="https://medium.com/@stevenwmayo/tradenosis-my-quest-to-build-a-mythical-stock-trading-platform-31d452683b6"><strong>Chapter 4</strong></a>, we will creat the order form and associated code to compile trade instructions.</li><li>In <a href="https://medium.com/@stevenwmayo/tradenosis-my-quest-to-build-a-mythical-stock-trading-platform-65a46823c606"><strong>Chapter 5</strong></a>, we will write the callback needed to submit an order to Alpaca.</li><li>In <a href="https://medium.com/@stevenwmayo/tradenosis-my-quest-to-build-a-mythical-stock-trading-platform-1771245c54a2"><strong>Chapter 6</strong></a>, we will compiled data for the Orders and Positions tabs.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e2c62f10e67b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[TRADEnosis™ — My Quest to Build a Mythical Stock Trading Platform]]></title>
            <link>https://medium.com/@stevenwmayo/tradenosis-my-quest-to-build-a-mythical-stock-trading-platform-chapter-1-90924cd09f3f?source=rss-310758628d4------2</link>
            <guid isPermaLink="false">https://medium.com/p/90924cd09f3f</guid>
            <category><![CDATA[stocks]]></category>
            <category><![CDATA[alpaca-markets]]></category>
            <category><![CDATA[dash]]></category>
            <category><![CDATA[tradenosis]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Steve Mayo]]></dc:creator>
            <pubDate>Sat, 29 Jul 2023 01:41:31 GMT</pubDate>
            <atom:updated>2023-08-23T00:24:24.328Z</atom:updated>
            <content:encoded><![CDATA[<h3>TRADEnosis™ — My Quest to Build a Mythical Stock Trading Platform</h3><h4>Chapter 1: Creating a responsive front-end with Python and Dash</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cffucWmKLkq_dd3ALLGsdg.png" /></figure><p>Frustrated with available trading platforms, I undertook a grueling quest to build my own. Unsure if I was following the path of the brave knights in <em>Excalibur</em> or those crazy guys from <em>Monte Python,</em> my half-noble half-absurd adventure, which took two years and thousands of hours climbing difficult learning curves that felt like I was battling dragons and evil wizards, eventually lead to a stock trading platform called <a href="https://www.tradenosis.com/">TRADEnosis™</a>.</p><p>This series of articles is my humble attempt to pay-it-forward for the next glory-seekers, or ambitious stock traders, who might want to travel this arduous path. In this first chapter, I hope to lessen the burden, for my fellow pilgrims, of <strong>building a responsive, interactive front-end using Python and Plotly’s Dash.</strong></p><blockquote>I won’t be giving you the Holy Grail. TRADEnosis is a commercial product with growing sales, and I intend to keep it that way. It’s value comes from the use of predictive machine learning and the API infrastructure that supports it, not from a trading interface, particularly one as basic as what we’ll be building here, even though this part of the quest still took a lot of code and a lot of research! But one can’t effectively implement an AI-powered algorithm without some way of dynamically generating stock graphs and trade orders. None of the trading platforms I found at the time would take an API feed so I built this first and am sharing it with you now, hopefully to save you from such a challenging task.</blockquote><h4>Assemble our armaments!</h4><p>To join in this adventure, you’ll need a basic familiarity with:</p><ul><li>Python, Pandas, Numpy,</li><li>Html 5 with Cascading Stylesheets (CSS), and</li><li>Bootstrap v5.</li></ul><p>Setting up a Python environment, installing packages, and learning their documentation are expected skills of anyone hoping to feast at the big round table. In preparation, install these packages:</p><ul><li>Python v3.9,</li><li>Pandas v1.5</li><li>Dash v2.11,</li><li>Dash Bootstrap Components v 1.4 (DBC),</li><li>Dash TradingView Lightweight Charts Component 0.1.1 (TVLWC), and</li><li>Alpaca Markets SDK v2.</li></ul><h4>Take heed, my liege</h4><p>Living in that mysterious realm between html and Python, these packages require you write in a strange declarative language while making a lot of trial and error refinements. Like an evil enchantress, they will temp you to abandon your quest and instead waste your life chasing the perfect layout. Don’t get beguiled, oh noble knight, keep your sights on our goal and save the tweaking until you have that golden (wooden?) cup in hand.</p><h4>Let our quest begin!</h4><p>Here’s our starting point:</p><pre>import pandas as pd<br>import plotly.graph_objs as go<br>from dash import Dash, dcc, html, callback, Input, Output, State, dash_table, no_update, Patch, ctx<br>from dash.exceptions import PreventUpdate<br>import dash_bootstrap_components as dbc<br>import dash_tvlwc<br><br>stock_list = [&quot;AAPL&quot;, &quot;MSFT&quot;, &quot;GOOG&quot;, &quot;TSLA&quot;, &quot;NVDA&quot;, &quot;AMZN&quot;, &quot;META&quot;, &quot;ADBE&quot;, &quot;AVGO&quot;, &#39;ASML&#39;]<br>df_watchlist = pd.DataFrame(data={&quot;Ticker&quot;: stock_list})<br>test_data = [{&#39;symbol&#39;: &#39;GOOG&#39;, &#39;open&#39;: 37.36, &#39;high&#39;: 38.45, &#39;low&#39;: 37.34, &#39;close&#39;: 38.35, &#39;volume&#39;: 42692420.0,<br>              &#39;trade_count&#39;: 35176.0, &#39;vwap&#39;: 38.09, &#39;time&#39;: &#39;2015-12-01 00:00:00&#39;},<br>             {&#39;symbol&#39;: &#39;GOOG&#39;, &#39;open&#39;: 38.45, &#39;high&#39;: 38.8, &#39;low&#39;: 37.95, &#39;close&#39;: 38.12,<br>              &#39;volume&#39;: 44607460.0, &#39;trade_count&#39;: 34959.0, &#39;vwap&#39;: 38.34, &#39;time&#39;: &#39;2015-12-02 00:00:00&#39;},<br>             {&#39;symbol&#39;: &#39;GOOG&#39;, &#39;open&#39;: 38.3, &#39;high&#39;: 38.45, &#39;low&#39;: 37.28, &#39;close&#39;: 37.63,<br>              &#39;volume&#39;: 51812820.0, &#39;trade_count&#39;: 38195.0, &#39;vwap&#39;: 37.77, &#39;time&#39;: &#39;2015-12-03 00:00:00&#39;},<br>             {&#39;symbol&#39;: &#39;GOOG&#39;, &#39;open&#39;: 37.66, &#39;high&#39;: 38.42, &#39;low&#39;: 37.5, &#39;close&#39;: 38.34, &#39;volume&#39;: 55145660.0,<br>              &#39;trade_count&#39;: 33245.0, &#39;vwap&#39;: 38.2, &#39;time&#39;: &#39;2015-12-04 00:00:00&#39;},<br>             {&#39;symbol&#39;: &#39;GOOG&#39;, &#39;open&#39;: 38.39, &#39;high&#39;: 38.44, &#39;low&#39;: 37.75, &#39;close&#39;: 38.16, &#39;volume&#39;: 36246280.0,<br>              &#39;trade_count&#39;: 23534.0, &#39;vwap&#39;: 38.13, &#39;time&#39;: &#39;2015-12-07 00:00:00&#39;}]<br><br>app = Dash(<br>    __name__,<br>    external_stylesheets=[<br>        dbc.themes.BOOTSTRAP,<br>        dbc.icons.BOOTSTRAP,<br>        &#39;assets/styles.css&#39;,<br>    ],<br>    meta_tags=[{&quot;name&quot;: &quot;viewport&quot;, &quot;content&quot;: &quot;width=device-width, initial-scale=1&quot;}]<br>)<br><br>navbar = &quot;&quot;<br><br>watchlist = &quot;&quot;<br><br>chart = &quot;&quot;<br><br>orders_card = &quot;&quot;<br><br>positions_card = &quot;&quot;<br><br>app.layout = dbc.Container(<br>    [<br>        navbar,<br>        dbc.Row(<br>            [<br>                dbc.Col(watchlist, xs=3, sm=2, md=1),<br>                dbc.Col(chart, xs=9, sm=10, md=11)<br>            ],<br>            className=&quot;mt-1&quot;,<br>        ),<br>        dbc.Row(<br>            [<br>                dbc.Col(<br>                    dbc.Tabs(<br>                        [<br>                            dbc.Tab(orders_card, label=&quot;Orders&quot;,<br>                                    activeLabelClassName=&quot;fw-bold&quot;,<br>                                    ),<br>                            dbc.Tab(positions_card, label=&quot;Positions&quot;,<br>                                    activeLabelClassName=&quot;fw-bold&quot;),<br>                        ],<br>                    ),<br>                    width=12)<br>            ],<br>        )<br>    ], fluid=False<br>)<br><br>if __name__ == &quot;__main__&quot;:<br>    app.run_server(debug=True, port=8000)</pre><p>Dash uses “components” which are converted into React code for the browser. They are configured with parameters and styled using the ‘style’ parameter, which is written a bit differently than native CSS. You can also add a traditional stylesheet as I’m doing here from an “assets” directory.</p><p>Dash Bootstrap Components (dbc) are similar to Dash Core Components (dcc), which we haven’t used yet, and in some cases you can swap dcc with dbc to get a Bootstrap-styled version. But more than likely, you’ll need to consult the documentation for nuanced differences.</p><p>One such notable difference is that dbc follows the Bootstrap model of using classes for styling, except written as className parameters. An example is className=&quot;mt-1&quot; to set a small margin above the first row. The dbc components can still accept the ‘style’ parameter as well. Just be aware that style will overwrite corresponding className settings.</p><p>As with using Bootstrap to lay out html, you must arrange dbc layout components within a Container -&gt; Row -&gt; Col(umn) structure. Follow the way I did it here and you should be fine. One big gotcha is that you must wrap multiple components with square brackets ([…]), like I did with the columns within the rows, and the rows within the container. Ignore that rule and the squires might laugh at you!</p><p>Bootstrap, as used by dbc, has a nice 12-column layout. Notice the columns containing the watchlist and chart. These columns will appear in a horizonal row that will dynamically re-size. On extra-small screens like a phone, those components will take 3 and 9 column-widths respectively, spaning the full 12 available column-widths, as set by the XS parameter. As the screen size increases to small (sm), medium (md), and larger (e.g., xl, xxl) the watchlist will fit in less space, leaving more room for the chart.</p><p>A somewhat confusing thing is how parameters, such as fluid=False for configuring the Container, can get buried below lines and lines of code. You can add children= ahead of the brackets to help clarify the nesting, but that adds a lot of unnecessary code. Yet, keep in mind the concept of these being children when we start adding interactivity. As a sneak peak, I will say what’s exciting about Dash is that children, along with other parameters, can be hot-swapped at runtime using callback functions. You get the benefits of React without having to slay that fearsome dragon!</p><h4>You can’t expect to wield supreme executive power just because some watery tart threw a sword at you!</h4><p>My starting template doesn’t seem very noble. But, notice I’m using variables like navbar and watchlist to isolate parts of the layout to keep the code more readable. Let’s add those components now. First, here’s the navbar code.</p><pre>navbar = dbc.NavbarSimple(<br>    [<br>        dbc.DropdownMenu(<br>            [<br>                dbc.DropdownMenuItem(&quot;Alpaca&quot;, id=&quot;btn-alpaca-settings&quot;, n_clicks=0),<br>            ],<br>            nav=True,<br>            in_navbar=True,<br>            label=&quot;Tools&quot;,<br>        ),<br>    ],<br>    brand=html.Span(<br>        [<br>            html.Span(<br>                className=&quot;&lt;bi bi-graph-up&quot;),<br>            &quot; My TRADEnosis™ Clone&quot;<br>        ], className=&quot;rfs-large&quot;<br>    ),<br>    brand_href=&quot;https://www.tradenosis.com&quot;,<br>    color=&quot;primary&quot;,<br>    dark=True,<br>)</pre><p>It uses a dbc component, dbc.NavbarSimple, to create a nice Bootstrap-like header. Within that component, I’ve inserted a DropdownMenuItem which we’ll later use to enter our Alpaca SDK keys. I also give you an example of how to incorporate an html.Span (the html package was imported from Dash in our initial code) into the brand parameter, something that can be done with many dcc/dbc components. In this case, I’m inserting an icon. bi bi-graph-up; in the prior code, we added dbc.icons.BOOTSTRAP to the Dash configuration.</p><p>Also, notice that I added aclassName=”rfs-large” to our brand parameter. In our initial code, that particular class is defined in our Dash configuration, external_stylesheets=[&#39;assets/styles.css&#39;], to make the font size change with differing screen sizes. Here’s the CSS code you should add to that styles.css file:</p><pre>/*Create a responsive font*/<br>.rfs-large{<br>  font-size: calc(0.5rem + 0.8vw);<br>}</pre><p>Next, here’s the code for the watchlist layout variable. It uses the Dash DataTable component with some styling to make it responsively fit our compact layout and make it scrollable.</p><pre>watchlist = dash_table.DataTable(<br>    data=df_watchlist.to_dict(&#39;records&#39;),<br>    columns=[{&quot;name&quot;: i, &quot;id&quot;: i} for i in df_watchlist.columns],<br>    style_cell={&#39;textAlign&#39;: &#39;left&#39;},<br>    style_as_list_view=True,<br>    style_header={&#39;borderTop&#39;: &#39;0px&#39;, &#39;fontWeight&#39;: &#39;100&#39;, &#39;fontSize&#39;: &#39;0.8em&#39;},<br>    style_data={&#39;border&#39;: &#39;0px&#39;},<br>    style_table={&#39;height&#39;: &#39;45vh&#39;, &#39;overflow&#39;: &#39;auto&#39;}<br>)</pre><p>In the initial code, I had created a Pandas dataFrame, df_watchlist, with a sampling of stock symbols. To use it within the DataTable, we first need to convert it to a dictionary of records using to_dict(‘records’) and then configure the columns.</p><p>Here’s the code for the chart. I’m using a package that wraps the free TradingView Lightweight Chart Javascript package. As an alternative, you could use Plotly, which Dash natively supports.</p><pre>chart = dash_tvlwc.Tvlwc(<br>    id=&#39;stock-chart&#39;,<br>    seriesData=[],<br>    seriesTypes=[&#39;candlestick&#39;],<br>    width=&quot;100%&quot;,<br>    height=&quot;50vh&quot;<br>),</pre><p>The last two missing parts of the layout are the content for the tabs. These also use the DataTable components, but here we define the columns expressly; we’ll load the data from Alpaca later.</p><pre>orders_card = dbc.Card(<br>    [<br>        dbc.CardBody(<br>            [<br>                dash_table.DataTable(<br>                    id=&#39;orders_table&#39;,<br>                    data=[],<br>                    columns=[<br>                        {&quot;name&quot;: &#39;Ticker&#39;, &quot;id&quot;: &#39;ot_ticker&#39;, &#39;type&#39;: &quot;text&quot;},<br>                        {&quot;name&quot;: &#39;Action&#39;, &quot;id&quot;: &#39;ot_action&#39;, &#39;type&#39;: &quot;text&quot;},<br>                        {&quot;name&quot;: &#39;Status&#39;, &quot;id&quot;: &#39;ot_status&#39;, &#39;type&#39;: &quot;text&quot;},<br>                        {&quot;name&quot;: &#39;Date&#39;, &quot;id&quot;: &#39;ot_date&#39;, &#39;type&#39;: &quot;text&quot;},<br>                    ],<br>                    style_cell={<br>                        &#39;textAlign&#39;: &#39;left&#39;,<br>                        &#39;height&#39;: &#39;auto&#39;,<br>                        # all three widths are needed<br>                        &#39;minWidth&#39;: &#39;100px&#39;, &#39;width&#39;: &#39;100px&#39;, &#39;maxWidth&#39;: &#39;100px&#39;,<br>                        &#39;whiteSpace&#39;: &#39;normal&#39;<br>                    },<br>                    style_as_list_view=True,<br>                    style_header={&#39;borderTop&#39;: &#39;0px&#39;, &#39;font-weight&#39;: &#39;600&#39;},<br>                    style_data={&#39;border&#39;: &#39;0px&#39;},<br>                    style_table={&#39;height&#39;: &#39;25vh&#39;, &#39;overflow-y&#39;: &#39;auto&#39;}<br>                )<br>            ],<br>        )<br>    ]<br>)<br><br>positions_card = dbc.Card(<br>    [<br>        dbc.CardBody(<br>            [<br>                dash_table.DataTable(<br>                    id=&quot;positions_table&quot;,<br>                    data=[],<br>                    columns=[<br>                        {&quot;name&quot;: &#39;Ticker&#39;, &quot;id&quot;: &#39;pt_ticker&#39;, &#39;type&#39;: &quot;text&quot;},<br>                        {&quot;name&quot;: &#39;Price&#39;, &quot;id&quot;: &#39;pt_price&#39;, &#39;type&#39;: &quot;text&quot;},<br>                        {&quot;name&quot;: &#39;Qty&#39;, &quot;id&quot;: &#39;ot_status&#39;, &#39;type&#39;: &quot;text&quot;},<br>                        {&quot;name&quot;: &#39;Mkt Value&#39;, &quot;id&quot;: &#39;pt_value&#39;, &#39;type&#39;: &quot;text&quot;},<br>                        {&quot;name&quot;: &#39;Status&#39;, &quot;id&quot;: &#39;pt_status&#39;, &#39;type&#39;: &quot;text&quot;},<br>                        {&quot;name&quot;: &#39;Date&#39;, &quot;id&quot;: &#39;pt_date&#39;, &#39;type&#39;: &quot;text&quot;},<br>                    ],<br>                    style_cell={<br>                            &#39;textAlign&#39;: &#39;left&#39;,<br>                            &#39;height&#39;: &#39;auto&#39;,<br>                            # all three widths are needed<br>                            &#39;minWidth&#39;: &#39;100px&#39;, &#39;width&#39;: &#39;100px&#39;, &#39;maxWidth&#39;: &#39;100px&#39;,<br>                            &#39;whiteSpace&#39;: &#39;normal&#39;<br>                        },<br>                    style_as_list_view=True,<br>                    style_header={&#39;borderTop&#39;: &#39;0px&#39;, &#39;font-weight&#39;: &#39;600&#39;},<br>                    style_data={&#39;border&#39;: &#39;0px&#39;},<br>                    style_table={&#39;height&#39;: &#39;25vh&#39;, &#39;overflow-y&#39;: &#39;auto&#39;}<br>                )<br>            ]<br>        )<br>    ]<br>)</pre><h4>A Time to Celebrate</h4><p>Finally, here’s how our layout will look on a mobile screen. As King Arthur commanded, it will adjust to screen size. When ready, you can hide the Dash Debugger (blue circle at the bottom) by removing “debug=True” from the last line; meanwhile, it will prove very helpful when we start adding interactivity in our next chapter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/664/1*3xwIvxKqhZnrMtDowRHzwA.png" /></figure><h3>A Summary of our Adventure:</h3><ul><li>In this chapter, we developed the user interface for a basic trading webpage using Plotly Dash.</li><li>In <a href="https://medium.com/@stevenwmayo/tradenosis-my-quest-to-build-a-mythical-stock-trading-platform-e2c62f10e67b"><strong>Chapter 2</strong></a>, we will create an Alpaca Settings dialog and write code to load candlestick price data into a stock chart.</li><li>In <a href="https://medium.com/@stevenwmayo/tradenosis-my-quest-to-build-a-mythical-stock-trading-platform-c1bf56372d7c"><strong>Chapter 3</strong></a>, we will review Alpaca’s trading rules.</li><li>In <a href="https://medium.com/@stevenwmayo/tradenosis-my-quest-to-build-a-mythical-stock-trading-platform-31d452683b6"><strong>Chapter 4</strong></a>, we will create the order form and associated code to compile trade instructions.</li><li>In <a href="https://medium.com/@stevenwmayo/tradenosis-my-quest-to-build-a-mythical-stock-trading-platform-65a46823c606"><strong>Chapter 5</strong></a>, we will write the callback needed to submit an order to Alpaca.</li><li>In <a href="https://medium.com/@stevenwmayo/tradenosis-my-quest-to-build-a-mythical-stock-trading-platform-1771245c54a2"><strong>Chapter 6</strong></a>, we will compile data for the Orders and Positions tabs.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=90924cd09f3f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>