Order Types at lemon.markets explained


blog photo
Joanne SnelJuly 21, 2021
Product


Hey! My name is Joanne and I’m part of the lemon.markets team. We’re working on a brokerage API that allows developers to bring their trading ideas to life. To increase your trading literacy, it is important to be able to differentiate between order types and know their advantages and disadvantages. In this article, I’ll show you how our API identifies order types, when each should be used, what the Pros and Cons are and outline a use case that shows different order types in action. Additionally, I’ll provide you with additional resources that help you develop more in-depth expertise. Have fun and happy reading 🤓.

order types and lemon markets api

When you start building your trading strategy or application using the lemon.markets API, you’ll notice that we currently offer four different order types:

  • Market order
  • Stop market order
  • Limit order
  • Stop limit order

But when to use which? We think that the best way to learn is by doing, so let’s get started with the orders endpoint right away.

Preparing Everything

Before we can get started using the API, we need to take care of a few things first. The easiest way to work with the lemon.markets API is by making use of thelemon.markets Python SDK. The first step for using the SDK 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 accessingenvironment 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.

Submitting Orders

Next, we can use the instantiated client to actually use the API. Let’s do that as part of a rather obvious use case: placing an order at the stock exchange.

To submit an order with lemon.markets, you can use the following request URL:

1https://paper-trading.lemon.markets/v1/orders

Let’s get serious

Can you identify what kind of order we submit in the following code snippet? (Hint: note the input parameters in the brackets)

1# create buy order
2response = client.trading.orders.create(
3    isin='US88160R1014',
4    side='buy',
5    quantity=1,
6)

If you want to run this code, you’ll have to replace the placeholders (YOUR-SPACE-ID and YOUR-API-KEY).

As you can see, there is no mention of the order type. So, have we tricked you? 😛 Not quite (and besides, we would obviously never do that #transparency).

One of the nifty features of our API is that you do not need to specify an order type. Instead, based on the query parameters, we can recognise the type of order automatically. As there are no order type query parameters in this code snippet, we assume you want to place a market order, the most basic order type we offer.

Types of Orders

Now that you’ve seen the market order in action, let’s discuss the what and when.

Market Order

A market order is a buy or sell order to be executed immediately at the current market price. If you place and activate a market order using the lemon.markets API, you instruct us to perform your trade at the best available price at that moment. You can be sure that the order will be placed, but you are not guaranteed a particular execution price. This means that, if the price moves quickly, you might end up trading an instrument at a vastly different price than when you entered the order.

You should use a market order when you want your order to be executed quickly and are not primarily concerned with getting a specific price. Or, alternatively when you are trading a highly liquid instrument with a narrow ask-bid spread. In the latter scenario, your trade will likely execute at an expected price.

Now, imagine we replace order_details with:

1# create buy order
2response = client.trading.orders.create(
3    isin='US88160R1014',
4    side='buy',
5    quantity=1,
6    stop_price=2750000 # stop price at €275
7)

What kind of order do you think we place here? Note that, at the time of writing, Microsoft was trading at around €277.00.

We fear this one might be a little too self-explanatory (ah, the struggle of having clear code 😅). If you didn’t get it, this triggers a stop market order, sometimes also simply called a stop order. On lemon.markets, all currencies must be specified as hundredths of a cent (i.e. add an extra four zeroes after €275).

Stop Market Order

A stop market order lets you set a stop price at which your order is triggered. You can use it to, for example, protect yourself from losses if the market moves too far in the wrong direction. To place a stop market order, you must define a trigger price (stop_pricein the code snippet above) at which you want the buy or sell to take place. A sell stop market order is placed below the current market price to prevent too much loss on a sale, whereas a buy market order is placed above the current market level to buy a stock before the price increases too much.

If the market price reaches the trigger price, the stop market order is executed as a market order. This means that your trade might not happen exactly at the trigger price. If the price moves quickly, it might continue to move between the moment the trigger price is hit and your order is executed. If the instrument does not attain the trigger price within the given time frame, the order expires and no trade takes place.

Limit Order

A limit order allows you to name your price, and, if the instrument reaches the specified price, it will (most likely) be filled. Why most likely? If the instrument you are trading is illiquid and you are trading a relatively large amount, then there might not be enough volume to fill your order. Or, if the instrument does not reach the specified price within the specified time frame (in our case, within 7 days), then the order will expire and no trade will take place.

How does our API recognise a limit order? We specify a new query parameter, limit_price in order_details:

1# create buy order
2response = client.trading.orders.create(
3    isin='US88160R1014',
4    side='sell',
5    quantity=1,
6    limit_price=2850000 # limit price at €285
7)

In the code snippet, we place a sell limit order for Microsoft at a limit price of €285.00.

Simpsons GIF "Name your price"

Stop Limit Order

With a stop limit order, you have even more control over when (and at what price) your order will be executed. To place this order type, the lemon.markets API requires both query parameters, stop_price and limit_price , which essentially serve as the interval within which you’d like to trade. We trust you that you can figure out the code for yourself 😉

The main drawback of using a stop limit order is that, just like with a limit order, you have no guarantee that the order will be executed, especially if you define a window as narrow as the one we have above.

In summary, we have four different types of orders: Market Order, Stop Market Order, Limit Order and Stop Limit Order. There is no ‘good’ or ‘bad’ order type, but one might be more appropriate than another in certain scenarios. By educating yourself on the different functionalities of each, you can prevent any unintended purchases (or sales, for that matter). The order types we offer are by no means the only ones available, see this article, but we feel like they serve as a good starting point and can fulfil most needs our users currently have.

As a quick recap:

  • A market order takes no additional query parameters and is immediately executed at the next best possible price.
  • A stop market order requires a stop price, and if it is hit, the order is converted into a market order.
  • A limit order requires a limit price, and if it is hit, the order is placed at the limit price.
  • A stop limit order requires both a stop and limit price, if the stop price is hit, the order is converted into a limit order.

What happens after you place an order?

An important concept of our API is the fact that after you place an order, it is not automatically executed. Instead, you still need to activate it. This step has a number of reasons concerned with ensuring more transparency and security for our users. For example, we want to transparently share the cost information of your order with you. One of the core principles of lemon.markets is to bring transparency into brokerage, so we want to clearly communicate what each order means for you from a cost perspective. Also, we want to provide one additional “layer” of security for you, so we want you to actively acknowledge the trade you are about to make. If you are curious about that step: feel free to leave us a comment or contact us directly via support@lemon.markets.

To activate the order, place a PUT request by using the following URL:

1https://paper-trading.lemon.markets/v1/orders/{order_id}/activate/

To complete this URL, you need to insert the order_id. “But where do I get the order_id from?”, you may ask yourself. Well, no problem there, you can simply access the request-response from your previous POST request. The response after you place an order will look something like this and you need to subsequently access the id from it and use it in your activation request URL.

Besides adding your Space UUID to the URL (which we talked about above), you specifically need to add the order UUID as well. “But where do I get the UUID from?”, you may ask yourself. Well, no problem there, you can simply access the request response from your previous POST request. The response after you place an order will look something like this and you need to subsequently access the “uuid” from it and use it in your activation request URL.

1{'result': {'created_at': '2021-11-15T20:21:46.488+00:00',
2            'estimated_price': 13300000,
3            'expires_at': '2021-11-22T22:59:00.000+00:00',
4            'id': 'ord_pyPTZbb55Hyz02QywWw5Ht1wSgYnSDWbMM',
5            'isin': 'US5949181045',
6            'limit_price': 2660000,
7            'notes': None,
8            'quantity': 5,
9            'regulatory_information': {...},
10            'side': 'buy',
11            'space_id': YOUR-SPACE-ID,
12            'status': 'inactive',
13            'stop_price': 2650000,
14            'venue': 'XMUN'},
15 'status': 'ok',
16 'time': '2021-11-15T20:21:46'}

Use this little code snippet to activate your order (obviously replace the placeholders with your correct values first):

1import requests
2requests.put("https://paper-trading.lemon.markets/v1/orders/{ord_pyPTZbb55Hyz02QywWw5Ht1wSgYnSDWbMM}/activate/",
3             headers={"Authorization": "Bearer YOUR-API-KEY"})

After you activated your order, you should be all set and the order should be executed, depending on what order type you specified.

Use Case

“What to do with that?”, you may now think. Well, we do not offer the above-mentioned order types by accident, but because we believe that they may potentially be a valuable addition to your automated trading strategy (or your brokerage product in general). So, let us go through a little scenario, in which some of the order types described above would make sense.

An exemplary Twitter bot

Let’s say you created a strategy that analyses the Twitter account of a well-known person. For fun, let us pretend that this person is the founder of multiple highly successful businesses and an overall eccentric billionaire with the tendency to tweet rather abstruse opinions at times. Far-fetched, I know.

So whenever that person tweets something about a specific company, this may trigger a signal for you to act upon that tweet immediately. For example, the tweet could look something like “Company XYZ will be the future of online grocery shopping!” (Yes yes, bold example but you get the point). Given the likelihood of that tweet having a major effect on the stock price of company XYZ, you would probably need to act fast → use an order type that guarantees you immediate execution, as you do not want to waste another second because prices for XYZ will most likely increase dramatically in a short amount of time. In this case, the market order comes in handy for you and it should probably be the one you use for the scenario described above.

However, a stock price that increases dramatically in a short amount of time also bears the risk of “balancing itself out”. A little while after the tweet and the rush on the XYZ stocks, people may realise that the company’s services are not that special after all and the price may fall again. So, to limit the risk of a potential loss, you could place an additional stop market sell order with the stop price slightly below your buy-in price after you placed your market order. If things should go south and the stock price would go below the stop price, e.g. because the XYZ founder is involved in a major scandal, the company has a critical data leak, or our beloved billionaire tweets “Nevermind. XYZ will not be the future of anything.”, you would have the option to conveniently limit your risk, as the stock is automatically sold when your specified threshold is crossed.

Finally, you might realise that XYZ truly is amazing and that you were a bit too pessimistic with your stock purchases. To increase your profit, you could create an additional stop limit buy order, which has the purpose of buying additional stocks once you realise that the stock price is rising even more than you previously anticipated (the stock prices crosses your defined stop_price). As soon as this threshold is passed, the order is converted into a limit order and executed if the current stock price is ≤ limit_price. This way, you could really participate in XYZs momentum and enjoy your profits with a cold drink (ordered on XYZ, perhaps? 😏).

I hope you got some good insights into potential use cases for different order types. In the upcoming weeks, we will provide more and more small example projects to get you started smoothly, so make sure to follow us on LinkedIn and check out our GitHub profile.

Additional Resources

While we tried to give you a condensed overview of all things related to order types available at lemon.markets and what their pros and cons might be, we are also fully aware that this may not be enough for you and that you might need additional information. So, we compiled a few additional resources that will let you dive deeper into the topic.

In general, Investopedia is a great place to get detailed information on all things related to investing. In an order type context, there are also specific articles on market orderslimit orders and stop orders.

There are also a few articles that outline differences between order types, e.g. this one, which discusses limit orders vs. stop orders or this one, which discusses market orders vs. limit orders.

Another important issue is the decision of where to place your stop and/or limit price? In the end, this depends entirely on your trading goals, but there are a few common strategies. In the above cases, we’ve continuously placed hard stops, but you might want to define a stop loss based on the average true range, or perhaps set up a trailing stop loss. This article is a good place to start when you’re not sure where to place your stop loss.

I hope you enjoyed this article. If you have any additional ideas or resources/use cases that we might have missed: feel free to comment your thoughts under this post, write us an email to support@lemon.markets or join our Slack community. And obviously: sign up to lemon.markets if you haven’t done so, yet.

See you on lemon.markets 🍋

Joanne

You might also be interested in

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.

Dive Deeper

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.

Contribute

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.

Need any help?
Get started with our DocumentationGet started with our DocumentationGet inspired on our BlogGet inspired on our Blog
© lemon.markets 2023Privacy PolicyImprint
Systems are down

As a tied agent under § 3 Sec. 2 WplG on the account and under the liability of DonauCapital Wertpapier GmbH, Passauer Str. 5, 94161 Ruderting (short: DonauCapital), lemon.markets GmbH offers you the receipt and transmission of orders for clients (§ 2 Sec. 2 Nr. 3 WpIG) of financial instruments according to § 2 Sec. 5 WpIG as well as brokerage of accounts.