Skip to content

moved the store position to HandleOrderEvent so that the positions ar…#56

Merged
Chocksy merged 3 commits intomainfrom
store-positions-handle-event
Jan 21, 2025
Merged

moved the store position to HandleOrderEvent so that the positions ar…#56
Chocksy merged 3 commits intomainfrom
store-positions-handle-event

Conversation

@ffahimi
Copy link
Collaborator

@ffahimi ffahimi commented Jan 20, 2025

…e continuously saved on OrderEvents

Summary by CodeRabbit

  • New Features

    • Enhanced position storage management during live mode operations.
  • Bug Fixes

    • Removed position storing logic at the end of the algorithm's execution in live mode.
  • Tests

    • Expanded test coverage for the HandleOrderEvents class to verify behavior under different LiveMode conditions.

@ffahimi ffahimi requested a review from Chocksy January 20, 2025 15:59
@coderabbitai
Copy link

coderabbitai bot commented Jan 20, 2025

Walkthrough

The changes involve modifications to the position storage mechanism in the order handling and algorithm execution processes. The HandleOrderEvents class now includes a conditional statement that triggers position storage during live mode operations. Concurrently, the position storing logic has been removed from the OnEndOfAlgorithm method in the main.py file, transferring the responsibility of position storage to the HandleOrderEvents class. Additionally, the test suite for HandleOrderEvents has been updated to reflect these changes and ensure proper functionality under different operational modes.

Changes

File Change Summary
Initialization/HandleOrderEvents.py Added self.positions_store instance variable. Introduced conditional call to store_positions() in Call method when self.context.LiveMode is true.
main.py Removed position storing logic from OnEndOfAlgorithm method, while retaining other execution and performance logging functionalities.
Tests/specs/initialization/handle_order_events_spec.py Initialized self.algorithm.positions_store. Added new test cases for Call method under different LiveMode conditions, and modified existing tests to ensure proper interaction with positions_store.

Poem

🐰 A Rabbit's Tale of Code Refactor
Positions dance, a new store takes flight,
From end of algo, logic takes might.
Live mode whispers, changes unfurl,
Code flows smooth, like a rabbit's pearl.
Refactoring magic, clean and bright! 🔧

✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

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 generate docstrings to generate docstrings for this PR. (Beta)
  • @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

@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: 1

🧹 Nitpick comments (2)
Initialization/HandleOrderEvents.py (2)

44-44: Remove unnecessary empty line.

This empty line creates extra spacing without adding readability.


45-46: Consider performance impact of frequent position storage.

The position storage is called on every order event in live mode. While this ensures continuous position tracking, it might impact performance if there are many rapid order events.

Consider adding a debounce mechanism or batch processing for position storage to optimize performance while maintaining data consistency.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between a382960 and ef6e575.

📒 Files selected for processing (2)
  • Initialization/HandleOrderEvents.py (1 hunks)
  • main.py (0 hunks)
💤 Files with no reviewable changes (1)
  • main.py
🧰 Additional context used
🪛 Ruff (0.8.2)
Initialization/HandleOrderEvents.py

37-37: PositionsStore may be undefined, or defined from star imports

(F405)

🔇 Additional comments (1)
Initialization/HandleOrderEvents.py (1)

37-37: 🛠️ Refactor suggestion

Add explicit import for PositionsStore.

The PositionsStore class is not explicitly imported. While it might be available through star imports, it's better to make dependencies explicit for better code maintainability and clarity.

Let's verify the PositionsStore class existence and location:

✅ Verification successful

Add explicit import for PositionsStore through the Tools package

Update the Tools import line to include PositionsStore:

from Tools import Logger, Helper, PositionsStore
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for PositionsStore class definition
rg -l "class\s+PositionsStore"

# Search for PositionsStore imports
rg "from.*import.*PositionsStore|import.*PositionsStore"

Length of output: 354


Script:

#!/bin/bash
# Check imports in HandleOrderEvents.py
rg "^from|^import" Initialization/HandleOrderEvents.py

Length of output: 149

🧰 Tools
🪛 Ruff (0.8.2)

37-37: PositionsStore may be undefined, or defined from star imports

(F405)

@codecov
Copy link

codecov bot commented Jan 20, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 71.33%. Comparing base (a382960) to head (2c53c7c).
Report is 3 commits behind head on main.

✅ All tests successful. No failed tests found.

Additional details and impacted files
@@            Coverage Diff             @@
##             main      #56      +/-   ##
==========================================
+ Coverage   71.12%   71.33%   +0.20%     
==========================================
  Files          30       30              
  Lines        2691     2693       +2     
==========================================
+ Hits         1914     1921       +7     
+ Misses        777      772       -5     
Flag Coverage Δ
unittests 71.33% <100.00%> (+0.20%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

@Chocksy Chocksy merged commit 2c53c7c into main Jan 21, 2025
3 of 4 checks passed
@Chocksy Chocksy deleted the store-positions-handle-event branch January 21, 2025 17:58
Copy link

@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: 1

🧹 Nitpick comments (2)
Tests/specs/initialization/handle_order_events_spec.py (2)

93-113: Add test documentation to clarify position storage triggers.

While the test correctly verifies position storage in live mode, it would be more maintainable to document the specific conditions that trigger position storage (e.g., order status, live mode state).

Add a descriptive comment before the test:

        with it('stores positions in live mode'):
+            # Verify that positions are stored when:
+            # 1. Algorithm is in LiveMode
+            # 2. Order is filled (Status=OrderStatus.Filled)
+            # 3. Position is found from the order event

115-135: Consider reducing test setup duplication.

The setup code for position and order mocking is duplicated between live mode and backtest mode tests. Consider extracting common setup into helper methods.

Example refactor:

def setup_position_and_order(self):
    position = MagicMock(
        orderTag="TEST_POS",
        legs=[MagicMock(symbol=self.order_event.Symbol)]
    )
    mock_order = MagicMock()
    mock_order.Tag = "TEST_POS"
    self.algorithm.Transactions.GetOrderById.return_value = mock_order
    
    self.handler.getPositionFromOrderEvent = MagicMock(
        return_value=(position, None, "close", mock_order)
    )
    return position, mock_order

Then use it in both tests:

with it('stores positions in live mode'):
    self.algorithm.LiveMode = True
    setup_position_and_order(self)
    self.handler.Call()
    self.algorithm.positions_store.store_positions.assert_called_once()
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between d412b72 and 2c53c7c.

📒 Files selected for processing (2)
  • Initialization/HandleOrderEvents.py (1 hunks)
  • Tests/specs/initialization/handle_order_events_spec.py (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • Initialization/HandleOrderEvents.py
🔇 Additional comments (2)
Tests/specs/initialization/handle_order_events_spec.py (2)

39-39: LGTM! Good test setup practice.

Initializing positions_store mock in before.each ensures consistent test state across all test cases.


93-158: Consider adding test coverage for position storage order of operations.

The current tests verify that position storage occurs in live mode, but don't verify when it happens in relation to other operations (e.g., before/after updating order stats, handling assignments, etc.). Consider adding tests to verify the correct sequence of operations.

Example test case to add:

with it('stores positions after handling the order'):
    self.algorithm.LiveMode = True
    position, mock_order = setup_position_and_order(self)
    
    # Track operation sequence
    operation_sequence = []
    position.updateOrderStats.side_effect = lambda: operation_sequence.append('update_stats')
    self.algorithm.positions_store.store_positions.side_effect = \
        lambda: operation_sequence.append('store_positions')
    
    self.handler.Call()
    
    # Verify store_positions is called after updating order stats
    expect(operation_sequence).to(equal(['update_stats', 'store_positions']))

Comment on lines +137 to +158
with it('handles missing positions_store in live mode'):
# Setup LiveMode but remove positions_store
self.algorithm.LiveMode = True
# No need to remove positions_store as it doesn't exist by default

# Setup mock position and order
position = MagicMock(
orderTag="TEST_POS",
legs=[MagicMock(symbol=self.order_event.Symbol)]
)
mock_order = MagicMock()
mock_order.Tag = "TEST_POS"
self.algorithm.Transactions.GetOrderById.return_value = mock_order

self.handler.getPositionFromOrderEvent = MagicMock(
return_value=(position, None, "close", mock_order)
)

# Should not raise an error
self.handler.Call()
# Test passes if no exception is raised

Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix incorrect test implementation for missing positions_store scenario.

The test claims to verify behavior when positions_store is missing, but positions_store is always initialized in before.each. This means the test isn't actually testing the intended scenario.

To properly test this scenario:

        with it('handles missing positions_store in live mode'):
            # Setup LiveMode but remove positions_store
            self.algorithm.LiveMode = True
-            # No need to remove positions_store as it doesn't exist by default
+            # Remove positions_store to test the scenario
+            delattr(self.algorithm, 'positions_store')
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
with it('handles missing positions_store in live mode'):
# Setup LiveMode but remove positions_store
self.algorithm.LiveMode = True
# No need to remove positions_store as it doesn't exist by default
# Setup mock position and order
position = MagicMock(
orderTag="TEST_POS",
legs=[MagicMock(symbol=self.order_event.Symbol)]
)
mock_order = MagicMock()
mock_order.Tag = "TEST_POS"
self.algorithm.Transactions.GetOrderById.return_value = mock_order
self.handler.getPositionFromOrderEvent = MagicMock(
return_value=(position, None, "close", mock_order)
)
# Should not raise an error
self.handler.Call()
# Test passes if no exception is raised
with it('handles missing positions_store in live mode'):
# Setup LiveMode but remove positions_store
self.algorithm.LiveMode = True
# Remove positions_store to test the scenario
delattr(self.algorithm, 'positions_store')
# Setup mock position and order
position = MagicMock(
orderTag="TEST_POS",
legs=[MagicMock(symbol=self.order_event.Symbol)]
)
mock_order = MagicMock()
mock_order.Tag = "TEST_POS"
self.algorithm.Transactions.GetOrderById.return_value = mock_order
self.handler.getPositionFromOrderEvent = MagicMock(
return_value=(position, None, "close", mock_order)
)
# Should not raise an error
self.handler.Call()
# Test passes if no exception is raised

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants