Using the API to DIY your ETF savings-plan using cost averaging

20. Oktober 2021

Or, in other words, setting up a ‘lazy’ automation for your periodically scheduled trades. 

Hey! I’m Joanne and I’m part of 🍋 , a start-up that’s making the brokerage experience accessible to developers. We’re creating an API that allows you to participate in and interact with the stock market, for example by implementing an automated trading strategy or creating a dashboard that visualises your portfolio.

In this article, I’ll walk you through a simple dollar-cost averaging strategy with which you can automate your savings plan. Nothing fancy — just making your life easier 😉. And, to top it off, I’ll also show you how to set up a Telegram bot that notifies you whenever a trade is placed. Even if you’re unsure of what to build with the API, this article is bound to get your creative juices flowing. You can begin by signing up to, here

What is ‘dollar-cost averaging’?

If you’re already investing by placing, for example, 10% of your monthly salary into an ETF or mutual fund, you’re dollar-cost averaging (maybe we should call it euro-cost averaging). Many ETF savings plans follow a similar set-up. So, what does this strategy actually entail? Imagine you have a large sum of money, say €10.000, that you want to invest. If you’re dollar-cost averaging (DCA from now on), you’d choose to spread out your buy-ins, perhaps by investing €1.000 monthly for a period of 10 months. The opposite of DCA is lump-sum investing, which would entail investing the entirety of the sum at one point in time. 

Why choose one over the other? Many investors choose DCA over lump-sum investing because it mitigates risk. You can expect the price of your chosen instrument to increase and decrease over these 10 months, but by consistently investing, you are ‘averaging out’ your cost basis (i.e. the average purchase price). Ideally, you’d just want to buy during downturns, but word has it, you can’t predict the market. 🤷‍♀ So, why would you ever do anything but DCA? The benefit of lump-sum investing is that your money begins to work for you right away. On the other hand, you run the danger of poorly timing the market, resulting in a too high buy-in price.

And why not use a platform that offers a pre-made savings plan? Simple: customisation and transparency. With a pre-made savings plan, you lack the flexibility to indicate trade execution date and time — and, very often, these happen at unfavourable times, which can cost you. Designing your savings strategy with the API means you have full control. You can avoid common buy-in dates, such as the beginning and end of the month. This way, you’ll have a price advantage over the others DCA-ing. You can choose what to trade, when your trades are executed, on which exchange to trade, how often to trade and for how long to trade. Also, you’re not limited to just ETFs — maybe you want to DCA Pinterest shares. It’s up to you.

Automating the DCA strategy 💵

Sure, you could sign into your brokerage account and manually place a trade weekly. But, you can also automate this process. I don’t know about you, but the latter sounds like much more fun (and future-you will probably thank you). Let’s jump right into the coding bit.

I’ve decided to use Python for this application, but feel free to use your preferred language — the logic remains the same. 

Setting the Scene

For effective use of the API, I will be using the Python SDK, which can very easily be installed through:

1pip install lemon

The initial step for using the SDK (and subsequently making requests to the API) is to instantiate a client, like this:

1def __init__(self):
2        self.client = api.create(
3            market_data_api_token=os.getenv("DATA_API_KEY"),
4            trading_api_token=os.getenv("TRADING_API_KEY"),
5            env="paper"
6    )

Note that in line 3 and 4 we are accessing environment variables, which you need to create and define before that step, typically in a .env file. Here, we are using separate API Keys for market data and trading, as required by the API. You can create your Trading and Market Data API Keys in the Dashboard.

Putting it all together

After defining our helper functions and API objects and setting up our Telegram bot, it’s time to put all the pieces together.

As a first step, we define the buy_order() function, which places and activates a buy order for one share, specified by its ISIN. Our API is structured such that an order is first placed (status: inactive), then it must be activated (status: activated) and lastly it is executed (status: executed). The function continuously checks the status of the order, and when it is finally executed we use telegram-send to send a summary message about the trade.

To schedule the trades, we’re using the Advanced Python Scheduler library. We call the buy_order() function every weekday at 10.30 CET.

1from apscheduler.schedulers.blocking import BlockingScheduler
2from apscheduler.triggers.cron import CronTrigger
3from lemon import api
4from dotenv import load_dotenv
5from pytz import utc
6import os
7import telegram_send
9# create your api client with separate trading and market data api tokens
10client = api.create(
11    trading_api_token=os.environ.get('TRADING_API_KEY'),
12    market_data_api_token=os.environ.get('DATA_API_KEY'),
13    env='paper'
15def buy_order():
16    """
17    This method places and activates a buy order for 1 unit of the specified instrument every week.
18    :param isin: isin of the instrument you want to buy
19    """
20    try:
21        placed_order =
22            isin="LU0274208692",
23            expires_at=0,
24            side="buy",
25            quantity=1,
26        )
27        order_id =
28        activated_order =
29        print(activated_order)
30        while True:
31            order_summary =
32            if order_summary.results.status == 'executed':
33                print('executed')
34                break
35        executed_price = order_summary.results.executed_price
36        executed_quantity = order_summary.results.quantity
37        telegram_send.send(messages=[f'Your automated trading strategy just purchased {executed_quantity} share(s) '
38                                     f'at €{executed_price/10000:,.2f} per share.'])
39    except Exception as e:
40        print(e)
41if __name__ == '__main__':
42    scheduler = BlockingScheduler(timezone=utc)
43    scheduler.add_job(buy_order,
44                      trigger=CronTrigger(day_of_week="mon-fri",
45                                          hour=10,
46                                          minute=30,
47                                          timezone=utc),
48                      name="Perform DCA")
49    print('Press Ctrl+{0} to exit'.format('Break' if == 'nt' else 'C'))
50    try:
51        scheduler.start()
52    except (KeyboardInterrupt, SystemExit):
53        pass

In the above code-snippet, I’ve decided to use an ETF that tracks worldwide developed equities. This way, we are further mitigating our risk. But, of course, this strategy can also be applied to individual stocks or different ETFs.

You might have noticed the line with the telegram_send(), wonder what that is all about? We still need to set up a Telegram bot to make sure the above code works. Let’s do that now.

Setting up a Telegram Bot 🤖

If you’re unfamiliar with Telegram, it’s a messaging software that supports bots. We’re going to use the Telegram API to configure a bot that automatically delivers a summary message to your smartphone once a trade has been executed.

The following section will show you how to set up Telegram notifications just like this one.

To begin, you need to register your new bot by sending /newbot to BotFather, further explanation can be found here. This yields a token, much like the token you are familiar with from the API.

To simplify the process, I’ll be using the telegram-send command-line tool, which can be installed from your terminal using pip as follows:

1$ pip install telegram-send
2$ telegram-send --configure

Your terminal will prompt you to insert your token, which connects your script to your bot. Then, after sending the given password to your new bot, you’ve successfully set up telegram-send. If this isn’t clear, full instructions can be found here.

We can then send messages using the following command:

1import telegram_send

In the following section, I will show you how to bring your Telegram bot to life (not literally).

Note: many aspects of this script can be adjusted, such as the amount, frequency and type of instruments being traded. We suggest using it as a starting point and adding your own functionalities. The above code can be found in this GitHub repo.

Possible Extensions

Ideally, you want to set up your script and forget about it — in order for this to work, it needs to be constantly running, even when your computer is powered off. For this, we suggest hosting your script in the cloud, using a platform such as Heroku, which you can conveniently connect to GitHub. We’ve covered how to use Heroku in this article, but you can also follow this or this step-by-step guide.

You’ll notice that in the case a trade is placed when the Trading Venue is closed, the trade will be placed at the next available moment: when the market reopens. However, you might want to avoid placing trades at market open as there’s usually more volatility at the beginning of a trading day. Perhaps you’d like to adjust the script such that trades are never placed before 15.30, to keep in mind NSYE/NASDAQ opening times.

You can even depart from the DCA strategy slightly — for example, by incorporating daily market data. If the price of your instrument decreases by, say, 10%, you could program your Telegram bot to notify you. Then, by interacting with the bot, you can either choose to buy additional shares, or place your trade earlier than planned. For Telegram functionality beyond simply sending messages, I suggest looking into the python-telegram-bot wrapper. Maybe you also want to add a function that notifies you if more money needs to be added to your Space.

In addition it’s worth noting that, to make the script more robust, we suggest stepping away from the time.sleep() function in Python. Why? When the script is sleeping runtime is fully blocked and you cannot wake it 💤. Instead, we suggest setting up a task queue that can be used to schedule periodic events, such as placing an order. We suggest Celery, and looking into this article to get yourself familiarised.

By setting up your own automated dollar-cost averaging strategy, you are affording yourself more flexibility than when you sign up for a standard savings plan. For example, you could set the execution time to be more flexible. You can make sure the ETF is bought at the best time during the day and not when it is most convenient for the bank. In addition, you can include multiple instruments in one savings plan, removing the need to create a separate one for each ETF, as many saving plans require you to do. The possibilities are endless, so, how would you customise this strategy?

I hope this article gave you some inspiration to get started using the API. If you haven’t signed up to yet, you can do so here. If you’d like to talk to us: leave a comment, email us or join our Slack community. We’d love to see you there!

Your lemoneer 🍋,


Das könnte Dich auch interessieren

blog photo

Using Time Series Forecasting to predict stock prices 🔮

In this article you will learn what time series forecasting is and how its application in finance looks like. Then you'll also dive into Facebook's Prophet Model for Time Series Forecasting and use it together with the Market Data API to forecast the development of the Tesla Stock.

blog photo

Dummies Guide to Trading with Machine Learning

Ever wonder how a trader with decades of experience on thousands of stocks and lightning fast reaction times might perform in the market? With some machine learning knowledge, you might be able to automate such a trader yourself! 💻 📈

blog photo

4 reasons why YOU should automate your trading strategy

In the current volatile market conditions, everyone is trying to find ways to minimise portfolio loss. In that context, have you ever thought about automating your trading strategy? In this article, we will dive into 4 reasons for doing so. Expect to learn how it can save you time, make your trading more efficient and lead to data-based decisions.

Tiefer eintauchen

Finde weitere Ressourcen für einen einfachen Einstieg

In unserer Dokumentation erfahrt Ihr mehr über unsere API-Struktur, die verschiedenen Endpunkte und spezifische Anwendungsfälle.


Tritt der Community bei

Tritt unserem Slack-Channel bei, um Dich aktiv an unserer Community zu beteiligen, Fragen an andere Nutzer:innen zu stellen und immer auf dem Laufenden zu bleiben.

Team unterstützen

Lust mit uns zu bauen?

Wir sind immer auf der Suche nach großartigen Ergänzungen für unser Team, die uns beim Aufbau einer Brokerage Infrastruktur für das 21. Jahrhundert helfen.

Brauchst Du Hilfe?
Stell Deine Fragen in unserer CommunityStell Deine Fragen in unserer CommunityLeg mit unserer API Dokumentation losLeg mit unserer API Dokumentation losLass Dich von unserem Blog inspirierenLass Dich von unserem Blog inspirieren
© 2022DatenschutzImpressum
Systems are down

Als vertraglich gebundener Vermittler gemäß § 3 Abs. 2 WpIG für Rechnung und unter der Haftung der DonauCapital Wertpapier GmbH, Passauer Str. 5, 94161 Ruderting (kurz: DonauCapital), bietet Dir die GmbH, die Anlagevermittlung (§ 2 Abs. 2 Nr. 3 WpIG) von Finanzinstrumenten im Sinne des § 3 Abs. 5 WpIG sowie die Vermittlung von Konten an.