Skip to content

New Components - oanda #16542

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

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open

New Components - oanda #16542

wants to merge 4 commits into from

Conversation

michelle0927
Copy link
Collaborator

@michelle0927 michelle0927 commented May 2, 2025

Resolves #15149

Summary by CodeRabbit

  • New Features
    • Introduced actions for OANDA: create trading orders, retrieve historical prices, and list trades.
    • Added event sources for OANDA: detect new open positions, new open trades, and new transactions in real time.
    • Provided sample events for easier testing and setup.
    • Enhanced OANDA integration with dynamic property options and improved account, trade, and instrument selection.
  • Chores
    • Updated dependencies and increased the package version.
  • Documentation
    • Added descriptive labels, summaries, and documentation links to actions and event sources for user guidance.

Copy link

vercel bot commented May 2, 2025

The latest updates on your projects. Learn more about Vercel for Git ↗︎

3 Skipped Deployments
Name Status Preview Comments Updated (UTC)
docs-v2 ⬜️ Ignored (Inspect) Visit Preview May 2, 2025 4:47pm
pipedream-docs ⬜️ Ignored (Inspect) May 2, 2025 4:47pm
pipedream-docs-redirect-do-not-edit ⬜️ Ignored (Inspect) May 2, 2025 4:47pm

Copy link
Contributor

coderabbitai bot commented May 2, 2025

"""

Walkthrough

This update introduces a comprehensive OANDA integration with new actions, sources, utility modules, and supporting constants. Three new actions allow users to create orders, list trades, and fetch historical prices from OANDA accounts. Three new polling sources emit events for new open trades, new transactions, and new open positions, each with sample event data for testing. A shared base module for sources is added, providing state management and event emission utilities. The OANDA app implementation is expanded with property definitions and methods for interacting with the OANDA REST API. A constants module centralizes enumerations and mappings for order types, trade states, and other OANDA-specific options. The package metadata is updated with a new version and dependencies.

Changes

File(s) Change Summary
components/oanda/actions/create-order/create-order.mjs
components/oanda/actions/get-historical-prices/get-historical-prices.mjs
components/oanda/actions/list-trades/list-trades.mjs
Added new action modules for creating orders, retrieving historical prices, and listing trades for OANDA accounts.
components/oanda/common/constants.mjs Introduced a constants module with enumerations and mappings for order types, trade states, granularity, and more.
components/oanda/oanda.app.mjs Fully implemented OANDA app with property definitions and API methods for account, trade, and order management.
components/oanda/package.json Bumped version to 0.7.0, updated @pipedream/platform dependency, and added md5 dependency.
components/oanda/sources/common/base.mjs Added a reusable base module for OANDA polling sources, including state and event management utilities.
components/oanda/sources/new-open-position/new-open-position.mjs
components/oanda/sources/new-open-position/test-event.mjs
Added new source for open positions and a corresponding test event data file.
components/oanda/sources/new-open-trade/new-open-trade.mjs
components/oanda/sources/new-open-trade/test-event.mjs
Added new source for open trades and a corresponding test event data file.
components/oanda/sources/new-transaction/new-transaction.mjs
components/oanda/sources/new-transaction/test-event.mjs
Added new source for transactions and a corresponding test event data file.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Action/Source
    participant OANDA App
    participant OANDA API

    User->>Action/Source: Configure and trigger
    Action/Source->>OANDA App: Call API method (e.g., createOrder, listTrades)
    OANDA App->>OANDA API: Send HTTP request
    OANDA API-->>OANDA App: Respond with data
    OANDA App-->>Action/Source: Return processed result
    Action/Source-->>User: Emit event or return action result
Loading

Assessment against linked issues

Objective Addressed Explanation
Emit new event when a new trade is opened for an Oanda account (#15149)
Emit new event whenever a trade is executed in the user's account. Users must authenticate and can optionally filter by instrument or trade type (#15149)
Emit new event when an open position is created. Users must authenticate and specify account ID (#15149)
Retrieve a list of trades for an account (#15149)
Create a new trading order by specifying the instrument, order type, units, and optional parameters (#15149)
Retrieve historical price data for a specified currency pair or instrument within a given time range (#15149)

Poem

Oh, OANDA, now you shine so bright,
With trades and prices day and night!
Orders placed with just a hop,
Positions, transactions—never stop!
Rabbits code and markets leap,
While polling sources never sleep.
🐇✨ Trade on, for profits deep!
"""

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

components/oanda/actions/get-historical-prices/get-historical-prices.mjs

Oops! Something went wrong! :(

ESLint: 8.57.1

Error [ERR_MODULE_NOT_FOUND]: Cannot find package 'jsonc-eslint-parser' imported from /eslint.config.mjs
at packageResolve (node:internal/modules/esm/resolve:839:9)
at moduleResolve (node:internal/modules/esm/resolve:908:18)
at defaultResolve (node:internal/modules/esm/resolve:1038:11)
at ModuleLoader.defaultResolve (node:internal/modules/esm/loader:557:12)
at ModuleLoader.resolve (node:internal/modules/esm/loader:525:25)
at ModuleLoader.getModuleJob (node:internal/modules/esm/loader:246:38)
at ModuleJob._link (node:internal/modules/esm/module_job:126:49)


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 6770547 and f4f2f00.

📒 Files selected for processing (1)
  • components/oanda/actions/get-historical-prices/get-historical-prices.mjs (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • components/oanda/actions/get-historical-prices/get-historical-prices.mjs
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: Verify TypeScript components
  • GitHub Check: pnpm publish
  • GitHub Check: Publish TypeScript components
  • GitHub Check: Lint Code Base
✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ 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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this 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: 11

🧹 Nitpick comments (10)
components/oanda/sources/new-transaction/test-event.mjs (1)

1-14: Test event looks good but uses a future date.

The transaction test event structure is appropriate with all the necessary fields for testing the new transaction source. However, note that the time field is set to a future date (2025-04-30).

While this works fine as test data, you might consider using a past or present date to avoid potential confusion for users testing the component.

components/oanda/sources/new-open-trade/test-event.mjs (1)

1-15: Test event structure is appropriate but uses a future date.

The open trade test event includes all necessary fields with appropriate sample values. However, the openTime field is set to a future date (2025-05-01).

While acceptable for test data, consider using a past or present date to avoid potential confusion for users testing the component.

components/oanda/actions/list-trades/list-trades.mjs (1)

47-52: Check prop name consistency with API parameter.

The prop is named beforeId but it's passed as beforeID (with capital "ID") in the params object (line 63). While this might be intentional to match the API's expected parameter name, consider being consistent in your naming convention or adding a comment to clarify this difference.

-  beforeId: {
+  beforeID: {
   type: "string",
-  label: "Before ID",
+  label: "Before ID",
   description: "The maximum Trade ID to return. If not provided the most recent Trades in the Account are returned.",
   optional: true,
 },
components/oanda/actions/create-order/create-order.mjs (1)

115-128: Consider improving property handling logic

The additionalProps method directly modifies the existing props object. While this works, it can lead to unexpected behavior if properties are accessed during initialization.

Consider this alternative approach that returns new property definitions instead of modifying existing ones:

  additionalProps(props) {
    if (!this.type) {
      return {};
    }
    const fields = constants.REQUIRED_FIELDS_FOR_ORDER_TYPES[this.type];
+   const additionalProps = {};
    for (const [
      key,
      value,
    ] of Object.entries(fields)) {
-     props[key].hidden = false;
-     props[key].optional = !value;
+     additionalProps[key] = {
+       ...props[key],
+       hidden: false,
+       optional: !value,
+     };
    }
-   return {};
+   return additionalProps;
  },
components/oanda/sources/new-open-position/new-open-position.mjs (1)

27-34: Hash collision risk with md5

Using md5 hash of the stringified position object might lead to collisions if the position object contains floating-point numbers or properties that can appear in different orders.

Consider using a more reliable identifier if available from the API:

  generateMeta(item) {
-   const hash = md5(JSON.stringify(item));
+   // Use position ID if available, otherwise fallback to hash
+   const id = item.position?.id || 
+     `${item.instrument}_${item.long.units}_${item.short.units}_${Date.now()}`;
    return {
-     id: hash,
+     id,
      summary: `New or Updated Position for instrument ${item.instrument}`,
      ts: Date.now(),
    };
  },
components/oanda/sources/new-open-trade/new-open-trade.mjs (1)

14-40: Optimize processing with array methods

The filtering and iteration can be streamlined using array methods for more concise code.

Consider refactoring to use more modern array methods:

  async processEvent(max) {
    const lastId = this._getLastId();
-   let count = 0;

    const {
      trades, lastTransactionID,
    } = await this.oanda.listOpenTrades({
      isDemo: this.isDemo,
      accountId: this.accountId,
    });

    if (!trades.length) {
      return;
    }

-   const newTrades = trades.filter(({ id }) => id > lastId);
-
-   for (const trade of newTrades.reverse()) {
-     this.emitItem(trade);
-     count++;
-     if (max && count >= max) {
-       break;
-     }
-   }
+   const newTrades = trades
+     .filter(({ id }) => id > lastId)
+     .sort((a, b) => b.id - a.id) // Sort in descending order
+     .slice(0, max || Infinity); // Limit the number of trades if max is specified
+     
+   newTrades.forEach(trade => this.emitItem(trade));

    this._setLastId(lastTransactionID);
  },
components/oanda/sources/common/base.mjs (2)

42-46: Fix typo in error message

There's a typo in the error message for the processEvent method.

  processEvent() {
-   throw new Error("processEvent is not iplemented");
+   throw new Error("processEvent is not implemented");
  },

30-47: Add namespace to state keys

The state management methods use generic keys that might conflict across different component instances.

Consider namespacing the database keys to prevent potential conflicts:

  methods: {
+   _getDbKey(key) {
+     return `${this.key}_${key}`;
+   },
    _getLastId() {
-     return this.db.get("lastId") || 1;
+     return this.db.get(this._getDbKey("lastId")) || 1;
    },
    _setLastId(lastId) {
-     this.db.set("lastId", lastId);
+     this.db.set(this._getDbKey("lastId"), lastId);
    },
    emitItem(item) {
      const meta = this.generateMeta(item);
      this.$emit(item, meta);
    },
    processEvent() {
      throw new Error("processEvent is not implemented");
    },
    generateMeta() {
      throw new Error("generateMeta is not implemented");
    },
  },
components/oanda/common/constants.mjs (1)

181-181: Correct misspelling of "Thursday".

There's a typo in the WEEKLY_ALIGNMENT_DAYS array where "Thursday" is misspelled as "Thrusday".

Fix the spelling:

- "Thrusday",
+ "Thursday",
components/oanda/oanda.app.mjs (1)

105-112: Add method documentation for listTransactions.

The listTransactions method would benefit from additional documentation to clarify the expected parameters, especially since it's being used for pagination in the new-transaction source.

Add JSDoc comments to clarify parameter usage:

/**
+ * List transactions for a specified account ID within an ID range
+ * @param {Object} opts - The options object
+ * @param {String} opts.accountId - The account ID to list transactions for
+ * @param {Object} opts.params - The query parameters
+ * @param {Number} opts.params.from - The starting transaction ID
+ * @param {Number} opts.params.to - The ending transaction ID
+ * @param {String} opts.params.type - Optional filter for transaction type
+ * @param {boolean} opts.isDemo - Whether to use the demo/practice API
+ * @returns {Promise<Object>} The transaction data
+ */
listTransactions({
  accountId, ...opts
}) {
  return this._makeRequest({
    path: `/accounts/${accountId}/transactions/idrange`,
    ...opts,
  });
},
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between fd5f05f and 6770547.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (13)
  • components/oanda/actions/create-order/create-order.mjs (1 hunks)
  • components/oanda/actions/get-historical-prices/get-historical-prices.mjs (1 hunks)
  • components/oanda/actions/list-trades/list-trades.mjs (1 hunks)
  • components/oanda/common/constants.mjs (1 hunks)
  • components/oanda/oanda.app.mjs (1 hunks)
  • components/oanda/package.json (2 hunks)
  • components/oanda/sources/common/base.mjs (1 hunks)
  • components/oanda/sources/new-open-position/new-open-position.mjs (1 hunks)
  • components/oanda/sources/new-open-position/test-event.mjs (1 hunks)
  • components/oanda/sources/new-open-trade/new-open-trade.mjs (1 hunks)
  • components/oanda/sources/new-open-trade/test-event.mjs (1 hunks)
  • components/oanda/sources/new-transaction/new-transaction.mjs (1 hunks)
  • components/oanda/sources/new-transaction/test-event.mjs (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: pnpm publish
  • GitHub Check: Publish TypeScript components
  • GitHub Check: Lint Code Base
  • GitHub Check: Verify TypeScript components
🔇 Additional comments (9)
components/oanda/package.json (2)

3-3: Version bump appropriately reflects new functionality.

The version increment from 0.6.0 to 0.7.0 correctly follows semantic versioning for the new OANDA integration features (new actions, sources, and utility modules).


16-17: Dependencies updated to support new functionality.

The @pipedream/platform update and new md5 dependency are appropriate for the new OANDA integration features. The md5 package is likely needed for generating unique identifiers or hashing in the new components.

components/oanda/sources/new-open-position/test-event.mjs (1)

1-36: Well-structured test event with comprehensive position data.

The open position test event provides a detailed representation of a trading position with both long and short sides, trade IDs, and profit/loss values. The structure aligns well with what would be expected from the OANDA API.

components/oanda/actions/list-trades/list-trades.mjs (3)

4-9: Action metadata is well-defined.

The action's key, name, description, version, and type are all properly defined with a helpful documentation link.


10-53: Props are well-defined with appropriate descriptions.

The props configuration is well-structured:

  • Using propDefinitions from the OANDA app for consistency
  • Using constants for the trade states
  • Including optional filters with clear descriptions
  • Setting appropriate dependencies between props (account selection depends on demo flag)

54-70: Well-implemented run method with proper response handling.

The run method correctly:

  1. Calls the OANDA API with appropriate parameters
  2. Exports a summary message with proper pluralization
  3. Returns the complete response object

The implementation provides a clean interface for listing trades with flexible filtering options.

components/oanda/common/constants.mjs (1)

1-445: Well-structured constants file with comprehensive options.

The constants file is well-organized and provides a comprehensive set of options, types, and required fields that will be useful throughout the integration. The structure of providing both values and human-readable labels for options is particularly helpful for UI display.

components/oanda/oanda.app.mjs (2)

1-131: Well-designed API client with comprehensive methods.

The OANDA app implementation provides a clean, well-structured API client with appropriate methods for interacting with the OANDA REST API. The property definitions with dynamic options are particularly valuable for creating intuitive user interfaces.


16-22: 🛠️ Refactor suggestion

Handle empty accounts response gracefully.

In the accountId property's options method, there's a possibility that accounts could be undefined or null, which could cause errors.

Improve null handling:

async options({ isDemo }) {
  const { accounts } = await this.listAccounts({
    isDemo,
  });
- return accounts?.map(({ id }) => id) || [];
+ if (!accounts || !Array.isArray(accounts)) {
+   console.warn("No accounts found or unexpected response format");
+   return [];
+ }
+ return accounts.map(({ id }) => id);
},

Likely an incorrect or invalid review comment.

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.

[Components] oanda
1 participant