/* eslint-disable max-len */ /* eslint-disable complexity */ import { useEffect, useState } from 'react'; import { PrintLog, // for log Sections, Section, // Layout Form, Field // Form } from '../../shared'; import MetaApi, { MetatraderAccount } from 'metaapi.cloud-sdk'; interface IHistoricalGetTicksProps { accountId?: string domain?: string symbol?: string token?: string } export function HistoricalGetCandles({ token: defaultToken, accountId: defaultAccountId, symbol: defaultSymbol, domain: defaultDomain }: IHistoricalGetTicksProps) { /* UI control */ const [areResourcesNarrowedDown, setAreResourcesNarrowedDown] = useState(true); const [isConnecting, setIsConnecting] = useState(false); const [isConnected, setIsConnected] = useState(false); /* Logging */ const [resultLog, setResultLog] = useState([]); const [errorLog, setErrorLog] = useState([]); const logErr = (...args: unknown[]) => setErrorLog(logs => { console.log(...args); return [...logs, ...args.map((arg: any) => arg.message || arg)]; }); const log = (...args: unknown[]) => setResultLog(logs => { console.log(...args); return [...logs, ...args]; }); /* Store main variables */ const [accountId, setAccountId] = useState(defaultAccountId || ''); const [domain, setDomain] = useState(defaultDomain || ''); const [symbol, setSymbol] = useState(defaultSymbol || ''); const [token, setToken] = useState(defaultToken || ''); /* Connect to MetaApi */ const connectToMetaApiAccount = async (): Promise => { /* Get instance of MetaApi with your MetaApi token */ const metaApi = new MetaApi(token, { domain }); const areTokenResourcesNarrowedDown = metaApi.tokenManagementApi.areTokenResourcesNarrowedDown(token); setAreResourcesNarrowedDown(areTokenResourcesNarrowedDown); /* Get MetaTrader account */ const account = await metaApi.metatraderAccountApi.getAccount(accountId); /* Wait until account is deployed and connected to broker */ log('Deploying account'); if (account.state !== 'DEPLOYED') { await account.deploy(); } else { log('Account already deployed'); } log('Waiting for API server to connect to broker (may take couple of minutes)'); if (account.connectionStatus !== 'CONNECTED') { await account.waitConnected(); } return account; }; /* Interaction with metaapi */ const fetchData = async () => { try { const account = await connectToMetaApiAccount(); /* Retrieve last 10K 1m candles The API to retrieve historical market data is currently available for G1 and MT4 G2 only */ const pages = 10; log(`Downloading ${pages}K latest candles for ${symbol}`); const startedAt = Date.now(); let startTime; let candles; for (let i = 0; i < pages; i++) { const newCandles = await account.getHistoricalCandles(symbol, '1m', startTime); log(`Downloaded ${newCandles ? newCandles.length : 0} historical candles for ${symbol}`); if (newCandles && newCandles.length) { candles = newCandles; } if (candles && candles.length) { startTime = candles[0].time; startTime.setMinutes(startTime.getMinutes() - 1); log(`First candle time is ${startTime}`); } } if (candles) { log('First candle is', candles[0]); } log(`Took ${Date.now() - startedAt}ms`); } catch(err) { logErr(err); throw err; } }; /* Use one for control request and rerender */ useEffect(() => { if (isConnected || !isConnecting) { return; } fetchData() .then(() => setIsConnected(true)) // If success .catch(err => console.log('failed', err)) // If failed .finally(() => setIsConnecting(false)); // Enable an interaction with UI }, [isConnecting]); // if change isConnecting run useEffect /* UI control */ const reset = () => { setIsConnecting(false); setIsConnected(false); setResultLog([]); setErrorLog([]); setAccountId(defaultAccountId || ''); setDomain(defaultDomain || ''); setToken(defaultToken ||''); }; const triggerToFetchData = () => { if (isConnected || !accountId || !token) {return;} setIsConnecting(true); }; return (

MetaApi. Historical Market Data. Get candles

Connect to your account

{!areResourcesNarrowedDown &&

Warning

It seems like you are using a admin API token.

Since the token can be retrieven from the browser or mobile apps by end user this can lead to your application being compromised, unless you understand what are you doing.

Please use Token Management API in your backend application to produce secure tokens which you can then use in web UI or mobile apps.

} {resultLog && resultLog.length > 0 &&

Logs

} {errorLog && errorLog.length > 0 &&

Errors

}
); }