sifting/io
Developer Tutorials
11 min readSiftingIO Team

Forex Position Size Calculator in Python with Live FX Rates

Calculate forex lot size from a cash risk budget and stop distance. Use Python and live FX rates for account currency conversion, with worked examples.

Forex Position Size Calculator in Python with Live FX Rates

A forex position size calculator turns a cash risk budget and a stop distance into a number of currency units. To work across different pairs, it also needs one conversion: the value of the pair's quote currency in the account currency.

That conversion is easy to overlook. A 25-pip move on EURUSD produces a dollar amount. The same move on EURGBP produces a pound amount. A calculator for a USD account needs to translate the second result before it can size the position.

This guide builds the calculation in Python, checks it with worked examples, then connects it to the SiftingIO Forex API for a current conversion rate. It is useful for a trading journal, a research dashboard or a position-sizing form. The code calculates an estimate and does not place orders.

The forex position size formula#

Start with three values:

InputMeaningExample
Cash risk budgetAmount allocated to the price move between entry and stop, in account currency100 USD
Stop distanceAbsolute difference between the intended entry and stop prices0.0025 for EURUSD
Quote-to-account rateAccount currency received for one unit of quote currency1 when both are USD

The calculation is:

Estimated loss per base unit = stop distance × quote-to-account rate
Position units = cash risk budget ÷ estimated loss per base unit
Standard lots = position units ÷ 100,000

For a USD account trading EURUSD, an entry of 1.1000 and a stop of 1.0975 give a distance of 0.0025 dollars per euro. With an illustrative 100 USD price-risk budget:

100 ÷ 0.0025 = 40,000 EUR
40,000 ÷ 100,000 = 0.40 standard lots

The formula follows the same relationship used to value an FX position: price difference multiplied by base units, then converted to account currency.

The budget is an input chosen by your application or its user. The examples here are arithmetic illustrations, not recommendations for an account or a trade. The estimate assumes the stated entry, stop and conversion rate; actual losses can differ because of execution prices, gaps, costs and currency movements.

Units, lots and pips#

In EURUSD, the position is measured in euros and the price is expressed in US dollars. In EURGBP, the position is still measured in euros, but the price difference is in pounds.

A standard FX lot is commonly 100,000 base-currency units. A mini lot is 10,000 and a micro lot is 1,000. Our forex lot size guide explains the relationship between units and notional value.

Most major non-JPY pairs use 0.0001 as one pip. JPY pairs commonly use 0.01. That means a 25-pip distance is 0.0025 for EURUSD and 0.25 for USDJPY. The calculator below uses the actual price difference, so it does not need a separate pip-size rule.

If your interface accepts pips, convert them to a price distance first. Keep the broker's contract size, minimum size and permitted size increment as explicit configuration. A 0.01-lot increment is used in the examples, but it is not a universal order rule.

Convert the quote currency into the account currency#

Read the rate as a sentence: "One unit of the quote currency is worth this many units of the account currency."

Position pairAccount currencyConversion neededCalculation
EURUSDUSDUSD to USDUse 1
EURGBPUSDGBP to USDUse GBPUSD
USDJPYUSDJPY to USDUse 1 divided by USDJPY
EURUSDGBPUSD to GBPUse 1 divided by GBPUSD

The pair being traded and the pair needed for conversion are often different. To size EURGBP in a USD account, the stop distance is already in pounds. GBPUSD supplies the pounds-to-dollars conversion.

For a midpoint estimate, calculate the mean of bid and ask. That gives a consistent conversion input for a calculator. Use the broker's applicable conversion convention when reconciling an executed trade or statement.

Here are three illustrative cases, all with a 100 USD cash budget and a 100,000-unit standard lot:

PositionPrice distanceConversion assumptionPosition unitsStandard lots
EURUSD0.0025USD to USD = 140,000 EUR0.40
EURGBP0.0025GBPUSD = 1.250032,000 EUR0.32
USDJPY0.50USDJPY = 150.0030,000 USD0.30

These are calculation examples, not current market quotes. They show why using a fixed dollar pip value for every pair can produce the wrong position size.

Build the calculator in Python#

Save the following as position_size.py. It uses Python's built-in Decimal module to preserve decimal inputs and make the rounding rule explicit. No third-party package is required.

from decimal import Decimal, ROUND_DOWN


def positive(value):
    number = Decimal(str(value))
    if not number.is_finite() or number <= 0:
        raise ValueError("Inputs must be finite positive numbers")
    return number


def position_size(risk_cash, entry, stop, quote_to_account="1",
                  units_per_lot="100000", lot_step="0.01",
                  inverse_conversion=False):
    risk_cash, entry, stop, conversion, contract, step = map(
        positive,
        (risk_cash, entry, stop, quote_to_account, units_per_lot, lot_step),
    )
    distance = abs(entry - stop)
    if distance == 0:
        raise ValueError("Entry and stop must be different")

    if inverse_conversion:
        raw_lots = risk_cash * conversion / (distance * contract)
    else:
        raw_lots = risk_cash / (distance * conversion * contract)
    lots = (raw_lots / step).to_integral_value(
        rounding=ROUND_DOWN
    ) * step
    units = lots * contract
    quote_loss = units * distance
    account_loss = (quote_loss / conversion if inverse_conversion
                    else quote_loss * conversion)

    return {
        "lots": lots,
        "units": units,
        "estimated_price_loss": account_loss,
    }


if __name__ == "__main__":
    result = position_size("100", "1.1000", "1.0975")
    print(f"Lots: {result['lots']:.2f}")
    print(f"Base units: {result['units']:.0f}")
    print(f"Estimated price loss: {result['estimated_price_loss']:.2f} USD")

Run it with python3 position_size.py:

Lots: 0.40
Base units: 40000
Estimated price loss: 100.00 USD

For a conversion quoted in the reverse direction, pass the quoted rate and set inverse_conversion=True. For example, position_size("100", "150", "149.5", "150", inverse_conversion=True) sizes USDJPY in a USD account. It returns 0.30 lots without requiring you to round a reciprocal rate first.

The function rounds down to the configured lot increment. If the raw result is 0.307 lots and the increment is 0.01, the result is 0.30 lots. Rounding to 0.31 would increase the modelled price loss beyond the supplied budget.

A result of zero means the budget does not accommodate one size increment under these inputs. Keep that result visible rather than silently raising the order size. A trading interface should also validate stop direction: below entry for a long position, above entry for a short position. The function calculates distance only.

Get a live FX conversion rate from SiftingIO#

For an EURGBP position in a USD account, request GBPUSD from the latest quote endpoint:

curl --fail-with-body \
  -H "X-API-Key: $SIFTING_API_KEY" \
  "https://api.sifting.io/v1/last/quote/forex/GBPUSD"

Use a private environment variable for the API key. You can create a SiftingIO account and generate the key in your dashboard. Run the request on your backend or local machine, keeping the key out of browser-delivered code.

The response below is a sample shaped exactly like this endpoint's output, with a fixed timestamp of 19 November 2026 at 15:34:00.306 UTC. It is an illustration, not a live quote:

{
  "s": "GBPUSD",
  "b": "1.31173",
  "B": "244965",
  "a": "1.3119",
  "A": "269490",
  "t": 1795102440306
}

For this calculation, b is bid, a is ask and t is the quote timestamp in Unix milliseconds. The midpoint is 1.311815 USD per GBP. The uppercase size fields are not used in the sizing formula.

At that conversion rate, a 100 USD budget and a 0.0025 EURGBP stop distance produce about 30,492 EUR before rounding. With a 0.01-lot increment, the calculator returns 30,000 EUR, or 0.30 lots, with an estimated price loss of 98.39 USD.

Connect the rate to the calculation#

Save this second file as live_position_size.py beside position_size.py. Set SIFTING_API_KEY privately in your terminal or application environment, then run python3 live_position_size.py.

import json
import os
import time
from datetime import datetime, timezone
from decimal import Decimal
from urllib.request import Request, urlopen

from position_size import position_size, positive


def parse_quote(data, max_age_seconds=60, now_ms=None):
    bid, ask = positive(data["b"]), positive(data["a"])
    timestamp = int(data["t"])
    current_ms = int(time.time() * 1000) if now_ms is None else now_ms
    age = (current_ms - timestamp) / 1000
    if ask < bid:
        raise ValueError("Ask is below bid")
    if age < -5 or age > max_age_seconds:
        raise ValueError("Quote timestamp is outside the allowed window")
    return (bid + ask) / Decimal("2"), timestamp


def latest_mid(pair):
    pair = pair.upper()
    if len(pair) != 6 or not pair.isascii() or not pair.isalpha():
        raise ValueError("Use a six-letter currency pair such as GBPUSD")
    request = Request(
        f"https://api.sifting.io/v1/last/quote/forex/{pair}",
        headers={"X-API-Key": os.environ["SIFTING_API_KEY"]},
    )
    with urlopen(request, timeout=15) as response:
        data = json.load(response, parse_float=Decimal)
    return parse_quote(data)


if __name__ == "__main__":
    # EURGBP position, USD account. Entry and stop are illustrative.
    gbp_usd, timestamp = latest_mid("GBPUSD")
    result = position_size("100", "0.8600", "0.8575", gbp_usd)
    observed = datetime.fromtimestamp(timestamp / 1000, timezone.utc)
    print(f"GBP to USD: {gbp_usd}")
    print(f"Quote time: {observed.isoformat()}")
    print(f"Lots: {result['lots']:.2f}")
    print(f"Base units: {result['units']:.0f}")
    print(f"Estimated price loss: {result['estimated_price_loss']:.2f} USD")

The output changes with the conversion rate. The 60-second freshness window is a sample application setting, not a statement about feed latency. Choose the window for your workflow and display the timestamp beside the result. A failed request or an out-of-window quote should leave the calculation unavailable until a suitable quote is obtained, rather than substituting an invented rate.

For a continuously updating dashboard, use the WebSocket stream to maintain the latest conversion quote on your backend. The sizing formula stays the same. Recalculate when the user changes the entry, stop or budget, or when a relevant conversion rate changes.

Make the result useful in an application#

A useful result card shows the assumptions alongside the size:

Result fieldExample
Pair and account currencyEURGBP, USD account
Entry and stop0.8600 and 0.8575
Conversion pair and rateGBPUSD, 1.311815
Calculated position0.30 standard lots, 30,000 EUR
Estimated price loss98.39 USD before additional costs
Quote time19 November 2026, 15:34:00.306 UTC

Keep three other inputs separate. Trading costs belong in the budget: if 100 USD is the total allowance and 5 USD is reserved for estimated costs, pass 95 USD to the sizing function. Margin is a separate broker requirement based on exposure and leverage. Execution prices determine the realised result; use entry and stop assumptions appropriate to the bid or ask side of the trade, so spread is neither omitted nor counted twice.

When saving a calculation to a journal, retain the entry, stop, conversion rate, quote timestamp, contract size and rounding increment. The saved result should remain reproducible after the live rate has moved.

For historical analysis, use a conversion rate from the relevant historical time instead of today's quote. SiftingIO's historical Forex bars provide OHLCV data for building that workflow. Choose a bar that was available at the calculation time; using a later close would introduce future information.

Common questions#

Does leverage change the position size formula?#

Leverage affects the margin required to hold a position. It does not change the price loss of a given number of base units moving through a given distance. Calculate the size from the budget and distance, then check the broker's margin and position limits separately.

Can the same function handle JPY pairs?#

Yes. Pass the actual price distance and the quote-to-account rate. For USDJPY in a USD account, pass the USDJPY conversion quote with inverse_conversion=True. If the form accepts pips, apply the pair's pip size before calling the function.

Does the calculator work for a short position?#

The distance calculation works in either direction. The surrounding application must validate that the stop is on the appropriate side and use consistent entry and exit price assumptions.

Can I reuse it for gold or oil?#

Keep the idea of a cash budget divided by loss per contract, but use the instrument's actual contract multiplier and size rules. The 100,000-unit FX lot convention should not be carried across to commodity contracts. The commodity API guide covers the available symbols and data requests.

Add the calculator to your project#

Start with the fixed-rate example so you can verify the arithmetic. Then replace the conversion input with a timestamped SiftingIO quote and save the assumptions with each result.

Get a free API key to try the request. When the calculator is ready for customer-facing use, choose the appropriate commercial package from Forex plans. The same data access can support the calculator, its price chart and the rest of your FX dashboard.

Keep reading

Related posts