Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add quoting logic of deactivated, stand-by, close-only modes of vaults #2299

Merged
merged 4 commits into from
Sep 20, 2024

Conversation

tqin7
Copy link
Contributor

@tqin7 tqin7 commented Sep 19, 2024

Changelist

in deactivated and stand-by mode, don't quote
in close-only mode: quote only if short or long

in another PR, i'm thinking:

  1. when setting a vault to deactivated or stand-by, cancel its existing orders, if any

Test Plan

unit tests

Author/Reviewer Checklist

  • If this PR has changes that result in a different app state given the same prior state and transaction list, manually add the state-breaking label.
  • If the PR has breaking postgres changes to the indexer add the indexer-postgres-breaking label.
  • If this PR isn't state-breaking but has changes that modify behavior in PrepareProposal or ProcessProposal, manually add the label proposal-breaking.
  • If this PR is one of many that implement a specific feature, manually label them all feature:[feature-name].
  • If you wish to for mergify-bot to automatically create a PR to backport your change to a release branch, manually add the label backport/[branch-name].
  • Manually add any of the following labels: refactor, chore, bug.

Summary by CodeRabbit

  • New Features

    • Enhanced vault order management with improved status checks and order placement logic.
    • Introduced a new cancellation function for vault orders to streamline operations.
    • Updated function to retrieve both vault and quoting parameters for better clarity.
  • Bug Fixes

    • Refined logic to prevent unnecessary order processing in inactive vault states.
  • Documentation

    • Updated function names and return values for clarity regarding vault and quoting parameters.
  • Tests

    • Expanded and restructured test cases to validate new functionalities and edge cases for vault orders and parameters.

@tqin7 tqin7 requested a review from a team as a code owner September 19, 2024 19:57
Copy link

linear bot commented Sep 19, 2024

Copy link
Contributor

coderabbitai bot commented Sep 19, 2024

Walkthrough

The changes primarily focus on enhancing the management of vault orders within the protocol. Key modifications include improved conditions for order placement based on vault status, refined order cancellation logic, and updates to the retrieval of vault and quoting parameters. New functions have been introduced for better organization, while existing tests have been updated to cover additional scenarios and ensure robustness. Overall, these changes aim to improve the accuracy and efficiency of vault order handling.

Changes

File Change Summary
protocol/x/vault/keeper/orders.go Enhanced vault order management logic, added new cancellation function, and refined order retrieval based on vault status.
protocol/x/vault/keeper/orders_test.go Updated tests to include position quantums, refined order refresh logic, and improved test structure for clarity.
protocol/x/vault/keeper/params.go Renamed function to reflect expanded functionality, updated return values for clarity in vault and quoting parameters.
protocol/x/vault/keeper/params_test.go Renamed test function to align with changes in vault and quoting parameters retrieval, updated assertions accordingly.
protocol/x/vault/keeper/withdraw.go Updated withdrawal slippage function to call new parameter retrieval function, simplifying the handling of quoting parameters.

Possibly related PRs

Suggested labels

indexer, proto

Poem

🐰 In the vaults where orders play,
A hop, a skip, they find their way.
With logic clear and tests anew,
The orders dance, as rabbits do!
So let us cheer, with joy and glee,
For vaults are managed perfectly! 🎉


Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between fac9716 and b1a062c.

Files selected for processing (5)
  • protocol/x/vault/keeper/orders.go (8 hunks)
  • protocol/x/vault/keeper/orders_test.go (30 hunks)
  • protocol/x/vault/keeper/params.go (1 hunks)
  • protocol/x/vault/keeper/params_test.go (2 hunks)
  • protocol/x/vault/keeper/withdraw.go (1 hunks)
Files skipped from review as they are similar to previous changes (3)
  • protocol/x/vault/keeper/params.go
  • protocol/x/vault/keeper/params_test.go
  • protocol/x/vault/keeper/withdraw.go
Additional comments not posted (12)
protocol/x/vault/keeper/orders.go (8)

37-38: LGTM!

The additional condition to skip vaults in CLOSE_ONLY status from placing orders is correct. Vaults in CLOSE_ONLY mode should not be actively quoting.


206-211: LGTM!

Returning no orders if the vault is in DEACTIVATED, STAND_BY, or CLOSE_ONLY with zero leverage is the correct behavior.


370-394: LGTM!

The new section to handle the CLOSE_ONLY vault status looks good. It correctly calculates the maximum reduce-only order size and filters the orders to only include the reduce side. This ensures that vaults in CLOSE_ONLY mode only place orders to reduce their position.


420-423: LGTM!

Using the new GetVaultAndQuotingParams function to retrieve the quoting parameters is a good change. It simplifies the code and ensures consistency. Returning an empty list of order IDs if the quoting parameters don't exist is also the correct behavior.


484-491: LGTM!

Using the new GetVaultAndQuotingParams function to retrieve the quoting parameters is a good change. It simplifies the code and ensures consistency.


492-495: LGTM!

Using the new CancelVaultClobOrder function to cancel the old order is a good change. It reuses the cancellation logic and ensures consistency.


455-474: Verify the order expiration calculation.

The new CancelVaultClobOrder function looks good. It correctly encapsulates the cancellation logic for vault CLOB orders. Calling the HandleMsgCancelOrder function from the CLOB keeper is the right approach.

Ensure that the order expiration calculation is correct:

Verification successful

Order expiration calculation verified

The order expiration calculation in the CancelVaultClobOrder function is correct. It properly sets the expiration time by adding orderExpirationSeconds to the current block time:

uint32(ctx.BlockTime().Unix())+orderExpirationSeconds,

This ensures that the order will expire after the specified duration from the current block time.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the order expiration calculation in `CancelVaultClobOrder`.

# Test: Search for the expiration calculation. 
# Expect: The expiration is calculated as the current block time plus the order expiration seconds.
rg --type go -A 5 $'uint32\(ctx\.BlockTime\(\)\.Unix\(\)\)\+orderExpirationSeconds'

Length of output: 501


130-144: Verify the usage of the new CancelVaultClobOrder function.

The new section to cancel stale orders looks good. It correctly iterates through the remaining most recent client IDs and cancels any orders that are no longer needed using the new CancelVaultClobOrder function.

Run the following script to verify the usage of CancelVaultClobOrder:

Verification successful

Verified: CancelVaultClobOrder is used correctly

The CancelVaultClobOrder function is implemented and used correctly in the codebase:

  • It's called in the RefreshVaultClobOrders function as reviewed earlier, with proper error handling.
  • The function signature matches the expected parameters (context, vaultId, orderId, orderExpirationSeconds).
  • It's also used in another context, likely for replacing orders, showing its reusability.
  • All usages include proper error handling.

The implementation aligns with the intended functionality of canceling stale or unnecessary orders in the vault CLOB system.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify `CancelVaultClobOrder` is only called with valid order IDs.

# Test: Search for the function usage. 
# Expect: Only occurrences with a check for order existence.
rg --type go -A 5 $'CancelVaultClobOrder'

Length of output: 501


Script:

#!/bin/bash
# Description: Verify `CancelVaultClobOrder` usage in the codebase

# Search for the function usage
rg --type go -A 5 'CancelVaultClobOrder'

Length of output: 1263

protocol/x/vault/keeper/orders_test.go (4)

Line range hint 36-57: LGTM!

The addition of the positionQuantums field enhances the test coverage by considering the vault's position when determining the expected order behavior. The field is correctly initialized in the test cases.


289-745: Great work on enhancing the test coverage!

The introduction of the Instance struct provides a modular approach to define test scenarios, improving the clarity and maintainability of the test function. The new test cases cover important scenarios related to vault status changes, ensuring the robustness of the RefreshVaultClobOrders function.

The changes are well-structured and do not introduce any apparent issues.


Line range hint 910-1665: Excellent addition of new test cases!

The new test cases cover important scenarios related to close-only vault status, ensuring the correctness of the GetVaultClobOrders function. The inclusion of the vaultStatus field in the test cases improves the test coverage by considering the vault's status.

The changes are well-structured and do not introduce any apparent issues.


1701-1706: Looks good!

The changes to the line numbers within the TestGetVaultClobOrderIds function are purely cosmetic and do not alter the functionality of the test. The test coverage remains unaffected.


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

Share
Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    -- I pushed a fix in commit <commit_id>, please review it.
    -- Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    -- @coderabbitai generate unit testing code for this file.
    -- @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    -- @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    -- @coderabbitai read src/utils.ts and generate unit testing code.
    -- @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    -- @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between cee80fc and fac9716.

Files selected for processing (5)
  • protocol/x/vault/keeper/orders.go (8 hunks)
  • protocol/x/vault/keeper/orders_test.go (30 hunks)
  • protocol/x/vault/keeper/params.go (1 hunks)
  • protocol/x/vault/keeper/params_test.go (2 hunks)
  • protocol/x/vault/keeper/withdraw.go (1 hunks)
Additional comments not posted (9)
protocol/x/vault/keeper/params.go (1)

97-119: LGTM! The changes improve the clarity and utility of the function.

The modifications to GetVaultAndQuotingParams enhance its usability and provide more comprehensive information to callers:

  • Renaming the function to GetVaultAndQuotingParams better reflects its expanded functionality of returning both vault parameters and quoting parameters.
  • Updating the return values to include both vaultParams and quotingParams ensures that callers receive all relevant information.
  • Returning the default quoting parameters when vaultParams.QuotingParams is nil guarantees that callers always receive quoting parameters, even if not specifically set for the vault.

Overall, these changes make the function more robust and informative, improving its utility within the codebase.

protocol/x/vault/keeper/params_test.go (1)

Line range hint 149-199: LGTM!

The test function TestGetVaultAndQuotingParams is well-structured and covers the necessary scenarios for retrieving vault and quoting parameters. The test cases verify the behavior with default quoting params, custom quoting params, and non-existent vault params. The assertions are correct and ensure the expected values are returned.

protocol/x/vault/keeper/withdraw.go (1)

58-58: LGTM! The change adapts to the refactored function signature while preserving the original functionality.

The updated function call to GetVaultAndQuotingParams suggests a refactoring in how vault-related data is accessed. The change maintains the retrieval of quoting parameters and the existence check, discarding the additional vault value that is not used in this context. The logic flow remains intact, ensuring the correct behavior of the GetVaultWithdrawalSlippage function.

protocol/x/vault/keeper/orders.go (6)

37-38: Handles CLOSE_ONLY status in order refresh logic

The updated condition now includes VAULT_STATUS_CLOSE_ONLY, ensuring that vaults in both QUOTING and CLOSE_ONLY statuses are processed correctly during the order refresh.


110-111: Improved order replacement condition by including Subticks

By adding the comparison of Subticks, the logic ensures that orders are replaced when there's a price change, enhancing accuracy in order management.


130-145: Cancellation of unnecessary orders to maintain order accuracy

The added logic correctly cancels orders that are no longer needed, preventing stale orders from remaining in the order book and ensuring the vault's orders reflect the current state.


206-212: Prevents order placement when vault is inactive or has no position

The function now returns no orders if the vault is DEACTIVATED, STAND_BY, or CLOSE_ONLY with zero leverage, which aligns with expected behavior to avoid unnecessary order placement.


370-389: Generates reduce-only orders in CLOSE_ONLY mode

When the vault is in CLOSE_ONLY status with a non-zero leverage, the code correctly generates reduce-only orders to close existing positions. It adjusts the order quantities based on the vault's inventory, ensuring orders do not exceed the position size.


Line range hint 414-418: Ensures quoting parameters exist before generating order IDs

By checking the existence of quoting parameters, the function avoids potential errors due to missing parameters, ensuring that order IDs are generated only when all necessary data is available.

protocol/x/vault/keeper/orders.go Show resolved Hide resolved
protocol/x/vault/keeper/orders_test.go Show resolved Hide resolved
protocol/x/vault/keeper/orders_test.go Show resolved Hide resolved
i = 1
}
for ; i < len(orders); i += 2 {
reduceOnlyOrders[i/2] = orders[i]
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: Rather than do the division, maybe just keep another index counter that you increment per loop iteration?

Copy link
Contributor Author

@tqin7 tqin7 Sep 20, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

changed to using closeOnlySide to filter. no more indexing

stepSize := lib.BigU(clobPair.StepBaseQuantums)
reduceOnlyMaxOrderSize.Quo(reduceOnlyMaxOrderSize, stepSize)
reduceOnlyMaxOrderSize.Mul(reduceOnlyMaxOrderSize, stepSize)
// If vault is long, only need sell orders (even indices).
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

non-blocking: I wonder if this code could be built slightly more future-proof by setting some closeOnlySide based on long/short, then filtering out the orders from the generated orders rather than using even/odd indices.

},
},
},
"Success - Orders refresh due to status changing to close-only. No more orders": {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: Note that the vault has no position in this test-case?

},
},
},
"Success - Orders refresh due to status changing to close-only. Sell orders only": {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: Another similar test-case for STAND_BY and DEACTIVATED?

Copy link
Contributor Author

@tqin7 tqin7 Sep 20, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

right now we simply skip refresh orders if status is stand_by or deactivated (no order is cancelled) . I'm planning to have another change that cancels existing orders if status is changed to stand_by or deactivated and will add these test cases in that change

41_666_000,
},
},
"Success - Vault Clob 1, close-only status, 2 layers, leverage 0.6, sell orders only, order size": {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: Update title to indicate this is for capped order size = position size.

reduceOnlyOrders := make([]*clobtypes.Order, quotingParams.Layers)
reduceOnlyMaxOrderSize := k.GetVaultInventoryInPerpetual(ctx, vaultId, perpetual.Params.Id)
stepSize := lib.BigU(clobPair.StepBaseQuantums)
reduceOnlyMaxOrderSize.Quo(reduceOnlyMaxOrderSize, stepSize)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: Return no orders if this is 0?

@tqin7 tqin7 merged commit 5abfb15 into main Sep 20, 2024
21 of 22 checks passed
@tqin7 tqin7 deleted the tq/tra-620 branch September 20, 2024 16:23
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Development

Successfully merging this pull request may close these issues.

2 participants