This is the question that can't be answered by one person, it's a very, very complex task and there are multiple people involved in it.
Overall, their work principle is simple, exchanges connect the people who want to buy and who want to sell. Exchanges also have reserves and offer you to buy/sell instantly but in a different rate. This is the basic, then comes the Futures Trading, Margin Trading, Staking, etc. For example, Binance lets you to become a liquidity provider and you earn money from those people who lose in Futures trading.
There is an AMM Formula explained:
https://www.binance.com/en/support/faq/33f38db8c23e4a0f949b5433cdc7193aYou can also find a lot of useful information in their FAQ question that should answer some of your questions:
https://www.binance.com/en/support/faq/c-5?navId=5