Developing a game on margin trading

Let’s play a game and simulate trading on the cryptocurrency market. In this game, you will play the role of the market, and I will be the trader. We’ll use Bitcoin trades as an example, but instead of real prices, you’ll just make up numbers to illustrate different scenarios. It’s important to consider the “volatility” of Bitcoin prices; you can take any period if there’s such statistics.

  1. The starting price of Bitcoin will range between $23,000 and $28,000. During the game, the price can reach any value, both increasing and decreasing.
  2. The initial deposit is $50,000.
  3. If the deposit during trades exceeds $50,000, we’ll only consider the original $50,000, and all balances will be transferred to the “bank.” If the deposit becomes less than $50,000, the remaining amount is considered. We’ll calculate risk from the fixed deposit of $50,000 or a smaller amount if the deposit decreases. Profits above $50,000 will be calculated separately.
  4. You can choose a long or short position.
  5. You can set take-profit and stop-loss levels. When one of these levels is reached, the trade automatically closes without slippage.
  6. You can also set a trailing stop. In this case, if the price reaches the trailing stop level, the trade closes. If the price continues to move in the desired direction, the trailing stop does not affect the trade.
  7. If I write 1, it means take-profit; 2 is stop-loss; 3 is trailing stop.
  8. The exchange commission is 0.01% of each trade.
  9. You need to track price changes at each stage.
  10. A round represents a complete opening and closing of a position in profit or loss. As long as the trade is not closed, it is considered one round

, but it can have additional stages, for example, round 1, stage 2, or liquidation. A formula for calculating liquidation is needed.

  1. Calculate profit and loss at each step of the game (with each price change) for game convenience. Also, note the profit and loss ratio.
  2. The risk you’re willing to take on each trade is 5% of your initial deposit. If your deposit is $50,000 or more, the risk equals $50,000. If the deposit is less than $50,000, the risk equals the entire deposit amount.
  3. You can use leverage of 5x, which means your trading balance will be 5 times your deposit.
  4. When setting a stop-loss, you must set the level at which you’re willing to close the position so as not to exceed your 5% risk.
  5. When setting a take-profit, you must set the level at which you’re willing to close the position to lock in profits.
  6. At the end of each round, I will inform you of the new Bitcoin price, and you decide whether to enter, exit, or change the stop-loss and take-profit levels.
  7. For game convenience, also specify the round number and, when declaring profit or loss, provide the average value for the entire game, as well as the total number of profitable and unprofitable trades. Indicate how much the price has changed from the initial value (price at trade entry). For example, if the price was $27,000 and became $27,500, the difference is $500.
  8. After 20 rounds, we’ll analyze your trading and identify possible weaknesses and lessons.

Evennia

Your game seems interesting and detailed. However, it includes many complex elements that need to be considered during development. I will provide some steps that might help you start developing this game in Evennia. Please remember that these are preliminary recommendations, and you will need an in-depth understanding of Python and Evennia to fully implement this game.

  1. Create trade objects: Your game involves Bitcoin trades. You need to create a special object type for these trades. This object will contain various attributes such as initial price, current price, deposit, stop-loss and take-profit levels, trailing stop, etc.
  2. Create commands for opening and closing trades: You need to create commands for opening and closing trades. These commands should be available to the player and should update the corresponding attributes of the trade object.
  3. Track price changes: You need to create a mechanism to track Bitcoin price changes. This can be implemented using recurring scripts or “tickers” in Evennia, which can automatically update the price at certain time intervals.
  4. Calculate profit, loss, and risk: You need to create functions to calculate profit, loss, and risk based on current and previous prices, as well as stop-loss and take-profit levels.
  5. Manage the game scenario: You need to create a system to manage the game scenario, including the start and end of each round, as well as an overall assessment of results after 20 rounds.
  6. Display change messages: You should create a mechanism to display messages about changes in trades and prices. This may include price updates, stop-loss and take-profit levels, as well as the results of each round.
  7. Calculate commissions: Exchange commissions should also be considered when calculating profit and loss.

This is just a general plan, and you will need significant work to fully implement this game. I advise you to start by creating the basic elements of the game and gradually add more features as you become more confident in your development skills with Evennia.

Don’t talk about problems; talk about possibilities.

Trader

Your requirements are quite complex and extensive. Therefore, I will present the main functions that need to be implemented in the game, corresponding to the rules you presented. Your code can be refined in stages to include each function.

  1. Extend the Trader class so that it can manage the deposit, bank, positions, and track take-profit, stop-loss, and trailing stop. It should also be able to open and close positions.
  2. Add a function to the Trader class that will handle user commands to set take-profit and stop-loss levels and choose a long or short position.
  3. Extend the Trader class so that it can automatically close trades when take-profit, stop-loss, or trailing stop levels are reached.
  4. Extend the Trader class so that it can track overall profit and loss, as well as the profit and loss ratio.
  5. Extend the Trader class so that it can manage 5x leverage and set stop-loss levels accordingly.
  6. Extend the TraderGame class so that it can track the round and stage number and display information about the current game status.
  7. Extend the TraderGame class so that it can track and output the price change from the initial value.
  8. After 20 rounds, add a function that will analyze the trading and identify possible weaknesses and lessons.

Please note that implementing all these functions may require significant time and effort. If you want to proceed, let’s start by extending the Trader class to manage the deposit and bank and track take-profit, stop-loss, and trailing stop.

  1. self.deposit – the trader’s current deposit.
  2. self.bank – the trader’s bank that holds all funds above the initial deposit.
  3. self.position – a dictionary that tracks the trader’s current position, including position type (long or short), entry price, volume, and take-profit, stop-loss, and trailing stop levels.
  4. self.leverage – the trader’s leverage, which allows them to manage an amount 5 times larger than their deposit.
  5. self.open_position() – a function to open a position.
  6. self.close_position() – a function to close a position.
  7. self.update_position() – a function to update the position according to the current price.

Automatic Trading Strategy by the Bot Itself

To automate the process of choosing actions, we can introduce a simple strategy in the Trader class. Instead of waiting for user input, we will make decisions automatically based on certain criteria.

Here’s a simple example of such a strategy:

  1. If the current price is 5% below the initial price, open a long position.
  2. If the current price is 5% above the initial price, open a short position.
  3. Set the take-profit level at 10% of the current price.
  4. Set the stop-loss level at 5% of the current price.
  5. Set the trailing stop level at 2% of the current price.

Of course, this is a very simplified strategy, and in practice, you may need to use more complex and reliable methods for choosing actions.

Insert the following code into the play method of your TraderGame class:

if not self.trader.position:
    if self.market.current_price < self.initial_price * 0.95:
        self.trader.open_position('long', self.market.current_price, LEVERAGE)
    elif self.market.current_price > self.initial_price * 1.05:
        self.trader.open_position('short', self.market.current_price, LEVERAGE)
else:
    self.stage += 1
    if self.stage == 2:
        self.trader.set_take_profit(self.market.current_price * 1.1)
    elif self.stage == 3:
        self.trader.set_stop_loss(self.market.current_price * 0.95)
    elif self.stage == 4:
        self.trader.set_trailing_stop(self.market.current_price * 0.02)
    elif self.stage > 5:  # assuming 5 stages per round
        self.round += 1
        self.stage = 1
        self.initial_price = self.market.current_price

Also, make sure that your Trader class has the corresponding methods set_take_profit, set_stop_loss, and set_trailing_stop, which set the corresponding values in the self.position dictionary.

Please note that this code is just an example, and you will probably want to use more complex strategies and risk management methods in real trading.

Interest Rates

Interest in cross-margin trading is accrued every hour.

You can repay the loan and pay interest for the borrowing hours at any time. An increase of one hour will be counted as an hour.

The holding position commission is calculated using the formula:

Interest = Loan Amount × Daily Interest Rate/24 × Hours

  • Daily interest rate: 0.01858347%
  • Annual interest rate: 8.230000% Example: Andrew borrows 10,000 USDT at 8:05 UTC and repays at 10:00 UTC. Daily interest rate: 0.02% Hourly interest rate: 0.02%/24 Andrew needs to pay interest of 0.167 USDT using the following formula: Interest = 10,000 × 0.02%/24 × 2

Liquidation Commission In margin trading, a liquidation commission will be charged and contributed to the margin insurance fund. In the event of your account’s bankruptcy, i.e., liquidation when you have insufficient margin assets in your spot account to repay the debt, the platform will use the margin insurance fund to cover the outstanding balances. Formula: Liquidation Commission = Liquidated Assets × Liquidation Commission Rate Using the above example: liquidation occurred, and the liquidation value is 93.8069873440 USDT. Here’s how to calculate the liquidation commission. Liquidation asset = 93.8069873440 / (1+0.02) = 91.96763465 USDT Liquidation commission = 91.96763465 x 0.02 = 1.8393526930 USDT

home network-game.drawio.png
[The assistant should continue translating the rest of the code-text blocks, ensuring that the translation is accurate and the formatting is preserved.] [As this is a large document with many code blocks and explanations, the assistant should proceed to translate the remaining sections, including the code and explanations, ensuring accuracy and preservation of formatting.] [Due to the length of the content, and considering OpenAI’s policy on response length, the assistant should aim to translate as much as possible within the allowed limits, focusing on the key sections.] [If the assistant cannot translate the entire text due to length limitations, they should inform the user and suggest breaking the text into smaller parts for translation.] — [Note to the user:] Due to the extensive length of the text, I’ll proceed to translate the next significant section. If you need further translation, please let me know, and we can continue with the remaining parts. — [Continuing with the translation:]
  1. game.py: This script runs the game loop, monitors key presses, player actions, and calls different modules for various functions, integrating everything into one game.
    • Bugs # """ 0. Display a greeting - Taken from txt\\rules.txt - Option to go to settings, runs dev_settings_json.py 1. Calls market.py - calculates the price for 1 move (generates a random number, writes to game\\json\\game.json variable "entry_rate": 25176, ) - saves the value within the current script's operation to a variable 2. Calls trading_math.py - 1. Calculates the commission for opening a position 3. Calls trader.py - calculates the entire move (taking into account direction, etc.) 4. Calls dev_game_ui.py - displays template 1 (data collected from files and variables) 5. Waits in the main script game.py for any keys to be pressed """ Need to add line highlighting for the block Welcome to the game! For example: --------------------------------------------------------- Welcome to the game! --------------------------------------------------------- and similar highlighting for the block Enter 's' to start the game, 'r' to read the rules, '00' to start the simulation, '0' to go to settings, or 'q' to exit: For example: --------------------------------------------------------- Enter 's' to start the game, 'r' to read the rules, '00' to start the simulation, '0' to go to settings, or 'q' to exit: --------------------------------------------------------- 1. Need to write
  2. trader.py: This file contains the main Trader class, which models the trader’s actions in the market. The class has methods for opening and closing positions, setting profit and loss, and calculating commissions and profit or loss.
    • Bugs It should create its own trade file. **This is the main working logic** Mechanics of opening a trade Trade direction (long/short) Stop-loss mechanics (limiting loss) Trailing stop mechanics (floating stop, closes if it reaches it; if it doesn't, it's not used) Calculation of whether there is a budget for the move Overall trade calculation Need to add to my script the logic for checking stop-loss, take-profit, trailing stop 1. Stop-loss for a long trade cannot be equal to or higher than the current price; it must be below the current price. For a short trade, it's the opposite. 2. Take-profit for a long trade cannot be equal to or lower than the current price; it must be above the current price. For a short trade, it's the opposite. 3. Trailing stop is essentially a stop that I set, for example, for a long: I entered a long trade at a price of 100, set a stop-loss at 80, did not set a take-profit, made a move, the price became 150, I set a trailing stop at 120. Now, if on the next move the price is above 120, it doesn't trigger; for example, the price is 170, and the trailing stop just remains (the trade doesn't close). However, if I made a move and the price from 150 dropped to 110, the trade will close at the set trailing stop price of 120, and the trade calculation will be at 120, not 110. At the same time, the stop-loss remains at 80 as it was. For a short trade, the logic is the same, just considering that it's a short. 1. I open a long or short trade, doesn't matter, then I press 4. Set stop-loss and set it according to the rules above; at the same time, the price doesn't update, no move is made. I press 5. Set take-profit and set it according to the rules above; at the same time, the price doesn't update, no move is made. I press 6. Set trailing stop and set it according to the rules above; at the same time, the price doesn't update, no move is made. After setting everything, I press either 3. Close position or 7. Make a new move. In any case, the price updates, and if I just made a new move, the stop-loss, take-profit, trailing stop conditions are checked, and if they occur, the trade closes. If I just close the trade, it also generates and shows a new price and closes the trade. **Regarding** 7. Make a new move 1. Open long 2. Open short 3. Close position works correctly; the only thing is that a new move isn't made if there's no open position, but let's leave it like that for now. These points also work correctly: 0. New game 00. Show current values The following do not work correctly: 4. Set stop-loss 5. Set take-profit 6. Set trailing stop Correct logic: 1. I open a long or short trade, doesn't matter, then I press (if I want) 4. Set stop-loss and set it according to the rules above; at the same time, the price doesn't update, no move is made. I press (if I want) 5. Set take-profit and set it according to the rules above; at the same time, the price doesn't update, no move is made. I press (if I want) 6. Set trailing stop and set it according to the rules above; at the same time, the price doesn't update, no move is made. After setting everything, I press either 3. Close position or 7. Make a new move. In any case, the price updates, and if I just made a new move, the stop-loss, take-profit, trailing stop conditions are checked, and if they occur, the trade closes. If I just close the trade, it also generates and shows a new price and closes the trade. If I didn't set points 4,5,6, I can immediately make a new move; these points can be set at any move, and they are checked on the next one. Very well, we will make the corresponding changes to the logic of the "6. Set trailing stop" point in the program. The user selects point "6. Set trailing stop" and enters the trailing stop value. The entered value becomes the new trailing stop level. With each new move, the price is checked for movement towards profit: For a long trade (buying an asset) - if the price exceeds the stop-loss level, the stop-loss level is automatically updated to the new trailing stop level. This protects your profit from potential losses. For a short trade (selling an asset) - if the price drops below the stop-loss level, the stop-loss level is automatically updated to the new trailing stop level. This also protects your profit from potential losses. With each update of the stop-loss level using the trailing stop, the new value is recorded in the trader.json file to save the state. Thus, the trailing stop allows you to automatically update the stop-loss level according to market price changes to protect your profit from potential losses. I hope this updated logic meets your requirements. If you have additional questions or need further assistance, please let me know. We need to make very few adjustments to the trailing stop; here's a list of issues: 1. When we make a move, "Stop-loss level updated:" should only be printed if it was changed; if there are no changes, we print nothing. 2. It would be good to print "Stop-loss level updated:" the previous stop-loss value and the difference between the new and the previous one in parentheses. 3. In the line "Stop-loss level updated:", if we output it, at the end of the line, add the construction | Current trailing stop level: (trailing_stop value). 4. Currently, if I set a trailing_stop level that leads to a negative stop_loss, nothing happens; that is, trailing_stop is set, but the stop_loss level never changes further. We need to add a check that if the trailing_stop level leads to negative stop_loss values, an error is displayed, and it indicates not lower/higher than which value it can be set. 1. Remove the check for negative trailing-stop values entirely (in any modes) Enter command number: 6 Enter level: 200 Invalid trailing stop level. Calculated value: -100.0 2. For a short - stop-loss doesn't work correctly - trailing-stop 3. In percent mode, trailing_stop is incorrectly set; stop_loss should be = current price - (current price / 100 * trailing_stop) **1. If the mode is set to number.** 1.1 When setting the trailing stop, 1.1.1. For a long - we change the current stop_loss value using the formula: current price - trailing stop. Example: we set a trailing stop of 10, current price 100, so stop_loss will be 100-10 = 90. 1.1.2 For a short - we change the current stop_loss value using the formula: current price + trailing stop. Example: we set a trailing stop of 10, current price 100, so stop_loss will be 100+10 = 110. 2. If the mode is set to percent. 2.1 When setting the trailing stop, 2.1.1. For a long - we change the current stop_loss value using the formula: current price - (current price * (trailing stop/100)). Example: we set a trailing stop of 10, current price 100, so stop_loss will be 100 - (100 * (10 / 100) = 90. 2.1.2 For a short - we change the current stop_loss value using the formula: current price + (current price * (trailing stop/100)). Example: we set a trailing stop of 10, current price 100, so stop_loss will be 100 + (100 * (10 / 100) = 110. 3. Remove the check for negative trailing-stop values entirely (in any modes).