Trading Venues at lemon.markets — the what, why and how


15. Juli 2021
Product


Hi! My name is Joanne, and I am a recent addition to the (steadily growing) lemon.markets team. We are building an API that allows developers to create their own brokerage experience at the stock market. I would like to introduce you to some of the functionalities of our API. This week’s topic: Trading Venues. Think of a trading venue as a stock exchange or other type of exchange where instruments are traded, for example, theLondon Stock Exchange (LSE).

At lemon.markets, we created a number of endpoints concerned with addressing specific trading venues. In this blog post, I will walk you through these endpoints and explain why you might want to use them. I will also show you how they can be used to set up automated emails that notify you when the market is closed.

Title Card for the Article "Trading Venues at lemon.markets"

Trading Venues is a new feature we decided to incorporate into our restructured API because we think it adds a powerful functionality. On our path to create a transparent 21st century broker, we think it is important that our users know (and have the option to decide) which trading venue they are placing their orders at. But before we discuss trading venues in a specific lemon.markets context, let us first dive into a bit of background information here:

At the time of writing this blog post (July 2021), there are 21 major stock exchanges in the world that have a market capitalisation of over $1 trillion US dollars, you might have heard of them referred to as the “$1 Trillion Club”. And there are also plenty of stock exchanges that have a smaller reach; have you heard of the Maldives Stock Exchange (MSE) that has just 10 listings? As you can see, the options (get it? 😉) for trading are endless.

Depending on what you are trying to do/build, it can be helpful to know the ins and outs of the stock exchange you are operating on to ensure that your trades go according to plan. By talking to our users, we noticed that there may be different needs and preferences regarding different trading venues, so we wanted to lay a flexible foundation for our API that allows us to integrate additional trading venues in the future.

A small Trading Venue Repository

We built a small project to demonstrate a number of use cases regarding trading venues. You can find the GitHub repository here 👩🏿‍💻👨‍💻👩🏼‍💻🧑🏿‍💻.

Setting the Foundation

Initially, we need to define a number of environment variables that we can use throughout our script:

  • DATA_API_KEY = “Your lemon.markets Market Data API key”
  • TRADING_API_KEY = “Your lemon.markets Market Data API key”
  • MIC = “Market Identifier Code of Trading Venue”

In general, lemon.markets offers different types of API Keys: market data API Keys to retrieve historical and real-time market data, as well as paper trading and live trading API Keys to do (well) paper and live trading. You can create those keys in your Dashboard.

Determining the Trading Venue

When all base work is done, we can move on and start to actually deal with Trading Venues.

Imagine you want to buy a few shares of your favourite stock, but are unsure about where to begin? We think a good first step is to determine through which Trading Venue you would like to place your order. There are a few reasons why you might choose one venue over another, for example, a larger offering, lower transaction costs or more desirable opening hours. To see which Trading Venues lemon.markets has incorporated, you can use the following request URL, which returns a list of all the venues we offer:

1https://data.lemon.markets/v1/venues/

The easiest way to make a request to that endpoint is to use thelemon.markets Python SDK. You can easily install the SDK via:

1pip install lemon

Afterwards, you can use the following code to retrieve a list of trading venues:

1import os
2from lemon import api
3from dotenv import load_dotenv
4class TradingVenues():
5    def __init__(self):
6        load_dotenv()
7        self.client = api.create(
8            market_data_api_token=os.getenv("DATA_API_KEY"),
9            trading_api_token=os.getenv("TRADING_API_KEY"),
10            env="paper"
11        )
12    def get_all_trading_venues(self):
13        response = self.client.market_data.venues.get()
14        print(response)
15if __name__ == "__main__":
16    TradingVenues().get_all_trading_venues()

If you use this endpoint and take a closer look at the request response, you will notice that we currently only support one trading venue: XMUN. However, keep your eyes peeled for additional trading venues. However, we built the API structure to potentially integrate additional stock exchanges in the future, which means even more stocks, bonds, funds, ETFs and warrants from which to choose. Obviously, our users will be the first to know when we integrate additional trading venues.

Besides getting an overview of all available trading venues, you can also retrieve a single trading venue by specifying the query parameter MIC:

1https://data.lemon.markets/v1/venues/?mic={mic}

Again, we are using the Python SDK to showcase a specific code snippet. Notice the “{mic}” parameter? This is the place where you can specify the trading venue you are interested in. It stands for“Market Identifier Code”.In our script, this is solved by setting an environment variable, which we then use inside the request URL, but you can obviously also set it manually if you are building a different kind of use case.

1import os
2from dotenv import load_dotenv
3from lemon import api
4class SingleTradingVenue():
5    def __init__(self):
6        load_dotenv()
7        self.client = api.create(
8            market_data_api_token=os.getenv("DATA_API_KEY"),
9            trading_api_token=os.getenv("TRADING_API_KEY"),
10            env="paper"
11    )
12    def get_single_trading_venue(self):
13        load_dotenv()
14        mic = os.getenv("MIC")
15        response = self.client.market_data.venues.get(mic=mic)
16        print(response)
17if __name__ == "__main__":
18    SingleTradingVenue().get_single_trading_venue()

Using this endpoint will result in the following response.

1{"time": "2022-08-23T14:51:21.057+00:00",
2"results": [
3{
4"name": "Börse München - Gettex",
5"title": "Gettex",
6"mic": "XMUN",
7"is_open": true,
8"opening_hours": 
9{"start": "08:00",
10"end": "22:00",
11"timezone": "Europe/Berlin"
12},
13"opening_days": 
14[
15"2022-08-23",
16"2022-08-24",
17...
18]
19}
20],
21"previous": null,
22"next": null,
23"total": 1,
24"page": 1,
25"pages": 1
26}

As you can see, besides general information about the trading venue, the endpoint also returns whether the trading venue is currently open, which in our opinion is a valuable piece of information that you can very easily integrate into your trading strategy. Additionally, one of the most requested features for our prototype that we launched in autumn last year was the possibility to check trading venue opening times. We took this feedback to heart and integrated just that.

With the response, you get the current and all future days and you can use that information to adapt your strategy so that it only places orders when the trading venue is actually open. This avoids a scenario where you place an order, only to realise it is a Saturday and the order will not be filled for another two days. Or to place a market order after close, only to have it filled at an undesirable opening price the next morning.

GIF about stating "That is a bummer"

But it does not have to be! By incorporating the opening times of your chosen market, you can configure your strategy such that, for example, unfilled orders expire after market close, no new orders are placed during the most volatile times of the trading day or you are notified when the market opens and closes.

Instruments

Each Trading Venue has a list of instruments that are tradable there, and you can conveniently find out which ones those are using the following endpoint:

1https://data.lemon.markets/v1/instruments/?mic={mic}&search=SEARCHTERM

In the code snippet below, we are creating a function that allows us to search for a specific search term (e.g. “Tesla”) and instrument type (e.g. “stock”), but you can also use other query parameters, such as the currency or whether it is currently tradable. Also, you can search for ISIN or WKN if you like those better. The more narrow you define your query parameters, the more specific your results will be.

1import os
2from dotenv import load_dotenv
3from lemon import api
4class TradingVenueInstrument():
5    def __init__(self):
6        load_dotenv()
7        self.client = api.create(
8            market_data_api_token=os.getenv("DATA_API_KEY"),
9            trading_api_token=os.getenv("TRADING_API_KEY"),
10            env="paper"
11    )
12    def get_trading_venue_instruments(self, search, type):
13        load_dotenv()

A little Use Case

We at lemon.markets aim to provide you with content that easily lets you start building things and hopefully inspires you to some extent. In our GitHub repo, we created a little Python script that checks whether the trading venue is currently open. If it is, your order is placed. If it is not, you get an automatic email telling you about it. Additionally, the script sends you an automated email at market close that tells you about your positions.

As mentioned above, we use Sendgrid to send emails and we highly recommend you do so as well, as it integrates with your python script perfectly.

Check out the repository to see the functionality for yourself.

Obviously, this little script is only a point of departure for you that shows you how to specifically use our trading venue endpoints to bring more flexibility and stability to your automated trading strategy. If you are interested, take a look at our public GitHub repository that accompanies this blog post and open a pull request. How about we send another email when the market reopens? How about we wait a little bit until we activate the order to get the best possible price? How about we place the order the next morning 2 hours after the trading venue opens. Feel free to play around with it and go crazy 😵. We are super excited to see your ideas.

Obviously, this little script is only a point of departure for you that shows you how to specifically use our trading venue endpoints to bring more flexibility and stability to your automated trading strategy. If you are interested, take a look at our public GitHub repository that accompanies this blog post and open a pull request. How about we send another email when the market reopens? How about we wait a little bit until we activate the order to get the best possible price? How about we place the order the next morning 2 hours after the trading venue opens. Feel free to play around with it and go crazy 😵. We are super excited to see your ideas.

What else to do with the Trading Venue endpoints?

While we covered a basic use case above, there are a lot of other interesting ideas for our trading venue endpoints.

Perhaps consider connecting your program to your calendar to automatically mark the days on which the market is closed. We suggest calling upon the GET /venues/?mic={mic} endpoint and accessing the opening-days element to obtain all the opening days of a given trading venue. For any day not included in the list, you can assume that the market is closed. You may also want to filter out weekends because we know that the market is closed then. These days can be fed into, for example, the Google Calendar API. Then, using the calendars() and events() resources both a new calendar and corresponding events can be created.

You can also configure your program to send an automated email outlining how your position has performed once the market closes. This can be achieved by requesting the same endpoint as above,GET/venues/?mic={mic}, and when “end” in opening hours matches the current time, to trigger an e-mail notification using the same email resource as in the use case we shared above. In the e-mail, you might want to simply report the overall growth of your position, by comparing the value of your position at market close to that of the day before (try using theGET /positions/endpoint). You might even want to get fancy by measuring performance using a (Python) library such as f.fn(). If you’re not a big fan of receiving emails: how about automatically updating your own trading dashboard at the end of each day with your positions value at the market close? We hate to repeat ourselves, but the possibilities are (almost) endless.

Do you have additional ideas? We would love to hear (and obviously see) what kinds of interesting applications for the Trading Venue endpoints you come up with.

To start building, make sure you sign up to lemon.markets to test out this API concept out in real life. Feel free to reach out to us by leaving a comment, emailing us at support@lemon.markets or joining our growing Slack community.

See you on lemon.markets 🍋

Joanne

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 lemon.markets 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.

Austauschen

Tritt der lemon.markets 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 lemon.markets 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
© lemon.markets 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 lemon.markets GmbH, die Anlagevermittlung (§ 2 Abs. 2 Nr. 3 WpIG) von Finanzinstrumenten im Sinne des § 3 Abs. 5 WpIG sowie die Vermittlung von Konten an.