GMX Perpetuals Trading
Cyfrin Updraft Courses · 3:35:54
Tasuku Nakamura, a smart contract engineer and educator, explains how developers build applications on the GMX protocol. The course examines contract architecture, order types, funding rates, liquidations and liquidity pools, with exercises for integrating perpetuals infrastructure into Solidity applications. It assumes Solidity and advanced Foundry experience.
Speakers
Topics
From Cyfrin Updraft Courses, hosted by Cyfrin.
Transcript
Welcome to the course for learning about the D5 protocol GMX V2. GMX is a decentralized perpetual exchange. The protocol allows you to create long and short positions up to 100x leverage. It also allows you to swap tokens at the market price or submit a limit order for your swap. What does all of that mean? Well, in this course, you'll find out. In this course, you'll learn what is GMXP2 and how it works. You also learn some of the advanced DeFi concepts and terminologies such as perpetual swap, leverage, long and short, and funding fees. Now, the way that I'm going to explain these terminologies and concepts might slightly be different from how it is explained or defined in the traditional finance sense. Here, I'll
explain these terminologies and concepts in a way so that you can understand GMX V2. In this course, there are exercises where you'll write Solidity code to interact with the GMX V2 contracts. So, you'll get some hands-on experience interacting with the protocol. Why should you take this course? You should take this course to expand your DeFi knowledge. You'll learn advanced concepts that I explained above, such as perpetual swaps. You can use this knowledge and apply it to audit contest and bug bounties that are relevant to perpetual exchanges. Some other reasons to take this course is that you might be thinking to build an application that integrates with GMXP2. In this course, I'll teach you about the contract architecture of GMXP2. So this might be helpful if you want to build an
application on top of GMXB2. And finally, if you're thinking about building your own perpetual exchange, then this course is also for you. Let's move on to prerequisites. The first prerequisite for this course is that you know basic D5 terminologies. I expect that you know what D, USDC, WE, WBTC are. Furthermore, I expect that you know what ERC20 decimals are, AMMs, price oracles, arbitum and etc. How much solidity should you know before taking this course? The requirement is intermediate to advanced solidity. In particular, it helps to understand how the solidity library works. What you need to know here is that state changing calls through a library uses delegate call. Before taking this course, make
sure that you know what delegate call is and how it works. GMXB2 utilizes a lot of library contracts. So, understanding how a library works will help you understand how GMXB2 works. You should also know about multicol. For those of you who don't know, multicol is a technique that is used to batch multiple transaction calls into a single transaction. The way it works is you put all of your transaction in an array and inside the function you loop through these transaction calls. This multiol is used extensively in GMXP2 to batch transaction calls. The final prerequisite is advanced foundry. Before taking this course, make sure that you know what it means to test on the fork.
And finally, make sure you know how to use the console log inside the Foundry test for debugging. The first step to doing the exercises in this course is to get clone this repo. Next, you'll need to set up Foundry to do the exercises. You can navigate to the instructions by clicking on this Foundry setup link. Basically, all you have to do is navigate to the folder Foundry and then set up the environment variable that is inside M.Aample. To build the exercises, you can type forge build. And to build a solutions, you can pass in the environment variable foundry profile equals solution and then type forge build. When you execute the test, it's going to try to execute the test on the latest state of the blockchain. If you
want your test to run faster, you can first specify a block to test on. By doing this, the next time you run the test, it will test on that same block. So, Foundry doesn't have to go get the latest state of the blockchain. It is already cached. This way you'll be able to run your test faster. And to do this, the first thing that you can do is type cast block number specifying the fork URL. This will print out the current block number. Put this in an environment variable and then run the test specifying the block number to fork. This will test your exercise. In the same way, you can also test the solution by prefixing it with the environment variable foundry profile equals solution. And then the rest of the command for testing is the same.
Although the solidity code can be found inside the folder foundry. Inside source there are two folders exercises and solutions. Solutions will contain the solutions for the exercises. And inside exercises this is the starter code where you will start writing your code. You can see here that a lot of the code is empty with some comments about what to do. The instructions for the exercises are contained under the folder foundry exercises. Inside here, you'll see some markdown files where it will instruct you on what to do. For example, here are some exercises to add and remove liquidity from the JB vault. So, the way that you would do the exercises is open one of these markdown files and then
also open the starter code under the folder source exercises and then write your code. After you're done writing your code, you can execute the test by copying and pasting the test command. So that's how you do the exercises for Foundry. Now to fully understand how GMXB2 works, I recommend that you run the transactions through a transaction debugger such as Tenderly.co. Under the link transactions, which is inside the same file, you'll see a list of transactions that I've sent. For example, here you can see that there's a transaction that swapped D to E. And scrolling down, there are other transactions such as creating a long position and short positions. Clicking on this link, this will take you to the blockchain explorer. In this course, I
interacted with GMXB2 which is deployed on arbitrum. So the blockchain explorer that we'll be using in this course will be RBN. To debug the transaction, I'll copy this transaction hash and then use a transaction debugger like tenderly.co. I'll paste the transaction as and this will open a transaction debugger where you'll be able to see all of the function calls, all of the contracts that are called, and the parameters that are passed. Furthermore, if you click on the debug button, then you'll be able to see the code that was executed and the inputs that were passed. So, use a transaction debugger to understand what inputs are being passed so that you can successfully complete the exercises. In this course, we'll look at some of the GMX contracts. The contracts that we'll
look at is located under the GitHub repo GMX synthetics and GMX contracts. So, if you want to follow along, make sure to get clone these two repos. Moving on, all course notes can be found under the folder notes. Inside this GitHub repo, there's a folder called notes. Inside here, there are markdown files and diagrams that I use in this course. And finally, if you have questions or comments, feel free to post them on discussions. GMXB2 is deployed on several chains. In this course, I'll be sending transaction to the GMX that is deployed on Arbitum. To send transactions on Arbitum, you'll need to have ETH on Arbitum to pay for the transaction fees. If you currently don't have ETH on Arbitum, one way to obtain
it is to send your ETH from the Ethereum mainet over to Arbitum. So, in this video, I'll show you how to send your E from Ethereum mainet over to Arbitum. I'm inside bridge.io. I'll leave a link to this application inside the GitHub repo. On the mainet, I currently have approximately 0.022 E. And on arbitrum, I currently have approximately 0.021 E. Let's send 0.01 E from mainet over to arbitum. 0.01. Then scroll down, then click on move bonds to arbitrum 1. Confirm the transaction.
Once I submit the transaction, I'll be taken over to the transaction history tab. The transaction is currently pending. And over here, it says that the time left is approximately 13 minutes. So, I'll wait about 13 minutes and then come back to see the status of this transaction. My transaction to send 0.01 E from ETH mainet over to Arbitum was processed. Let's check the balance on my wallets. Going back to bridge tab, my balance on Ethereum mainet is approximately 0.012 E. And then on Arbitum, I have approximately 0.031 E. My 0.01 E from mainet has been allocated to arbitrum 1. GMX is a decentralized perpetual exchange. It allows traders to create long and short
positions up to 100x leverage. It also allows traders to swap tokens at the market price or submit a limit order. If you're not a trader, there's other ways to potentially earn yields on GMXB2. This is by either providing liquidity to the GM pools or to the GB Bolt. The difference between a GM pool and the GB Bolt is that the GB Bolt is a collection of the GM pools. Whether you're swapping tokens, creating a long or a short position, or providing liquidity, it involves two steps. The first step is you submitting a transaction which sends a request to the GMX protocol to take some action. For example, for a swap, creating long position or short position or providing liquidity. Those are all requests that are sent by you. In the
next transaction, the GMX protocol will execute this order to fulfill your request. The main reason that there are two transactions is to mitigate MEB. For example, if an order to long, short or swap can be executed in a single transaction, then IMEB bot can submit a transaction that is to be executed before yours to make some kind of profit. By splitting the order into two transactions, the GMX protocol have some control over which orders to execute first and protect users of the GMX from MEB. The last key feature of GMX that I will highlight here is the adaptive funding fee. The funding fees are paid and claimed between the long and short positions. The funding fee is gradually
adjusted over time depending on the ratio of the long and short positions. Don't worry if most of the features that I explained in this video did not make sense to you. In this course, I'll be teaching you all of these terms so that by the end of the course, you understand what a perpetual exchange is, what longs and shorts are, and what funding fees are. The GMX B2 protocol has three essential users. The trader, liquidity provider, and keepers. Keepers are authorized account of GMX. Let's see how each of the users interact with the GMX protocol. Let's start with liquidity providers. Liquidity providers provide tokens to the GMXB2 protocol. These tokens will be used to pay out the profit for the traders. The traders can
create a long or a short position. So, the liquidity providers provide liquidity for the long and the short tokens. I haven't explained what a long or a short position is yet. So, for now, think that liquidity providers provide tokens and these tokens will be used to pay out the profit for the traders. The liquidity providers can either deposit their liquidity or withdraw their liquidity. In both cases, this will involve two transactions. The first transaction is to create an order to deposit or withdraw. The second transaction will be executed by a keeper to execute this order. To execute the order, the user that creates an order must pay a execution fee. The keeper will use this execution fee to execute
this order. And any excess amount of execution fee that was paid here will eventually be repaid to the user. Let's now look at the trader. The trader can either create an order to swap, create a long position, create a short position, or close these positions. For swaps, they'll be sending token in and then receiving some other token out. For creating a long or a short position, their profits will be paid by the tokens that were provided by the liquidity provider. However, if a trader makes a loss either from long or short position, they'll have to pay the loss from the collateral that they deposit when they created these positions. Like the liquidity provider, when they create an order either to swap long or short,
they'll have to pay a execution fee. Funding fees are paid between the long and the short positions depending on the market condition. By placing a long or a short position, depending on the market, the trader will be able to claim the funding fee. I haven't explained what making a profit or a loss from long or short position is and I also haven't explained what funding fees are. For now, you can think about it as a trading strategy that can either make a profit or a loss. And finally, we have the GMX keeper which will execute the orders submitted by the users. The users being the traders and the liquidity providers.
The GMX protocol relies on oracles to get the accurate price of different tokens. When the keeper executes the order, they submit the prices that are to be set inside the oracle. After the order is executed in the same transaction, these oracle prices will be reset. For executing the order, the keepers will receive the execution fee which were paid out from the users. Any excess amount of execution fee that these user pay will eventually be repaid by the GMX protocol. So this is a quick overview of how GMXB2 works and how different users interact with this protocol. What is a perpetual swap? If you ask an AI, it will give you an answer that looks something like this. A perpetual swap is a type of derivative
contract that allows trader to speculate on the price of an asset without ever needing to settle the contract. You can keep on reading this explanation and you may come across some words that you are not familiar with. For example, future contracts and margin requirements. trying to understand what a perpetual swap is from this explanation might confuse you. So I'll give you an alternative explanation that will suit us better to understand how GMX works. So what is a perpetual swap? Now keep in mind that the explanation that I'm about to give you might differ from the traditional explanation. A perpetual swap is a bet on the direction of the price of a cryptocurrency. If the price of this cryptocurrency moves in the same direction as your bet, then you can make a profit. If the price moves in the
opposite direction as your bet, then you will lose money. Notice here that I've highlighted that this is a bet on the direction of the price of the cryptocurrency. So, you won't need to trade with the actual tokens. No tokens are needed for this trade. Let's contrast this perpetual swap with a regular swap. If you go to a centralized exchange or a decentralized exchange, you can swap tokens. In short, you can bet on the direction of the price. If you buy a token and if the price moves up, then you'll make a profit. If you buy a token and the price goes down, then you lose money. The difference between a perpetual swap and a regular swap is that in a perpetual swap, you're only betting on the direction of the price and no physical tokens are traded.
So, for example, you can speculate on the price of the Bitcoin without actually trading the Bitcoin. Therefore, one benefit of a perpetual swap is that you don't need the cryptocurrency to bet on the price of that cryptocurrency. These bets in GMX are called positions. So from here on out, I'll refer to these bets as positions. Positions have no expiry. Hence, they are called perpetual swaps. This means that if you create a position, you're betting on the direction of the price of a cryptocurrency. This bet that you made has no expiry. You can close your position at any time to claim profit or pay the loss. Except there's one condition where your position is forcefully closed. When you create a position, also called opening a
position, you'll need to deposit a collateral. This collateral will be a token that will be used to repay for the loss. You can close a position to claim the profit or pay for the loss. And finally, the losses are paid out from your collateral. As long as your collateral can cover for the current losses, you can keep your position open. However, if the current loss is really close to the value of your collateral, then GMX will forcefully close your position, repaying this loss using your collateral. So, in summary, a perpetual swap is a bet on the direction of the price of a cryptocurrency without actually having to trade that cryptocurrency. You make a profit if the price moves in the same direction as your bet. You will lose money if the
price moves in the opposite direction as your bet. These bets are called positions. Positions have no expiry, hence they are called perpetual. When you open a position, you'll need to deposit a collateral. You can close a position at any time to claim profit or pay for the losses. The losses are paid out from your collateral. And if the amount of losses is really close to the value of your collateral, then your position will be forcefully closed by GMX. There are two types of directional bets or you can think about it as two types of positions. If you want to bet on the price going up, then this is called long. You're creating a long position. If you want to bet on the price going down, then this is called short or creating a short position.
Let's look at some examples. Let's say that you create a long position for one ETH and the price goes up. The price of ETH goes up and down, up and down. And let's say that the current price of E is one E equal to $2,000. And we open a position here. We open a long position here for one E. Over time, let's say that the price of E keeps going up. And now the price of E is one E equal to $3,000. When we go long, we bet on the price going up. And since the price has gone up, we'll make a profit. So let's claim our profit now. The profit will be equal to the current price of one E $3,000 minus the initial price of E when we open the position. This is $2,000.
3,000 minus $2,000 is equal to $1,000. So our profit will be $1,000. This is the profit that you make in a perpetual swap. Now you can make a similar profit with market swaps. For example, let's say that you bought one ETH when the price was at 2,000 USD. And then let's say that you sold this one ETH when the price of ETH was at 3,000 USD. Bought at 2,000, sold at 3,000. The profit will again be 1,000. So the profit that you made from a perpetual swap is similar to buying one ETH at 2,000 and then selling at 3,000. The difference between a market swap and a perpetual swap is that in a perpetual swap, we then actually had to buy the ETH and then sell the ETH. We're only betting on the price of
the ETH. Let's look at another example. What happens if we long one ETH and the price goes down? Let's say that the current price of ETH is 1 E equal to 2,000 USD. We create our long position here. We're speculating that the price of E bee is going to keep going up above 2,000 USD. However, what if the price moves against our bet? The price of beef decreases. And let's say that the current price of beef is now 500 USD per one beef. We don't want to make our loss any larger than it is now. So, let's close our position here. The loss is the current price of beef 500 USD minus the initial price of beef when we created a long position 2,000 USD. 500US 2,000 is equal to - 1,500. This is a loss if we
were to create a long position when the price of beef is 2,000 and then close this position when the price of beef has gone down to 500 USD. Now, we could have made a similar loss if we were to do this move on a market swap. For example, let's say that we bought one E when the price of E was 2,000 USD and then we sold this one E when the price of E beef was 500 USD. So, we bought one ETH at price 2,000 USD and then sold it at when the price of ETH was 500 USD. And again, the loss will be minus 1,500. Similar loss is made between a perpetual swap and a market swap, except in a perpetual swap, there is no tokens that we are trading. We're not trading ETH. We're simply speculating on the price of ETH.
Next, let's look at two more examples. Shorting one ETH when the price goes down and shorting one E when the price goes up. Let's start if shorting one E and the price goes down. Remember that we'll make a profit from a short position if the price goes below the price when we created the position. So let's say that the current price is 1 E 2,000 USD. We create a short position for 1 E. Over time, the price of E goes down to 1,000 USD. Let's close our position here to claim our profit. The profit will be the initial price of beef when we created this position, 2,000 USD, minus the current price of beef when we closed this position, 1,000 USD.
The difference is 1,000 USD. This is the profit that we would have made in a perpetual swap, but we can make a similar profit on a market swap. And here's how you would do it. You first borrow one E when the price of ETH was at 2,000 USD, and you would immediately sell this one E. So you have a cash of 2,000 USD. Over time, the price of ETH goes down to 1,000 USD. We buy back this one E at 1,000 USD and then repay the one E that we borrowed. We started out with 2,000 USD and we only had to repay 1,000 USD. The difference is 1,000 USD.
This is the profit that you make in a perpetual swap. And if you wanted to make a similar profit using market swaps, here is how you would do it. borrow one ETH, sell it, and then buy back one ETH when the price has gone down and then repay the one E. The difference is in a perpetual swap, you didn't have to do this borrowing, selling, and then buying back the ETH. Finally, let's look at example of creating a short position for one ETH. And let's say that the price goes up. We create a short position for one ETH when the price of one E is 2,000 USD. When we short, we make a profit when the price goes below the price when the position was created. However, let's say that the price of beef goes up to, let's say, 4,000 USD. We want to limit our loss.
So, let's close our position before our loss gets any bigger. Now, let's calculate our loss. The initial price of beef when we created a short position is 2,000 USD. When we close the position, the price of EF was 4,000 USD. The difference is minus 2,000 USD. This is a loss that we'll have to pay if you were to close a position in a perpetual swap. Now, a similar thing can happen if you were to borrow tokens and then use market swaps. So, here's how it goes. Let's say that when the price of one ETH is 2,000 USD, we borrowed one ETH and then immediately sold this one E. So, our position will be 2,000 USD in cash.
Here, we're speculating that the price of beef is going to go down. So, when we repay our one E, we have to pay less and the difference will be the profit. However, let's say that the price of beef goes up to 4,000 USD. And now when we repay our one E, we need to buy this one E at 4,000 USD. We sold it at 2,000 and we need to buy it back at 4,000. The difference will be 4,000 - 2,000, which is equal to - 2,000. This is the loss that you would have made if you borrowed one E, sold it, bought it back, and then repaid it, which is similar to the loss that you would have made on a perpetual swap. And again, the difference is in a perpetual swap, we didn't have to borrow any tokens or swap any tokens. In a
traditional finance sense, leverage means to buy something with borrowed money. However, for the purpose of understanding GMX, I'm going to redefine what a leverage is. So, in GMX, a leverage means to open a position that is X times the USD value of the collateral that you deposit when you create a position. For example, let's say that you create a position and you put in a collateral of 1,000 USDC. Let's also say that 1 USDC is close to $1. So this value of the collateral will be roughly 1,000 USD. With 1,000 USD as the value of the collateral, what does it mean to do a 2x leverage? Well, it means to create a position that is 2 times the USD value of the collateral. So the size
of the position will be equal to since we're creating a 2x leverage, this will be two times the USD value of the collateral. We put in 1,000 USD as collateral, which is roughly equal to 1,000 USD. 2 * 1,000 USD will be 2,000 USD. How about another example? What does it mean to create a position with 5x leverage? In this case, the position size will be five times the value of the collateral. The value of the collateral is 1,000 USDC which is roughly 1,000 USD. 5 times 1,000 USD will be 5,000 USD. So to create a position with 5x leverage means to create a position that is five times greater than the amount of
collateral that we deposited which is roughly equal to 5,000 USD. Now often when you're looking at the code for GMX, you'll come across a term called position size N USD. And what this is is leverage times the USD value of the collateral when this position is created. This term will become important when we need to calculate the profit and loss of a position. The purpose of leverage is to amplify the profit and the loss. So in this video, I'll give you examples of how leverage will amplify the profit and how it can also amplify the loss. Let's start with example of how it can amplify the profit. Let's say that we create a long position in E and the price goes up. For example, when we create a long position,
the price of beef is 2,000 USD. Our position will consist of 1,000 USD as collateral. Let's say that this is roughly 1,000 USD with a 5x leverage. Now, before we move any further, we'll need to do some calculation so that we can calculate the profit at the end. Recall from the previous video that this means that having a collateral worth roughly 1,000 USD and 5x leverage means that the position size is roughly 5,000 USD. Before we move any further, we need to calculate the position size in terms of E. How much E will we have if we were to buy E with 5,000 USD where the current price of E is 2,000 USD? So, we have 5,000 USD as our position. One E is
worth 2,000 USD. So we will have 2.5 E. This is our position size in terms of beef. Keep this number in mind. We'll need this when we calculate the profit later on. Okay. Let's say that time has passed and the price of beef has gone up to 3,000 USD. One E is 3,000 USD. If we close our position now, we will make a profit. So let's calculate how much profit we will make. So we will close our position when one E is 3,000 USD. The profit is our position represents 2.5 E. We closed our position when the price of E is 3,000 USD. In our initial position, when we open the position, we started out with 2.5 E and the price of E was 1 E2,000 USD. Calculate the
difference and the profit is 2500 USD. So this is a situation where if we long E with 5x leverage, we will make a profit of 2500 USD. Let's compare this profit with if he were to not take any leverage. If leverage was equal to one one next leverage, then our position size will be the amount of collateral which is 1,000 USD. And our position size in terms of EF, so this will be 1,000 USD. The price of EF will be 2,000 USD. So we will get our position size in terms of E will be 0.5 E. Our profit will be 0.5 E over here and 0.5 E over here as well. Do the calculation and
this will be 1500 minus 1,000 which will be equal to 500. If he did not take any leverage, if the leverage was 1x, then we would have made a profit of 500 USD. Compare this with 5x leverage. With 5x leverage, we would made a profit of 2500 USD. the profit is five times more compared to if you did not take any leverage. So this is an example of how leverage can amplify the profit. Next, let's take a look at how leverage can amplify the loss. Let's see what happens when we use leverage to long and the price goes down. The current price of E is 1 E equal to 2,000 USD. Let's open a position here with the same amount of
collateral as in the previous example, 1,000 USDC with 5x leverage. So the position size will be 5,000 USD and the position size in terms of E will be 2.5 E over time. Let's say that the price of E goes down to 500 USD and we close our position here. Let's now calculate what the loss is. So the loss is we have a position size of 2.5 beef. The price of beef is 500 USD. We started out with 2.5 beef when the price of beef was 2,000 USD. Taking the difference, the loss is - 3750.
Like in the previous example, if he did not take any leverage, if leverage was equal to one, then this 2.5 will be equal to 0.5. So the loss will be half of minus 1,500, which is equal to -750. By taking a leverage, you can see here that the loss is also amplified. Now, if you're having a difficult time understanding how this loss is calculated, think about it like this. You buy 2.5 E when one E is equal to 2,000 USD. And then you sold this 2.5 E when the price of E beef is 500 USD. You bought it at high price and then you sold it at a lower price. So you will realize a loss. And this loss is equal to minus 3,750
USD. So these are two examples of how leverage can both amplify the profit and the loss. When you're looking at the code for GMX, you'll come across terms such as market and market tokens. You can think about a market as a place to long and short a cryptocurrency. The cryptocurrency that you're betting the price on is called a index. A market is defined by three components. An index, a long token, and a short token. The index is the cryptocurrency to bet on the price. Long tokens are token used to pay out the profit for a long. And short tokens are token used to pay out the profit for a short position. Let's look at some examples of markets. For example, let's say that we have a market where the index is ETH, long token is
WE, and short token is USDC. This means that we're betting on the price of ETH, long profits are paid in W, and short profits are paid in USDC. Since in perpetual swap, we're betting on the price of a token, that token that we're betting on doesn't have to exist on the blockchain. For example, let's say that we have Dogecoin and it doesn't exist on Arbitum. Let's also say that long tokens are and short tokens are USDC. In this market, we're betting on the price of Doge and long profits are paid in web and short profits are paid in USDC. We can also have a market where the long and the short token are the same token.
For example, let's consider index equal to Bitcoin and long and short token equal to wrap Bitcoin WBTC. In this market, we're betting on the price of Bitcoin and for the long profits, we're paying out WBTC and for the short profits, we're also paying WBTC. So, these are some examples of our market. Our market is defined by the index, long token, and the short token. We saw some examples of markets in the previous video. On some markets, the index was a token that existed on arbitum and in other markets, index was a token that did not exist on arbitum. We can classify these two markets as fully backed and synthetic. Fully backed means that the index is equal to or similar to a long token and the short token is a
stable coin. Here, they don't have to be exactly equal. For example, index can be E and the long token can be W. And for synthetic markets, the index is not equal to the long token. The example we saw in the previous video was where index was equal to doge and the long token was equal to. Now let's see why this market is called fully backed and this market is not fully backed. Let's start with an example of a fully backed market. Okay, so here's one. Index equal to E, long token equal to W, and the short token equal to USDC. Does it fit our definition of a fully back market?
Index is E, long token is W. E and W are similar tokens. The short token is a stable coin. USDC is a stable coin. So let's see how this market is fully backed. Let's say that the current price of E one E is equal to 2,000 USD. and this market has 100 W and 200,000 USDC available to be paid out as profits. We'll also say that there are 90 W long positions. This means that when we sum up all of the long positions, it will be equal to 90 W. And likewise, let's say that there are 180,000 USDC short positions. When we sum up all of the short positions, it equals 180,000 USDC.
Now, let's see how this market is fully backed. Consider the case where the price of E 10 X's. What would be the maximum profit of all of the long positions? Well, there are 90 W long positions. If all of these positions were created when the price of W was equal to zero, then the maximum profit will be 90 W. For example, let's say that we long 90 W when the price of E was equal to zero. Anything above price zero is our profit. So our profit which will be paid in W, the maximum profit will be 90 W. And how much we does this market have available to be paid out for profit? Well, it is equal to 100 W. So you can see that in the extreme case, even when the price of beef goes up by
10x, we still have enough we to pay out all of the profits. How about when the price of beef goes to zero? For example, let's say that the price of beef is 2,000 USD and the price of beef goes to zero. We need to pay out the short positions. Can we pay out all of the short positions? Now let's try to come up with an upper bound for the profit of all of the short positions. If all of the short positions were created when one E was equal to 2,000 USD and the price of ETH went straight down to zero, then what is the maximum profit of all the short positions? All of the short positions were created when one ETH is equal to 2,000 USD. When we sum up all of the short positions, this is equal to 180,000 USDC. The maximum profit from
all of these short positions will be less than or equal to 180,000 USDC. The way to think about it is let's say that one ETH is 2,000 USDC and we only create one position. We only create one short position for 180,000 USDC. You're the only person that created a short position. And let's say that the price of EF goes to zero. What would be your profit if you were to close this position? Well, it's going to be 180,000 USDC. So this is the maximum profit for a short position assuming that there are 180,000 USDC short positions. Okay. And how much USDC is available to be paid out for profit in this market? Well, it is 200,000 USDC. And you can notice that
the maximum profit of short position is strictly less than the amount of USDC that is available in this market. So we can see from this example that this market is fully backed whether the price of beef 10 x's or the price of beef goes to zero all of the profit can be paid out from this market. Now let's take a look at another example a synthetic market and let's see how this market is not fully backed for example let's say that we have index equal to doge long token equal to we and short token equal to USDC let's say that the current price of one doge is equal to 50 cent and one is equal to 2,000 USD the market has 100 and 200,000 USDC again these are token
that are available to be paid out as profit for long and for short positions There are 360,000 Doge long positions and 180,000 USDC short positions. Now, let's see what happens when the price of Doge 10Xes, but the price of W stays the same. Let's calculate the maximum profit of all of the long positions. And for simplicity, assume that we only created one long position. You're the only user that created a long position and the size of the position that you created is 360,000 Doge. Let's also assume that when you created this position, the price of Doge was equal to 0. What we're doing here, we're simplifying the math just to figure out the maximum profit of all of the long positions. So only one user and
we created a long position when the price of Doge was exactly equal to 0. So what will be the upper bound to the profit of all of the long positions? There are 360,000 Doge long positions. The price of Doge has 10 next starting from 50. So we multiply this by 50 cent * 10 which is equal to $5. 360,000 * 5 turns out to be 1.8 million. This is the maximum profit of all of the long positions. And again, if you're the only person with a long position of 360,000 Doge, you've created this position when the price of Doge was equal to zero and the current price of Doge is equal to $5. Then the profit that you can make
will be 1.8 million USD. The profits of the long position is paid out from the long token. In this case, the long token is W. So what is the current value of W? Well, the price of W stay the same and there are 100 W. So the USD value of the W in this pool will be 100 W times 2,000 USD. The price of W stay the same. It is equal to 1 W equal to 2,000 USD. and this is equal to 200,000 USD. So notice that the profit can go up to 1.8 million. However, the USD value of tokens that can be paid out for a long position is only 200,000 USD. The long token USD value in the pool is less than
the profit of long positions. In this example, you can see how a synthetic market cannot be fully backed. So far, we've seen that markets have long token and short tokens. These are tokens that are used to pay out for the profit of positions. But where do these tokens come from? Who provides the long tokens and the short tokens? The answer is liquidity providers. Liquidity providers are users who deposit the long and the short token to a market. And why would they want to do this? Well, liquidity providers will earn fees. Since their tokens are used to pay out for the profit for the long positions and the short positions, liquidity providers win when the traders lose and they will lose their tokens when the traders win. When the traders win, their profit will be
taken out from this long and short tokens. Hence, they will lose while the traders will win. And the opposite is also true. When the traders lose, the amount of loss that they'll have to pay will go to the liquidity providers. Position size in terms of USD and position size in terms of tokens are two important concepts that are needed to calculate the profit and loss of a position. So in this video I'll give you equations for how to calculate position size. Position size in terms of tokens and how to calculate the profit and loss of positions. Let's say that L is equal to leverage. C 0 will be the USD value of a collateral at entry. I Z will be the price of index at entry and we'll denote I as the current price of index.
We also denote S0 as the position size in USD. This is equal to L * C0 leverage times the USD value of the collateral when this position was created. And T0 we'll denote it as the position size in terms of token. And this is equal to the position size in USD divided by the price of index at entry when the position was created. This equation might be a little bit confusing. So let me give you example. Let's say that the index is the price of beef. If the position size was 5,000 USD and the price of E when this position was created, let's say, is 2,000 USD, then this will be 5,000 divided by 2,000, which is equal to 2.5. If we had 5,000 USD and we bought ETH when the price of
E was 2,000 USD, we will get 2.5 E. That is a position size in terms of token. Now, with these two terms defined, let's now calculate the profit and loss of a position. We denote P as the profit and loss of a position in USD. There are two types of position. Long position and short position. Let's first calculate the profit and loss of a long position. A long position will make a profit if the current price of the index is greater than the price of the index when the position was created. We can express this profit and loss in terms of position size and position size in terms of tokens. Currently, we have T0 amount of tokens. This is position size in terms of tokens. The current price of the index is given by i. When this
position was created, we also had t0 amount of tokens. Position size in terms of tokens is equal to t0. The price of the index token when this position was created is denoted by i. Now going back up, we see that t0 is equal to s0 / i. And over here, we're multiplying this t0 by i. So this i over here and this i over here cancels out. And what we're left with is this part of the equation is going to simplify to S0 / I0 * I which is simply equal to S0. So this is the profit and loss of a long position.
How about the profit and loss of a short position at entry? The position size in terms of token was T0. The index price was I. The same simplification for long positions when we simplify this T0 * I with S0 applies here. This T0 * I is equal to S0. If you were to close this position, the position in terms of tokens will be T0 and the current price of index will be I. So this is the equation for profit and loss for a short position. Next, let's take a look at some examples. Let's look at some examples of how to calculate the profit and loss of a long and a short position.
For these examples, we'll say that the leverage L is equal to 5. C0, which is the USD value of the collateral when this position was created, we'll set it equal to 1,000 USD. I Z will be the price of the index when this position was created, 2,000 USD. And I will be the current price of the index, 3,000 USD. To calculate the profit and loss, we first need to calculate the position size and the position size in terms of tokens. Let's start with position size in terms of USD. leverage is five. We multiply this with the USD value of the collateral when the position was created. This is 1,000 USD. So, our position size will be equal to 5,000 USD. We also need to calculate the position size in terms of tokens. And
this is equal to position size 5,000 USD divided by the price of index when this position was created. I this is equal to 2,000 USD. 5,000 divided by 2,000 is equal to 2.5. Okay. Okay, let's now calculate the profit and loss for a long and a short position. The equations that we'll be using are the equations that derived in the previous video. Let's start with the profit and loss of a long position. Since we created a long position and the price of the index went up, we expect this number to be a positive number. And for the short position, we expect this to be a negative number. Okay, so let's start with the long position. The profit and loss of a long position t0 is equal to 2.5. Multiply this by the current price
of the index, 3,000. And then minus S0, the position size when this position was created. This is 5,000 USD. 2.5 * 3,000 is 7,500 minus 5,000. This is equal to 2500 USD. The profit for a long position is 2500 USD. Next, let's calculate the profit and loss for a short position. S0 will be 5,000 USD. We minus this with t0 * i t0 the position size in terms of tokens is equal to 2.5. Multiply this by the current price of the index. The current price of the index is 3,000.
5,000US 2.5 * 3,000. 2.5 * 3,000 is 7,500. 5,000US 7,500 is equal to minus 1,500. So this was an example of how to calculate the profit and loss of a long position and a short position. Remember that in a perpetual swap there is no expiry. You can keep a position open as long as you want. However, there is one exception. This is when the USD value of your loss is close to the USD value of your collateral. In this case, your position will be forcefully closed and this is called a liquidation. So liquidation is when a position is forcefully closed and the collateral is taken by the protocol. This collateral
is used to pay for the losses. More specifically, liquidation happens when the following condition is met. First, take the USD value of the collateral from this minus the position losses. There are some onetime fees and ongoing fees for creating a position and keeping a position open. When this value on the left side of the equality is less than some minimum amount of USD value specified by the GMX protocol, your collateral can be liquidated by the protocol. To be more precise, let's say that collateral is the current USD value of the collateral. Notice that for position sizes, we look at the USD value of the collateral when the position was created. However, for liquidation, we're looking at the current USD value of the
collateral. Position losses will come in two forms. For a long position, there's a loss when the current index price is less than the index price at entry. And for a short position, there's a loss when the current index price is greater than the index price at entry. In the first case, you're betting that the price of the index will go up. However, what happened was that the price of the index went down. And for the short case, you're betting that the price of the index will go down. But what happened was that the price of the index went up. And then there are some fees when you open a position, close a position, and then some ongoing fees. We'll look at what's included in this fees later in the course. For now, let's just say fees to GMX. Finally, min will be the minimum USD value of any position set by GMX.
So, when we take the current USD value of the collateral minus the position losses minus the fees, when this is less than some minimum amount set by the protocol, then a liquidation can happen. Other than the term position size, open interest is another important term that you need to understand before you can understand code of GMX. There are two types of open interest. long open interest and short open interest. Long open interest is the sum of all open long position sizes in a market. Remember that position size is equal to leverage times the USD value of the collateral when the position was created. You sum up all the long position sizes that are currently open and you get long open interest. In the
same manner, short open interest will be the sum of all open short position sizes in a market. Next, I'm going to make these two terms more clear by using equations. So, for the equations that I'm about to show you, you can think about it as either long open interest or short open interest. Let's calculate the open interest. The math is going to be the same for long and short. So, for this example, you can think about it as calculating long open interest. Let's say that there are n open positions. To calculate the open interest, what you'll have to do is sum up all of the open position sizes. So let's say that L by is the leverage for position I. Cabi will be the USD value of the collateral at entry for position I. I buy will be
the price of index at entry for position I. And Sabi will be the position size in USD for position I. This is equal to leverage times the USD value of the collateral when this position was created. The GMX protocol keeps track of open interest in terms of USD and open interest in terms of tokens. So let's also calculate the open interest in terms of tokens. You'll say ty will be the position size in terms of token for position I. And we saw that in the previous video this was equal to the position size divide by the price of the index at entry. Now we're ready to calculate open interest. Open interest let's denote this as s is equal to the sum of all position sizes s a bite. and open interest in terms of token. Let's
denote this as T is equal to the sum of all position sizes in terms of token. Sum all of TIS. One of the dynamic fees that you'll have to pay for keeping a position open is called funding fee. How it works is that the side with the longer open interest will have to pay fees to the smaller side. For example, if the long open interest is bigger than short open interest, then the long positions will have to pay funding fees to the short positions. On the other hand, if short open interest is larger than long open interest, then shorts will have to pay a funding fee to the longs. There are four types of open interest that are tracked by the GMX protocol. The first one is long open interest with long token as collateral.
Next one is long open interest with short token as collateral. We also have short open interest with long token as collateral. And finally, we have short open interest with short token as collateral. Let's look at some examples. For this example, we'll use E as index, WE as long token and USDC as short token. An example of long open interest with long token as collateral will be long ETH where the collateral is W. An example of long open interest with short token as collateral will be long open interest for ETH with USDC as collateral. An example of short open interest with long token as collateral will be short open interest for EV with W as collateral. And finally, an example
of short open interest with short token as collateral will be open interest for short EV with SDC as collateral. Let's take all of the terminologies that we learned so far and see how it fits inside the GMX protocol. Here I have the GMX application open and what you're looking at is the ETHUSD market. What this means is that the index is ETH. The long token will be ref and short token will be USDC. On the left, you see the price of ETH going up and down, up and down. And currently, it looks like the trend is going down. Now, there are a lot of components to be explained, but let's start with the simple part. The simplest part is the swap. Over here, you see three tabs, long, short, and swap. Furthermore, for swaps, you see
two other tabs, market, and limit. So, let's start with swap for market. Market swap means that you're swapping tokens at the market price. So this is similar to like a centralized exchange or a decentralized exchange. You're simply swapping tokens. Where do the tokens that you're swapping come from? Well, it comes from the market pools that are managed by GMX. The long and short tokens managed by GMX. These are used both to pay out the profits of positions and also used for swaps. To show you this, let's see some markets. Head over to earn and then scroll down. Here you'll see two sections GLB Bolt and GM pool. GLB Bolt we'll discuss it when we talk about liquidity. And inside GM pool
there are all these different markets. For example, if we search for E, you see that we have index E, long token W, short token USDC. We also have E index long and short token both WE and we have other markets as well. If you were to swap USDC to WE or WE to USDC, you'll be swapping tokens with this market pool. Now, there are other pools that are only used for swapping. For example, if I search for D, you can see that this pool is called swap only. The tokens are USDC and D. In this pool, you won't be able to create a long or a short position.
You can only use this pool to swap tokens. So, when you swap tokens on JMX, you're swapping tokens on the market pools. To go back to the trading page, you can either click on the GMX icon or click on trade. Okay, I'm back in the EU USDC market. Now, let's execute a swap. For this example, I'm going to swap 0.001 E and I want to swap it with USDC. So, if I were to give 0.1 E, I'll get approximately 1.91 USDC. Scrolling down, you can see some fees here. It has what's called price impact/fees.
I'll explain price impact in details later in the course. For now, you can think about it as fee for how much you make the pool imbalanced in this swap. If you were to take out a lot of USDC, then this will make the imbalance in the pool large. So, the price impact fee will also be large. Furthermore, if your swap was to bring the pool closer to balance, then you'll get a rebate. Okay? And then we also have fees over here. There's a price impact fee and swap fee on USDC. For swap fees, the fees are taken out from token in. And then we also have network fee. What this is is the fee that you'll have to pay the GMX protocol to execute an order. When we send a transaction to swap these tokens, there's going to be two transactions involved. The first transaction will
create an order to swap tokens. The next transaction, which is executed by one of the authorized accounts of GMX, will actually execute the order. when it executes the order, it's going to use the gas fee that was sent from this transaction and whatever leftover gas will be sent back to us. Okay, so let's now actually send the transaction. I'll click on swap and then I'll click confirm. Now, there's going to be two transactions that are involved in this market swap. We can check this by going to a blockchain explorer. Okay, here's a transaction that I sent for a market swap from ETH to USDC. Let's scroll down. Now notice here that I specified 0.1 E. However, the actual amount that was
sent is a little bit bigger than that. This amount is sent to the GMX protocol. In the next transaction, it will try to execute the order with this much amount of gas. If there's any leftover, then I will get a refund. Okay. And then scrolling down further, here is the actual function that was called multicol. What it's actually doing here is sending multiple transactions in a multi call. The first transaction will send the gas fee and the amount of ETH to swap. And the second transaction is a transaction to create an order for market swap. We'll look at the details of multi call later in the course. Okay, so this is the first transaction that was sent to create an order for a market swap. How about the transaction that was executed for the market swap? Well, to navigate there, I'm going to first
navigate to my account. Next, I'm going to scroll down and then click on internal transactions. Since the transaction to execute the order was not sent by me. It was sent by authorized account of GMX. And over here we see a transaction. Let's click on this. And then scrolling down, scrolling down to here, click on net transfer. So this is my account. And you can see over here that I've received approximately 1.909 USDC. Scrolling back up. So over here that is my account and you can see that this much amount of gas was refunded back to my account. Let's also scroll down and look at what function was called. Click on more details and the function that was called is called execute order. Okay, which contract did
it call? Well, going back up, interacted with this contract. Click on it and then the name of the contract is called order handler. You won't need to remember this for now. We'll come back to this later. Okay, so that was an example of our market swap. We swap 0.001 E for some amount of USDC. The transaction involved two transactions. The first transaction was to create an order and the second transaction was to execute the order. When we create an order, we also need to send some gas which is used to execute the order. And whatever excess amount of gas that we sent, we will receive it as refund. In the previous video, I swapped ETH to USDC. Let's now swap this USDC back to E using limit swaps. Limit swaps will
allow us to execute a swap if the price is at or lower than the limit price that we specify. The current mark price, which is the aggregate price of exchanges, is 1,950. One E is approximately 1,915 USDC. If you want to buy E lower than this price, then we can create a limit order for a swap. For example, if you specify 1 910 which is lower than the mark price, then this order will be executed or the GMX will try to execute this order when the mark price is at or lower than this price. Let's create a limit order for 913.
Confirm the transaction and then our order is submitted. Here's a transaction that I sent to create a limit order. You can see here that I approximately sent 1.909 USDC. And then in the following transaction which was executed by account authorized by GMX. You can see here that it executed the order and I received this much amount of beef. In this video you saw example of a limit order. Limit orders are orders to swap tokens when the price of the token is at or below the limit price that you specify. Long position means that we're betting that the price of the index is going to go above the price when we create a long position. Let's use the E market to create a long position. To
create a long position, click on the long tab. And under it, there are several other tabs. For now, we'll just focus on market. Market means that the long position will be created with the market price. The current price of E. Let's create a position for 0.01 E. Now, notice here that it says pay and not collateral. This is the token that we're paying for the collateral. Over here, you can specify the collateral. If you specify as USDC, this means that we're paying ETH to swap our ETH into USDC. If you don't want to swap, you can simply change this to W. We're putting in 0.01 E and this will be converted into W, which is our collateral. We can also
specify a leverage. Higher the leverage, the higher the risk of liquidation, but also if you're right, then you have a higher return of profits. For example, you can do 1x leverage. You can do 2x leverage all the way up to 100x leverage. Now, notice here there's what's called liquidation price. This is the price where your collateral will be liquidated. At 1x, you'll notice that the price of liquidation is roughly 1,000 USD. As we increase the leverage, you can see that the liquidation price go up. As we increase our leverage, we're taking on more risks for our collateral to be liquidated. So let's create a 2x leverage. Okay. And you can also see here that this refers to our position size in USD. If you were to put
in this much amount of ETH as collateral, it's approximately $19. Multiply this by leverage, which is roughly $38, which you can see over here. Okay. Next, we also have pool. We can specify a pool that we're going to put our collateral in. Here W USDC refers to the long token being W and the short token being USDC. Click on it and you see other options. For example, W and W. So both the long and the short tokens are ref. Then we also have WST with USDE. Moving over to the right, we have net rate and impact fees. Impact fees are fees that you'll have to pay for making the open interest of long and shorts imbalanced. If you bring the long
open interest and short open interest to a more balanced 50% long open interest and 50% short open interest, then you'll get some rebates. But for now, it looks like if you were to create a long position, then this would further bring the open interest of long and shorts to imbalance. Hence, you'll have to pay an impact fee. And then we also have net rates. You can see that some of them are negative and others are positive. What you're seeing here is the funding fees. Remember that funding fees are paid from the larger open interest to the smaller open interests. So if you were to create a long position in the W USDC pool, then I'll have to pay at a rate of this much to the short positions. And the same
goes for the last pool. For the middle pool, you can see that it is a positive rate. This means that if I were to create a long position in this pool, then I'll be able to claim some funding fees. The negatives I'll have to pay. the positives I am receiving from the other side. In this case, this will be the short positions. You can see this by scrolling up. You can see here the ratios of open interest. This shows the open interest for the pool with W as long token and USDC as short token. As you can see, there are more long positions. Hence, the open interest for long position is 51%. Whereas the open interest for short positions is 49%. the long open interest is greater than short
open interest. So this is why over here if you were to create a long position then you'll have to pay at this rate to the short positions. And if I were to switch the pools to we now you can see that open interest is 42% for longs and 58% for shorts. If I were to create a long position then I'll be receiving funding fees from users who created a short position. Okay. So going back to WESDC pool, let's create a long position. We'll pay 0.01 E and use W as collateral. Now there's other options take profit and stop-loss and you see some options, but for now I will not discuss it here. We'll take a look at this later. For now, let's focus on
trying to create a long position. Now notice that there is a fee to open currently 0.06% of the position size. This is a onetime fee for opening a position. And then finally we have network fee. This is the execution fee paid in gas to execute a order to create a long position like what we saw in the market and limit swaps. All transactions whether to create long position or short positions will involve two transactions. The first transaction is to create an order. The second transaction is to execute the order which is done by authorized account of GMX. Okay. So let's create a long E. confirm the transaction and then on the left you can see the position that I just created. This is the
position that I created 2x long for E with ETH as collateral. Over here you can see that the P&L the profit and loss after fees is currently minus. So if I were to close this position now I will approximately lose 5 cents. And why is that? Well because over here I created the position when the price of beef was 1,917. If I were to close this position now, then the price of beef is approximately 1,950. I long this position, but the direction of the price is moving down. It looks like the price of beef is going to go up a little bit. So, let me wait a little bit. See if I can make a profit. Okay, it looks like it's not happening. So, let me close the position now. Now, before I close the position, I can also
edit the collaterals. And why would you want to do that? Well, depositing the collateral will decrease your leverage. So you decrease the risk of your collaterals being liquidated. And if you were to withdraw your collateral, then this will increase your leverage. So this will also increase your risk of your collaterals being liquidated. Okay. So let's close our position. Now click on close. Let's close all of the position. So I'll put in max. Now there are several options. Remember that we put in EH as collateral. You also have a option to receive another token as collateral. For example, if you wanted USDC, then you can click on USDC and you will receive USDC when you close this position. What's happening under the
hood is it's going to first close the position and then does a market swap. For this example, I'll simply receive E. Close the position and receive E. Okay, there's a network fee that I'll have to pay. Remember that when we open this position, two transactions were executed. Closing position is also the same. There are two transactions involved. one to create an order to close a position and the next transaction is to execute the order and then there are other fees. You can see over here that there's borrowing fee, funding fee and close fee. Close fee is a onetime fee that you'll have to pay for closing a position. Funding fee since there are more long open interest than short open interest. This is the amount that I'll have to pay which is
paid out to the short open interest. And then borrowing fee. For creating a position, you'll have to pay a ongoing borrowing fee to the liquidity providers. The reason why there is a borrowing fee is to incentivize the traders to not keep their position open for a long time. If there was no borrowing fee, what I can do is maybe create a long position and then keep it open for one year until the price of beef goes up and then I want to claim the profit. By having the borrowing fee, it forces me to close the position before the borrowing fee gets too large. Okay. So, let's close this position.
Okay. And my long position is closed. So, in the previous video, I created a long position and I lost some money. Next, I'm going to create a short position and see if I can make some profit. So, click on the short tab and there are several options. We'll focus on market. Market means that we're creating a short position with the market price. Again, let's put in 0.01 E as collateral. And to do this, make sure that for collateral in you select W. If you select USDC, this means that you're paying ETH, but your ETH will be swapped into USDC. And then for the size, let's again do 2X leverage. Remember that position size is the USD value of the collateral multiplied by the leverage.
The USD value of the collateral is approximately $19. Leverage is 2. 2 * 19 is $38. Okay, scrolling down, let me explain liquidation price here. Liquidation price here behaves differently for long and short positions. Remember that when we increase the leverage for a long position, the liquidation price started out low and then approach the current price of beef. On the other hand, the liquidation price for a short position will approach the current price of beef from above. It starts high and as we increase the leverage, the liquidation price will go down and approach the current price of beef. Next, position price impact and fees. Notice here that this is positive. Well, this is because currently there are more open interest
than short open interest. So if I were to create a short open interest, this will bring the ratio of long open interest and short open interest into balance. Hence for bringing the open interest into more balanced, I'll be receiving a rebate. On the other hand, by creating a position, if the open interest become imbalanced, then I'll have to pay a fee. Next, let's look at the fees. There are fees for opening a position and network fee is the gas fee that I'll have to pay for GMX to execute my order. Okay, so let's create a short position for E. We're betting that the price of E is going to go down below the price. I create this position. Okay, and here is my position. So I created a 1.99x
short position for E. The entry price, the price when this position was created is 1,950. The current price is 1,960. The price of beef is going against my bet. Hence, currently, if I were to close this position, I will lose money. Let's see if the price of beef goes down and I can close this position with a profit. Okay, the price of beef has gone up and notice that my loss has increased. This is because I bet that the price of beef is going to go down. However, in reality, it went up. Let me close this position now. So, I'll hit close. I'll put in max for the position size and then click on close.
Okay, and my position is closed. Now, the profits of long and short positions are paid out from tokens provided by the liquidity provider. So, to become a liquidity provider, you'll need to deposit tokens into a market. To do this, click on earn, then scroll down. You'll see two sections, GLB and GM pool. Both are ways to provide liquidity to the GMX protocol. The difference is when you provide liquidity to a GM pool, you're only providing liquidity to a single market. Whereas if you provide liquidity to a GLB vault, then you're providing liquidity to a basket of GM pools. Let's first look at GM pool. How to provide and remove liquidity from GM pools since this is the easier one to understand. You can see here that there
are several markets. For example, Lidle USD. In this market, you're betting on the price of Lidle and the long tokens are and the short tokens are USDC. As a liquidity provider, you're either providing REF or USDC or both. And another example, we have the BTC USD. You're betting on the price of BTC. For the long tokens, you're providing WBTC. And for the short tokens, you're providing USDC. Since I only have ETH in my wallet, let's provide liquidity to the ETHUSD market. Where the long tokens are and the short tokens are USDC. To provide liquidity, you'll need to click on buy. In the middle, you can see the current composition of this market.
There are 50.55% of W and 49.45% or 5% of USDC. To provide liquidity, there are two options, single and pair. Single means you're paying with a single token and pair means you're providing both of the long and the short token. Since I only have E in my wallet, you'll provide single liquidity. Let's put in 0.001 E. And if I were to provide this much amount of E as liquidity, then this is the amount of tokens, the GM token per the market EUSD that I will receive. If you wanted to provide liquidity to other ETH markets, then you can select W and W or WSD and USDE. For this example, I'll be using WE and USDC. There's also fees
and price impact. Here, price impact means when you provide liquidity, if you bring the token compositions into more balanced 50/50, then GMX will reward you with some tokens. However, by adding liquidity, if you make this composition more imbalanced, then you'll have to pay a fee. So that is price impact for liquidity pools. And then we also have buy fee. This is a onetime fee that you'll have to pay when we deposit liquidity. And then network fee is the execution gas fee that we'll have to pay. Similar to the trades, when we want to deposit liquidity, it involves two transaction. The first transaction will create an order to deposit into this market. And the second transaction executed by GMX will actually execute the order and deposit our ETH as
liquidity into GMX. Okay. So let's add liquidity. Click on buy and then click confirm. Okay, the buy order was executed. So now I should have some GM token for this market. To check this, you can go back to the earn page. And from here, if I scroll down, you can now see that I have some GM tokens in this market. Let's now try removing liquidity. To remove liquidity, I'll have to click on sell. And how much GM token are we going to sell? Well, for this example, let's sell all of our GM tokens. Click on max. For doing this, I'll receive approximately 0.95 USDC and 0.005 amount of EF. Now, there's no option to remove liquidity in a single token. When
we remove liquidity with GM tokens, we're going to receive two of the tokens of the market. In this market, the two tokens are WE and USDC. So, we'll have to receive USDC and W. And again, there's fees for removing liquidity. Surprisingly, the only fee that is involved is a onetime fee for removing liquidity. So, you might be thinking, why isn't there a price impact fee? The answer is since we're removing liquidity in proportion to the current composition of the pool, when we remove liquidity, this doesn't change the current composition of the pool. Hence, the price impact will be zero. For example, let's say that we have $100 amount of GM token. And if he were to remove liquidity, we will approximately receive $50.54
of WET and $49.46 of USDC. This does not change the ratio of the balance of the pool. Hence, the price impact is zero. And again, there's also a network fee which will be the execution fee for the gas. Again, it involves two transactions. The first one to create an order and the second one that will execute the order. Okay. So, let's now remove liquidity. We remove liquidity by clicking on sell GM. Click on confirm. Okay. So now I've removed liquidity from this market. Let's go back to the earn page and then scroll down to see the list of GM pools. We deposit it and then withdrew liquidity from this market. So now we don't have any GM tokens for this market. For GM pools, there's another option called
shift. This will basically swap your tokens between GM pools. Currently I have some GM tokens inside the Lidal USD market. Let's do a shift and shift this liquidity over to EUSD. Click on shift and then let's shift all of our GM tokens inside the lid USD. Click max. Let's swap our tokens into the GM EUSD pool. Click on approve. GM tokens are USD token and we need to approve or spend. Confirm and then shift GM. Confirm the transaction again. Okay, we've shifted our GM tokens from Vital USD to ETH USD. Let's go back. And now we have GM tokens in ETHUSD market instead of vital USD. So that was an
example of shifting GM tokens. We saw examples of depositing and withdrawing liquidity from GM pools. Next, let's do the same for GB Bolts. The difference between a GM pool and a GB Bolt is that GB Bolt is a basket of GM tokens. So when we deposit our liquidity into GB Bolt, we're earning profits from the basket of GM tokens that are specified by the GMX protocol. But if there are losses in the GM pool that is inside GB, then we're also taking on that loss. In my wallet, I have a little bit of USDC. Let's try adding liquidity to the GB vault for BTC USDC. The long tokens will be WBTC and the short tokens will be USDC. To add liquidity, I'll click on buy. Okay. And here are the token
compositions of the GB Bolt. When we add liquidity to the GB Bolt, it's going to add liquidity to one of these markets. the GB vault will take ownership of this market token and when we withdraw it will burn that market token and then withdraw the liquidity from that market. So for example, let's add liquidity. Again, we have a option to add either single or pair. Let's add single. Since I have a little bit of USDC, let's add USDC. Let's put in max. Take a note over here. You can specify which market we want to put our USDC into. We can put it into the BTC USD or we can put into other markets. For example, we can put into Fartcoin USD. For this example, I'll simply pick what I know and stick
with BTCUSD. We're going to add our USDC into the BTCUSD market. It will print some market tokens. That market token will be owned by the GB Bolt and then click on confirm. Okay. And our transaction is successful. Let's go back to see how much GB tokens we have. We can see over here that we have 7.5790 amount of GB token for the BTC USDC vault. To remove liquidity, you'll click on sell and let's put in max for our GB tokens. This is the amount of USDC that we'll get and this is the amount of BTC that we'll get. Let's remove all of the GB tokens. You can also specify which pool that you're going to withdraw this JB tokens from. For example, you can
pick Fcoin or any other tokens listed here. For this example, I'll again pick the BTC USDC market pool. The JB token is a ERC20 token. So, approve spend, confirm, sell the GB to remove liquidity, then confirm the transaction again. Okay, I've successfully removed liquidity from the GB vault. What you're looking at is a diagram of some of the contracts in GMXB2 and how they connect with each other. Here, I've selected some of the contracts that I think are essential to understand how GMXB2 works. So, you won't be seeing all of the contracts in the GMX protocol or all the function calls that are made between the contracts. The contracts that you see over here are grouped into several
categories. Starting from the left are contracts that the users call. These contracts will call into other contracts where the name ends with handler. These handler contracts are also entry point for the GMX keepers. The logic of the GMX protocol is contained inside contracts that end with utils. Here you'll see logic such as storing orders and executing orders. And the orders will be stored inside a contract called the data store. Here I grouped some of the contracts that are mostly called by all of these other contracts. Some of these contract contain the core logic for how to calculate fees, how to calculate profit and loss and how to calculate the amount of tokens to be minted when liquidity is added. Finally, at the bottom, we have contracts that
deal with tokens. The tokens will be transferred between the vaults and the market tokens. When adding liquidity or creating positions, your tokens will be locked inside the market token. Okay, so that is the overview. Let's now zoom in and go into the details. Let's start with over here. The contracts that the users can call the entry contracts for the users are the exchange router contract and the GLB router contracts inside the codebase of GMX synthetics. These contracts are found inside the folder router. Let's start with the exchange router. Exchange router is a contract that a user can call to create positions, swap tokens, and to add and remove liquidity into the GM pools. Some of the functions that the user can call
are send W&T. Here WT stands for wrapped native token. On Iverchum the wrapped native token will be ref token is E. There's another function called send tokens where the user will call to send their tokens into the vault. Let's come back to this later. Okay. So going back up, the user can call the function create deposit to add liquidity into the GM pool. Create withdrawal to remove liquidity from the GM pool. create shift to shift their liquidity between GM pools and create order for opening closing a position or for swaps. And finally, there's a function called claim funding fees to claim the funding fees for their position. Now, keep in mind that when the user calls these
functions, it's only creating the order for the GMX keeper to execute the order later. We also have the GB router. The GLB router is used to add and remove liquidity from the GB vault. The functions responsible for adding and removing liquidity from the GLB bolt is the create GB deposit and create GB withdrawal. Now before calling these functions, the user also has to send their execution fee and the tokens that they want to add as liquidity. The user will have to call send W&T to send their execution fee and call the function send tokens to send their tokens as liquidity. So that's the exchange router and the GB router. Now let's take a look at the vaults. The vaults are responsible for temporarily storing the
execution fee and the tokens when the user calls send W&T and send tokens. Once the user calls these functions, both their execution fee and their tokens will be temporarily stored in one of these bolts. For creating order, tokens and execution fees must be sent to the order vault. For depositing market liquidity, tokens and execution fees are sent to the deposit vault. And likewise for removing liquidity from a GM pool, the user will have to send their market token into the withdrawal vault along with the execution fee. And finally, we have the GB vault. For adding liquidity to a GB vault, here you'll send the execution fee and the tokens that you want to deposit. For removing liquidity, you'll send the execution fee and the GB token to this
bolt. Okay, so that is the bolts. Okay, let's move on. The next part is the handlers. All of these function calls to create some kind of order will go through these handlers. So let's look at example of depositing liquidity. When depositing liquidity, this will call into the deposit handler contract. The deposit handler contract will call into other util contracts. The main contract it calls is the deposit utils to store the deposit order. And then the deposit utils is eventually going to call into the data store contract where this order will be stored. Let's look at another example. If a user creates an order to withdraw liquidity from the GM pools,
the withdrawal handler will be called and then the withdrawal handler will call withdraw utils to create an order for a withdrawal. And again, the withdrawal utils will call into the data store to store this order. And the same goes for the rest of the handlers. Once the orders are created, the next step is for the GMX keeper to execute the order. The GMX keeper will execute a order by calling one of these contract. These handler contracts can either be called by the exchange router GB router or an authorized account of GMX. For the keepers, these are the entry contracts where it will execute the rest of the code. When the keeper calls into one of these contracts to execute an order, the first thing that happens, it will set
the prices of the tokens for the oracle. The prices of the tokens are provided as inputs when the keeper calls into these contracts. After the keeper is done executing the orders, the prices that are set inside the oracle will be reset to zero. The reason why it sets the prices in the oracle is so that these contracts over here can get the price of the tokens that they need. When the keeper calls one of these contracts, it will call into the contracts that contain the logic for the order. For deposit, this will call into execute deposit utils. For withdrawal, it will call into execute withdrawal utils. For orders, there's the execute order utils.
And for GB deposits and withdrawal, there's the GB deposit utils and the GB withdrawal utils. Now, for orders, there are several types of orders. You can create a order to open a position, close a position or you can create a order to swap tokens. So the logic of execute order utils is further split into several parts. For example, we have the increase position utils when you're opening a position, decrease position utils for closing a position or decreasing the size of a position. And then we also have swap utils which is responsible for transferring tokens between the vaults, market tokens, and the users. When the orders are executed, it's eventually going to call into these
contracts over here. First of all, it has to remove the order. So, it'll call into the data store to remove the order. And if it was to create a position, then it will store the position inside the data store. Furthermore, calculation of the fees and position profit and loss are done by these contracts. And to understand how pricing and fees are calculated in GMXB2, these are the contracts that you'll need to study. And finally, let's look at the GB token and the market token. Let's say that a user deposits liquidity into a GM pool. So, they're specifying one of these markets to add liquidity into. Most of these markets are backed by long token being or WBTC and the short token being USDC.
Now, there are other markets where both the long and the short are backed by the same token. For example, there's a market where both the long and the short token is web. There's also a market where the index is not equal to the long token. For example, the Doge USD market. The index is Doge. The long token will be ref and the short token will be USDC. All of the market tokens will control two tokens, a long token and a short token. Usually, the long and the short tokens are different, but sometimes they can be the same. When adding liquidity to the GM pool, market tokens are minted for depositing one of these tokens into the appropriate market. When removing liquidity, these market tokens will be burnt and these tokens will be sent to
the user. Once you understand market tokens, GB tokens are also easy to understand. GB tokens represent a basket of market tokens. So, when you're adding liquidity to a GB vault, it first adds liquidity to the market token, mint some market token. And for the amount of market token that was minted, it will mint a GB token. The owner of the market token will be the GB token. The GOB token that was minted will be sent to the user. Next, I'm going to explain how the tokens are transferred from the bolts. Remember, when a user creates an order, either for a trade or for adding or removing liquidity, the tokens are sent to the bolts along with the execution fee. Let's first take a look at the tokens. Where do they go from
here? When the keeper executes the order by calling into one of these contract, these contracts are going to call into the utils contracts. Along the way, it's going to take the tokens that are inside the vault. Depending on the action, it will either transfer it over to the market token or send the tokens out from the market token. So, for example, let's say that we create a deposit order. Deposit liquidity into the GM pool. Currently, the tokens and the execution fees are locked inside the deposit vault. Next, the keeper executes this order to actually add liquidity into the market. It is at this point that the tokens inside the deposit vault will be transferred over to the market token.
And likewise, if there was a swap, the tokens will first be locked inside the order vault. The keeper will execute the order and the tokens that are inside the order vault will be transferred into the market token. Since this is a swap, there will be a token in and there will be a token out. Token out will be sent to the user. And finally, let's look at execution fee. Remember that when a user creates an order, their execution fee will also be locked in one of these vaults. After the keeper is done executing the order, it will eventually call into the gas utils contract. This is a contract that is responsible for paying the keepers for executing the order and then sending any excess amount of execution fee back to the user. Okay, this was an overview of how the GMX B2
contracts interact with each other. When you create a long or a short position, you can specify the collateral. For example, in the EUSD market, we can decide to long ETH and specify our collateral as WE or USDC. And likewise, if you were to short ETH, we can specify our collateral again as WE or USDC. In this video, I'll explain why you might want to choose one over the other. What we're going to analyze is the payoff diagram of the four strategies. Long ETH with W as collateral. Long ETH with USDC as collateral. Short ETH with W as collateral. And short ETH with USDC as collateral. Now, what is a payoff diagram? It's a diagram that represents the amount of profit or the loss that
we'll make depending on how the price moves. On the horizontal axis, we'll plot the price of E. On the vertical axis, we'll plot the profit and the losses. We'll keep this simulation simple and we'll say that all of the fees are set to zero. The entry price of the index, let's say, is 100 USD. The price of ETH at entry is 100 USD. Now, we're going to have two collaterals to simulate with ETH as collateral and USDC as collateral. For E as collateral, let's say that we bought this E when the price of E was 50 USD. That's P 0. The amount of E that we bought, let's keep it simple and say, is equal to 1. And then the amount of USDC collateral that we have, let's say, is 30 USDC. We assume that 1 USDC is exactly equal to 1
USD. So 30 USDC is exactly equal to 30 USD. And then we'll label E as the position size in terms of tokens. Okay, let's start by plotting the entry price I Z. We're going to analyze several options. Creating long positions at this entry price and creating short positions at this entry price. Our goal is to combine the payoff diagrams of longing or shorting ETH with different collaterals. The answer might not be obvious, but if we break this problem down into smaller, simpler questions, then at the end, we'll have our answer.
So, let's start by analyzing the payoff diagram of creating a long position. For now, we won't consider what collateral we're using. If we were to create a long position when the entry price is at 100 USD, this is the payoff diagram. If the price of the index, think price of E, moves above 100 USD, then we make a profit. Everything in the green region is profit. Assuming that fees are all set to zero. And if the price of the index moves below the price of entry, then this is a loss that we all have to pay. This is the region highlighted in red. This is the payoff diagram for creating a long position. Now, if you were to create a leveraged position, all we have to do is change this position size in terms of tokens. If we increase
this, you'll see that the line also change. The slope becomes more steep as we increase our leverage. This tells us that with little price movement in the positive direction, we can make a lot of profit. And likewise, little price movement in the opposite direction, we lose a lot of money. For simplicity, let's set the leverage equal to one. Okay, so this is the payoff diagram of a long position with 1x leverage. How about the payoff diagram of a short position? If we were to create a short position with 1x leverage, this is what it would look like. The entry price is 100 USD. If the price of the index goes below 100, then we make a profit. If the price of index reaches zero, then we make a max profit of 100 USD. On the other hand, if the price of index goes
above 100, then we lose money. The amount of money that we can lose is unbounded since the price of beef can in theory go to infinity. The region highlighted in green is a profit for the short position. If the price of the index goes below the price of entry, then this is our profit. The region highlighted in pink is a part where we will make a loss. If the price of the index goes above the price of entry, this is all losses that we'll have to pay. Okay, so these are two simple payoff diagrams of a long position and a short position. Next, let's take a look at the payoff diagrams of our collateral. Let's start with cash. We said that we have 30 USDC as collateral.
And what is the payoff diagram? Well, it's simple. It's simply a straight line. Why is that? Whether the price of Eevee goes up or down, you do not lose your cash or you do not gain any cash. Hence, it is a straight line. How about the payoff diagram of holding ETH? The payoff diagram of holding ETH depends on the price that we bought ETH and the amount of E that we bought. For example, if you bought one ETH when the price of E was 50 USD and the current price of E is 100 USD, then our profit is 50 USD. If we bought two EETs when the price of one ETH was 50 USD and the current price of ETH is 100 USD. If we were to sell both of our ETH, then our profits will be 100 USD. So that is the payoff
diagram of ETH. With these four simple payoff diagrams, we can now analyze the payoff diagrams of different strategies. Let's start with longing ETH with USDC as collateral. What we simply need to do is combine the payoff diagram of longing E with having USDC as collateral. So combining these two lines, what do we get? The payoff diagram is exactly the same as payoff diagram of longing E except the line is shifted to the left. The way to understand this graph is that at entry there is no profit or loss. So the amount of cash that we have is the amount of USDC we have 30 USDC. If the price of index increases, the amount of money we'll make is described by this
long position. Hence, the slope doesn't change. The amount of money that we'll lose is the same as the long position. When the price of index decreases by $30, then we will have to spend this $30 in cash to pay off our losses. Hence, the amount of cash that we'll have is zero. So, this is the payoff diagram of longing ETH with ESDCS collateral. Next, let's take a look at the payoff diagram of longing ETH if with ETH as collateral. What we'll need to do is combine payoff diagram of longing E with payoff diagram of holding E. And what do we get? Again, we get a payoff diagram that is linear. However, the slope is larger. And this is because we're combining these two lines. Hence, the slope becomes larger. If the price of E
increases, then we make profit from our long position and also for holding E. However, if the price of E decreases, then we lose money from our long position and also the ETH that we're holding losses its value. Hence, the slope is steeper for longing E with E as collateral compared to longing E or holding E. Okay, let's move on to the payoff diagrams of shorting a position. Let's look at shorting E with USDC as collateral. The payoff diagram that we'll have to combine is shorting E with the payoff diagram of holding cash.
Combining these two, what do we get? Shorting ETH with USDCS collateral. This is what we get. The slope is the same as shorting one E. The only thing that is different is that the line is shifted to the right. If the price of the index is equal to the price of entry, then there's neither profit or loss to be made. The amount of cash that we have is simply the amount of collateral that we have 30 USD. If the price of index increases by 30 USD, then our loss is 30 USD. This loss is covered by the amount of cash that we have. Hence, at this point, the amount of cash that we'll have is equal to zero. And finally, let's take a look at the payoff diagram of shorting ETH with ETH as collateral.
So, we'll combine the payoff diagram of shorting with the payoff diagram of holding ETH. And for simplicity, we'll first move the price of ETH, the price that we bought the E, let's say, is exactly equal to the entry price. This will simplify our analysis. And then once we understand that, we can move this back over to 50. Here's the payoff diagram of shorting ETH with ETH as collateral. Now, you might be surprised that this time we get a flat line. In financial terms, this is called delta neutral. Since whether the price decreases or increases, our payoff diagram is always flat. Our payoff is neutral to the delta in the prices.
Hence, it is called a delta neutral strategy. Now, let's analyze why shorting ETH with E as collateral will produce a delta neutral strategy. Well, by creating short for one E position, if the price of index decreases, then we'll make a profit. However, since our collateral is in E, our collateral will lose value in terms of USD. The profit from our short position offsets the losses from holding E as collateral. Hence, it is equal to zero. And the opposite is also true. If the price of index increases, then the value of our E collateral increases. However, we need to pay for the loss for our short position. The profit from holding on to EF offsets the loss for holding on to the short position. As a result, we get
a payoff diagram that is always equal to zero. So this is example when we created a short position where the entry price is 100 USD and we also bought E when the price of E is 100 USD. Now let's consider what happens if you bought E at a lower price for example at 50. Then the payoff diagram is similar except it is shifted up. We bought at 50 and if he were to sell at 100, then our profit is 50 USD. If the price of EF increases above the entry price, then we make more than $50 in our profit for holding on to E. However, we also need to pay for the loss for having a short position. These two cancel out and the payoff diagram is flat. The same is true if the price of
the index decreases. We make profit from our short position. However, the USD value of our collateral decreases. Combining these two, we get a payoff diagram that is flat. And finally, let's see all of the payoff diagrams that we've discussed so far. Here's a simple long. Here's cash. Here's holding on to ETH. Here's longing ETH with ESDC as collateral. Here's longing ETH with ETH as collateral. And then here's shorting ETH with ESDC as collateral. And finally, here's shorting ETH with ETH as collateral. Now, keep in mind that all of this simulation was done assuming that all of the fees are equal to zero.
In reality, the fees are never equal to zero. So, the payoff diagram will slightly look different from this. There are various fees involved with trading on GMX. For example, to create either a long or a short position, there's the network fee, which is the gas fee that you'll have to pay for your order to be executed. There's also a one-time fee for opening and closing a position. Furthermore, to keep the position open, there's the borrowing fee and the funding fee. There's also price impact which rewards you for bringing the pool into more balance and penalizes you for bringing the pool into more imbalanced for swaps. There's also the price impact and there's a swap fee on token in what's not shown here is the UI fee fee for using this user interface. The common fees between opening closing a position and swaps are the execution fee
here it's called network fee and the price impact. Furthermore, if you're using this user interface then there's a UI fee. Most of the fees are straightforward to understand. However, the price impact, the borrowing fee, and the funding fee need further explanation. So, starting from the next video, I'll explain more about price impact. The purpose of the price impact is to keep the pools balanced between long and shorts. Here, long and short means different things, whether it is a swap or creating a position. For swaps, this long will refer to the USD value of the long tokens and shorts will refer to the USD value of the short tokens in the pool. for creating or closing positions.
Long will refer to the long open interest and short will refer to the short open interest. If an action either a swap, opening or closing a long position, opening or closing a short position or depositing liquidity reduces the imbalance, then this is called a positive impact and there will be some kind of rebate. On the other hand, if your action increases the imbalance, then this is called a negative impact and you'll have to pay some kind of penalty. Imbalances measured in different ways depending on your action. The positive impacts are rewarded and negative impacts are penalized also in different ways depending on the action.
So we'll look at imbalance. Positive impact and negative impact for swaps, long and short positions and for depositing liquidity. Let's start with swaps. For swaps, imbalance is defined to be the difference of the USD value of the long tokens in the pool and the USD value of the short tokens in the pool. Positive impact will result in more token outs and negative impact will result in some of the tokens being deducted from amount in. As a result, in both cases, you either receive more token or receive less token. A positive impact will give you more token out and negative impact will give you less token out. The logic for this code can be found inside the contract swap utils.
Swap. Let's take a look at this function inside the GMX syntax code repo under the folder contracts and then furthermore under the folder swap. The contract is called swap utils. The function is called underscore swap. First, it calculates the price impact in terms of USD by calling the contract swap pricing utils and the function get price impact USD. Once this price impact USD is calculated, next it handles the case whether it is a positive impact or a negative impact. for a positive impact. You can see here that to amount out to the amount of token that's going to go out, some amount is added. Price impact amount. From the price impact USD, a price impact amount is calculated and then added to the amount of tokens that's going to go out. For a negative
price impact, you can see here that from amount in a price impact amount is deducted. Since there's less amount coming in, there will be less amount that will be going out. So that is how price impact works for slots. Next, let's take a look at how price impact works for long and short positions. The imbalance for long and shorts is defined to be the difference of the long open interest and short open interest. Remember that both long open interest and short open interest are in terms of ESD. For the rewards and penalties of price impact, we'll need to consider two cases for opening a position and closing a position. For opening a position, furthermore, there's two cases. Is it a long position or is it a short position?
For a long position, when there's a positive impact, the size delta and tokens will be increased. Remember that when you create a position, you specify a position size and then from the price of the index at entry, the size in terms of token is calculated. This size in terms of tokens will be increased for a positive impact. And you'll see later that this has the same effect as lowering the execution price. If you were to create a position, then this means that lowering the entry price for a long position. And for a negative impact, there will be a decrease in the size delta and tokens and this will result in a higher execution price. For opening a short, the idea is the same as opening a long position. However, we need to manipulate the price in the opposite direction. For a positive impact, we decrease the size delta in
terms of tokens. This has effect of setting the execution price higher. And for negative impacts, we increase the size delta in tokens. And this has a effect of lowering the execution price. And then for closing a position, if there's a positive impact, you'll receive more tokens. The token that you receive depends on what you specify. And finally, for negative impact, you'll have to pay from the collateral. Okay, where do we find the code for all of this logic? The logics are contained over here. So let's take a look at one at a time. Let's start by looking at when you open a position. The logic is contained inside the function get execution price for increase under the contract position utils. The position utils contract is located under the folder positions position utils. The function that we're interested now is
called get execution price for increase. And first you'll notice that it calls a function called position pricing utils dot get price impact. It will calculate the price impact in terms of USD. Later in the course, we'll look into details how the price impact is calculated. The next part calculates the price impact amount. Based on the price impact USD, it divides this price impact USD by the index price. This amount will be added to the size delta in tokens. If the price impact was positive, then this number will be positive. And if the price impact was negative, this number will also be negative. Okay. And then scrolling down, here's the most important part of the code to understand how price impact for creating a position either rewards or penalizes the action.
If the position is a long to the starting size delta in tokens, add price impact amount. Again, if the price impact was positive, then this will be a positive number. So this will increase the size delta in tokens. If price impact was negative, then this will decrease the size delta in tokens. Otherwise, if it is a short position, if it is a positive impact for creating a short position, then minus it from size delta and tokens. Otherwise, if it is a negative impact, then negative minus negative will become a plus. So the size delta and tokens will be increased. Okay, let's now see why either increasing or decreasing the size delta and tokens has a positive or negative effect on your position. I've split the screen into two parts. On top, you'll see a function called get position P&L
USD, which is located under the same contract position utils. This function is called to calculate the profit and loss of a position when the position is closed. And inside here, you can see here how some of the profit and loss is calculated. We first calculate the current position value size in tokens multiply by the current price of the index. And if it is a long position then we take this position value and then minus it with the size in USD which was set when the position was created. If it was a short position then it is the opposite. Take the size in USD and then minus it with the position value. Going back if it was a long position and the price of the index has increased compared to when you created the position then this position value will
be greater than size in USD. So you'll make a profit. And similarly for short positions if the price of the index has decreased since the position was created then this position value will be less than sizing USD. So again you'll make a profit. Okay. So that is how the profit and loss is calculated. Now let's take a look at over here how does changing the size delta in tokens for price impact affect this profit and loss above. Well if the size delta in tokens is increased. You can see over here that this size in tokens is also increased. So the position value will be increased.
Hence this number over here will be larger. Your profit will be larger. On the other hand, for negative impact for opening a long position, this value will be decreased since the size delta and tokens will also be decreased. In this case, this profit will be decreased and it can also turn into a loss. And the same is true for opening a short position. When we're creating a short position, let's say that there's a positive impact. Size delta and tokens will be decreased. Hence, this position value will be decreased. So the profit will be increased. However, if there's a negative impact, then this size delta in tokens will be increased. So this value will also be increased and the profit will be decreased. So that is how changing the size delta in tokens has an effect on the position's profit and
loss. Okay. How about for closing a position? You either receive token or pay from the collateral. The logic is located under the contract decrease position collateral utils under the function process collateral. The contract decrease position collateral utils is located under the folder position inside the function process collateral. You can see here that price impact ESD is returned from the function get execution price for decrease. Then scrolling down if the price impact ESD was greater than zero then it calculates amount to be deducted from the pool and then this amount is allocated to you. So for positive impact you'll receive some tokens. Scrolling down further, if the price impact was negative, then for the price impact ESD, you'll have to pay
from your collateral tokens. This is done by calling an internal function called pay for cost. And finally, let me explain what imbalance for depositing liquidity is and the effects of positive and negative impacts. The imbalance for depositing liquidity is measured by taking the USD value of the long tokens in the bull and then taking the difference with the USD value of the short tokens in the pool. For positive impact, additional liquidity provider tokens will be minted. The liquidity provider tokens in this case is the market token. And for negative impacts, these will be deducted from the amount of tokens that came in. The code for this logic can be found in the contract execute deposit utils under the function execute deposit. The execute deposit utils contract is located under the folder deposit. The function execute
deposit is called once for the long token and once for the short token. Inside this function, you can see here that if price impact USD was greater than zero, then to the amount of market tokens to be minted, it adds for the amount of price impact amount. Otherwise, if the price impact was less than zero, then it deducts the negative price impact amount from either the amount of long or short token that was deposited. In this video, I explain how imbalance is measured for different actions, how positive impact is rewarded, and how negative impact is penalized depending on your action. Next, I'm going to explain the formula for how price impact is calculated. But before we do that, I first need to explain two terms, same side and crossover. Same side means that the imbalance remains on the same side after
an action. For example, let's say that the long is less than short and the next long after an action is also less than the next short. For a swap, this long will be the USD value of the long tokens and the USD value of the short tokens. And for positions, this long will refer to the long open interest and short will refer to the short open interest. As another example, let's say that the imbalance is there are more longs than shorts. Also, after an action, the next long is also greater than or equal to the next short. This is what same side means. So, once you understand what the same side is, crossover is easy to understand. Crossover basically means not the same side. We're now ready to understand the formula for price impact.
Let's say that D0 is the initial imbalance in USD and D1 is the next imbalance in USD. Now the way the price impact is calculated is different whether it's a same side or a cross over. Let's start with same side. If D 0US D1 is positive then this means that the next imbalance is less than the current imbalance. If D 0US D1 is negative then this means that the next imbalance is greater than the current imbalance. So depending whether the difference of the difference is positive or negative there is a different impact factor. This impact factor f is used in the next part of the formula. For a same side, the price impact is defined by taking this D0, the initial imbalance, raising it to the power of B, some
exponent factor, and then multiplying by the impact factor F, and then minusing it with D1, the next imbalance in USD, taking it to the power B, multiplying it by the impact factor F. For a crossover, the impact factor is calculated in a similar way to the same side. However, there's a slight difference. For a crossover, the price impact is calculated by taking this same equation and replacing this impact factor. The first f will be replaced by what's called positive impact factor and the second f is replaced by negative impact factor. The code for this formula can be found in the links over here. The code is pretty straightforward, so I'll omit the explanation of the code. Here's the graph of the price impact. I'll first
explain how to read this graph and what same side and crossover price impact looks like. In this graph, on the horizontal axis, we map the imbalance. For example, for a position, the imbalance is defined as long open interest minus short open interest. Zero on the x-axis will mean that long open interest is exactly equal to short open interest. The initial imbalance is set to x0 equal to 2. The difference between long open interest and short open interest is equal to two. On the vertical axis, we map the price impact.
Now, keep in mind that all of these coordinates are in terms of USD. Long open interest and short open interest are in USD terms. So, the x-axis is in terms of USD. The price impact is also in terms of USD. So, this y-axis is in terms of USD. So, let's say that the initial imbalance is 2. X0 equal to two which you can see over here. Now what does it mean for a same side price impact? Well, let's play around with this number. Let's say that X1 represents the next imbalance. X0 represents the current imbalance and X1 represents the next imbalance. Remember that same side imbalance means that if the long is greater than or equal to short, then in the next imbalance the
long is also greater than or equal to short. In this case, what would it look like? Currently the imbalance is equal to two and the imbalance is defined as long open interest minus short open interest. There are more long open interest than short open interest. So what does it mean for the next imbalance to also have larger long open interest than short open interest. This means that our next imbalance must stay on the positive side of the x-axis. For example, if we move it to here, this is on the same side. This will also be on the same side. And furthermore, the next imbalance of 2.2 is also on the same side. This is a case of initial long open interest greater than or equal to
short open interest and the next long open interest also greater than or equal to the next short open interest. For a same side, there's also the other case for the current short open interest greater than or equal to the current long open interest and the next short open interest greater than or equal to the next long open interest. What would this look like on a graph? Let's start by mapping the initial imbalance. So we have more shorts than longs. We can visualize this by moving this indifference let's say to minus2. What this express is that there are more short open interest than long open interest. Okay. Now what would same side mean here? Since currently we have more shorts than longs. The next imbalance should also have more shorts than longs.
For this to happen this point must be less than or equal to zero. This will be a same side and this will be the same side. However, if we cross over this x-axis equal to zero, then this is no longer the same side. Initially, we have more shorts than longs. But over here, we will have more longs than shorts. Hence, it is no longer same side. And then going back to let's say a imbalance of two, there are more longs than shorts. This will be the same site. We still have more longs than shorts.
However, this will not be the same side. This will be a crossover since initially we have more longs than shorts. But in the next imbalance, we have more shorts than longs. Okay, so that is what same side and crossover mean. Next, I'm going to highlight some of the characteristics of this price impact graph. The first thing that you'll notice is that for negative price impact, so this will be the blue line below y equals to zero. That will be negative impact. For negative impacts, you see that the line sharply drops. For example, you can see that a small change in the next imbalance produces a large negative price impact. And the same is true on the opposite side. So what this means is that the negative price impact is penalized heavily. The other characteristic of the price impact is
that for positive impacts, it favors the next imbalance to be on the same side over having it crossed over to the other side. For example, let's say that the next imbalance is on the same side and it is equal to 0.8. In this case, the impact will be positive 1.008. 008. However, if the next imbalance crosses over to the other side and the difference, let's say is negative 0.8. In this case, the price impact will be negative 0.08. The magnitude of the next imbalance is the same in both cases 0.8. However, for the same side, the price impact was positive. The price impact when the next imbalance crossed over is negative. So from this example you can see that the price impact favors the
next imbalance to be on the same side over the next imbalance crossing over to the other side. The way that price impact is calculated for a swap and for position is different. For swapping it is located under swap pricing utils and for positions it is located under position pricing utils. However in both cases there is a mention of virtual inventory. You can see it over here. First swap pricing utils and for the function get price impact USD inside position pricing utils. Here's a mention of virtual inventory again. So here I'll explain what virtual inventory is. Virtual inventory means different things for a swap and for positions. For swaps it keeps track of two virtual inventories. One for the total amount of long tokens in the GMX protocol and one for the total amount of short tokens in
the GMX protocol. Remember that in GMX there are different markets and most of them are either backed by WE USDC or WBTC and USDC. The virtual inventory for a long token if it was will keep track of the total amount of weft that is inside the GMX protocol. For shorts, it will be the total amount of USDC in the GMX protocol. The virtual inventory for a position is similar. However, instead of tokens, it'll keep track of the long open interest and the short open interest. Again, there are multiple markets, different long open interest and different short open interest. The total of these open interest will be kept tracked by virtual inventory for a position. Furthermore, this virtual inventory is a int 256. If the virtual
inventory is positive, then this is interpreted as more short open interest than long open interest. Otherwise, it is interpreted as more long open interest than short open interest. You can find the exact code for this logic inside the function get next open interest for virtual inventory under the contract position pricing utils. Take a look at over here. If virtual inventory is greater than zero, then set it equal to short open interest. Otherwise, set it equal to the negative of long open interest. Okay, that is virtual inventory for swaps and for position.
But what is the purpose of a virtual inventory? The purpose of a virtual inventory is to help prevent price manipulation. For example, let's say that we have two markets where the long token is web and the short token is USDC. And let's say that we were going to swap a lot of USDC for W. If there was no virtual inventory, then we can avoid paying some of the price impact fees by splitting our trade between different markets. By having a virtual inventory, the price impact is calculated both for the markets that are involved in the swap and with the virtual inventory. So whether you swap 100 USDC with a single market or with multiple markets, the price impact fee that you'll have to pay is the larger of the price impact fee between the markets
and the price impact fee of virtual inventory. We can also imagine a similar situation for positions. Let's say that we have two markets where the price of the indices are similar. The price of the indices move in a similar behavior. But however, since we have two markets, we can replicate our positions in two markets and decrease the price impact. However, by having a virtual inventory, you won't be able to split your positions into two different markets. So, that is the purpose of virtual inventory. For swapping tokens, there's a price impact, execution fee, and then there's also a onetime fee on the token that's going in. And then what's not shown here is the user interface fee.
The code for calculating the swap fee and the user interface fee is located under the contract called swap pricing utils under the folder pricing and the name of the function is called get swap fees. The first part of the code gets the fee factor. This is the fee factor that is to be multiplied by the amount of token that came in. Different actions may have different fee factors. Here we have one for swapping. Here we have one for shifting liquidity. Here we have one for depositing liquidity. And here we have one for withdrawing liquidity. The amount of fee to be collected is calculated by taking this fee factor and then multiplying by the amount that came in. The next part is calculating the UI fee. Take some UI fee factor and then multiply by the amount. Total fees are the fee amount, the amount that was
multiplied by the fee factor and the amount that was multiplied by the UI fee factor. Let's look at the fees that are involved for opening closing a position and for maintaining a position open. The fee for opening a positions will involve price impact and there's also a onetime fee for opening this position. The same goes for closing a position. You'll have some price impact, network fee, and a onetime fee for closing a position. Furthermore, for keeping the position open, you'll have to pay a borrowing fee and a funding fee depending on the market activity. The funding fee is continuously changing. Depending on the market activity, you'll receive funding fees, and other times you'll have to pay your funding fees from your position.
The way that borrowing fees and funding fees are calculated is complex. So in the next few videos, I'll explain more about borrowing fees and funding fees. Borrowing fee is paid out from a trader who created a position to the liquidity provider when that trader closes the position. The borrowing fee to be paid increases over time and the rate at which it increases changes with the market activity. The purpose of the borrowing fee is to both incentivize liquidity providers to provide liquidity and for the traders to close their position in a short time. If there is no borrowing fee, then a trader can keep their position until they can make a profit. Now, if the borrowing fee, they have to decide to see if they can make a profit in the future or close their position and pay the borrowing fee. The way that the borrowing fee for a
position is calculated might be confusing if you are not already familiar with this algorithm. So, in this video, I'll explain the math behind how the algorithm works. So, let's say that we have the borrowing fee rate, also called the borrowing factor, that is different every second. Let's also say that Alice created a position size of 100 from time t = to 2 and then closes his position at time t = to 5. Now let's calculate how much borrowing fee Alice owes to the liquidity provider. She created a position size of 100. From time t2 to t3 that's 1 second.
The borrowing factor is over here denoted as r2. Her size is 100 and the borrowing factor per second per position size is R2. That's the amount of borrowing fee that Alice owes to the liquidity provider after 1 second. How about in the next second from time T3 to T4, her position size is still equal to 100 and the borrowing factor per second per position size is given by R3. So now in addition to the previous second, she now owes the borrowing fee of 100 multiplied by R3. And then the same goes for the last second she has her position open. Position size is 100. The rate per second per position size is given by R4.
In total, this is the amount of fee that Alice owes to the liquidity provider for opening a position size of 100 for 3 seconds. We can generalize the equation for borrowing fee for all users. Let's denote the position size of user U at time I as S U I. Then the borrowing fee of user u from time k to n is given by the summation from i = k to n minus one. For each second multiply the position size by the borrowing factor per second per position size. So now we have equation to calculate the borrowing fee for all users at all times. But we cannot use this equation inside our contract to calculate the borrowing fee of all users. The problem is at every
second we'll need to calculate this for all users which uses too much gas. So next I'm going to show you a simplification of this equation that is used inside the code of GMX to calculate the borrowing fee of all users. Let's begin by simplifying borrowing fee of Alice. The most important thing about this simplification that I'm about to show you is that the position size of Alice is a constant 100 for this 3 seconds. So we can pull out the 100 and this becomes 100 * R2 + R3 + R4. Multiply her position size by adding all of the borrowing rates while her position was open. Next, we rewrite this part of the equation. Add up all of the rates from time t = to0 to t = to 4.
Since now we have too much rates in here, we need to subtract them. Subtract all of the rates less than t = to 2. Now, why did I show you this? Well, by writing it this way, we can now calculate the borrowing fee of every user. So, all we have to do to calculate the borrowing fee of any user is to record this number when they open the position and then calculate this number when they close the position. Taking the difference will give us this part of the equation and we can calculate their borrowing fee. In general, if you wanted to calculate the borrowing fee of a user U with position size C from time K to N, then their borrowing fee is given by multiplying their position size C multiply by the difference of the
summations of the rates. Sum up all of the borrowing rates up until time n minus one and then subtract it with all of the rates summed up to time k minus one. This value on the right will be available when this user creates a position and this number will be available when the user closes the position. This is the form for how to calculate the borrowing fee that you'll see inside the code of GMX. The code for how to calculate the borrowing fee for a position is located under contract market utils under the function get borrowing fees. Remember that to calculate the borrowing fee for a position, we multiply the size and USD of the position by the difference of the sum of the rates. This sum of the rates is called cumulative borrowing factor.
So over here you can see that it calculates the current cumulative borrowing factor with the cumulative borrowing factor that is stored when the position was last updated called position.barring factor. Take the difference and then multiply by the size of the position. This is how the borrowing fee is calculated for any position. For the borrowing fees that we calculated we assume that the size of the position is a constant. However, in reality users will be updating their position. So the size of their position is not a constant. But this problem is easily fixed by updating how much borrowing fee the position owes before the size of the position is updated. So every time a position is updated, it will first update the cumulative borrowing factor and then it will
calculate the amount of borrowing fee that a position owes, subtract that fee from the collateral, and then update the borrowing factor for that position. This is the same whether you increase the position or decrease the position. So what you're looking at here is highlight of some of the functions that are called when a position is increased and a position is decreased. When order to increase a position is executed, it first updates the cumulative borrowing fee. This is done inside the contract called position utils. The function is called update funding and borrowing state. Inside here, it's going to call another function called market utils.update cumulative borrowing factor. This will update the cumulative borrowing factor to its latest value.
The borrowing fees for a position is calculated inside the function called process collateral inside the contract increase position utils. Once the borrowing fee is calculated over here, it would deduct the borrowing fee from the current amount of collateral and then it would update the amount of collateral that is locked inside the position by calling the function set collateral amount. The latest cumulative borrowing factor is retrieved by calling market utils get cumulative borrowing factor. And then the total borrowing fees is updated. And finally, the borrowing factor for the position is updated. This is an example of how the borrowing fee is calculated and updated for a position when the position increases. I'll leave it up to you to check how the borrowing fee is updated when a position size is decreased.
Again, you'll notice the same pattern. First, update the cumulative borrowing factor to its latest value. calculate the current amount of borrowing fee that is owed and then subtract it from the collateral and also set the borrowing factor of the position to the latest value. Let's look at how the next cumulative borrowing factor is calculated. The way that the cumulative borrowing factor is calculated is a little bit different from the math that we've seen. In the end, you'll see that the math and the code are equivalent. The difference is the code is optimized to save gas. The first thing it does is calculate durations in seconds. duration since the last time cumulative barring factor was updated. And then we call another function called get barring factor per second to get the barring factor per second. We'll look into
details what this function does in a later video. For now, just think we call this function and we get some borrowing factor per second. The current cumulative borrowing factor is stored in the data store of g ofx. This function will get the current cumulative borrowing factor. In the math that I showed you, we would take this borrowing factor per second and then sum it up for each second. If this borrowing factor per second is the same for some time interval, then we can simply multiply it. So this is what's going on over here. Take the time duration since the last time it updated during this duration. The borrowing factor per second is the same. So instead of running a loop to add it, simply multiply it and then add it to the previous cumulative borrowing factor.
This is how the cumulative barring factor is updated to its latest value. The code for the function get borrowing factor per second is complex. It calls into multiple functions. So here I've created a summary of what functions it calls and I've also created a formula for how to calculate the borrowing factor per second. But before we can understand this, I first need to explain what usage factor is. And before I explain usage factor, let me first explain reserved USD. The function get reserved USD calculates the total amount of USD that is required for all of the position on one side. In other words, it will calculate the total amount of USD that is needed if all the one side of the positions were to close. For example, if all of the long positions
were to close, how much USD do we need? And likewise, if all of the short positions were to close, how much USD are needed? For the long position, we get the open interest in terms of tokens. Then we multiply this by the index price. That is the total amount of USD that is needed. And the way to understand this is let's say that all of the long positions were created when the price of the token was equal to zero. Now if all of the long positions were to close their profit will be the long position size in terms of tokens multiplied by the current price of the index which you can see over here. And for a short position the maximum profit can be reached when the price of the index is equal to zero. Therefore, if you sum up all of the short positions,
then we get the maximum amount of USD that is needed to pay out the short positions. This is what the function get reserve USD is doing. Calculate the maximum amount of profit that needs to be paid out to one side if all of the position on that side is to be closed. The usage factor is defined to be the maximum of reserve usage factor and open interest usage factor where reserve usage factor is defined to be the reserved USD divided by the maximum reserve. This maximum reserve is calculated by taking the pool USD, the USD value of the long and short tokens in a pool and then multiplying it by some reserve factor. Take the current reserved USD and then divide it by the max reserve. This is reserve usage factor. Then we also have open interest
usage factor. Open interest usage factor is equal to the open interest divided by the max open interest. This usage factor is later used to calculate the borrowing factor per second under one condition. And this is if the optimal usage factor is not equal to zero. The function borrowing factor per second has two conditional statements. If the optimal usage factor is not equal to zero, then the borrowing factor per second is calculated by another function called get kink borrowing factor. And inside here it will use a logic for calculating the usage factor that we just discussed.
Otherwise, if this optimal usage factor is equal to zero, then the borrowing factor is calculated by this equation. Take the reserve USD, raise it to some power, divide by the USD value of the pool, and then multiply it by some other borrowing factor. In this way, the barring factor per second will look like a curve that curves upward. Otherwise, if the optimal usage factor is not equal to zero, then the borrowing factor per second is calculated by calling the function get kink borrowing factor. If you're familiar with how a B3 calculates its borrowing and interest rates, then you already know what this equation expresses. It's a linear line that gently increases up until some optimal usage factor. If the usage factor is
greater than this optimal usage factor, then the slope of the borrowing factor increases. Okay, so that is how the barring factor per second is calculated in GMX. Next, I'm going to show you a graph of what this kink barring factor looks like. Here's an example of what the kink barring factor will look like. The horizontal axis will represent the usage factor. The vertical axis will represent the borrowing factor. For this example, I'll say that the optimal usage factor is 80%, 0.8. Let's say that the current usage factor is below this optimal usage factor. For example, let's say 50%. So between 0 and 80%, you can see that the borrowing factor per second gently increases. As the usage factor increases, so does the borrowing fee per
second up until the usage factor reaches the optimal usage factor, 80% for this example. Once it goes above the optimal usage factor, the slope increases. This means that if the usage factor is above the optimal usage factor, then the borrowing factor per second increases rapidly. and if you're going to open a position or leave a position open, then it becomes more expensive. After you open a position, you'll either receive funding fee or you'll have to pay a funding fee. This will depend on the time and the market activity. It is constantly changing. The way it works is that the side with the larger open interest pays a funding fee to the side with the smaller open interest. The purpose of a funding fee is to incentivize the balancing on long and short positions. If there was more
demand for one side of the open interest, then it becomes more expensive to open a position on that side. For example, let's say that there's no funding fee and you see that the price of beef keep going up. Then you and including everyone else will probably want to open a position for long. This will create a large amount of open interest for longs. By having a funding fee, it will become more expensive to open a position with the larger side. Okay, but why should the protocol be concerned with balancing out the amount of longs and the short positions? The answer is to protect the protocol and the liquidity providers from making a huge loss. By balancing out the long and short demands, traders will pay each other for the profit and loss instead of the liquidity providers directly
covering for their profits. As an example, again, let's say that there's no funding fee and there's a massive amount of open interest for longs. If they are correct, then their profits will be paid out from the liquidity providers. However, with a funding fee which incentivizes the pool to be balanced, the trader's profit will come from the opposite position. Therefore, this protects the protocol and the liquidity providers from realizing a massive loss. How do you claim the funding fee on the user interface? To do this, go to the trading page and then scroll down. You'll see tabs such as position, orders, trades, and claims.
Click on claims. And over here, if you have some funding fees that you can claim, you'll be able to click on this claim button. Currently, I can claim 7 cents of funding fees. Click on claim and then click on confirm. And that's it. You can see under the claim history that I claimed some funding fees. 14 cents a few months ago and 7 cents just now. The way that the funding fee is calculated for all position is similar to how the borrowing fees were calculated for all users. Basically, it keeps track of two cumulative funding fees. the current cumulative funding fee and the cumulative funding fee when the position was created. But multiply this with the position size and that is how the funding fee is calculated. Because of the market dynamics, sometimes long will pay shorts and other times shorts
will pay long. However, for the math that I'm about to show you, you can assume that long open interest is always the larger side. Longs pay the shorts. This simplifies the math. And if you're concerned about what happens when shorts pay the long, then we can easily fix this problem by keeping track of another cumulative funding fee. One for the long and one for the short. When the long pays the shorts, update the cumulative funding fee for the longs. When the shorts pay the long, update the cumulative funding fee for the shorts. Imagine that there's a funding fee that is to be paid from the longs to the short and at every second these value may be different. And for each second, the long open interest might also be different. And let's say that the user had a position open from time t2 to t5.
To calculate the funding fee that this user has to pay, we first need to divide this funding fee by the total position size at that time, which is equal to the long open interest at time t. So take the funding fee at time t, the amount to be paid to the other side, divided by the long open interest at that time. This will give us the funding fee per position size. And we do the same for the side that is going to claim this funding fee. Take the funding fee at time I, the amount to be paid from long to shorts. And then divide by the total position size of shorts, which is equal to the short open interest at time I.
This will be the amount of funding fee that shorts can claim per position size at time I. Remember when I explained the math for the borrowing fee, the first step was to come up with a generalized equation for the borrowing fee of any user. Here we'll do the same for the funding fees. Again, remember that in this example, we're saying that the longs will always pay the shorts. Let's define L U, I to be the long position size of user U at time I. And S U, comma I will be the short position size of user U at time I. The long funding fee that user U has to pay from time K to N is given by this equation. Sum from time I = to K to I = to N minus one. for each second multiply their position size by
the funding fee per position size. The amount of funding fee that can be claimed by the short is defined in a similar manner. Starting from time I k and going up all the way to n minus one. For each second, take the position size of this short position at time i and then multiply by the claimable amount of funding fee per size. Add up all of this from time i= k to n minus one. And this is the amount of claimable funding fee of user u from time k to n. The next step is to simplify these two equations.
Recall in the math for the borrowing fee, we simplify the equation by assuming that the position size was a constant for some time interval. Then we also kept track of a cumulative borrowing factor. Here we'll use the same trick to calculate the funding fees. So let's say that user u has long position of size l from time k to n. How do we calculate the funding fee of this user? Well, we start with this equation that I've discussed above. Since L is a constant, we can pull it out and then inside we take the difference of the cumulative funding fees per position size. This will represent the current cumulative funding fee per position size and this will represent the cumulative funding fee per position size when this long position was created. The trick
that you're seeing here is exactly the same trick that we saw when we calculated the borrowing fee of a user. The same trick applies to calculating the claimable funding fee for a short position. So let's say that some user U has a position size of S from time K to N. Here's a general equation to calculate their claimable funding fee. And since their position is constant in this time interval, then we apply this same trick over here inside the code of GMX. These two forms are what you'll see for calculating the funding fee and for calculating the claimable funding fee.
The way that a funding fee is updated for position holders is similar to the way that the borrowing fee was updated for the position holder. First, they will update the cumulative borrowing fee per size. This is done inside the function update funding states inside the contract market utils. Over here, I've highlighted some of the functions that are called when order to increase a position is executed. I'll leave it up to you to check out the details. In both case of increasing a position size and decreasing a position size. The first step is that the cumulative funding fee per size is updated by calling this function. And then in the next step it will involve calculating the funding fee. This is done by calling an internal function called get funding fee. Here funding fees to be paid and to be claimed are calculated. The funding fees
to be paid from this position is deducted from the collateral. And the final step is to set the cumulative funding fee per size to its latest value for this position. and then update the claimable funding fee per size for this position. This is an example of what goes on when a position is increased. You'll see a similar pattern when a position is decreased. So when a position is decreased, it first updates the cumulative funding fee factor per size. It will calculate the amount of fees and then deduct it from the collateral. Set the funding fee per size to its latest value for this position. And the same goes for the claimable funding fee per size. The next funding factor per second is calculated based on the difference of the long and open short interest. Basically, the larger
the difference between the long and the short open interest. The funding factor per second will also be large. The details of the formula for the funding factor per second is complex. So on the bottom I summarized the formulas and on the top I have the code open. I'll go through the code and explain the formula for the funding factor per second. On the bottom I have the formula that are summarized. So before we begin, I'm going to first explain about these symbols. F will be the funding factor per second. This is the value to be returned by this function. L will be the long open interest. S will be the short open interest. E will be the funding exponent factor. And there are also other symbols that I'll explain later.
Going back to the code, the first part is to calculate the difference. Calculate the difference between the long open interest and the short open interest. And also get the total of the open interest. Long open interest plus the short open interest. And then it gets the funding increase factor per second. Inside my notes, I've labeled this as FI, funding increase factor per second. Okay. And then moving on, then the way the funding factor per second is calculated is by first getting the funding exponent factor. In my notes, I label this as E and then raise the difference of the long and open interest by this funding exponent factor. Inside my notes, this will be the absolute value of L minus S raised to the power of E. The next step is to divide this part by the total open interest L plus S
inside the code. You can see this over here. Okay. And then moving on, it gets a funding factor. This will be just a number that is set by the protocol. And then also it gets the max funding factor per second. Inside my notes, I label this as F_OM max, the maximum funding factor per second. If the funding factor per second which is calculated by taking this part and then multiplying it by the funding factor for this market I've called this f market. If the calculated funding factor per second was greater than the maximum funding factor per second then it sets the funding factor per second to this maximum value and then it returns the funding factor per second. To summarize, what's going on here is if funding increase factor per second is set to zero, then the funding
factor per second to be returned is the minimum of this expression multiply by some value and the maximum funding factor per second. Okay, so that's this part of the code. Moving on, if funding increase factor per second is not equal to zero, then we move on. It gets the saved funding factor per second, the funding factor per second that was stored last time this function was called. Then I get some settings threshold for stable funding and threshold for decreased funding. Inside my notes, I've label this as TS and TD. These values will be used to compare with this value F. And then depending on the inequality, it will try to either increase the funding fee per second or decrease it. The next part is to determine whether the next funding rate
is in the same direction as the previous funding rate or not. The way we do this is first it gets the saving funding factor per second. If this value f0 is greater than zero then this means that long pays the shorts. Otherwise if it was less than zero then this means that shorts pay the long. Okay. And if long pays the shorts then the same direction would mean that the current long open interest is greater than the short open interest which you can see over here. Otherwise if in the previous call the funding factor per second was negative then the same direction would be that the short open interest is greater than long open interest. If the previous skew is in the same direction as the next funding, then we move on to this part of the code. Basically, what this part of
the code says is that if this f that we calculated over here is greater than the threshold that we got, then the next step is to increase the current funding rate. Otherwise, if this F is less than the threshold TV, threshold for decreasing funding, then decreasing the funding rate. Otherwise, if the skew is not in the same direction, then we're going to increase the funding rate. So, this part of the code is determining whether to increase the next funding rate or to decrease it. And then we move on to the next part of the code. In the next part of the code, if the funding rate was to be increased, then it's going to increase it by the previous value plus or minus. This will depend on the previous direction of the funding.
Add the value f multiply by f of where f of i is some number that we got earlier. funding increase factor per second. This number is multiplied by the time elapsed dt. And you can see this by over here increase value. Multiply diff USD to open interest factor multiply by the funding increase factor per second and then multiply by the duration in seconds duration since the last time this was updated. Otherwise, if the funding rate is to be decreased, then we move on to this part of the code. We first calculate the value to decrease by. This is done by multiplying funding decrease factor per second by duration in seconds. In my note, I denote it as FD multiply by DT where FD is equal to the
funding decrease factor per second. Then we move on to the conditional statement. If the previous the saved funding factor per second, if the magnitude of this value is less than or equal to the value to be decreased, then we set the next funding factor per second either to plus or minus one depending on the direction of the previous funding. Otherwise we know that the magnitude of the previous funding factor per second is greater than decrease value. So what we do is take the absolute value of the previous funding factor minus it with f of d multiply by dt. In code this is decrease value and then to preserve the signs we multiply by the previous funding factor and then divided by the absolute value
of the funding factor. This part will give us plus or minus one depending on the value of f0. And this is how the funding factor is decreased. Further down in the code, there's some code that bounds the funding factor. I'll leave it up to you to check the logic of this code. The takeaway from this video is that the next funding factor increases when the difference between the long and the open interest are large. Furthermore, if the factor called funding increase factor per second is set, then the funding factor per second gradually increases or decreases, adding some change to the previous funding factor per second. Let's say that I wanted to create a long position for EAS index. The current price of beef is 252.
I also want to take a profit when the price of beef is above 2,100 and I want to cut my loss if the price of beef is less than 2,000. Sure, I can manually do this. I can stare at the screen and when the price of beef goes above 2,100, close my position or if the price of beef falls below 2,000, I can also close my position to cut the loss. However, we can also ask GMX to do this for us. This is the feature of take-profit and stop-loss. Take profit means to close our position when there's some amount of profit that we specify and stop loss means to close our position when our loss is more than some amount that we specified. So for a long position, the current price of beef is 250. Let's say that we wanted to create a long position
for 0.01 E. And then over here we can specify the price to take profit and cut our losses by specifying the price for stop-loss. For take profit, let's set it to 2,100. And for stop-loss, let's set this to 2,000. Close our long position to take a profit when the price of beef is at or above 2,100. And likewise, close our position to cut our loss if the price of beef is at or less than 2,000. When you submit a transaction to create this order, it actually sends three orders. The first order is to open a position for a long. The next order is an order to take profit and the last order is an order for the stop-loss. We can do something similar if you were to take a short position. For a short
position, the prices will flip. Profit means if the price of the index is below the price of entry. So if you were to enter a position at here 1 E 2015, then our profit will be when the price of E is less than this price. For example, let's say that we want to take a profit when the price of E beef reaches at or below 2,000. And for stop-loss, we will make a loss if price of beef goes above 2,50. So, let's set our stop loss at 2,100. And then we'll be able to create a short position where we would take a profit if the price of beef is at or below 2,000 and also cut our loss if the price of beef is above 2,100. Again, this will create three orders. One to open a position for short, one order for take
profit, and one order for stop-loss. Now, if you were to submit this order, it will submit three orders. And let's say that we manually close our position. Then inside GMX protocol, we will still have this take-profit and stoploss order. But since our position is closed, these orders are no longer needed. So when we close our position, we should also cancel these orders. This feature is accomplished by what's called auto cancel. On the user interface, this is automatically set. But if you're manually interacting with the smart contract, you'll need to specify auto cancel set to true. It's now time to explore the advanced features of GMX for trading. For swaps, there's market and limit. And for long and short positions, there's market limit, TPSL, which is take-profit and stop-loss, and then stop
market. Let me explain all of them one at a time. Let's start with swap. We've already discussed what a market swap is. It basically swaps a token at market price. How about swap with limit limit swap? What does this do? Limit swaps are orders to swap a token when the current price is at or below some price that we specify. For example, here I have 1 USDC and I've set the limit price to 2,000. If the current price of beef is at or below 2,000, then this order will execute a swap for 1 USDC to some amount of beef. And I've created an order over here. Clicking on the orders tab, swap 1 USDC for some amount of E when the price of one E is less than 2,000 USDC.
There's also a limit for longs and shorts. Let's take a look at long. What does creating a limit order for a long mean? It basically means to create a long position when the current price is below the limit price that we specified. So for example, let's say put in USDC for a long position. And let's set our limit price to let's say 2,000. This order will be executed, meaning that our long position will be open when the current price of beef is less than 2,000. Okay. How about creating a limit for short? For short positions, the limit price must be above the current price. We're specifying that we want to create a short position when the current price of the index is above some price that we specified. For example, let's say 2,100. This short position will be
created when the current price of the index is above 2,100. Moving on, we have the takerit and stop-loss tab, which we've already discussed. So, let's move on to stop market. Stop market is like the opposite of limit orders. For a long, it will allow us to create an order above the current price. The current price of beef is 2045. Let's set this stop price to let's say 2060. If you were to create this order, then this order will be executed when the current price of beef is above 2060. We also have a stop market for short. In this case, we need to specify the stop price below the market price. For example, let's say 2040. This order to open a short position will be executed when the current price of E is below 2040. Okay,
so that's stock market. Let's say that a user created a swap order from D to USDC and from USDC to W. Here I'll give you explanation of how the tokens move around in the GMX contracts and what functions and contracts are called. The first step a user created a order to swap from D to W. In the next transaction, a keeper will execute this order. The keeper is an authorized account of GMX. It will call a function called execute order on the order handler contract. The order handler will call the function transfer out on the order bolt. Inside the order bolt, there's the die token and if now you might be asking where did these tokens come from? Well, when the user created an order to swap its die to web, the user sent his die to the order bolt and
also if to execute this order. So that is why inside the order vault we have die and if die to swap the tokens and if to execute this order. When the order handler calls the function transfer out it will transfer this die over to the market token. The market token for a die and USDC is swap only. It is not used to create any long or short positions. And then on the bottom we also have a market token where it locks USDC and W. This is used for creating long and short positions. Next, the order handler will call transfer out on the market token.
By this point, the order handler has already calculated how much USDC to send for the amount of die that was sent. It will send this amount to the next market token USDC and W. And then it will call transfer out again. Again, by this point, the order handler, which calls into other library contracts, already calculated the amount of W to send out based on the amount of USDC that came in and then send out the W to the user. If the user had specified that they wanted EF instead of W, then on the way out, this W will be converted back to E. The last part involves refunding gas. The order handler will refund gas from the amount of E that is locked inside the order B. Remember again that this E came from the user sending for the execution
fee. Some of the E is paid out to the keeper for executing this order and the remaining E inside the order bolt is sent back to the user. GMX has many contracts and it's difficult to understand how each of these contract interact with each other. The best way that I found out to figure out how all of these contracts fit together is to take the transaction hash for an order and then debug it with some kind of transaction debugger. So here you're seeing a transaction hash for creating a market swap. I'm going to copy this and then head over to tenderly.co. On the search bar, I'm going to paste a transaction hash. This will open a transaction debugger. Scrolling down, I can see all of the contracts that were called and along with the functions that were called. The number of functions
that are being called when creating a order and executing the order is large and it's easy to get lost and confused about what's going on just looking at the transaction debugger. So here I've created a note highlighting some of the functions that I think are important to understand how GMX works. For example, here I've highlighted some of the function calls when an order is created for a market swap. And likewise here you'll see some of the function calls that are executed when an order is executed. Use this along with the transaction debugger to understand how contracts interact with each other in the GMX protocol. Let me explain what contracts and functions are called when we create a order for market swap. So let's start with our entry. Which contract does it call and what function
does it call? The contract that it calls is exchange router. The function that it calls is multicol. It calls multi call because inside this transaction there are three separate calls. The first one is to send W NT. The next one is to send tokens and the last one is to create order. Let's start with the first one. Send WT. What is this doing? Well, W NT stands for wrapped native token. For if wrapped native token refers to W. Okay. So, what is this doing? What's actually sending the execution fee to be used to execute this order? This execution fee will be used by authorized account of GMX after this transaction to execute the order for a market swap. This
transaction will create order for a market swap from D to web. So the first transaction will send the execution fee. Okay, where does it send it to? It sends it to this address. I'll copy this address and then look it up on RB scan the blockchain explorer for arbitrum one. Okay, here's the address. Let's see what contract it called. Click on contracts. Scroll down. It calls the order bolt. The function called to send W NT sends to the order bolt the execution feed. Okay, let's move on to the next function call. Exchange router send tokens. This is the token. The receiver is this address which is the order bolt which you can see over here
starts with 0x31 and it starts with 0x31 over here as well for the amount for this much amount. So this function call sends dye to the order vault for the amount of dye that we specified. And then the last transaction is to create an order. Create an order for market swap. Let's take a look at the input. To do this, I'm going to click on this line. And then I'm going to click on debug. On the top, you'll see the code. And on the bottom, you'll see the inputs and the outputs that were passed. Scrolling all the way down, here is the input params. You'll notice that there are a lot of parameters inside this inputs. Let's look at it one at a time.
receiver. This will be the receiver of W since we're sending a market swap from D to W. And then we have some addresses that are all set to zero. Here we have a UIP receiver which is not set to zero address. And then we have a market the address of the market token but this is not used for swaps. Initial collateral token 0xd8. Remember that this is the die token. And then we have swap paths. This is the market tokens. The first one is the die USDC and the next one is the USDC web market token. And how do I know this? Well, we can check that the first one has D and USDC and the second one has USDC and W. Going back to RB scan, this is the first market token that we saw. Scrolling down, click on token
holdings and you can see over here that it has a lot of USDC and a lot of D. And here's the second market token. Scrolling down, click on token holdings and you can see here that it has WE and USDC. Okay, so that's the swap path. This specifies the tokens to be swapped and the path to be used. Here it specifies to swap die to USDC and then from USDC to W. Okay, let's scroll down. A lot of the numbers are zero, but here you can see execution fee. This is the amount of gas that we sent for this order to be executed. If the order used less gas than this, then the remaining gas will be refunded back to our account. And then min output amount for sending some amount of D. This is the
minimum amount of F that we expect to get back. And then here's the important one. Order type. This specify what kind of order it is. Here it's shown as a number, but actually this is enum and solidity code. The enum order type is located under the folder order under the contract order. Here you can see various order types. The transaction that we looked at was order type equal to zero which is equal to market swap. Okay, we're almost done with the input. The last parameter that is relevant for market swap is should unwrap native token. If this is set to true, then instead of receiving W, we will receive E. Since this is equal to true, before the swap completes, it will convert the
W into E if and then send the E back to us. Okay, so that is the input. Let's also look at the output which is also important. The output is a single output a bytes 32. This is like the ID of the order. This ID identifies the order and it will be used in the following transaction to execute this order by an authorized account of GMX. Okay, that was input and output. Let's go back to the function calls. I'm going to stop debugging and this will take me back to the function calls. Also click here to remove this code. Okay, so we were at create order. I just explained what the inputs are and what the output is. From here the exchange router will call the contract order handler call the function
create order and then it will call other functions but the actual function called to store the order is located here. The order handler will call the library contract order utils. Notice that it calls a fallback. Since this is going to be a call to a library, you'll see often that when you see fallback, this probably means that it's calling into a library contract. And if you expand this, you'll see the actual call that was called. Call the order utils library. Call the function create order. Again, there are a lot of functions that are being called, but the next important one are these two function calls. Order bolt record transfer in and order bolt record transfer in. Remember in the first step, it sends if to the order bolt and it also sends die to the order
bolt. Here what it's doing is it's calculating how much E and how much D was sent to the order B. Next it checks the type of order is position order returns false. Is this a increase order? False. Is this a decrease order? False. Is this a market order? True. Okay. And then moving on it validates the swap path. There are other validations. And then the order that we submitted is actually created over here. Now you can't see the function over here but if you click on this line you'll see that it calls into the function order store utils set. Okay so that is how an order is created. Here's an example that creates an order to short ETH. The amount of collateral that is sent is
0.01 E with 1x leverage. Our entry is again exchange router multi call and inside here it makes two function calls send W&T and create order. Since our collateral is in ETH, this send W&T NT includes the execution fee and the amount of collateral to be deposited for this short position. I've already explained about the function create order when we did a cold walk through for market slots. So here I'll just focus on the inputs that are being passed when we create a short position. Click on this line and then click on debug. We're interested in the inputs that are being passed. the receiver that is my account. The first important parameter for creating a position is the market. This specifies the market that
we're creating a position for. This market has ETH as index, the long token as well, and the short token as USDC. This is the market that we're creating a position for. And then initial collateral. Since we're sending ETH, our collateral will be converted into W. This is the address of then next we have swap path. The swap path specifies whether we want to swap our tokens to another collateral. This swap path is a market token that contains web and USDC. I wanted to create a position where ETH is collateral. However, in this transaction, I accidentally specified to swap my ETH collateral into USDC. So that is why this swap path is not empty.
If you don't want your collateral to be swapped, then you will leave this empty. Okay. And the most important part to understand how positions are created are the numbers. Size deltaUSD. This is a number with 30 decimals. Going back to my code editor, I'm going to open Python shell since it's good with numbers and then paste that number. Since this number has 30 decimals, I'm going to divide this by 30 decimals. We need 30. And we get approximately 34.19. This is our position size in terms of USD. How do we calculate leverage from this? Well, remember that position size was equal to leverage multiplied by the USD value of the collateral when this position was created. I don't know the exact price of beef when I submitted this transaction. However, I'm going to use this price acceptable price. This
should be close to the market price when I open this position. Paste it into my Python shell. This has 12 decimals, so I'll divide it by 112. So, the market price of E was probably around 3,419. 3,419. I sent 0.01 E. The USD value of my collateral when I opened this position was 34.19. and the position size was also approximately 34.19. This means that the leverage is equal to 1. Now if I created a leverage with 10x then we will multiply this number by 10. And if I created a 100x leverage then we would multiply this number by 100. Okay. And then moving on we have order type. Order type is two. Remember that the order
type maps to the enum. Market swap zero, limit swap is one. Market increase is two. And finally, since we're creating a short position, we set the is long to false. Okay, so these are the inputs that are being tested when we're creating a short position for 0.01 if 1x leverage when the price of E was around 3,419. Here's a transaction that creates an order to close my position. Let's take a look. The first part is that it send some gas fees, send W&T. And then the next part is to create an order to close my position. the function calls that it's going to make is basically the same as market swaps and for opening positions. So in this video I want to focus on the inputs that are passed when we want to close a position. I'll click
on this line and then click on debug so that we can see the inputs. Okay. And here are the inputs for closing a position. We'll need to specify the market. This market will be E as index as long token and USDC as short token. And then we have our initial collateral token. What is the collateral? Let's copy this and then see it on RB scan. Here's the contract address that I've just copied. The token is USDC. Why is my initial collateral USDC? The answer is I accidentally specified to swap my collateral from W to USDC. So when I've created an order to open the short position, it swapped my E to USDC. So that is why now this position has USDC as collateral. In this transaction, I
close the position. So the amount of collateral that I want to get back is all of the collateral that I sent. The amount of collateral is specified over here. Initial collateral delta amount. USDC has six decimals. So that's the decimal part. And this is approximately 34 USDC. If you remember when I open this short position, the USD value of the collateral was roughly $34. $34 in and $34 out for the collateral. And then scrolling down, the order type is set to four. The order type four is market decrease since we're closing this position using the market price. Okay.
And our position was a short position. So is long is set to false. The last parameter that is important for closing a position is decrease position swap type. This decrease position swap type is a enum that can be found also inside order. The options are no swap, swap P&L token to collateral token or swap collateral token to PNL token. So when we decrease our position, we can specify to not do any swaps, swap our profit and loss token to the collateral token or swap our collateral token to the profit and loss token. Okay, that is the input that is best when we create an order to close a position. Let's look at an example of shorting E taking the profit when the price of E is 2,200 and cutting
our loss when the price of E is 2,260. You'll notice that inside this multi call, there are three function calls to create order. once over here, once over here, and the final one over here. And before each create order, it sends W&T. What's going on here is that it sends the gas fee before creating the order. The first order is a order to create a short position. And then it will send some gas fees again. And then we have another order that is being created. Send some gas. And then we have our final order that is being created. Okay, the first order is going to create a short position. So let's move on to the second order. What does it do? I'll click on this and then click on the debugger to see the inputs inside here.
Let's first check the order type. What is this order type? Order type is six. Going back to my code editor and inside the contract order. So let's see what is order type six. Zero is market swap. 1 2 3 4 5 6. So order type six is stop loss decrease. Decrease our position to stop our losses. Moving on. What parameters are we passing in here? The interesting part is inside the numbers. Since this is a stop-loss, I specify the stop loss to be at 2260 USD. This number looks like the parameter that I passed in trigger price. I'm going to copy this number, open a Python shell, paste it, and I want to verify that this has 12 decimals and when we divide it by 10^
the 12, this turns out to be 2260. So divide by 1 12 and we get 2260. Okay, so this trigger price is the price that I specify for this stop loss. And finally, size delta USD and initial collateral delta amount. In this order, I've specified to close my position. So the size delta USD is my current position size and initial collateral delta amount is my current amount of collateral. Okay, let's move on. Let's look at the last order. The last order create order. Again, I'll check the parameters by clicking on debug. And then inside here, I'll first go to order type. Order type is five. Order type six is stop-loss decrease. So order type five will be limit decrease. Limit decrease means to decrease our position when some price
that we specify is reached. Inside the inputs, we can see that the trigger price is set to this number. Since I've created a takerit at 2,200 USD, let's check that this turns out to be 2,200. Again, inside my Python shell, I'll paste the number and then divide this by 112. And we get 2,200. Okay. Okay. And the size delta USD, my current position size is this number and my current amount of collateral is this number. Here I'm saying close my position and take the profit when the price of E is less than 2,200 USD. One final note, notice that decrease position swap type is not equal to zero. It is set to one.
And what does this mean? Decrease position swap type set to one. This will be swap P&L token to collateral token. So whatever profit that I make, swap it to my collateral token. My collateral token is USDC. So, it will swap any of my profit or loss to USDC. Okay. So, those are some important parameters to pass when you're creating orders for take profit and stop-loss. Whether you're creating a order for a market swap, opening or closing a position, it's going to follow this same pattern of sending some execution fee, sending some tokens, and then creating the order. It's super important that all of these function calls happen in the same transaction. If these function calls were done in separate transactions, then another user can step in between these
function calls to create an order before your order and use your execution fee and your tokens. Let's see in details how this can happen. So let's assume that execution fee was sent and tokens were sent as well. For creating an order, the execution fee and the tokens are sent to the order bolt. Here you're looking at a transaction for creating a market swap. The function call that we're concerned with is exactly the same for swaps and for creating or closing a position. So it doesn't matter which order you're creating. Inside the function called create order, the way the amount of execution fee and the tokens that were sent is recorded is by a function called record transfer in.
Here it is order bolt record transfer in. Let's see what this function does. Going back to my code editor, the order bolt is a strict bank. And over here there's a function called record transfer in which calls an internal function called record transfer in. What it does is it calculates the amount of tokens that are sent by taking the difference between the current amount of tokens that is locked inside this contract with the previous amount that was stored. If you send 10 d to the order vault and then call the function record transfer in then this value will be equal to 10. If you call record transfer in again since the token balances are all in sync it will return zero. Now where is this record transferring called? When we create an order when we create an order the
contract order utils is called inside here. You can see that the function record transferring is called. It's called once over here to calculate the amount of tokens that was sent. Initial collateral delta amount. It's also called again to calculate the amount of execution fee that was sent. These two values are later stored inside here inside the order. initial collateral delta amount in is stored for the order and the execution fee is also stored for the order and finally this order is stored inside GMX inside the data store contract so now let's imagine that three separate transactions were sent send execution fee send tokens and then send create order in between these
transaction another user calls create order they can use the execution fee and the tokens that were sent to the order bolt to create their order using your token tokens. So this is why it's important that when you're creating the order, sending execution fee and sending tokens must also be in the same transaction. Otherwise, another user can create an order using your execution fee and the tokens that you send. And that also explains why when using the user interface, it wraps all of these three function calls in a multi call. It makes sure that all three function calls are done in the same transaction. Let's analyze the transaction for claiming funding fees. contract that you need to call is exchange router and the function that you need to call is claim funding
fees. Let's also look at what inputs are being passed. Click on the debugger and then inside the inputs you can see that it passes the address of the markets to claim the funding fees from and then followed by the tokens to claim. The address starting with 0x82A is wrapped ether web and the address starting with 0x AF88 is USDC. This is W. This is USDC and this is ref again. And the receiver of the funding fees is my account. Okay. So these are the inputs that you need to remember to claim funding fees using the smart contract. Let's look at the exact condition for a position to be liquidated. The function is called is position liquidatable under the contract
position utils which is under the folder position. It's going to return a boolean. If this position is liquidatable then it will return true. So let's go all the way down to see what conditions where a position is liquidatable. Okay, so here it has the keyword return, return true, return true, return true, and return false. Let's look at what the conditions are for liquidation. The first condition is if the remaining collateral USD is less than some minimum collateral USD. This minimum collateral USD is a value specified by GMX and it is stored inside the data store. Okay, so that's one condition. Now the remaining collateral USD, we'll analyze what this value is.
But for now, you can think about it as the USD value of the collateral minus all of the fees. That's the remaining collateral USD. The other condition is if the remaining collateral USD is less than or equal to zero. And the final condition is if the remaining collateral USD is less than min collateral USD for leverage where min collateral USD for leverage is calculated over here. Okay, let's take a look at this. Multiply the position size in terms of USD by some main collateral factor. Remember that position size is defined by the leverage multiply by the value of the collateral at entry. We're going to get some fraction of the value of the collateral at entry. So this over here says if the remaining collateral USD is less than
some amount of collateral at entry then this position can be liquidated. Okay. So these are the three conditions where a position can be liquidated. All you have to do to understand this code is understand what remaining collateral USD is. So scrolling up, remaining collateral USD is the collateral USD, the current value of the collateral in terms of USD plus position P&L in terms of USD, the current positions profit and loss plus price impact. And then from here it minuses collateral cost USD which is fees dot total cost amount multiply by the price of the collateral.
Okay, so fees dottotal cost amount the total cost of the fees. The total fees are calculated in the function get position fees under the contract position pricing utils. The position pricing utils is located under the folder pricing. Click on position pricing utils and then we'll look for the function get position fees. Okay, here it is. And then I'm going to scroll all the way down. Here it is. Total cost amount. Total cost amount is total cost amount excluding funding plus the funding fee amount. Okay. So what is total cost amount excluding funding?
Well, it is equal to the positioning fee amount, borrowing fee, liquidation fee, UI fee and some kind of discount if there's a referral. Going back to the function is position liquidatable. We calculate the fees and this fee will involve fees such as funding, borrowing, UI fees, liquidation fee, and fees for closing the position. and then minus it from the USD value of the collateral and then add the profit and loss and the price impact. And that is how the remaining collateral USD is calculated. When you create a long or a short position, there is the liquidation price. The price at which your position will be forcefully closed. The way to calculate the price of liquidation involves several multiplication, addition, and subtraction. This might be difficult to do when you want a quick
estimate of the liquidation price. However, under certain conditions and with few assumptions, we can come up with a simplified equation that will allow us to easily approximate the liquidation price. The condition for liquidation is given by this formula. CUSD is the current USD value of the collateral. We can further split this USD value of the collateral into two parts. The amount of collateral token and the price of the collateral. We also label PC0 to be the price of the collateral at entry. PUSD is the profit and loss of the position in terms of USD. There are several fees involved for opening, closing, and keeping a position open. We'll simply label this as F. And finally, we'll label M as the minimum
USD value for a position. Now, let's go back to this equation. What does this say? CUSD is the current USD value of the collateral. Add the profit and loss of this position minus the fees. And when this value is less than some minimum USD value for a position then this position can be liquidated. Okay. Before we move on to derive the estimate price of a liquidation, I first want to show you two equations. The first equation will involve explicitly writing what profit and loss of a position is in terms of the price of the index and then also show you the equation of a position size in terms of the USD value of the collateral. Let's start with explicitly coming up with a equation for the profit and loss of a position. We'll label S0
as the size of the position in terms of tokens. Pi will be the current USD price of the index and PI0 will be the USD price of the index at entry when this position was created. The profit and loss for a long is given by multiplying S0 multiply this by the current price of the index minus S0 multiplied by PI0. When the current price of the index is greater than the price of the index at entry, this will be a positive number. So this will be positive. This means that there's a profit. On the other hand, when the price of the index is less than the price of the entry, then this will be a negative number. So you can see that all of this will be a negative number. Hence, it is a loss.
For a short position, all you have to do is flip the prices. Price of the index at entry minus the current price of the index. If the current price of the index is less than the price of the index at entry, this will be a positive number. So there will be a profit for the short position. Otherwise, if the price of the index is greater than the price of the index at entry, this will be a negative number. So this value will be negative and there is a loss for this short position. Okay, this is the explicit equation for the profit and loss that we will be using in this video. Next, I'm going to write the position size in terms of the USD value of the collateral when this position was created. The position size is given by the size of the position in terms of tokens.
Multiply this by the price of the index at entry. And the value of the collateral at entry is given by the amount of collateral that was deposited. Multiply this by the price of the collateral at entry. Since both of the terms are in USD, we can simply write that the position size is some multiple of the USD value of the collateral. This will be a useful equation that we will use later to simplify our equations. Okay, let's now derive some approximation for the liquidation prices. Let's begin by approximating the liquidation price for a long position. We'll start with this equation, the condition for liquidation. And then we'll rewrite the equation above, replacing C USD with C 0 multiplied by PC, where C 0 is the amount of collateral and PC is the current value
of the collateral. We also replace the profit and loss of this position for long. This is given by this equation. Multiply the position size in terms of tokens by the difference of the current price of the index minus the price of the index at entry. And then we also have fees and this must be less than some minimum amount of collateral. To come up with a liquidation price, we need to solve for P a bite. Inside this equation, there are two unknowns. P of which we want to solve and then there's also P of C. Both of these depend on the market price. Everything else C 0 S0 and PI of0 are known. Furthermore, we'll say that the fee F and this minimum collateral amount is small enough that we'll simply set it equal to zero. So,
we have two unknowns PC and PI. We want to solve for PI. Under certain conditions, we can conclude what this PC is equal to. The two conditions are when PC the price of the collateral is always equal to one. In other words, the collateral is a stable coin. Hence, it is always equal to one. In the other case is when PC is equal to PI. when the collateral is equal to the index. For example, we have the E as index, W as long token and USDC as short token. In that market, if you were to use WE as collateral, since the index is EF, we can simply say that the price of W is equal to the price of E. Technically, the price of F and the price of E are not the same. But for simplification,
let's just say that the price of F is equal to the price of E. So these are two conditions when we can simplify this equation to say something about the liquidation price via a bite. Let's start with the case when the collar that we deposit for the position is a stable coin. We'll first use this equation and then paste it here. And also we're going to be needing this equation later on. So I'll simply copy and then paste it over here as well. Remember this K represents some kind of leverage for this position. Since PC is always equal to one, this is a stable coin. We can simplify this equation. PC is equal to one. Let's just remove it. Then the same over here. The price of the stable coin is always equal to one. So the price of the stable coin
at entry, we'll also assume that it was equal to 1 USD. From this equation, I'm going to bring P of to one side of the inequality and the rest to the other side of the inequality. I'll bring this F over to this side. Also bring C0 to the other side of the equation. This will become a minus. Next, I'm going to expand this part of the equation. This will be S0 * P of I minus S0 * P of I0. And then I'm going to bring this over to the right side of the equation. This will become a plus. Finally, I'm going to divide both side of the equation by S0. On the left side, we're left with PE. On the right side, we'll have this part / S0 and the S0 that was over here cancels out with the S0 that we just
divided. Okay, so this is a simplified equation. PI is on the one side of the inequality. To simplify this equation, we're going to assume that the minimum amount of collateral to be locked is equal to zero and the fee is also equal to zero. So this equation becomes m is zero and f is also zero. So this is the equation that we have. Going to bring this over to this side of the equation. And this is the equation that we have. We're going to use this equation to further simplify this equation. Over here we have that s0 * pi of 0 is equal to k * c 0. Let's replace this s0. So s0 will be equal to this. Now let's replace s0. Remove s0 and then plug it in here.
The p 0 is going to come to the top. The c 0 on top cancels out with the c 0 on the bottom. And we're left with this equation. We can further simplify this. The denominator will be k. The numerator will be k minus one and then it multiplies with p 0. So that is our final form of equation. This says that the liquidation price of the index is less than k -1 / k multiplied by the price of the index at entry. Notice how simple this equation is. To estimate the liquidation price, we only have to remember our leverage and the price of the index at entry. Let's see if this is a good approximate to the actual liquidation price. If you were to create a long position with USDCS collar, our
estimate says that the liquidation price is less than K minus one divided by K multiply by the price of the index at entry. If you were to plug in leverage equal to 1, K minus one will be equal to zero. So the liquidation price must be close to zero. Over here you can see that the liquidation price is not equal to zero but it is equal to $11. This is because of the fees that in our equation we set it equal to zero. But if you were to increase this leverage, let's see if this liquidation price becomes closer to our estimate at 2x leverage. K is equal to 2. K minus 1 is equal to 1. The price of the entry is let's say 1,980. 1,980 / 2 is roughly 1,000. The actual
liquidation price is close to the estimate that we calculated. Moving on, let's come up with an estimate for the liquidation price when the price of the collateral is exactly equal to the price of the index. Starting off, here's the inequality that expresses the condition for liquidation. Scrolling up, we're going to be using this equation again, notice that since the price of the collateral is equal to the price of the index, here the price of the collateral is replaced by the price of the index. Since the price of the index is always equal to the price of the collateral, we can say that P of I of0 is exactly equal to P of C of zero. These two cancel out.
Like in the previous calculation, the next step is to bring pi to one side of the inequality and the rest to the other side of the inequality. I'll copy this equation and then first of all going to bring f to this side of the equation. And then next I'm going to expand this part of the equation. S0 * p of minus s sub0 * p 0. And then bring this over to the right. I have a pi over here and I have a pi over here. So I can pull this out and simply say pi multiply by c 0 + s0. And finally I can divide both side of the inequality by this value. So this will come to the bottom. Okay. So we now have our inequality. Pi on one side of the inequality and everything else on
the right side of the inequality. Next let's make a simplification to our inequality. Let's say that m is equal to zero and the fee is also equal to zero. So we can remove this m and this f. Next let's replace S0. Over here we said that S0 is equal to K * C 0. So let's replace this S0 with K * C 0. And also do the same over here. Replace S0 with K * C 0. Since we have C 0 on the top and on the bottom they cancel out. Remove this C 0.
We can also remove this and we can also remove this. So this inequality will be equal to on the top we have a k and on the bottom we have 1 + k or we'll rewrite it as k + 1. Then multiply this by pi of zero. This is our approximate liquidation price. When we create a long position where our collateral is equal to the index. Let's compare our estimate with the actual liquidation price. If we were to create a long position using ref as collateral in the market eusd. So in this case, what is the liquidation price? The liquidation price is 996.
Remember our equation said that liquidation price must be close to K over K + 1 times the price of the index at entry. The price of the index at entry is 1,981. Simply, let's say 2,000. Our leverage is 1. So K over K + 1 will be 1 / 2. Multiply this by the price of the index at entry. We simply round it up to 2,00. 2,000 divided by 2 is 1,000. Actual liquidation price is pretty close to our estimate. We're coming up with an approximate price of the liquidation for a short position. I'll leave it up to you to verify that when M is equal to 0 and F is equal to zero. Furthermore, when the collateral is a stable coin that is always equal to 1 USD, then the
liquidation price PI must be greater than K + 1 / K multiplied by the price of the index at entry. And likewise, when the price of the collateral is always equal to the price of index, the liquidation price must be greater than K over K minus one multiplied by the price of the index at entry. Remember that there's two types of markets, fully backed and synthetic markets. Fully backed markets means that the long and the short tokens provided by the liquidity provider can fully back the profit of the traders. The example that we saw was EA as index, W as long and USDC as short token. We also saw example of synthetic market where the long token may not be able to fully back the profit of the traders. Specifically, we looked at the example of DOA as index as long
and USDC as shorts. When the price of the index significantly increases compared to the price of the long token, then the long token may not be able to fully back up the profit of the long positions. To avoid this case, GMX has a feature called ADL, auto deleveraging. This feature automatically closes your position when your profit exceeds the market's configured threshold. This feature helps to ensure that the market remains solvent and that the profit at the time of closing can be fully paid. When you add liquidity to a GM pool, you'll receive GM token in return. But how is the price of this GM token determined? The short answer is the price of the GM token is given by the total USD value of the pool and then
divided by the market token total supply. The total USD value of the pool is given by the USD value of the long plus the short plus a fraction of the pending borrow increase minus any profit and loss and then minus the amount that is reserved for the position impact pool. Where can we find this code? We can find this code inside the contract execute deposit utils. The function is called underscoreexecute deposit. This function is called every time there's a deposit for a long and a short token. Inside here it calculates the amount of market tokens to mint. The first step to calculating the amount of market tokens to mint is to calculate the value of the pool of the market. This is done here by calling the function market utils.pull value input. Let's take a look at this
function. Here I have the market utils contract and here add the function get pull value input. Inside here we can see that the pool value is initialized as the long token USD plus the short token USD. the total amount of long token in terms of USD plus the total amount of short tokens in terms of USD. The next part involves calculating the total borrowing fee both for the long and for the short position and then a fraction of this borrowing fee is added to the pool value. The next part is calculating the profit and loss for longs and for shorts and then this profit and loss is subtracted from the pool. The profit of positions will be paid out from the pool and the losses will be paid into the pool. Hence here you see a negative sign and then it calculates the impact pool
amount the amount that is to be reserved for the position impact pool. So that is how the pool value in terms of USD is calculated. So once we had the pool value in terms of USD let's scroll down on this line it gets the total supply of the market tokens. Then how does it actually calculate the amount of market tokens to mint? Well this is done scrolling down by calling this function. You can see over here to the current amount of market tokens to mint. The amount to be added is calculated by calling the function USD to market token amount. Okay, so that is how the mint amount is calculated. There's also a function called get market token price inside the contract market utils which calculates the market token price and again it's the same as what I explained before. Calculate the pool value in
terms of USD. Divide the pool value by the total token supply. That is the market token price. What are the fees for depositing and withdrawing liquidity from a GM pool? Here I have the GM pool for ETH USD. If I were to add liquidity to this pool, the fees will be the price impact and a onetime fee for depositing liquidity. There's also the network fee, which is the execution fee that you'll need to pay to execute this order. And finally, if you're using the user interface, there's also the UI fee. Those are the fees for depositing liquidity. How about for withdrawing liquidity? If you were to withdraw liquidity, then again, there is the execution fee. And hovering over the fees, you can see that there's no price impact. There's only a onetime fee for withdrawing liquidity. I've sent a
transaction to create an order to deposit liquidity into the GM pool if ESD. And here's the transaction debugger. The first thing to note is that the contract it calls is the exchange router multi call. Inside the multicol equals two other function send W&T and fallback. Send W&T is sending the execution feed. The receiver is this address. Let's check what contract this is. I'll copy this address and then look it up on RBcan. Scroll down then click on contracts and the contract is the deposit bolt. And then the last function call is a fallback. If you open this, you can see that it calls the function create deposit on exchange router. Now you'll notice that the parameter is
null. This might be due to the transaction debugger not being able to decode the input. So let's dig deeper to see what the input is. The next function that is being called is the deposit handler.create deposit. Let's click on this line and then click on debugger. Inside here, you can notice that the input for the deposit is directly passed into here since the keyword uses call data. Okay, so this is the input. Let's look at the input that was passed for a deposit. The receiver will be the receiver of the GM token. This is my account. Call back contract is set to zero. UIP receiver is a nonzero address.
The market will be the address of the market token. Here I'm depositing liquidity into the market where ETH is index, long is ref and short is USDC. And then the initial long token and the initial short token. The initial long token is WE and the initial short token is USDC. Okay, so these are some inputs that you'll need to keep in mind when depositing liquidity into a GM pool. Let's also look at the output. Since we're creating an order, remember that for creating orders, it returns a bytes 32 that identifies the order. the ID of the order and you can see this over here as well. This is the ID for creating an order to deposit liquidity into a GM pool. Here's a transaction that creates an order to withdraw liquidity from a GM pool. The GM pool that I'm using here is
if index longest web and shortest USDC. Again, we start by calling multi call on the exchange router. And then inside the multi call, it calls three functions. Exchange router send W&T. Exchange router send tokens. And then finally, exchange router create withdrawal. The send W NT sends an execution fee. Send tokens sends the market tokens. And create withdrawal creates the withdrawal order. Recall that for orders, we send the execution fee to the order bolt. And for deposits, we sent the execution fee to the deposit bolt. So let's check who the receiver is for a withdrawal. I'm going to copy this address and then look it up on RBcan. Scroll down, click on contracts, and we can see that the contract name is the withdrawal bolt.
So, we're sending execution fee to the withdrawal bolt. How about our GM tokens? We can guess that it's going to send it also to the withdrawal bolt. The receiver starts with 0x0628. How about the withdrawal bolt? The withdrawal bolt starts with 0x0628. Send execution fee to the withdrawal bolt and send RGM tokens also to the withdrawal bolt. And then the final function call is the create withdrawal. Let's look at the input. So I'll click on this line and then click on the debugger and then expand the input and outputs. Okay, here's the input. The receiver is this address. This is my account. The next interesting input is the market. We need to specify which market we're withdrawing from. And then
the minimum amount of long and short tokens that we expect to get back. The parameters to pass to a withdrawal is not so complicated. The GB vault owns a basket of market tokens. So the price of a GB token will be the USD value of the GB vault divided by the total supply of the GB token. The USD value of the GB vault will be the sum of the USD value of the market tokens that is owned by the GB vault. We can check the code by going to GB utils get GB token price. Okay, here's the function inside here.
We can see that it first calculates the value of the GB vault and then gets the total supply of the GB token and then calls the function get GB token price. Let's check this code out. You can see over here that it divides the value of the GB, the USD value of the GB by the total supply of the GB token. So that is how the token price of a GB is calculated. Let's also check how the USD value of the GB bolt is calculated. So we need to go here. Okay, here it is. Inside here you can see that it is running a for loop. The market addresses will be the market token addresses that is contained in this JB bolt and for each market token that this JB bolt owns. It will calculate the USD value of that market token. This is done inside
the function get JB market value. It runs a for loop and then add this to the total value of GB. Let's also look at the function get GB market value. Inside here it gets the market token total supply and also the balance of market token that the GB bolt has. Next it calculates the pool value of the market token get pool value info and then it calculates the USD value of the market token it has by calling the function market utils market token amount to USD passing in the amount of market token it has the USD value of the pool and the market token supply. So that is how the USD value of the market token that GB Bolt has is calculated. It sums up the USD value of all of the market token
that it has and then divides it by the total supply of GB tokens. That is how the price of each GB token is calculated. The fees to be paid for depositing and withdrawing liquidity from the GB vault is basically the same fees that you'll have to pay for GM pools. This is because when you add liquidity through the GLB vault, eventually those liquidity will be put into a specific market. You can already guess that the way liquidity is added to the JB vault is not so different from the way liquidity is added to the GM pools. Here's a transaction where I created an order to add liquidity to the JV bolt. The first thing that you'll notice is that instead of the exchange router here, we're calling the GLV router. And again, we're wrapping multiple function calls with a multi
call. Inside the multi call, it calls two functions. send W&T and create GLB deposit. Which contract does it send the execution fee to? It's probably not going to be the deposit bolt. So, let's double check. Let's copy this address and then look it up on RB scan. Inside RV scan, scroll down to the contract tab and you can see that this contract is the GB vault. So, our guess was correct that this receiver is not the deposit vault. This is the GB vault. Okay. And then it calls the function create GB deposit. Let's look at the input. Click on the line and then click on debugger.
Then expand the bottom part to see what the inputs are. The input mostly looks the same from depositing liquidity into a GM pool. However, there are slight differences. For example, here we need to specify the token address of the GLB. And then we need to specify the market that we're adding liquidity to. The receiver will be the receiver of the GB token. This is my account. Furthermore, we need to specify initial long token and initial short token. long is FE and short is USDC. Okay, so that is the input that you need to pass to add liquidity to GB. This is a transaction for removing liquidity from a GB bolt.
Let's look into the details. First, the contract. What contract does it call? It calls the GB router with multiol. Inside the multiol, it calls send W&T. And who does it send W&T to? It sends it to this address. Let's check this out. I'm going to copy this address. Paste it into RBcan. Scroll down. Click on contracts. And in this case it is the GB bolt. The next step is to send tokens and this token will be the GB token. And the final step is to create the GB withdrawal order. Let's check the input.
Click on the debugger. The inputs mostly look the same as the inputs for withdrawing liquidity from a GM pool. The only difference is that we need to specify the address of the GB token. Okay. So this is the example of the input that you'll need to pass to remove liquidity from a GB bolt. GMX token is a governance token that is used for voting on proposals. Furthermore, when you stake your GMX, you'll be earning some of the protocol fees. To obtain GMX, click on the buy GMX button. Here, it'll show you some options of how to buy GMX. Going back to the earn page in my wallet, I have 0.1 GMX. By staking GMX, I'll be earning protocol fee. And this will also give me voting power so that I can vote on proposals. To stake GMX,
I'll click on stake. I have 0.1 GMX. Click on max and then I'll click on stake. The transaction went through and the GMX balance in my wallet is now equal to zero and the stake balance has increased by 0.1. Also notice that my voting power has increased by 0.1. Next, let's take a look at voting. Now I can vote for the proposals or I can delegate my voting power to some other account to vote on my behalf. So let's click on delegate. This will take me to the website tally.xyz.
Currently, my voting power is approximately 0.43 GMX. For this example, I've already delegated my voting power to some other account. Currently, I've delegated 0.43 of my voting power to this account. Now, if I were to change delegation, how would I do this? Well, I can click on update delegation, click someone else, and let's explore some of the delegates. Okay, here they are. So, I've delegated to this account. If I wanted to delegate to some other account, then I can click on these accounts. Next, let's take a look at the proposals. Okay. So, here are some proposals that's been executed already. And there's one active. Let's click on this. Here's the proposal.
Let's see what happens if we click on this button, bolt on chain. Notice that my voting power is equal to zero. This is because I've delegated my voting power to this account over here. If I did not delegate my voting power, then I would had voting power to be able to vote for this proposal. Finally, let's go back to the GMX website to unstake the GMX. Back inside the GMX website, let's unstake some of the GMX by clicking on unstake. Let's unstake, for example 0.2 GMX, and then click on unstake, then confirm the transaction. The transaction went through and my voting power has gone down by 0.2 as well. And finally, let's look at how to claim rewards.
Rewards will come in the form of GMX. Where does this GMX come from? Part of it comes from the buyback mechanism. So, what is a buyback mechanism? The GMX protocol is collecting fees from the users for using the protocol. Part of this fees are used to buy back the GMX tokens that are in the market. And this is where the GMX reward is coming from. Let's claim some GMX rewards. Let's click on claim. confirm the transaction. The transaction went through and the amount of GMX that I can claim has decreased. In this video, I showed you a demonstration of staking GMX, delegating my voting power to some account, unstaking GMX, and then finally claiming GMX rewards. Let's examine the total
supply of GMX and how it is distributed. According to the dashboard, there are 10.03 million total supply of GMX. 34% are not staked, 61% are staked, and 5% are in liquidity. Since 61% of the 10.03 million GMX is staked, this is currently helping to reduce the inflation of GMX token by having the majority of GMX token supply being staked. This reduces the circulating supply of GMX token, which in turn reduces the sell pressure of GMX. According to the documentation, the forecasted max supply is 13.25 25 million GMX. The breakdown of how this 13.25 million GMX is allocated is listed over here. Add all of these numbers up
and you'll get 13.25 million. Now, this is the forecasted max supply. The current total supply is 10.03 million. According to the documentation, the supply displayed on the dashboard is calculated based on the total minted GMX tokens minus the tokens that are locked in these contracts. The total supply of GMX is this number. I'm going to use a Python shell to divide the total supply by 10^ the 18 since GMX has 18 decimals. And we get back approximately 10.58 million. From 10.58 million GMX minus the amounts that are locked inside these contracts and you'll get the amount that is displayed on the dashboard, 10.03 million. We looked at how to stake and
unstake GMX. Under the same page, there's another option called stake and unstake escrow GMX. So, what is a escrow GMX? In this video, I'll explain what it is and what are the rewards of staking escrow GMX. According to the documentation, escrow GMX has historically been awarded as an incentive for GMX staking GLP referrals and other programs. Currently, there's no way for me to obtain this escrow GMX. So, if I go back to the staking page and then click on stake, I need to stake escrow GMX. However, my balance of escrow GMX is zero. And there's no way for me to get this. So, I won't be able to show you a demo of staking escrow GMX. If you have escrow GMX, there's two
things that you can do. The first option is to stake escrow GMX for rewards similar to regular GMX tokens. The other option is to best your escrow GMX to earn GMX tokens over a period of time. Let's look at the first option first. Staking escrow GMX to earn rewards. According to the docs, each staked escrow GMX token will earn the same amount of GMX rewards as a regular GMX token. We can verify this inside the code. The code for staking GMX and escrow GMX is done by calling the contract reward router v2. This contract is located under the GitHub repo called GMX contracts. Again the name of the contract is called reward router v2.
When gmx is staked the function that is called is stake gmx. When escro gmx is staked the function that is called is stake esgmx. In both cases it calls the same function called underscore stake gmx. Inside the internal function underscore stake gmx. The actual staking is done by other contracts which you can see over here. At first glance, it's a little bit confusing what's going on over here. What's basically happening is that to the first contract, stake GMX tracker, we either stake GMX or ESGMX and then earn ESGMX. When we stake GMX or ESGMX into this contract, it's going to mint another token which will be
staked into the second contract. Bonus GMX tracker. Here you'll be earning BN GMX for staking the first token into this contract. This contract is going to mint another token which will be staked into the next contract extended GMX tracker. The reward for staking the token into extended GMX tracker is GMX. And finally for staking tokens into extended GMX tracker, it's going to mint another token which will be staked into the fee GMX tracker which will earn you rewards in W. We can check this by looking at the reward router B2 contract. The contract where GMX and ESGMX is staked is the contract stake GMX tracker. Inside the contract stake
GMX tracker, you can see over here that it has approximately 6 million GMX and a little over 1 million ES GMX. These are the tokens that are staked inside this contract. The reward token for staking into this contract is shown here. This reward token turns out to be escrow GMX ESG GMX. So far we learned that staking GMX or ESGMX into the contract stake GMX tracker will earn rewards in ESGMX. Now when you stake your tokens into a reward tracker, it's going to mint another token. Let's take a look. The contract is called reward tracker. The function is called stake for account. It's going to call internal function called stake.
Inside here, you can see that it transfers the token, transfers the token to be stake, and then it mints a token. This token that was minted is used in the next contract for staking. So we stake GMX or yes GMX. It mints a token. That token will be staked in the next contract. And for staking that token, we'll get this B and GMX reward. For staking some token into this bonus GMX tracker, it's going to mint another token which will be staked into the extended GMX tracker which will earn rewards and GMX. and for staking tokens into here. Again, it's going to mint another token which will be staked into the last contract, the GMX tracker. So, that is how staking GMX or ESGMX earns you various rewards. So, that's staking
escrow GMX. The other option is to best your escrow GMX and then earn some GMX tokens over some period of time. So, if you have escrow GMX, you can best it by going to the earn page. This is the same page where you can stake your GMX and stake your escrow GMX. Scroll all the way down. There's a section called vest. Here you'll be able to deposit your escrow GMX and then earn GMX over time. Under the option to stake GMX, there is the GLP token. You can buy or sell a GLP. There's also an option to stake this GLP. So, what is the difference between GMX and the GLP token? The difference between the tokens GMX and GLP is that GLP is a liquidity provider
token for GMXB1. On the other hand, GMX is a governance token for GMX B2. Since GLP is a liquidity provider token for GMX B1, I won't be covering any further for this token. The function calls for staking and unstaking GMX and claiming rewards are simple. So, I'll leave it up to you to figure out what functions and contracts are called when these actions are performed in the GitHub repo. I'll leave all of the transaction hashes that are relevant. If you want to debug these transactions, you can copy these transaction hash and then paste it into a transaction debugger such as Tenderly to see what's going on inside the transaction. Here you'll be able to find what contracts functions that it calls
and what parameters are passed. This will be helpful in doing the exercises for staking and unstaking GMX. For the final project of this course, you'll be building a vault that earns funding fees. If you remember earlier in the course, we analyzed the payoff diagrams of creating long and short positions with different collaterals. One of the strategies that we looked at was shorting E with E as collateral. The payoff diagram for this strategy was a flat line. Whether the price moves up or down, you don't lose any money and you also don't gain any money. The idea for this project is that we create this strategy when a short position will be receiving the funding fees. When there's more long open interest than short open interest over time, the short positions
will start receiving the funding fees. So the strategy that we'll use is short E using E as collateral. For example, we'll do 0.01 E as collateral. create a short position with 1x leverage and make sure that the collateral is in W. This will create a payoff diagram that is flat. And if we create it at the right time when the short position will be receiving funding fees, the position will be neutral to the price. We neither gain profit or lose money. However, since we're claiming the funding fees, we'll be earning some profit. So, that's the idea for this project. Now, keep in mind that there's also the borrowing fee and the price impact fees which will affect the profit and loss made by this vault. Here's the architecture of the
contracts that we will be building. We'll have the vault contract where the users will deposit and withdraw their W. The vault contract is mainly responsible for accepting deposits from the users and then withdrawing W back to the user. Next, we have the strategy contract which takes the W inside this vault contract and then interacts with the GMX protocol. The strategy contract is responsible for managing a short position in GMX. Both the vault contract and the strategy contract will have a privileged user. Let's call him admin.
He'll be able to take the we inside the vault contract and then transfer it over to the strategy. And likewise, he'll be able to take the we inside the strategy and then transfer it back over to the vault contract. The main responsibility of the admin is to take the weft inside the vault, put it inside the strategy and then create a short position inside GMX. Here we assume that the admin is a good trader that can make good decisions to create a short position so that the users who deposited the W do not lose too much on this position that the admin created. Furthermore, the admin will have to make a decision concerning the funding fees for the short and the borrowing fees. The admin will be able to take the W from the bolt and then increase the short position size or
decrease it in case something goes wrong. The admin will also be able to cancel the order. The order to either increase or decrease the position. There's also a public function where anyone will be able to call to claim the funding fees. Both the admin and any user will be able to call the function claim to claim the funding fees. And finally, let's take a look at the withdrawal call back contract. The withdraw call back contract is needed here for the user to withdraw their W in case the W is locked inside the GMX contract. So let's say that a user calls withdraw sending their execution fee to the vault. If the vault has enough W, the user will simply get the W withdrawn from the vault contract. However, if the vault does not have enough W to withdraw
to the user, this will call the strategy contract to create a order to decrease the position size. The strategy contract will relay this message over to GMX, creating the order to decrease the position size. GMX will execute this order and then call back into the withdrawal call back contract sending both the execution fee that the user sent and some amount of W that was withdrawn for decreasing the size of the position. The withdrawal call back contract will send the W and the execution refund to the user. And also inside the bulk contract there will be a data that stores a order that the user created in order to withdraw W from GMX.
When this withdraw callback is called this will delete the withdrawal order that is stored in the bulk contract. This is the architecture of the funding fee vault that you'll build for the final project. To do the exercises you'll need to have an understanding of the call back utils contract. The functions inside here will be called when we create a order and specify an address for the call back contract. A callback contract is executed after an order is executed. Inside the callback utils contract, there are several functions that you need to understand. The first function that you need to remember is the after order execution function. This will call the function after order execution on the callback contract that you specify when you
create the order. One of the contract that you'll complete for the final project is called the withdrawal call back contract. This contract is located on the source exercises app. The contract name is withdrawal call back. Inside here, there's a function called after order execution. This is a function that is called by the call back util. After an order is executed, GMX will call this function after order execution, which will call the function after order execution on the call back contract that we specified. In this final project, you'll set this call back contract to the address of the withdrawal call back. There are other callbacks that are called in other cases after order cancellation. When the order is canceled, it will call into the
function called after order cancellation. This function also is declared inside the withdrawal call back contract which you will have to implement for the final project. And the same goes for after order frozen. After either of these three call back functions are called, the last function that is called is the function refund execution fee. This function is called to refund execution fee to the call back contract that is specified calling the function refund execution fee. One of the exercises in this final project is for you to also implement this function.
When the callback utils call the function refund execution fee inside here you'll implement the logic to refund execution fee to the user that created a withdrawal