/Mida

The open-source and cross-platform trading engine

Primary LanguageTypeScriptMIT LicenseMIT



Mida Mida


The open-source and cross-platform trading engine

HomeDocumentationAPIEcosystem




Introduction

Mida is an open-source and cross-platform trading engine developed by Reiryoku Technologies and its contributors. The engine can be used for trading financial assets such as crypto, forex, stocks or commodities in global financial markets. The engine is designed from the ground up to provide a solid, versatile and platform-neutral environment for creating algorithmic trading systems, indicators, market analysis tools or just trading applications depending on use cases.

Languages

Mida can be used with TypeScript/JavaScript on Node.js and is distributed on npm. The Mida ecosystem is built from the ground up in TypeScript and C++.

Community

Join the community on Discord and Telegram to get help you with your first steps.

Table of contents

Ecosystem

Project Status Description
Mida Image The Mida core
Mida Binance Image A Mida plugin for using Binance
Mida cTrader Image A Mida plugin for using cTrader
Mida Tulipan Image A Mida plugin providing technical analysis indicators
Apollo Image A JavaScript library for getting real-time economic data

Supported platforms

Mida is platform-neutral, this means that any trading platform could be easily integrated in the ecosystem. Trading systems/applications built with Mida can be easily executed on different trading platforms without code changes. Here are some of the most popular trading platforms supported by Mida.





Installation

To get started use the command below in your terminal, the installer will pop up and create an empty Mida project.

npm init mida

Usage

Account login

How to login into a Binance Spot account.

import { login, } from "@reiryoku/mida";

const myAccount = await login("Binance/Spot", {
    apiKey: "***",
    apiSecret: "***",
});

Read how to use Binance to get the apiKey and apiSecret credentials.

How to login into a cTrader account.

import { login, } from "@reiryoku/mida";

const myAccount = await login("cTrader", {
    clientId: "***",
    clientSecret: "***",
    accessToken: "***",
    cTraderBrokerAccountId: "***",
});

Read how to use cTrader to get the clientId, clientSecret, accessToken and cTraderBrokerAccountId credentials.

Balance, equity and margin

How to get the account balance, equity and margin.

import { info, } from "@reiryoku/mida";

info(await myAccount.getBalance());
info(await myAccount.getEquity());
info(await myAccount.getFreeMargin());
info(await myAccount.getUsedMargin());

Orders, deals and positions

How top open a long position for Bitcoin against USDT.

import { info, MidaOrderDirection, } from "@reiryoku/mida";

const myOrder = await myAccount.placeOrder({
    symbol: "BTCUSDT",
    direction: MidaOrderDirection.BUY,
    volume: 1,
});
const myPosition = await order.getPosition();

info(myOrder.id);
info(myOrder.executionPrice);
info(myOrder.positionId);
info(myOrder.trades);
info(myPosition);

How to open a short position for EUR against USD.

import { info, MidaOrderDirection, } from "@reiryoku/mida";

const myOrder = await myAccount.placeOrder({
    symbol: "EURUSD",
    direction: MidaOrderDirection.SELL,
    volume: 0.1,
});
const myPosition = await order.getPosition();

info(myOrder.id);
info(myOrder.executionPrice);
info(myOrder.positionId);
info(myOrder.trades);
info(myPosition);

How to open a long position for Apple stocks with error handler.

import {
    info,
    MidaOrderDirection,
    MidaOrderRejection,
} from "@reiryoku/mida";

const myOrder = await myAccount.placeOrder({
    symbol: "#AAPL",
    direction: MidaOrderDirection.BUY,
    volume: 888,
});

if (myOrder.isRejected) {
    switch (myOrder.rejection) {
        case MidaOrderRejection.MARKET_CLOSED: {
            info("#AAPL market is closed!");

            break;
        }
        case MidaOrderRejection.NOT_ENOUGH_MONEY: {
            info("You don't have enough money in your account!");

            break;
        }
        case MidaOrderRejection.INVALID_SYMBOL: {
            info("Your account doesn't support trading Apple stocks!");

            break;
        }
    }
}
More examples

How to open a long position for GBP against USD with stop loss and take profit.

import { MidaOrderDirection, } from "@reiryoku/mida";

const symbol = "GBPUSD";
const lastBid = await myAccount.getSymbolBid(symbol);
const myOrder = await myAccount.placeOrder({
    symbol,
    direction: MidaOrderDirection.BUY,
    volume: 0.1,
    protection: {
        stopLoss: lastBid.subtract(0.0010), // <= SL 10 pips
        takeProfit: lastBid.add(0.0030), // <= TP 30 pips
    },
});

How to close an open position.

import {
    MidaOrderDirection,
    MidaPositionDirection,
} from "@reiryoku/mida";

await myPosition.close();
// or
await myPosition.subtractVolume(myPosition.volume);
// or
await myAccount.placeOrder({
    positionId: myPosition.id,
    direction: myPosition.direction === MidaPositionDirection.LONG ? MidaOrderDirection.SELL : MidaOrderDirection.BUY,
    volume: myPosition.volume,
});

How to retrieve all open positions and pending orders.

import { info, } from "@reiryoku/mida";

info(await myAccount.getOpenPositions());
info(await myAccount.getPendingOrders());

How to set take profit and stop loss for a position.

await myPosition.changeProtection({
    takeProfit: 200,
    stopLoss: 100,
});

Decimals

Decimal numbers and calculations are accurately represented by the MidaDecimal API, computers can only natively store integers, so they need some way of representing decimal numbers. This representation is not perfectly accurate. This is why, in most programming languages 0.1 + 0.2 != 0.3, for financial and monetary calculations this can lead to unrecoverable mistakes.

import { decimal, } from "@reiryoku/mida";

0.1 + 0.2; // 0.30000000000000004
decimal(0.1).add(0.2); // 0.3
decimal("0.1").add("0.2"); // 0.3

In Mida, every calculation under the hood is made using decimals and every native number passed to Mida is internally converted to decimal, input values in the Mida APIs such as a limit price can be expressed as a MidaDecimalConvertible which is an alias for MidaDecimal | string | number, the input values are internally converted to MidaDecimal and all Mida interfaces exposes decimal numbers unless otherwise stated.

Read more about the Decimals API.

Symbols and assets

How to retrieve all symbols available for your trading account.

import { info, } from "@reiryoku/mida";

const symbols = await myAccount.getSymbols();

info(symbols);

How to retrieve a symbol.

import { info, } from "@reiryoku/mida";

const symbol = await myAccount.getSymbol("#AAPL");

if (!symbol) {
    info("Apple stocks are not available for this account!");
}
else {
    info(symbol.digits);
    info(symbol.leverage);
    info(symbol.baseAsset);
    info(symbol.quoteAsset);
    info(await symbol.isMarketOpen());
}

How to get the price of a symbol.

import { info, } from "@reiryoku/mida";

const symbol = await myAccount.getSymbol("BTCUSDT");
const price = await symbol.getBid();

info(`Bitcoin price is ${price} USDT`);

// or

info(await myAccount.getSymbolBid("BTCUSDT"));

Ticks and candlesticks

How to listen the ticks of a symbol.

import { info, MidaMarketWatcher, } from "@reiryoku/mida";

const marketWatcher = new MidaMarketWatcher({ tradingAccount: myAccount, });

await marketWatcher.watch("BTCUSDT", { watchTicks: true, });

marketWatcher.on("tick", (event) => {
    const { tick, } = event.descriptor;

    info(`Bitcoin price is now ${tick.bid} USDT`);
});

How to get the candlesticks of a symbol (candlesticks and bars are generically called periods).

import { info, MidaTimeframe, } from "@reiryoku/mida";

const periods = await myAccount.getSymbolPeriods("EURUSD", MidaTimeframe.M30);
const lastPeriod = periods[periods.length - 1];

info("Last candlestick start time: " + lastPeriod.startTime);
info("Last candlestick OHLC: " + lastPeriod.ohlc);
info("Last candlestick close price: " + lastPeriod.close);

How to listen when candlesticks are closed.

import {
    info,
    MidaMarketWatcher,
    MidaTimeframe,
} from "@reiryoku/mida";

const marketWatcher = new MidaMarketWatcher({ tradingAccount: myAccount, });

await marketWatcher.watch("BTCUSDT", {
    watchPeriods: true,
    timeframes: [
        MidaTimeframe.M5,
        MidaTimeframe.H1,
    ],
});

marketWatcher.on("period-close", (event) => {
    const { period, } = event.descriptor;

    switch (period.timeframe) {
        case MidaTimeframe.M5: {
            info(`M5 candlestick closed at ${period.close}`);

            break;
        }
        case MidaTimeframe.H1: {
            info(`H1 candlestick closed at ${period.close}`);

            break;
        }
    }
});

Trading systems

How to create a trading system (expert advisor or trading bot).

import {
    info,
    MidaTradingSystem,
    MidaTimeframe,
} from "@reiryoku/mida";

class SuperTradingSystem extends MidaTradingSystem {
    watched () {
        return {
            "BTCUSDT": {
                watchTicks: true,
                watchPeriods: true,
                timeframes: [ MidaTimeframe.H1, ],
            },
        };
    }

    async configure () {
        // Called once per instance before the first startup
        // can be used as async constructor
    }

    async onStart () {
        info("The trading system has started...");
    }

    async onTick (tick) {
        // Implement your strategy
    }

    async onPeriodClose (period) {
        info(`H1 candlestick closed at ${period.open}`);
    }

    async onStop () {
        info("The trading system has been interrupted...");
    }
}

How to execute a trading system.

import { login, } from "@reiryoku/mida";
import { SuperTradingSystem, } from "./SuperTradingSystem";

const myAccount = await login(/* ... */);
const mySystem = new SuperTradingSystem({ tradingAccount: myAccount, });

await mySystem.start();

Technical indicators

Install the plugin providing technical analysis indicators.

import { Mida, } from "@reiryoku/mida";
import { TulipanPlugin, } from "@reiryoku/mida-tulipan";

// Use the Mida Tulipan plugin
Mida.use(new TulipanPlugin());

How to calculate SMA (Simple Moving Average).

import { info, Mida, MidaTimeframe, } from "@reiryoku/mida";

// Get latest candlesticks on H1 timeframe
const candlesticks = await myAccount.getSymbolPeriods("EURUSD", MidaTimeframe.H1);
const closePrices = candlesticks.map((candlestick) => candlestick.close);

// Calculate RSI on close prices, pass values from oldest to newest
const sma = await Mida.createIndicator("SMA").calculate(closePrices);

// Values are from oldest to newest
info(sma);

How to calculate RSI (Relative Strength Index).

import { info, Mida, MidaTimeframe, } from "@reiryoku/mida";

// Get latest candlesticks on H1 timeframe
const candlesticks = await myAccount.getSymbolPeriods("BTCUSDT", MidaTimeframe.H1);
const closePrices = candlesticks.map((candlestick) => candlestick.close);

// Calculate RSI on close prices, pass values from oldest to newest
const rsi = await Mida.createIndicator("RSI", { period: 14, }).calculate(closePrices);

// Values are from oldest to newest
info(rsi);

License and disclaimer

LICENSE

Trading in financial markets is highly speculative and carries a high level of risk. It's possible to lose all your capital. This project may not be suitable for everyone, you should ensure that you understand the risks involved. Mida and its contributors are not responsible for any technical inconvenience that may lead to money loss, for example a stop loss not being set.

Contributors

Name Contribution GitHub Contact
Vasile Pește Author and maintainer Vasile-Peste vasile.peste@reiryoku.com