Understanding the lemon.markets Market Data API
Hey there. My name is Marius, and I’m the community developer at lemon.markets, an early-stage startup from the heart of Berlin, Germany. We are working on building an infrastructure that enables developers to build their own brokerage experience at the stock market. In this blog post, I want to take a closer look at one of our core products: the Market Data API. Together, we will explore how the API is structured, what kind of data you can retrieve with it and how that might be helpful for your very own trading product.
What’s the point of getting Market Data?
If you ever were in the position of wanting to develop your own trading strategy (since you managed to click on this blog post and read until this sentence, we assume that the probability of this is rather high), you most certainly thought about using (historical) market data for it. While there are some examples where quantifiable market data plays a subordinate role (sentiment analysis of text data being the most prominent example), a large majority of (automated) trading strategies indeed work with historic or real-time stock prices to make a buy or sell decision. Check out one of our previous articles for an overview of popular, beginner-friendly trading strategies. You will notice that there are many ways to integrate market data into your trading strategy, which is why we do not want to dive too deep into what the best way to do so actually is.
However, we want to outline why we at lemon.markets think that Market Data is important. The answer lies (at least partly) in our name. The goal of lemon.markets was always to improve the experience of buying equities at the stock market. While we have a clear developer focus right now, the underlying principle goes much deeper. We want to avoid that people make uninformed investment decisions. How do you avoid that? We think by using data.
“Without data you’re just another person with an opinion”
This quote by the famous statistician W. Edwards Deming perfectly captures how we think about lemon.markets and making investment decisions in general. If you have access to extensive data, chances are high that you will make better decisions. Obviously, historical patterns do not necessarily imply future patterns, but they are definitely a good place to start. In the case of buying equities at the stock market, this data is market data. And that is how we can bridge the gap to the famous Market for Lemons Theory, which deals with information asymmetry between buyer and seller along the example of used cars (in American slang, used cars that turn out to be broken after purchasing them, are referred to as “lemons”). By giving the buyer (our customers who want to buy or sell equities) structured and extensive information and the freedom/flexibility to build their brokerage product based on this, we believe that we can close the information asymmetry gap at the stock market (at least to some extent). By looking at our users’ behaviour, we noticed that the market data endpoints are among the most frequently used ones, which pretty much proved our point that access to market data is an important use case and thus product for us at lemon.markets.
Market Data API Structure
Realising that market data is important is one thing. Translating that realisation into an API structure is another. Below, find the structure that we came up with.
The base URL of our Market Data API is:
1https://data.lemon.markets/v1/
Using that base URL, we implemented five different endpoints that fulfil different purposes. We will discuss those in a second. However, the principle behind each endpoint structure is the same. For example, if you want to retrieve instruments, you would use the/instruments/endpoint.To specify your request, you can use different query parameters (e.g. ?search to search for ISIN, WKN or Title, or ?type to search for stocks, bonds, ETFs, warrants or funds. Find out more about the respective endpoint query parameters and the Market Data API in general in our docs).
Using the Endpoints
Actually trying out the different endpoints is probably the best way to understand the API structure. herefore, let’s dive right into some code examples. In general, all of them make use of the lemon.markets Python SDK, which makes communicating with the API that much easier. You can install the SDK 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 lemon.markets API. You can create your Trading and Market Data API Keys in theDashboard.
Trading Venues
Now, let’s get specific and make our first request against the Market Data API. In our example, we want to retrieve all trading venues offered by lemon.markets:
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 we wanted to retrieve a specific venue, we could add mic={mic} after .get in line 17.
Feel free to play around with it a little bit and see how the API reacts to your modified request URLs. Check out our documentation for specific information on the /venues/ endpoint.
Instruments
Our Market Data also offers the possibility to search for/filter for different instruments. Following a similar concept as above, we define the endpoint that is added to the base URL.
1response = client.market_data.instruments.get(
2 search='tesla',
3 tradable=True,
4)
Again, check out our docs to find a full list of query parameters for the/instruments/endpoint.
Quotes
Using the /quotes/ endpoint, you can access (well): Quotes. Using quotes can be helpful for your trading strategy, as you get information about the price and trading volume of a specific instrument (how it is “quoted” on the stock exchange). As quotes are always returned for a specific ISIN, that query parameter is mandatory, leading to the following “minimal” request URL with the ISIN for Coinbase:
1# get latest quotes
2response = client.market_data.quotes.get_latest(
3 isin='US19260Q1076',
4)
You could also add additional query parameters, such as ?decimals, which is a Boolean value with which you can decide between returning the numbers in the API response either as Decimal or Integer. In a similar fashion, you could also set the date in your preferred format (?epoch=true for UNIX Timestamp or ?epoch=false for the ISO Date). Again, check out our docs for a full list of query parameters for the /quotes/ endpoint.
OHLC Data
Using the /ohlc/ endpoint, you can retrieve the typical candlestick data (Open High Low Close) for specific instruments. Here, you need to additionally add {x1} to the URL, which specifies what type of OHLC data you want to retrieve (m1 for data on a per-minute basis, h1 for data on a per-hour basis, d1 for data on a per-day basis). Similar as with the /quotes/ endpoint, the ?isin query parameter is also mandatory here. By the way, you can also request data for multiple instruments by adding a second ISIN to the query parameters, either divided by a comma or by adding a second isin={ISIN}.
1# get ohlc
2response = client.market_data.ohlc.get(
3 isin=['US88160R1014'],
4 period='d1',
5 from_=datetime(2022, 1, 2)
6)
Check out the docs for more information on the OHLC endpoint.
Trades
Finally, you also have the option to retrieve trades for a specific instrument using the /trades/ endpoint. Same as with the /quotes/ and /ohlc/ endpoint, setting an ISIN as query parameter is mandatory, as the API returns previous trades for a specific instrument. Take a look at this basic request example.
1# get trades
2response = client.market_data.trades.get_latest(
3 isin=['US88160R1014', 'US0231351067'],
4)
To specify your request, e.g. to get the trades for multiple instruments in a numbers and date format of your choice, check out the docs for more information on the /trades/ endpoint query parameters.
Possible Extensions
We tried to give you a condensed overview of our Market Data API. However, when talking market data, you almost naturally think about real-time data. We did not simply forget this feature, but we need some time until we can offer it to you. Right now, a clear priority for us is to build stable and scalable services, which is why we are tackling different projects one by one to “do things right”. We will of course immediately inform you when we have a stable real-time market data service. To stay up to date: sign up for lemon.markets now and join our Slack Community.
While we provide you with “raw” market data through our API, there are a lot of possibilities to use the data to calculate different key performance indicators that might help you in making an investment decision. Check out one of our previous articles that discusses 10 resources to get you started in automated trading.
And if you are still missing something: let us know. We believe that lemon.markets will never be “finished” and we are trying to integrate user feedback/suggestions whenever possible.
Takeaways
We hope you got a good understanding of our Market Data API. Let us sum up our main takeaways:
- The Market Data API is a separate product within the lemon.markets universe
- It consists of 5 different main endpoints:
- /venues/
- /instruments/
- /quotes/
- /ohlc/{x1}
- /trades/
- You can specify your request for each endpoint by using Query Parameters
We are really excited to see all of your trading projects in action soon. We hope that the Market Data API will help you make better investment decisions. If you are in desperate need of inspiration for a project: check out our other blog articles where we present different use cases and ideas. If you are interested in getting featured on our blog with your own project, just send us an email to support@lemon.markets and we will get back to you 🙂.
Looking forward to seeing you on lemon.markets soon.
Marius🍋
You might also be interested in
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.
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! 💻 📈
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.
Find more resources to get started easily
Check out our documentation to find out more about our API structure, different endpoints and specific use cases.
Interested in building lemon.markets with us?
We are always looking for great additions to our team that help us build a brokerage infrastructure for the 21st century.