### Install and Run React Examples Manually Source: https://github.com/metaapi/metaapi-javascript-sdk/blob/main/examples/react/README.md Provides instructions to set up and run the MetaApi React example applications locally. This involves cloning the repository, installing dependencies, and starting the development server. ```bash git clone https://github.com/metaapi/metaapi-javascript-sdk.git cd metaapi-node.js-sdk/examples/react/app/ npm install npm run dev # runned at localhost:5173 ``` -------------------------------- ### Install and Run Vue Example Source: https://github.com/metaapi/metaapi-javascript-sdk/blob/main/examples/vue/README.md Provides commands to clone the MetaApi JavaScript SDK repository, navigate to the Vue example directory, install project dependencies, and start the development server. ```bash git clone https://github.com/metaapi/metaapi-javascript-sdk.git cd metaapi-node.js-sdk/examples/vue/app/ npm install npm run dev # runned at localhost:5173 ``` -------------------------------- ### Start React Examples with Docker Compose Source: https://github.com/metaapi/metaapi-javascript-sdk/blob/main/examples/react/README.md Details how to launch the MetaApi React example application using Docker Compose. This is useful for managing multi-container Docker applications or for a simpler setup. ```bash docker-compose up ``` -------------------------------- ### Run Angular Example Manually Source: https://github.com/metaapi/metaapi-javascript-sdk/blob/main/docs/ui/angular.md Provides commands to install dependencies and start the Angular example application locally. The application will be accessible at localhost:4200. ```bash npm install npm start # runned at localhost:4200 ``` -------------------------------- ### Clone and Run Vue 3 MetaApi Example Manually Source: https://github.com/metaapi/metaapi-javascript-sdk/blob/main/docs/ui/vue.md Guides users through cloning the MetaApi JavaScript SDK repository from GitHub and running the Vue 3 example application locally. It includes steps for installing dependencies and starting the development server, typically on localhost:5173. ```bash git clone https://github.com/metaapi/metaapi-javascript-sdk.git cd metaapi-node.js-sdk/examples/vue/app/ npm install npm run dev # runned at localhost:5173 ``` -------------------------------- ### Run Angular Example Manually Source: https://github.com/metaapi/metaapi-javascript-sdk/blob/main/examples/angular/README.md Provides the command-line steps to clone the MetaApi JavaScript SDK repository, navigate into the Angular example directory, install project dependencies using npm, and start the development server to run the application locally. ```bash git clone https://github.com/metaapi/metaapi-javascript-sdk.git cd metaapi-node.js-sdk/examples/angular/app/ npm install npm start # runned at localhost:4200 ``` -------------------------------- ### MetaApi Copy Trade Setup Example (JavaScript) Source: https://github.com/metaapi/metaapi-javascript-sdk/blob/main/examples/browser/copyfactory/copyTrade.html This JavaScript code snippet demonstrates how to configure copy trading using the MetaApi SDK. It connects to MetaApi, retrieves account details, and sets up a provider-subscriber relationship for copying trades. Requires MetaApi SDK and valid account credentials. ```javascript const infoElement = document.getElementById('info'); function log() { if(typeof arguments[1] === 'object'){ arguments[1] = JSON.stringify(arguments[1]); } const el = document.createElement('div'); el.innerHTML = [].join.call(arguments, ' '); infoElement.appendChild(el); console.log(...arguments); } const buttonElement = document.getElementById('connect-button') const onSubmit = async () => { buttonElement.disabled = true; const token = document.getElementById('token-input').value; const providerAccountId = document.getElementById('provider-account-id-input').value; const subscriberAccountId = document.getElementById('subscriber-account-id-input').value; if (token && providerAccountId && subscriberAccountId) { const api = new MetaApi.default(token); const copyFactory = new MetaApi.CopyFactory(token); async function configureCopyFactory() { try { let providerMetaapiAccount = await api.metatraderAccountApi.getAccount(providerAccountId); if(!providerMetaapiAccount.copyFactoryRoles || !providerMetaapiAccount.copyFactoryRoles.includes('PROVIDER')) { throw new Error('Please specify PROVIDER copyFactoryRoles value in your MetaApi account in ' + 'order to use it in CopyFactory API'); } let subscriberMetaapiAccount = await api.metatraderAccountApi.getAccount(subscriberAccountId); if(!subscriberMetaapiAccount.copyFactoryRoles || !subscriberMetaapiAccount.copyFactoryRoles.includes('SUBSCRIBER')) { throw new Error('Please specify SUBSCRIBER copyFactoryRoles value in your MetaApi account in ' + 'order to use it in CopyFactory API'); } let configurationApi = copyFactory.configurationApi; const strategies = await configurationApi.getStrategiesWithInfiniteScrollPagination(); const strategy = strategies.find(s => s.accountId === providerMetaapiAccount.id); let strategyId; if(strategy) { strategyId = strategy._id; } else { strategyId = await configurationApi.generateStrategyId(); strategyId = strategyId.id; } // create a strategy being copied await configurationApi.updateStrategy(strategyId, { name: 'Test strategy', description: 'Some useful description about your strategy', accountId: providerMetaapiAccount.id }); // create subscriber await configurationApi.updateSubscriber(subscriberMetaapiAccount.id, { name: 'Test subscriber', subscriptions: [ { strategyId: strategyId, multiplier: 1 } ] }); } catch (err) { console.error(err); } } await configureCopyFactory(); } buttonElement.disabled = false; } ``` -------------------------------- ### Run Angular Example via Docker Compose Source: https://github.com/metaapi/metaapi-javascript-sdk/blob/main/docs/ui/angular.md Command to start the Angular example application using Docker Compose, making it accessible at localhost:4200. ```bash docker-compose up # runned at localhost:4200 ``` -------------------------------- ### Install MetaApi SDK Source: https://github.com/metaapi/metaapi-javascript-sdk/blob/main/readme.md Installs the MetaApi Cloud SDK using npm, making it available for use in Node.js or browser applications. ```bash npm install --save metaapi.cloud-sdk ``` -------------------------------- ### Install and Run Manually (npm) Source: https://github.com/metaapi/metaapi-javascript-sdk/blob/main/docs/ui/react.md Installs project dependencies using npm and starts the development server. The application will be accessible at localhost:5173. ```bash npm install npm run dev # runned at localhost:5173 ``` -------------------------------- ### MetaAPI RPC API Example Source: https://github.com/metaapi/metaapi-javascript-sdk/blob/main/examples/exampleGenerator/browser/rpcExample.html This JavaScript code snippet demonstrates connecting to a MetaAPI account, waiting for synchronization with the MetaTrader terminal, and then invoking various RPC methods. It includes examples for retrieving account information, positions, orders, trade history, calculating margin, and placing a limit buy order. Ensure you replace placeholder token and account ID with your actual credentials. ```javascript const infoElement = document.getElementById('info'); function log() { if (typeof arguments[1] === 'object') { arguments[1] = JSON.stringify(arguments[1]); } const el = document.createElement('div'); el.innerHTML = [].join.call(arguments, ' '); infoElement.appendChild(el); console.log(...arguments); } const token = ''; const accountId = ''; const api = new MetaApi.default(token); async function testMetaApiSynchronization() { try { const account = await api.metatraderAccountApi.getAccount(accountId); log('Waiting for API server to connect to broker (may take couple of minutes)'); await account.waitConnected(); // connect to MetaApi API let connection = account.getRPCConnection(); await connection.connect(); // wait until terminal state synchronized to the local state log('Waiting for SDK to synchronize to terminal state (may take some time depending on your history size)'); await connection.waitSynchronized(); // invoke RPC API (replace ticket numbers with actual ticket numbers which exist in your MT account) log('Testing MetaAPI RPC API'); log('account information:', JSON.stringify(await connection.getAccountInformation())); log('positions:', JSON.stringify(await connection.getPositions())); //log(await connection.getPosition('1234567')); log('open orders:', JSON.stringify(await connection.getOrders())); //log(await connection.getOrder('1234567')); log('history orders by ticket:', JSON.stringify(await connection.getHistoryOrdersByTicket('1234567'))); log('history orders by position:', JSON.stringify(await connection.getHistoryOrdersByPosition('1234567'))); log('history orders (~last 3 months):', JSON.stringify(await connection.getHistoryOrdersByTimeRange(new Date(Date.now() - 90 * 24 * 60 * 60 * 1000), new Date()))); log('history deals by ticket:', JSON.stringify(await connection.getDealsByTicket('1234567'))); log('history deals by position:', JSON.stringify(await connection.getDealsByPosition('1234567'))); log('history deals (~last 3 months):', JSON.stringify(await connection.getDealsByTimeRange(new Date(Date.now() - 90 * 24 * 60 * 60 * 1000), new Date()))); log('server time', JSON.stringify(await connection.getServerTime())); // calculate margin required for trade log('margin required for trade', JSON.stringify(await connection.calculateMargin({ symbol: 'GBPUSD', type: 'ORDER_TYPE_BUY', volume: 0.1, openPrice: 1.1 }))); // trade log('Submitting pending order'); try { let result = await connection.createLimitBuyOrder('GBPUSD', 0.07, 1.0, 0.9, 2.0, { comment: 'comm', clientId: 'TE_GBPUSD_7hyINWqAlE', expiration: { type: 'ORDER_TIME_SPECIFIED', time: new Date(Date.now() + 24 * 60 * 60 * 1000) } }); log('Trade successful, result code is ' + result.stringCode); } catch (err) { log('Trade failed with result code ' + err.stringCode); } } catch (err) { log(err); } return; } testMetaApiSynchronization(); ``` -------------------------------- ### Run Vue 3 MetaApi Example with Docker Compose Source: https://github.com/metaapi/metaapi-javascript-sdk/blob/main/docs/ui/vue.md Explains how to start the Vue 3 MetaApi example application using Docker Compose. This approach simplifies the management of multi-container Docker applications, allowing for quick setup and execution of the example. ```bash docker-compose up # runned at localhost:5173 ``` -------------------------------- ### Install MetaApi SDK via CDN (HTML) Source: https://github.com/metaapi/metaapi-javascript-sdk/blob/main/examples/browser/README.md Include the MetaApi SDK script in your HTML file using either the UMD or ES6 module syntax. This makes the MetaApi library available for use in your browser application. ```html ``` ```html ``` -------------------------------- ### Run React Examples with Docker Source: https://github.com/metaapi/metaapi-javascript-sdk/blob/main/examples/react/README.md Explains how to build and run the MetaApi React example application using Docker. This method allows for a containerized environment, ensuring consistent execution. ```bash docker build -t metaapi-app-example -f Dockerfile . docker run -d -p 5173:5173 metaapi-app-example # runned at localhost:5173 ``` -------------------------------- ### Run Vue Example with Docker Source: https://github.com/metaapi/metaapi-javascript-sdk/blob/main/examples/vue/README.md Instructions for running the Vue MetaApi example using Docker. This includes building a Docker image and starting a container, or using docker-compose for orchestration. ```bash docker build -t metaapi-app-example -f Dockerfile . docker run -d -p 5173:5173 metaapi-app-example # runned at localhost:5173 # Or use docker-compose: docker-compose up # runned at localhost:5173 ``` -------------------------------- ### Connect and Stream with MetaAPI JavaScript SDK Source: https://github.com/metaapi/metaapi-javascript-sdk/blob/main/examples/browser/metaapi/stream.html This snippet shows how to initialize the MetaAPI SDK, connect to a trading account, and access real-time data like prices, positions, and orders. It includes examples of waiting for connection, synchronizing terminal state, and executing trades like placing a limit buy order. ```javascript const infoElement = document.getElementById('info'); function log() { if(typeof arguments[1] === 'object'){ arguments[1] = JSON.stringify(arguments[1]); } const el = document.createElement('div'); el.innerHTML = [].join.call(arguments, ' '); infoElement.appendChild(el); console.log(...arguments); } const onSubmit = () => { const token = document.getElementById('token-input').value; const accountId = document.getElementById('account-id-input').value; if (token && accountId) { const api = new MetaApi.default(token); return api.metatraderAccountApi.getAccount(accountId) .then(account => { console.log(account); log('Waiting for API server to connect to broker (may take couple of minutes)'); return account.waitConnected() .then(() => { let connection = account.getStreamingConnection(); return (connection.connect(), connection); }) .then(connection => { log('Waiting for SDK to synchronize to terminal state (may take some time depending on your history size)'); return connection.waitSynchronized() .then(async () => { log('Testing terminal state access'); let terminalState = connection.terminalState; log('connected:', terminalState.connected); log('connected to broker:', terminalState.connectedToBroker); log('account information:', JSON.stringify(terminalState.accountInformation)); log('positions:', JSON.stringify(terminalState.positions)); log('orders:', JSON.stringify(terminalState.orders)); log('specifications:', JSON.stringify(terminalState.specifications)); log('EURUSD specification:', JSON.stringify(terminalState.specification('EURUSD'))); log('EURUSD price:', JSON.stringify(terminalState.price('EURUSD'))); let historyStorage = connection.historyStorage; log('deals:', JSON.stringify(historyStorage.deals.slice(-5))); log('history orders:', JSON.stringify(historyStorage.historyOrders.slice(-5))); // calculate margin required for trade log('margin required for trade', JSON.stringify(await connection.calculateMargin({ symbol: 'GBPUSD', type: 'ORDER_TYPE_BUY', volume: 0.1, openPrice: 1.1 }))); // trade log('Submitting pending order'); try { let result = await connection.createLimitBuyOrder('GBPUSD', 0.07, 1.0, 0.9, 2.0, { comment: 'comm', clientId: 'TE_GBPUSD_7hyINWqAlE', expiration: { type: 'ORDER_TIME_SPECIFIED', time: new Date(Date.now() + 24 * 60 * 60 * 1000) } }); log('Trade successful, result code is ' + result.stringCode); } catch (err) { log('Trade failed with result code ' + err.stringCode); } return; }) }) }) .catch(error => console.error(error)); } } ``` -------------------------------- ### Install MetaApi SDK Source: https://github.com/metaapi/metaapi-javascript-sdk/blob/main/docs/ui/react.md Installs the MetaApi cloud SDK using npm for use in JavaScript projects. ```bash npm install --save metaapi.cloud-sdk ``` -------------------------------- ### Clone MetaApi SDK Examples Source: https://github.com/metaapi/metaapi-javascript-sdk/blob/main/docs/ui/react.md Clones the MetaApi JavaScript SDK repository from GitHub to access React integration examples, including historical data, risk management, and quote streaming. ```bash git clone https://github.com/metaapi/metaapi-javascript-sdk.git cd metaapi-node.js-sdk/examples/react/app/ ``` -------------------------------- ### Install MetaApi SDK Source: https://github.com/metaapi/metaapi-javascript-sdk/blob/main/examples/vue/README.md Installs the MetaApi JavaScript SDK using npm. This command is a prerequisite for integrating the SDK into your project. ```bash npm install --save metaapi.cloud-sdk ``` -------------------------------- ### Install MetaApi SDK with npm Source: https://github.com/metaapi/metaapi-javascript-sdk/blob/main/examples/react/README.md Installs the MetaApi Cloud SDK into your project using npm. This is the first step to integrate MetaApi functionalities into your application. ```bash npm install --save metaapi.cloud-sdk ``` -------------------------------- ### Start via Docker Compose Source: https://github.com/metaapi/metaapi-javascript-sdk/blob/main/docs/ui/react.md Starts the application using Docker Compose. This command assumes a docker-compose.yml file is present in the project root. The application will be available at localhost:5173. ```bash docker-compose up # runned at localhost:5173 ``` -------------------------------- ### MetaAPI JavaScript SDK Streaming Example Source: https://github.com/metaapi/metaapi-javascript-sdk/blob/main/examples/exampleGenerator/browser/synchronizationExample.html This example demonstrates connecting to a MetaTrader account via the MetaAPI JavaScript SDK, synchronizing terminal state, and accessing live trading data. It covers connecting to the API, waiting for synchronization, accessing terminal state properties like positions and orders, and performing a trade operation like calculating margin and submitting a limit order. Dependencies include the MetaApi SDK and browser DOM elements for logging. ```javascript const infoElement = document.getElementById('info'); function log() { if(typeof arguments[1] === 'object'){ arguments[1] = JSON.stringify(arguments[1]); } const el = document.createElement('div'); el.innerHTML = [].join.call(arguments, ' '); infoElement.appendChild(el); console.log(...arguments); } const token = ''; const accountId = ''; const api = new MetaApi.default(token); async function testMetaApiSynchronization() { try { const account = await api.metatraderAccountApi.getAccount(accountId); log('Waiting for API server to connect to broker (may take couple of minutes)'); await account.waitConnected(); // connect to MetaApi API let connection = account.getStreamingConnection(); await connection.connect(); // wait until terminal state synchronized to the local state log('Waiting for SDK to synchronize to terminal state (may take some time depending on your history size)'); await connection.waitSynchronized(); // access local copy of terminal state log('Testing terminal state access'); let terminalState = connection.terminalState; log('connected:', terminalState.connected); log('connected to broker:', terminalState.connectedToBroker); log('account information:', JSON.stringify(terminalState.accountInformation)); log('positions:', JSON.stringify(terminalState.positions)); log('orders:', JSON.stringify(terminalState.orders)); log('specifications:', JSON.stringify(terminalState.specifications)); log('EURUSD specification:', JSON.stringify(terminalState.specification('EURUSD'))); log('EURUSD price:', JSON.stringify(terminalState.price('EURUSD'))); let historyStorage = connection.historyStorage; log('deals:', JSON.stringify(historyStorage.deals.slice(-5))); log('history orders:', JSON.stringify(historyStorage.historyOrders.slice(-5))); // calculate margin required for trade log('margin required for trade', JSON.stringify(await connection.calculateMargin({ symbol: 'GBPUSD', type: 'ORDER_TYPE_BUY', volume: 0.1, openPrice: 1.1 }))); // trade log('Submitting pending order'); try { let result = await connection.createLimitBuyOrder('GBPUSD', 0.07, 1.0, 0.9, 2.0, { comment: 'comm', clientId: 'TE_GBPUSD_7hyINWqAlE', expiration: { type: 'ORDER_TIME_SPECIFIED', time: new Date(Date.now() + 24 * 60 * 60 * 1000) } }); log('Trade successful, result code is ' + result.stringCode); } catch (err) { log('Trade failed with result code ' + err.stringCode); } } catch (err) { log(err); } return; } testMetaApiSynchronization(); ``` -------------------------------- ### Run Angular Example via Docker Source: https://github.com/metaapi/metaapi-javascript-sdk/blob/main/docs/ui/angular.md Instructions for building a Docker image for the Angular example and running it as a detached container. The application will be accessible at localhost:4200. ```bash docker build -t metaapi-app-example -f Dockerfile . docker run -d -p 4200:4200 metaapi-app-example # runned at localhost:4200 ``` -------------------------------- ### Create MetaApi Instance with Token (JavaScript) Source: https://github.com/metaapi/metaapi-javascript-sdk/blob/main/examples/browser/README.md This snippet demonstrates the standard way to create an instance of the MetaApi client using your provided API token. This instance is the primary entry point for interacting with MetaApi services. ```javascript // Get instance of MetaApi with your MetaApi token const metaApi = new MetaApi(token); ``` -------------------------------- ### MetaApi JavaScript SDK: Equity Tracker Example Source: https://github.com/metaapi/metaapi-javascript-sdk/blob/main/examples/browser/riskManagement/equityTracking.html Demonstrates how to use the MetaApi JavaScript SDK to create, manage, and monitor an equity tracker. It includes setting up event listeners, fetching tracking statistics and equity charts, and cleaning up resources by removing the tracker. Requires DOM elements with specific IDs for input and logging. ```javascript const infoElement = document.getElementById('info'); function log() { if(typeof arguments[1] === 'object'){ arguments[1] = JSON.stringify(arguments[1]); } const el = document.createElement('div'); el.innerHTML = [].join.call(arguments, ' '); infoElement.appendChild(el); console.log(...arguments); } const onSubmit = async () => { class ExampleTrackerEventListener extends MetaApi.TrackerEventListener { async onTrackerEvent(trackerEvent) { log('tracker event received', JSON.stringify(trackerEvent)); } async onError(error) { log('error event received', error); } } const trackerName = document.getElementById('tracker-name-input').value; const accountId = document.getElementById('account-id-input').value; const token = document.getElementById('token-input').value; if (token && accountId && trackerName) { try { const riskManagement = new MetaApi.RiskManagement(token); const riskManagementApi = riskManagement.riskManagementApi; // creating a tracker const trackerId = await riskManagementApi.createTracker(accountId, { absoluteDrawdownThreshold: 5, name: trackerName, period: 'day' }); log('Created an event tracker ' + trackerId.id); /* adding a tracker event listener */ const trackerEventListener = new ExampleTrackerEventListener(accountId, trackerId); const listenerId = riskManagementApi.addTrackerEventListener(trackerEventListener, accountId, trackerId.id); log('Streaming tracking events for 1 minute...'); await new Promise(res => setTimeout(res, 1000 * 60)); riskManagementApi.removeTrackerEventListener(listenerId); log('Receiving statistics with REST API'); const events = await riskManagementApi.getTrackerEvents(undefined, undefined, accountId, trackerId.id); log('tracking events', JSON.stringify(events)); const statistics = await riskManagementApi.getTrackingStatistics(accountId, trackerId.id); log('tracking statistics', JSON.stringify(statistics)); const equityChart = await riskManagementApi.getEquityChart(accountId); log('equity chart', JSON.stringify(equityChart)); /* removing the tracker */ await riskManagementApi.deleteTracker(accountId, trackerId.id); log('Removed the tracker'); } catch (error) { log(error) } } } ``` -------------------------------- ### Install MetaApi SDK Source: https://github.com/metaapi/metaapi-javascript-sdk/blob/main/docs/ui/angular.md Installs the MetaApi cloud SDK package using npm. This is the primary step to include the SDK's functionalities in your project. ```bash npm install --save metaapi.cloud-sdk ``` -------------------------------- ### Initialize MetaApi SDK in Browser (ES6) Source: https://github.com/metaapi/metaapi-javascript-sdk/blob/main/examples/browser/README.md For ES6 module usage, import the MetaApi library and specific components directly. This approach allows for cleaner imports and better tree-shaking. ```javascript import MetaApi, { RiskManagement, CopyFactory } from 'metaapi.cloud-sdk'; ``` -------------------------------- ### Build and Run Vue 3 MetaApi Example with Docker Source: https://github.com/metaapi/metaapi-javascript-sdk/blob/main/docs/ui/vue.md Provides instructions for building a Docker image for the Vue 3 MetaApi example application and running it as a detached container. This method facilitates easy deployment and execution in a consistent, isolated environment. ```bash docker build -t metaapi-app-example -f Dockerfile . docker run -d -p 5173:5173 metaapi-app-example # runned at localhost:5173 ``` -------------------------------- ### Run Angular Example with Docker Source: https://github.com/metaapi/metaapi-javascript-sdk/blob/main/examples/angular/README.md Offers instructions for deploying the Angular MetaApi example using Docker. This includes building a Docker image from a Dockerfile and running it as a detached container, or using docker-compose for orchestration, both exposing the application on port 4200. ```bash docker build -t metaapi-app-example -f Dockerfile . docker run -d -p 4200:4200 metaapi-app-example # runned at localhost:4200 ``` ```bash docker-compose up # runned at localhost:4200 ``` -------------------------------- ### Install MetaApi SDK Source: https://github.com/metaapi/metaapi-javascript-sdk/blob/main/examples/angular/README.md Installs the MetaApi Cloud SDK package using npm. This command is essential for adding the MetaApi library as a dependency to your Angular project, enabling access to its functionalities. ```bash npm install --save metaapi.cloud-sdk ``` -------------------------------- ### Establish MetaTrader Account Connection (JavaScript) Source: https://github.com/metaapi/metaapi-javascript-sdk/blob/main/examples/browser/README.md Connect to a MetaTrader account by first retrieving the account object using its ID. Then, wait for the connection to be established and synchronized before proceeding to use the RPC or streaming connection. ```javascript const account = await metaApi.metatraderAccountApi.getAccount(accountId); // Get connection instance await account.waitConnected(); const connection = account.getRPCConnection(); /* For WS connection use: const connection = account.getStreamingConnection(); */ // Wait until connection is established await connection.connection(); await connection.waitSynchronized(); ``` -------------------------------- ### Initialize MetaApi SDK in Browser (UMD) Source: https://github.com/metaapi/metaapi-javascript-sdk/blob/main/examples/browser/README.md When using the UMD (Universal Module Definition) script tag, you can access the MetaApi instance via `MetaApi.default`. This allows you to create a MetaApi object by passing your API token. ```javascript const metaApi = new MetaApi.default(token); ``` -------------------------------- ### App Component Example Source: https://github.com/metaapi/metaapi-javascript-sdk/blob/main/examples/angular/README.md An example Angular component that demonstrates how to inject and utilize the `MetaapiService` to fetch and display MetaTrader account information. It includes basic error handling for asynchronous operations. ```typescript // app.component.ts import { Component } from '@angular/core'; import { MetaapiService } from 'metaapi.service'; import { MetatraderAccountInformation } from 'metaapi.cloud-sdk'; @Component({ selector: 'app-root', template: `

{{ accountInfo | json }}

`, }) export class AppComponent { accountInfo?: MetatraderAccountInformatipon; constructor(private metaApiService: MetaapiService) { this.fetchData(); } async fetchData() { try { this.accountInfo = await this.metaApiService.getAccountInformation(); /* You can work directly with MetaApi: this.metaApiService.metaApi... */ } catch (error) { console.error(error); } } } ``` -------------------------------- ### Connect to MetaApi Source: https://github.com/metaapi/metaapi-javascript-sdk/blob/main/readme.md Initializes the MetaApi SDK by providing an API token to the constructor, enabling interaction with the MetaApi services. ```javascript import MetaApi from 'metaapi.cloud-sdk'; const token = '...'; const api = new MetaApi(token); ``` -------------------------------- ### Install MetaApi SDK with npm Source: https://github.com/metaapi/metaapi-javascript-sdk/blob/main/docs/ui/vue.md Installs the MetaApi JavaScript SDK using npm. This command is essential for adding the SDK as a dependency to your Vue 3 project, enabling access to MetaApi functionalities. ```bash npm install --save metaapi.cloud-sdk ``` -------------------------------- ### Create MT5 Demo Account with MetaApi SDK Source: https://github.com/metaapi/metaapi-javascript-sdk/blob/main/docs/metaApi/managingAccounts.md Demonstrates how to create a MetaTrader 5 demo account using the `createMT5DemoAccount` method from the MetaApi JavaScript SDK. It covers specifying account parameters such as account type, balance, leverage, server name, and contact details. The example also includes how to optionally provide a provisioning profile ID. ```javascript const demoAccount = await api.metatraderAccountGeneratorApi.createMT5DemoAccount({ accountType: 'type', balance: 100000, email: 'example@example.com', leverage: 100, serverName: 'ICMarketsSC-Demo', name: 'Test User', phone: '+12345678901', keywords: ["Raw Trading Ltd"] }); // optionally specify provisioning profile id if servers file not found by server name const demoAccount = await api.metatraderAccountGeneratorApi.createMT5DemoAccount({ accountType: 'type', balance: 100000, email: 'example@example.com', leverage: 100, serverName: 'ICMarketsSC-Demo', name: 'Test User', phone: '+12345678901' }, provisioningProfile.id); ``` -------------------------------- ### Stream Period Statistics Source: https://github.com/metaapi/metaapi-javascript-sdk/blob/main/examples/browser/riskManagement/periodStatisticsStream.html This example demonstrates how to stream period statistics using the MetaAPI JavaScript SDK. It includes setting up an event listener for statistics updates, creating a tracker, retrieving equity chart data, and managing the tracker lifecycle. Requires account ID, tracker name, and a terminal access token. ```javascript const infoElement = document.getElementById('info'); function log() { if(typeof arguments[1] === 'object'){ arguments[1] = JSON.stringify(arguments[1]); } const el = document.createElement('div'); el.innerHTML = [].join.call(arguments, ' '); infoElement.appendChild(el); console.log(...arguments); } const onSubmit = async () => { class ExamplePeriodStatisticsListener extends MetaApi.PeriodStatisticsListener { async onPeriodStatisticsUpdated(periodStatisticsEvent) { log('period statistics updated', periodStatisticsEvent); } async onPeriodStatisticsCompleted() { log('period completed event received'); } async onTrackerCompleted(){ log('tracker completed event received'); } async onConnected() { log('on connected event received'); } async onDisconnected() { log('on disconnected event received'); } async onError(error) { log('error event received', error); } } const trackerName = document.getElementById('tracker-name-input').value; const accountId = document.getElementById('account-id-input').value; const token = document.getElementById('token-input').value; if (token && accountId && trackerName) { try { const riskManagement = new MetaApi.RiskManagement(token); const riskManagementApi = riskManagement.riskManagementApi; /* creating a tracker */ const trackerId = await riskManagementApi.createTracker(accountId, { absoluteDrawdownThreshold: 5, name: trackerName, period: 'day' }); log('Created an event tracker ' + trackerId.id); /* adding a period statistics listener */ const periodStatisticsListener = new ExamplePeriodStatisticsListener(accountId, trackerId); const listenerId = riskManagementApi.addPeriodStatisticsListener(periodStatisticsListener, accountId, trackerId.id); log('Streaming period statistics events for 1 minute...'); await new Promise(res => setTimeout(res, 1000 * 60)); riskManagementApi.removePeriodStatisticsListener(listenerId); const equityChart = await riskManagementApi.getEquityChart(accountId); log('period statistics', JSON.stringify(equityChart)); await riskManagementApi.deleteTracker(accountId, trackerId.id); log('Removed the tracker'); } catch (error) { log(error) } } } ``` -------------------------------- ### Create MT4 Demo Account with MetaApi SDK Source: https://github.com/metaapi/metaapi-javascript-sdk/blob/main/docs/metaApi/managingAccounts.md Demonstrates how to create a MetaTrader 4 demo account using the `createMT4DemoAccount` method from the MetaApi JavaScript SDK. It shows how to specify account details like balance, leverage, server, and contact information. An optional parameter for provisioning profile ID is also illustrated. ```javascript const demoAccount = await api.metatraderAccountGeneratorApi.createMT4DemoAccount({ balance: 100000, accountType: 'type', email: 'example@example.com', leverage: 100, serverName: 'Exness-Trial4', name: 'Test User', phone: '+12345678901', keywords: ["Exness Technologies Ltd"] }); // optionally specify a provisioning profile id if servers file is not found by server name const demoAccount = await api.metatraderAccountGeneratorApi.createMT4DemoAccount({ balance: 100000, accountType: 'type', email: 'example@example.com', leverage: 100, serverName: 'Exness-Trial4', name: 'Test User', phone: '+12345678901' }, provisioningProfile.id); ``` -------------------------------- ### Start via Docker Source: https://github.com/metaapi/metaapi-javascript-sdk/blob/main/docs/ui/react.md Builds a Docker image for the application and runs it as a detached container. The application is exposed on port 5173, accessible at localhost:5173. ```bash docker build -t metaapi-app-example -f Dockerfile . docker run -d -p 5173:5173 metaapi-app-example # runned at localhost:5173 ``` -------------------------------- ### Install MetaApi SDK via CDN (HTML) Source: https://github.com/metaapi/metaapi-javascript-sdk/blob/main/docs/ui/html.md Shows how to include the MetaApi SDK using CDN links for both UMD and ES6 module formats in an HTML file. This is the first step to using the SDK in a web application. ```html ``` ```html ```