Skip to content

Create A Market Order

Overview

A market order is essentially an instruction from a trader to their broker to buy or sell a specific asset at the current market price.

Unlike limit orders, which allow traders to set a specific price at which they want to execute a trade, market orders prioritize immediate execution, making them useful when a trader values speed and certainty over price.

Market orders are straightforward and are typically executed quickly, ensuring that traders enter or exit positions at the prevailing market rates. However, because they rely on current market prices, the final execution price may slightly differ from the expected rate at the time of order placement.

How to create a market order

In this article you will learn how to create a market order, which is a type of order that is executed immediately at the current market price. You can use market orders to open a new trade or close an existing trade. To create a market order, you need to follow these steps:

  1. Login (see the tutorial here)

  2. Create an OpenOrderFactory object

  3. Create a Market Order Request

  1. Login (see the tutorial here)

  2. Create an OpenOrderFactory object

  3. Create a Market Order Request

  1. Login (see the tutorial here)

  2. Create an OpenOrderFactory object

  3. Create a Market Order Request

  4. Creating Listeners

  5. Creating Workers to pass results to be printed.

  6. Printing the results in a readable format.

  7. Updating the html to include our new JavaScript files.

  8. The main JavaScript file.

Step 1: Login

Follow the steps in the login tutorial here

Step 2: Create an OpenOrderFactory object

You need to create an OpenOrderFactory object, which is a helper class that helps you set up the order parameters, such as the instrument, the direction, the amount, and the slippage.

OpenOrderFactory

let OpenOrderFactory = /** @class */ (function () {
    function OpenOrderFactory() {
    }
    OpenOrderFactory.create = function (manager, offersManager, accountId, offerId, amount) {
        return manager.getRequestFactory().createMarketOrderRequestBuilder()
        .setAccountId(accountId)
        .setAmount(amount)
        .setOfferId(offerId)
        .setBuySell('B')
        .setTimeInForce('IOC')
        .build();
    };
    return OpenOrderFactory;
}());
this.#buildRequest(account, amount, instrument) {
    let requestFactory = this.ordersManager.getRequestFactory();
    return requestFactory.createMarketOrderRequestBuilder()
        .setAccountId(account.getAccountId())
        .setAmount(amount)
        .setOfferId(instrument.getOfferId())
        .setBuySell('B')
        .setTimeInForce('IOC')
        .build();
}
let request = this.#buildRequest(account, amount, instrument);
this.ordersManager.createOpenMarketOrder(request);

In the JavaScript version we need to create the order worker class orders\order-worker.js. This class is responsible for passing the results to the printing functions and is responsible for creating the order.

class OrderWorker {
    constructor(session, accountCommissionsManager, offersManager) {
        this.accountCommissionsManager = accountCommissionsManager;
        this.offersManager = offersManager;

        this.accountsManager = session.getAccountsManager();
        this.marginProvider = session.getMarginProvider();
        this.tradingSettingsProvider = session.getTradingSettingsProvider();
    }

    #buildRequest(ordersManager, account, amount, instrument) {
        let requestFactory = ordersManager.getRequestFactory();
        return requestFactory.createMarketOrderRequestBuilder()
            .setAccountId(account.getAccountId())
            .setAmount(amount)
            .setOfferId(instrument.getOfferId())
            .setBuySell('B')
            .setTimeInForce('IOC')
            .build();
    }

    #getAccount() {
        let accountsInfo = this.accountsManager.getAccountsInfo()[0];
        return this.accountsManager.getAccountById(accountsInfo.getId());
    }

    #getDataManagerStateString(state) {
        if (state.isNotLoaded())
            return 'not loaded';

        if (state.isLoading())
            return 'loading';

        if (state.isLoaded())
            return 'loaded';

        return '(has error)'
    }

    #getPip(amount, offer, instrument) {
        let pipCost = offer.getPipCost();
        let pipCostAmount = this.tradingSettingsProvider.getPipCostAmount(instrument);

        return amount * pipCost / pipCostAmount;
    }

    placeOpenOrder(ordersManager, instrument) {
        let account = this.#getAccount();
        let amount = this.tradingSettingsProvider.getMinQuantity(instrument, account);
        let offer = this.offersManager.getOfferById(instrument.getOfferId());

        let pip = this.#getPip(amount, offer, instrument);
        console.log(`Per Pip: ${pip}`);

        let commission = this.accountCommissionsManager.getOpenCommission(offer, account, amount, 'B', offer.getAsk());
        console.log(`Commission: ${commission}`);

        let mmr = this.marginProvider.getMMR(instrument, account);
        console.log(`Used Margin: ${mmr}`);

        let request = this.#buildRequest(ordersManager, account, amount, instrument);
        ordersManager.createOpenMarketOrder(request);
    }

    updateState(state) {
        document.getElementById('state')
            .textContent = this.#getDataManagerStateString(state);
    }
}

See also IOrdersManager, getRequestFactory, MarketOrderRequestBuilder

Step 3: Create a Market Order Request

You can use the OpenOrderFactory object to create a market order request, which is an object that contains all the information needed to place the order.

Create a market order.

let instrument = instrumentsManager.getInstrumentBySymbol("EUR/GBP");
//getting offer Id
let offerId = instrument.getOfferId();
let amount = 100; //any integer
//create ordersManager
let manager = session.getOrdersManager();
//create offersManager
let offersManager = session.getOffersManager();
//create accountManager
let accountsManager = session.getAccountsManager();
//get first account
let account = accountsManager.getAccountById(accountsManager.getAccountsInfo()[0].getId());// a user can have multiple accounts.
//create using order factory
let request = OpenOrderFactory.create(manager, offersManager, account.getAccountId(), offerId, amount);
//create market order
manager.createOpenMarketOrder(request);
let account = this.#getAccount();
let amount = this.tradingSettingsProvider.getMinQuantity(instrument, account);
let offer = this.offersManager.getOfferById(instrument.getOfferId());

let pip = this.#getPip(amount, offer, instrument);
console.log(`Per Pip: ${pip}`);

let commission = this.accountCommissionsManager.getOpenCommission(offer, account, amount, 'B', offer.getAsk());
console.log(`Commission: ${commission}`);

let mmr = this.marginProvider.getMMR(instrument, account);
console.log(`Used Margin: ${mmr}`);

let request = this.#buildRequest(account, amount, instrument);
this.ordersManager.createOpenMarketOrder(request);

In the same file orders\order-worker.js we have the method placeOpenOrder which is responsible for creating the actual order.

placeOpenOrder(ordersManager, instrument) {
    let account = this.#getAccount();
    let amount = this.tradingSettingsProvider.getMinQuantity(instrument, account);
    let offer = this.offersManager.getOfferById(instrument.getOfferId());

    let pip = this.#getPip(amount, offer, instrument);
    console.log(`Per Pip: ${pip}`);

    let commission = this.accountCommissionsManager.getOpenCommission(offer, account, amount, 'B', offer.getAsk());
    console.log(`Commission: ${commission}`);

    let mmr = this.marginProvider.getMMR(instrument, account);
    console.log(`Used Margin: ${mmr}`);

    let request = this.#buildRequest(ordersManager, account, amount, instrument);
    ordersManager.createOpenMarketOrder(request);
}

Step 4: Creating Listeners

These listeners listen for changes in both the orders list and the open positions list so that we can pass the changes to be printed. positions\open-position-change-listener.js
class OpenPositionChangeListener {
    constructor(openPositionsManager, ordersManager, orderWorker, placeCloseOrderAction) {
        this.openPositionsManager = openPositionsManager;
        this.placeCloseOrderAction = placeCloseOrderAction;
        this.ordersManager = ordersManager;
        this.orderWorker = orderWorker;

        this.positionWorker = new PositionWorker();
    }

    onChange(openPositionInfo) {
        //do nothing
    }

    onAdd(openPositionInfo) {
        let positionId = openPositionInfo.getId();
        console.log(`OpenPosition ${positionId} added.`);

        let openPosition = this.openPositionsManager.getOpenPosition(positionId);
        this.positionWorker.showPositionDetails(openPosition);

        this.placeCloseOrderAction.execute(openPosition);
    }

    onDelete(openPositionInfo) {
        let positionId = openPositionInfo.getId();
        console.log(`OpenPosition ${positionId} deleted.`);
    }    

    onRefresh() {
    }
}
orders\order-change-listener.js
    class OrderChangeListener {
    constructor(ordersManager) {
        this.ordersManager = ordersManager;
    }

    onChange(orderInfo) {
        let order = this.ordersManager.getOrderById(orderInfo.getOrderId());
        console.log(`Order ${orderInfo.getOrderId()} changed to status '${order.getStatus()}'.`);
    }

    onAdd(orderInfo) {
        console.log(`Order ${orderInfo.getOrderId()} added.`);
    }

    onDelete(orderInfo) {
        console.log(`Order ${orderInfo.getOrderId()} deleted.`);
    }


    onError(orderInfo) {
        console.log(`Order error: ${orderInfo.getError().getMessage()}`);
    }
} 
orders\order-state-listener.js
class OrderStateListener {
    constructor(instrumentsManager, orderManager, orderWorker) {
        this.instrumentsManager = instrumentsManager;
        this.orderManager = orderManager;
        this.orderWorker = orderWorker;
    }

    onStateChange(state) {
        this.orderWorker.updateState(state);
        if (!state.isLoaded()) 
            return;

        let instrument = this.instrumentsManager.getInstrumentBySymbol('EUR/USD');
        this.orderWorker.placeOpenOrder(this.orderManager, instrument);
    }
}
orders\place-close-order-action.js
class PlaceCloseOrderAction {
    constructor(orderManager) {
        this.ordersManager = orderManager;
    }

    #buildRequest(position) {
        let requestFactory = this.ordersManager.getRequestFactory();
        return requestFactory.createCloseMarketOrderRequestBuilder()
            .setTradeId(position.getTradeID())
            .setAmount(position.getAmount())
            .setRateRange(10)
            .setTimeInForce('IOC')
            .setCustomId('custom-id-close')
            .build();
    }

    execute(position) {
        console.log(`Placing a close market order...`);

        let request = this.#buildRequest(position);
        this.ordersManager.createCloseMarketOrder(request);
    }
}

Step 5: Creating Workers to pass results to be printed.

The orders worker we have shown you already, we also have the open positions worker positions\position-worker.js
class PositionWorker {
    constructor() {
        this.tableBuilder = new PositionTableBuilder();
    }

    showPositionDetails(position) {
       this.tableBuilder.renderPositionDetailsSubtable(position);
    }
}

Step 6: Printing the results in a readable format.

For printing the results of the command, we have first created a file which will contain our TableBuilder class. Follow the instruction in the Table Builder tutorial here.

Next we have the positions\position-table-builder.js which passes the results to the table class.

class PositionTableBuilder {
    constructor() {
        this.builder = new TableBuilder();
    }

    #getPositionDetails(position) {
        return new Map([
            ['Trade ID', position.getTradeID()],
            ['Account ID', position.getAccountId()],
            ['Used Margin', position.getUsedMargin()],
            ['Amount', position.getAmount()],
            ['Buy/Sell', position.getBuySell()],
            ['Open Rate', position.getOpenRate()],
            ['Close Rate', position.getCloseRate()],
            ['Stop Rate', position.getStopRate()],
            ['Limit Rate', position.getLimitRate()]
        ]);
    }

    #renderPositionTableHeader() {
        let columns = [
            { className: 'col-sm-12', value: 'Open Position' }
        ];

        return this.builder.createHeaderTableRow(columns);
    }

    renderPositionDetailsSubtable(position) {
        let row = this.#renderPositionTableHeader();

        let details = this.#getPositionDetails(position);
        let columns = this.builder.createDataSubtableColumns(details);

        this.builder.createDataSubtable(row, columns, 'row mb-3 details');

        this.builder.showContainer();
    }
}

Step 7: Updating the html to include our new JavaScript files.

<script src="connection_management/connection-status-change-listener.js"></script>
<script src="orders/order-change-listener.js"></script>
<script src="orders/order-state-listener.js"></script>
<script src="orders/order-worker.js"></script>
<script src="orders/place-close-order-action.js"></script>
<script src="positions/open-position-change-listener.js"></script>
<script src="positions/position-table-builder.js"></script>
<script src="positions/position-worker.js"></script>
<script src="common/table-builder.js"></script>
<script src="index.js"></script>

Step 8: The main JavaScript file.

index.js
const sessionFactory = FXConnectLite.FXConnectLiteSessionFactory;
const LoggerFactory = FXConnectLite.LoggerFactory;

function getOpenPositionManager(session, ordersManager, orderWorker) {
    let openPositionManager = session.getOpenPositionsManager();
    let action = new PlaceCloseOrderAction(ordersManager);
    let openPositionChangeListener = new OpenPositionChangeListener(openPositionManager, ordersManager, orderWorker, action);

    openPositionManager.subscribeOpenPositionChange(openPositionChangeListener);

    return openPositionManager;
}

function getOrdersManager(session, instrumentsManager, orderWorker) {
    let ordersManager = session.getOrdersManager();
    let orderChangeListener = new OrderChangeListener(ordersManager);
    ordersManager.subscribeOrderChange(orderChangeListener);
    ordersManager.subscribeStateChange(new OrderStateListener(instrumentsManager, ordersManager, orderWorker));

    return ordersManager;
}

document.addEventListener('DOMContentLoaded', () => {
    let session = sessionFactory.create('PlaceMarketOrderSample');
    session.setLogger(LoggerFactory.createLogger(LoggerFactory.LEVEL_DEBUG));

    let accountCommissionsManager = session.getAccountCommissionsManager();
    let instrumentsManager = session.getInstrumentsManager();
    let offersManager = session.getOffersManager();

    let orderWorker = new OrderWorker(session, accountCommissionsManager, offersManager);
    let ordersManager = getOrdersManager(session, instrumentsManager, orderWorker);

    let openPositionManager = getOpenPositionManager(session, ordersManager, orderWorker);

    let connectionStatusChangeListener = new ConnectionStatusChangeListener(
        session, 
        accountCommissionsManager, 
        instrumentsManager, 
        offersManager, 
        openPositionManager
    );
    session.subscribeConnectionStatusChange(connectionStatusChangeListener);

    bindConnectionRelatedEvents(session, () => {
        offersManager.refresh();
        instrumentsManager.refresh();
        openPositionManager.refresh();
        accountCommissionsManager.refresh();
        ordersManager.refresh();
    });

});

See also createOpenMarketOrder, Get open positions article.

When the order is created, you can:

  1. Get available instruments.
  2. Subscribe and Unsubscribe to instruments.
  3. Get price updates for an instrument.
  4. Get historical prices for an instrument.
  5. Get open positions.

Conclusion

In this article, you learned how to create a market order using the FCLite API. A market order is a type of order that is executed immediately at the current market price. You learned how to create an OpenOrderFactory object, which is a helper class that helps you set up the order parameters. You also learned how to create a market order request, which is an object that contains all the information needed to place the order. Finally, you learned how to use the ordersManager object to send the request to the FCLite server. You can use market orders to open a new trade or to close an existing trade quickly and easily. You can also modify or cancel your market orders using similar methods. To learn more about the FCLite API and its features, you can refer to this official documentation.

Download the sample Node TypeScript, Node JavaScript, JavaScript, Java.

Table of Contents
Order Types
This page will explain each of the different types of orders in the system.
Get All Orders
The article teaches how to get a list of all orders.
Modify an Order
The article teaches how to modify an order
Create a Market Order
The article teaches how to create a market order
Create an Entry Order
API Command used to create an entry order
Create a Close Market Order
The article teaches how to create a close 'market order'
Create an OCO Order
API Command used to create an OCO order
Create a Stop and/or Limit Order
This article provides information about how to add a stop/limit to an order
Cancel an Order
This article provides information about how to cancel an order