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

chore: update simple chart with real data #13

Merged
merged 1 commit into from
Feb 4, 2025

Conversation

shafin-deriv
Copy link
Contributor

@shafin-deriv shafin-deriv commented Feb 4, 2025

This pull request includes several changes to the codebase, primarily focusing on the integration of a new chart component that displays market data using WebSocket, and the removal of the old WebSocket implementation from the App. Below are the most important changes:

Integration of Chart Component:

  • src/components/Chart/Chart.tsx: Introduced the Chart component which displays market data using WebSocket integration. This component handles real-time price updates, connection status, and error handling.
  • src/components/Chart/README.md: Added documentation for the Chart component, detailing its usage, props, implementation details, and future enhancements.

Dependency Updates:

  • package.json: Added the lightweight-charts library as a new dependency to support the charting functionality.

Removal of Old WebSocket Implementation:

Structural Documentation Update:

  • src/STRUCTURE.md: Updated the project structure documentation to include the new Chart component under reusable UI components.

Test Cleanup:

These changes collectively enhance the application's ability to display real-time market data and streamline the code by removing redundant WebSocket implementations.

Summary by Sourcery

Introduce a new Chart component to display real-time market data using a WebSocket connection. Remove the old WebSocket implementation from the App component and update tests accordingly.

New Features:

  • Display real-time market data with the new Chart component.

Tests:

  • Update tests to reflect the changes in the Chart and App components.

Copy link

sourcery-ai bot commented Feb 4, 2025

Reviewer's Guide by Sourcery

This pull request introduces a new Chart component that displays market data using WebSocket, replacing the old WebSocket implementation in the App component. It also includes dependency updates and test cleanup.

Sequence diagram for Chart component WebSocket interaction

sequenceDiagram
    participant C as Chart Component
    participant WS as WebSocket Hook
    participant S as Market Server
    participant CH as Chart Library

    C->>WS: Initialize with R_100 instrument
    WS->>S: Connect
    S-->>WS: Connection established
    WS-->>C: isConnected = true

    loop Real-time updates
        S->>WS: Price update
        WS->>C: onPrice callback
        C->>CH: Update chart data
        C->>C: Update current price display
    end

    Note over C,S: Connection can be lost
    S-xWS: Connection lost
    WS-->>C: isConnected = false
    C->>C: Show disconnected message
Loading

Class diagram for Chart component structure

classDiagram
    class Chart {
        +className?: string
        -chartContainerRef: RefObject
        -chartRef: IChartApi
        -seriesRef: BaselineSeries
        -currentPrice: number
        -currentTime: string
        -priceHistory: ChartData[]
        +render()
    }

    class ChartData {
        +time: UTCTimestamp
        +value: number
    }

    class useMarketWebSocket {
        +isConnected: boolean
        +onConnect(): void
        +onError(error: Error): void
        +onPrice(price: Price): void
    }

    Chart --> ChartData: uses
    Chart --> useMarketWebSocket: uses
Loading

File-Level Changes

Change Details Files
Introduced a new Chart component to display market data using WebSocket.
  • Implemented the Chart component using lightweight-charts library.
  • Integrated WebSocket to receive real-time price updates.
  • Displayed current price and time information.
  • Handled connection status and displayed a disconnected message when WebSocket is not connected.
src/components/Chart/Chart.tsx
Added documentation for the Chart component.
  • Documented the usage, props, and implementation details of the Chart component.
  • Included future enhancement suggestions.
src/components/Chart/README.md
Updated dependencies by adding lightweight-charts.
  • Added lightweight-charts library to package.json.
  • Updated package-lock.json to reflect the new dependency.
package.json
package-lock.json
Removed the old WebSocket implementation from the App component.
  • Removed the useMarketWebSocket hook from App.tsx.
  • Removed related useEffect hook for connection status logging.
src/App.tsx
Removed tests related to the old WebSocket implementation.
  • Removed mocks and tests for the useMarketWebSocket hook.
  • Removed tests related to WebSocket connection status and error handling.
src/App.test.tsx
Updated project structure documentation to include the new Chart component.
  • Added the Chart component to the list of reusable UI components in STRUCTURE.md.
STRUCTURE.md
Removed outdated tests for the Chart component.
  • Removed the old Chart.test.tsx file.
src/components/Chart/__tests__/Chart.test.tsx

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!
  • Generate a plan of action for an issue: Comment @sourcery-ai plan on
    an issue to generate a plan of action for it.

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

Copy link

Deploying champion-trader with  Cloudflare Pages  Cloudflare Pages

Latest commit: 0255f8a
Status: ✅  Deploy successful!
Preview URL: https://ab32639f.champion-trader.pages.dev
Branch Preview URL: https://shafin-championtrader-feat-c.champion-trader.pages.dev

View logs

Copy link

github-actions bot commented Feb 4, 2025

Dependency Review

✅ No vulnerabilities or license issues or OpenSSF Scorecard issues found.

OpenSSF Scorecard

PackageVersionScoreDetails
npm/fancy-canvas 2.1.0 UnknownUnknown
npm/lightweight-charts 5.0.1 🟢 6
Details
CheckScoreReason
Maintained🟢 1030 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 10
Code-Review⚠️ 2Found 4/15 approved changesets -- score normalized to 2
Token-Permissions🟢 9detected GitHub workflow tokens with excessive permissions
Packaging⚠️ -1packaging workflow not detected
Dangerous-Workflow🟢 10no dangerous workflow patterns detected
CII-Best-Practices⚠️ 0no effort to earn an OpenSSF best practices badge detected
Binary-Artifacts🟢 10no binaries found in the repo
Pinned-Dependencies⚠️ 0dependency not pinned by hash detected -- score normalized to 0
Security-Policy⚠️ 0security policy file not detected
Vulnerabilities🟢 100 existing vulnerabilities detected
License🟢 10license file detected
Branch-Protection⚠️ -1internal error: error during branchesHandler.setup: internal error: githubv4.Query: Resource not accessible by integration
Signed-Releases⚠️ -1no releases found
Fuzzing⚠️ 0project is not fuzzed
SAST⚠️ 0SAST tool is not run on all commits -- score normalized to 0
npm/lightweight-charts ^5.0.1 🟢 6
Details
CheckScoreReason
Maintained🟢 1030 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 10
Code-Review⚠️ 2Found 4/15 approved changesets -- score normalized to 2
Token-Permissions🟢 9detected GitHub workflow tokens with excessive permissions
Packaging⚠️ -1packaging workflow not detected
Dangerous-Workflow🟢 10no dangerous workflow patterns detected
CII-Best-Practices⚠️ 0no effort to earn an OpenSSF best practices badge detected
Binary-Artifacts🟢 10no binaries found in the repo
Pinned-Dependencies⚠️ 0dependency not pinned by hash detected -- score normalized to 0
Security-Policy⚠️ 0security policy file not detected
Vulnerabilities🟢 100 existing vulnerabilities detected
License🟢 10license file detected
Branch-Protection⚠️ -1internal error: error during branchesHandler.setup: internal error: githubv4.Query: Resource not accessible by integration
Signed-Releases⚠️ -1no releases found
Fuzzing⚠️ 0project is not fuzzed
SAST⚠️ 0SAST tool is not run on all commits -- score normalized to 0

Scanned Manifest Files

package-lock.json
package.json
  • lightweight-charts@^5.0.1

Copy link

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

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

Hey @shafin-deriv - I've reviewed your changes - here's some feedback:

Overall Comments:

  • Tests for the Chart component were removed without replacement. Please add new tests before merging to maintain code quality and prevent regressions.
  • The Chart component has a hardcoded instrument ID 'R_100'. Consider making this configurable via props to improve component reusability.
Here's what I looked at during the review
  • 🟡 General issues: 3 issues found
  • 🟢 Security: all looks good
  • 🟢 Testing: all looks good
  • 🟢 Complexity: all looks good
  • 🟢 Documentation: all looks good

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.


const { isConnected } = useMarketWebSocket("R_100", {
onConnect: () => console.log("Market WebSocket Connected in Chart"),
onError: (err) => console.log("Market WebSocket Error in Chart:", err),
Copy link

Choose a reason for hiding this comment

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

suggestion (bug_risk): Consider implementing proper error handling for WebSocket errors

Instead of just logging to console, consider showing an error state to users and implementing reconnection logic.

}
};

window.addEventListener("resize", handleResize);
Copy link

Choose a reason for hiding this comment

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

suggestion (performance): Consider debouncing the resize handler to improve performance

Frequent resize events could impact performance. Consider using a debounced version of the handler.

Suggested implementation:

    // Import at the top of the file
    import debounce from 'lodash/debounce';

    // Handle window resize with debouncing
    const handleResize = debounce(() => {
    return () => {
      window.removeEventListener("resize", handleResize);
      handleResize.cancel(); // Cancel any pending debounced calls

You'll need to:

  1. Install lodash if not already installed: npm install lodash or yarn add lodash
  2. Optionally adjust the debounce wait time by passing a second argument to debounce if needed, e.g., debounce(() => {...}, 250)

time: Math.floor(timestamp.getTime() / 1000) as UTCTimestamp,
value: price.ask,
};
setPriceHistory((prev) => [...prev, newPrice]);
Copy link

Choose a reason for hiding this comment

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

suggestion (performance): Consider implementing a limit on price history to prevent unbounded growth

The price history array will grow indefinitely. Consider implementing a maximum length and removing older entries.

Suggested implementation:

  const MAX_PRICE_HISTORY = 1000; // Keep last 1000 price points
  const { isConnected } = useMarketWebSocket("R_100", {
        setPriceHistory((prev) => {
          const updatedHistory = [...prev, newPrice];
          return updatedHistory.length > MAX_PRICE_HISTORY
            ? updatedHistory.slice(-MAX_PRICE_HISTORY)
            : updatedHistory;
        });

});

useEffect(() => {
if (!chartContainerRef.current) return;
Copy link

Choose a reason for hiding this comment

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

suggestion (code-quality): Use block braces for ifs, whiles, etc. (use-braces)

Suggested change
if (!chartContainerRef.current) return;
if (!chartContainerRef.current) {


ExplanationIt is recommended to always use braces and create explicit statement blocks.

Using the allowed syntax to just write a single statement can lead to very confusing
situations, especially where subsequently a developer might add another statement
while forgetting to add the braces (meaning that this wouldn't be included in the condition).

@shafin-deriv shafin-deriv merged commit a5df84f into master Feb 4, 2025
3 checks passed
@shafin-deriv shafin-deriv deleted the shafin/ChampionTrader/feat-chart branch February 4, 2025 17:14
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.

1 participant