Backtrader: Oanda Margin and Leverage

The concept of margin and leverage can be a tricky one to setup correctly in a backtest environment. Each country and broker may have different rules and regulations for how margin is applied. To further compound the confusion, the definition of margin itself can also differ. In some markets, margin is simply a fixed size deposit you must provide to enter into a position. In other’s (like Forex) you need to be aware of both an initial margin (the deposit) to open a position and subsequent maintenance margin to keep the position open.

Backtrader’s architecture only supports the concept of margin as an initial deposit. Should you want to simulate maintenance margin and margin closeouts, you will need to manage this yourself. In this post, we are going to just do that.

Before we begin

There are a number of things we must consider when setting up Backtrader to account correctly for margin and leverage.

  1. The regulatory requirements in your country/region
  2. The type of asset you are trading.
  3. Your broker’s rules/calculation method.

Links and some brief notes covering all three points will follow but they are not a one size fits all solution. Instead, they focus rules and regulations for Oanda, trading a single Forex pair and assuming the base account is USD. In a future post, I aim to expand on this by adding multiple instruments and accounting for instruments that are not denominated in your account currency. However, after having investigated actually trying to do Forex conversions before/after trading an instrument (think going long on EUR/USD on a GBP account), there appear to be trade-offs that would make this post too complex. Thus, I decided to initially focus on a simple use case to lay the foundations first. Finally, the cost of financing (the interest that is charged when you use leverage) will also be covered in a separate post.

Disclaimer: The examples in this post and margin rates used were correct as of August 2017 As time moves on the rates and regulations may change. 

Doing the research

To make sure we setup correctly we need to take a look at the Oanda website to see how they calculate margin and margin closeouts. First of all, I suggest you become familiar with margin jargon. Oanda has a good overview of all the margin related terms on their USA regulatory overview page. For some reason, they do not include a summary of terms on the European version! So Europeans should still take a look at the US page to get familiar with the terminology, then search for their own regulatory page.

Some terms that we really need to be familiar with are as follows. However, there are many more terms listed on the page. I do encourage you to read them all!.

Margin: A good faith deposit or performance bond. In leveraged trading, the margin amount is held in deposit while the trade is open. The amount of margin required to enter a trade is determined by the rules discussed below. Although there is no minimum margin deposit required to open an fxTrade account with OANDA, the Margin Available in your account will limit the size of the positions you can open.

Leverage: The reciprocal of Margin. For example, 2% margin is the same as 50:1 leverage. The maximum leverage allowed is determined by the regulators in each geographic region. Clients and OANDA may choose to be conservative and limit leverage utilized to lower levels than allowed by the regulators.

Margin Closeout Value: The Margin Closeout Value is equal to your balance plus your unrealized P/L from all open positions, converted into the currency of the account, all calculated using the current midpoint rates. See the Margin Closeout Value Calculation Example below for an example of how to calculate your account equity.

Initial Margin: The Initial Margin for a trade is equal to the trade size multiplied by the Margin Requirement. This amount is then converted into the currency of the account. When opening a new trade, your Initial Margin must be less than or equal to your Margin Available. If your Initial Margin is greater than your Margin Available, you cannot open the trade.

Margin Closeout: If your Margin Closeout Value falls to less than half of your Margin Used, all open positions will be automatically closed using the current fxTrade rates at the time of closing. If trading is unavailable for certain open positions at the time of the margin closeout, those positions will remain open and the fxTrade platform will continue to monitor your margin requirements. When the markets reopen for the remaining open positions, another margin closeout may occur if your account remains under-margined.

Check your margin rates

Before you trade a particular instrument, you need to know the margin rate for it. Also be aware that because your account has a leverage of 50:1, it does not mean that you will always get to use it all. As you will see, some exotic pairs and CFD’s require a 5% (20:1) initial margin regardless of how much leverage your account has.

US customers also have to deal with comparatively strict regulatory compliance which forces a maximum leverage of 20:1 on all minor pairs. You can thank the CFTC for protecting your wallet.

The Commodity Futures Trading Commission (CFTC) limits leverage available to retail forex traders in the United States to 50:1 on major currency pairs and 20:1 for all others.

Margin Calculations

The initial margin and margin closeout descriptions quoted above provide all the information we need to make the calculations needed in the strategy. They are:

Initial Margin =  (price x size) / leverage.

Margin Closeout Value* = Balance + open PnL

Margin Closeout = Margin Closeout Value < (Initial Margin / 2)

*In backtrader the margin closeout value is simply the same as the

Putting it all together

In this code example, we are going to trade EUR/USD using a base USD base account subject to US regulations and utilizing 50:1 leverage.

A copy of the data I use for testing can be found here: EUR_USD-2005-2017-D1


For testing purposes, the strategy is pretty simple. It just opens and closes portions on set bars.

Next, the check_mco() method is used to check whether a margin close out should be applied. One we are in a position, we need to call check_mco() on every call of next() to see if the margin close out value has dipped below the threshold. If so, we close the position and use addinfo() to flag that it was closed due to having insufficient margin rather than as part of the strategy.

Finally, we set self.margin attribute once we receive the order.Completed notification. This allows us to access the executed price and therefore calculate the executed initial margin requirement. We do this following a notification (rather than during the next() call) because, for market orders, Backtrader fills the order using the opening price of the following bar. If it gaps up or down, we could run the risk of incorrectly calculating the initial margin.

The Results

The first two screenshots are when the trade size is set to $100,000. The script executes without a margin close out. This is the baseline test.

Chart showing the two entries and exits without a margin close out Output from the terminal when running the code as is

Second, we crank up the size to $200,000 and force a margin close out as the trade goes against us.

Margin and leverage causing automatic close out early

Margin close out warning in the terminal.

You can see from the terminal output, it took 3 days before the position was closed. In addition, the trade lost so much money, that there was not enough cash left to cover the margin on the second trade.