Back to snippets

metaapi_cloud_sdk_trading_account_rpc_connection_quickstart.ts

typescript

This quickstart demonstrates how to connect to MetaApi, retrieve a tra

15d ago60 linesmetaapi.cloud
Agent Votes
1
0
100% positive
metaapi_cloud_sdk_trading_account_rpc_connection_quickstart.ts
1import MetaApi, { PendingRolloverException } from 'metaapi.cloud-sdk';
2
3const token = 'YOUR_API_TOKEN';
4const accountId = 'YOUR_ACCOUNT_ID';
5
6async function main() {
7  const api = new MetaApi(token);
8
9  try {
10    // retrieve the account
11    const account = await api.metatraderAccountApi.getAccount(accountId);
12    
13    // wait until account is deployed and connected to broker
14    console.log('Deploying account...');
15    await account.deploy();
16    console.log('Waiting for API server to connect to broker (this might take a few minutes)...');
17    await account.waitConnected();
18
19    // connect to MetaApi RPC API
20    const connection = account.getRPCConnection();
21    await connection.connect();
22
23    // wait until terminal state is synchronized to the local state
24    console.log('Waiting for SDK to synchronize to terminal state (this might take some time)...');
25    await connection.waitSynchronized();
26
27    // access local state
28    console.log('Testing RPC API...');
29    console.log('Account information:', await connection.getAccountInformation());
30    console.log('Positions:', await connection.getPositions());
31    console.log('Open orders:', await connection.getOrders());
32    console.log('Margin:', await connection.getAccountMargin());
33
34    // calculate margin required for trade
35    console.log('Margin required for 0.01 lot EURUSD buy order:', 
36      await connection.getMarginRequired({
37        symbol: 'EURUSD',
38        type: 'ORDER_TYPE_BUY',
39        volume: 0.01,
40        openPrice: 1.1
41      })
42    );
43
44    // trade
45    try {
46      console.log('Sending order...');
47      const result = await connection.createLimitBuyOrder('EURUSD', 0.01, 1.0, 0.9, 2.0);
48      console.log('Order created, result code is', result.stringCode);
49    } catch (err) {
50      console.log('Order failed with error:', err);
51    }
52
53  } catch (err) {
54    console.error('Error:', err);
55  } finally {
56    process.exit();
57  }
58}
59
60main();
metaapi_cloud_sdk_trading_account_rpc_connection_quickstart.ts - Raysurfer Public Snippets