# Market Making in Stellar 101: Fundamentals & Kelp

Brief introduction to Market Making in Stellar. Main concepts in security markets and market making. The importance of fostering this activity in Stellar and introduction to Kelp.

# Market Making in General

A market maker is a participant who provides both, bids and ask quotes in a security market.
Its objective is to provide a smoother flow and a better experience to the rest of the market participants by guaranteeing the possibility of a trade execution.

If the previous paragraph seems too daunting or difficult to understand because of all the jargon, do not worry. I'll be dissecting its different pieces to make it simpler.

## Basic terminology in a Security Market

A security market or exchange is the place where one trades ones asset for another. In general an exchange will list multiple security markets, one for each trading pair: XLM/USD, XLM/BTC, etc.

In the following picture we can see how the XLM/USD(anchor) security market in the Stellar DEX, through StellarX looks like.

The order book lists the current outstanding orders for both sides: offering the security and bidding for it.
In market terminology a bid offer is an offer to buy a certain amount of the asset at a certain exchange rate, in the view these are the ones in light blue.
While an ask offer is the one where the placing party is willing to sell a certain amount of the asset at a specific exchange rate.
The ask prices will always be higher than the bid prices, otherwise those offers would be executed and the market would be clearing.

The difference between the lowest ask price and highest bid price is what's called the spread.
The spread can be thought of the cost of entering and exiting positions in the market, the tighter(smaller) the spread the cheaper it is to get in and out of a position.
Smaller spreads are signs of a liquid active markets, while large spreads are usually signs of either an illiquid market, a volatile market or both: as volatility tends to reduce liquidity due to uncertainty perceived by market participants.
We'll see how the spread is relevant for market makers in the next sections.

From the order book, the market depth can be derived.
The depth of the market is determined by how effectively it can absorb a market order in either way without altering the price of the security.
The deeper the market is, the harder it is to move the price through a single market order.
Market depth is generally correlated with market liquidity and volatility: the more liquid the market the deeper it tends to be while the more volatile the market is the shallower it will be.
Having deep markets is something any security market aspires to have as it makes it easier for participants to get in and out of it.

Let's discuss a bit about the different types of orders that can be placed in security markets.
We can categorize orders based on whether they increase or remove liquidity in the security market, in general they are given the names of maker order or taker orders respectively.
A maker order is an order that goes into the order book and doesn't get immediately executed, thus it increases the market liquidity and depth.
On the contrary, a taker order gets immediately filled out by triggering the execution of outstanding orders in the order book until either the order is completely, there are no more orders available or a price limit is reached.
It is possible that a taker order becomes a maker order, this happens when an order is partially filled and the remainder of it is kept in the order book awaiting to be taken.

That classification is a conceptual one, exchanges usually allow two types of orders: limit and market orders.
Market orders don't state any price only quantity of the asset to sell or buy and the exchange clears operations in the orderbook until the order is fulfilled. Market orders are never maker orders, they only take liquidity from the market.
On the other hand, limit orders state a explicit price limit for the asset being transacted; in the case of a sell order it indicates the minimum selling price while on bid orders the maximum buying price. Limit orders can be taker, maker or taker then maker, depending on the limit and the orderbook state when the order was submitted. A limit order whose price crosses the other side will get executed immediately thus considered a taker order. If the order cannot get fulfilled because there are not enough offers below the limit, the remainder stays in the orderbook waiting fulfilment becoming a maker order then. If from inception, the order never crossed the opposite's side best offer then the order is a maker order and sits in the orderbook until an order gets matched to it.

To conclude this section, let's discuss how price actually gets affected by orders.
The price that is listed for the asset is the price of the last executed trade, thus taker trades are the ones that move the price along with the depth of the market.
In the recent order panel we can see last executed offers, if the price is stated that it dropped it means that a sell order decided to take outstanding bid orders which will generally be below the last trading price. The opposite is true if the stated executed order shows a price increase.
It is also possible the price remains the same, this is common in very liquid and tight markets where the spread is almost non-existent.

## Why Market Makers are important?

Now that we have discussed the basics of a security market and what a market maker does, we can go into the reason why fostering market makers is a good idea.

When a market participant wants to exchange an asset for another, the only possible way for that to happen is if there's someone on the other side of the trade.
Having to wait for that to happen would not make a smooth, pleasant nor reliable market experience which discourages participation.
That's where the importance of market makers come into play. By having open orders on both sides of the orderbook they allow any participant to make a trade without having to wait for a counter-party.
It is the market-maker's job to be there for anyone who wants to trade.

Market makers inherently increase market liquidity and the depth of the market, thus making it more robust and easier to get in and out of positions for the rest of the participants.
The more market makers there are, the more available liquidity is going to be. Also, as market makers compete with each other for orders the spread tightens, making it more attractive for the rest of participants to be involved in the market.

## How do Market Makers benefit?

You might be wondering what's in it for the market makers, as they are not charitable organizations.
Well, market makers are in that business for the profit it generates.
They generate profit from the spread between their bid and ask orders; they literally buy low and sell high. The larger the spread, the more profitable the market maker is.

The follow-up question would be: why don't they make their spread really large?
And if they could, they would do it but the only way for them to generate profit is by having their offers taken on both sides, if the spread is too large there are going to be other participants (or market makers) willing to bid/ask closer to the middle, removing profitability from the market maker.
This is strictly related as to why liquid markets with multiple market makers tend to have tighter spreads.

But market making is not a risk-free business, inherently market makers are on the “wrong-side” of the trade with informed investors making the taker orders.
Their profitability relies on the assumption that the market will behave like a random walk with a similar number of buys and sells at around the same price.
If that doesn't hold, the market maker will build up inventory on one side of the market and will not be able to generate profit.
Making things worse, an unbalanced trading situation will move the price against the positions of the market maker, putting it in the position of waiting for a mean reversal or taking losses to balance its inventory.

Because of this, most market makers will either remove their offers or significantly increase the spread in times of high-volatility or market turmoil.
Apart from withdrawing the offers market makers tend to have multiple offers on each side open with each offer widening the spread. This way, they are able to provide the same liquidity but mitigating the risks of a sudden price change compromising their entire inventory

# Market Making in Stellar - The Stellar DEX

The Stellar ecosystem doesn't require an external exchange handling the order matching and execution.
Stellar has a built-in exchange with all the operations built-in as native protocol operations, this is the Stellar DEX.

The different Stellar exchange apps, such as Interstellar and StellarX, provide a nice user interface to see the state of the different security markets in the DEX as well as an easy way to interact with it.
But there is no requirement of using this exchange apps to interact with the DEX, just by having an Stellar Account and being able to create and publish Stellar Transactions is all you need; it can perfectly be done through the Stellar Laboratory.

The operations that are going to be used in the context of market making are: Manage Buy Offer and Manage Sell Offer.
With just these two operations, we are able to open, modify or withdraw outstanding offers on both sides of the orderbook.

All offers in the Stellar DEX are limit orders, but market orders can be emulated through the issuance of a path payment strict receive/send to oneself with a really high max send or min receive value. This effectively acts as a market order that will clear the outstanding orders until fulfilled or fails completely.

Every market maker needs to have a strategy. A strategy defines what offers to make and their lifecycle: when to modify them, when to cancel, etc.
There are several different strategies, each one with its pros and cons.
There is no "best" strategy as some have specific use-cases while others are more general but depending on the market conditions they can lead to very different results.
It is outside of this article's scope to discuss the different market making strategies.

Once a strategy for market making has been chosen, one could manage the offers manually through the issuance of these operations, but that would be pretty hard-working and exploitable as changes in the market happen more quickly than the speed a human can react to.
The next step would be to build a script that based on market conditions manages the outstanding offers and this is where Kelp comes into play.

# Kelp - Becoming a Market Maker in the Stellar DEX

Kelp is the implementation of a modular automatic trading bot primarily focused on the Stellar DEX. It is open source and written in Go.

Its objective is to make it easy for parties to start participating in the Stellar DEX without having to implement a lot of the boilerplate required for doing automatic trading.

It comes with several strategies already implemented, making it easier to start participating right away just by configuring it properly. These strategies are focused on the following objectives: making markets, providing liquidity and price-discovery for ICOs and mimicking orderbooks from other exchanges.
Kelp also contains several external exchange integrations by default and as it is capable to interact with CCXT, it allows interactions with over 120 exchanges.

Even though it comes with a lot of things by default, its modular design allows developers to customize key behaviors, such as adding new trading strategies or integrating with other exchanges without having to get into the weeds of the bot itself.

In order to start working with it, you can either download a precompiled binary from their GitHub Page or compile the source code yourself.
If interacting with other exchanges through CCXT is desired, then CCXT needs to be setup separately and should be reachable by Kelp.
Lastly, Kelp has the capability of storing the trades in a Postgres database, if you want to use the feature you will need an instance of Postgres with appropriate credentials and Kelp should be able to access it.

Once all the required components are setup, it is turn to create the required configuration files.
There is a main bot configuration file that contains general configuration, a sample can be found here.
A second configuration file is required, which basically is going to modify the strategy's behavior. This file is specific for the trading strategy that was chosen, the example files are pretty well explained.

Finally, the bot can be launched with the configuration files and the trading strategy.

\$ kelp trade --botConf ./path/trader.cfg --strategy buysell --stratConf ./path/buysell.cfg


Each instance of the Kelp bot can only handle a single security market, that is a single trading pair.
In order to operate on multiple trading pairs, multiple instances need to be launched, each will need its own configuration.
If you don't want to have different funding accounts for each security market, you can use a nice Kelp feature: the decoupling of the funding account from the trading account.
Kelp can be configured to issue the transactions managing the offers from one account (the trading) while using the funding account as the source account for the offer operations.
This enables you to have a single funding account with multiple bots, each having their own trading account, using its funds in different security markets.
It is necessary to do it this way because Stellar doesn't allow to issue multiple transactions from the same source account in parallel: each one requires the correct sequence number.

Kelp is a good option to start the journey of becoming a market maker in the Stellar ecosystem, the ramp up to have things setup is small and not hard at all.
But, beware that this can be a double-edged sword, by making it easy to setup and get started it also makes it easier to launch something you don't fully understand and make you lose money.
And, like all automated trading tools, if misconfigured it can actually make you lose money pretty fast.
The best advice I can give is to make sure you get acquainted with market making in general, the strategy you are using and the configuration details of Kelp.
Before launching this into the actual Stellar DEX in the mainnet, run it in a controlled environment and in the testnet to validate that things are working according to your expectations.
And last but not least, start with a little amount of assets (and something you can afford to lose) and grow slowly as you get more understanding of the different moving parts.

# Conclusion

If we want the Stellar project to succeed, its DEX needs to have healthy security markets.
Participation in those markets needs to be smooth, easy and cheap. The transaction costs work in its favor but currently its security markets are too illiquid and shallow.

In order to get better liquidity, depth and tighter spreads in those markets, a good number of market makers are needed.
As more market makers participate, healthy competition will kick in and we'll be able to enjoy healthier markets.
And once we get healthier markets, a positive feedback loop can be established attracting more people to the Stellar ecosystem, further improving its markets.

There is currently a good opportunity before the space gets crowded to enter in this business line and learn while competition is not so fierce.
Kelp makes it easy to enter the arena and start experimenting without needing to develop a lot of software, allowing you to focus on the important parts: your market making strategy.

If you are reading this, it means that you already are somewhat interested in the space.
I would encourage you to give it some more thought, do some extra research and experiment with market making in the Stellar DEX. Kelp will make the experimentation much easier than if you start from scratch.