sifting/io
Developer Tutorials
14 min readSiftingIO Team

Technical indicators in C#: SMA, EMA and RSI from market data

Fetch EURUSD bars in C# with HttpClient and System.Text.Json, then compute SMA, EMA and RSI with paste-ready functions and worked numeric checks.

Technical indicators in C#: SMA, EMA and RSI from market data

Technical indicators in C# need two things: a list of closing prices and a few short loops. This post fetches hourly EURUSD bars from the SiftingIO REST API with HttpClient and System.Text.Json, computes a simple moving average (SMA), an exponential moving average (EMA) and Wilder's relative strength index (RSI) in dependency-free functions you can paste, and then repeats the same three calculations with the community NuGet package Skender.Stock.Indicators so you can compare the two paths.

There is no official SiftingIO SDK for C# (the first-party SDKs are Go, Python and JavaScript), so every request here is a plain HTTP call. The code targets .NET 8 and the default console template with implicit usings. It was written against the documentation and has not been compiled or run against the API for this post, and every number in the worked checks comes from a synthetic fixture, which is labelled where it appears.

Fetch market data in C# with HttpClient#

The historical forex endpoint is GET /v1/hist/forex/{pair}/bars. The request below asks for hourly EURUSD bars:

curl -H "X-API-Key: $SIFTING_KEY" -H "Accept-Encoding: gzip" --compressed \
  "https://api.sifting.io/v1/hist/forex/EURUSD/bars?start=2026-05-01&end=2026-05-06&interval=1h"

The documented response is an envelope with a data array and a meta object. This is the example from the docs page, shortened to one bar. It is a documentation sample, not a response captured for this post:

{
  "data": [
    { "t": 1745971200000, "o": 1.0837, "h": 1.0844, "l": 1.0831, "c": 1.0840, "v": 486215040 }
  ],
  "meta": {
    "symbol": "EURUSD",
    "interval": "1h",
    "as_of": "2026-05-19T15:21:32Z",
    "next_cursor": "eyJzIjoxNzQ2MTQ0MDAwMDAwfQ"
  }
}

Four details from the docs shape the C# client.

The endpoint requires gzip. A request without Accept-Encoding: gzip gets 406 gzip_required. In .NET you don't set that header by hand: HttpClientHandler.AutomaticDecompression sends it and decompresses the body for you.

start is required unless you pass a cursor, and it accepts YYYY-MM-DD or a full RFC 3339 timestamp. Epoch milliseconds in start or end return 400 invalid_parameter, even though the bars themselves use epoch milliseconds in t.

t is the bar's open time in UTC as an int64 of Unix milliseconds, and each bar covers the interval starting at t. Bars come back oldest first by default, which is the order the indicator functions below expect.

v on forex bars is a reported tick count when the historical source supplies one, otherwise 0. It is not traded currency volume, so leave it out of anything volume-weighted.

The page size defaults to 1000 bars with a maximum of 2000. When more bars remain, meta.next_cursor carries an opaque token and the last page has none. The docs list the intervals 1m, 5m, 15m, 30m, 1h, 1d, 1w and 1mo; this post uses 1h.

Here is the fetch code, with the JSON types it deserializes into:

using System.Globalization;
using System.Net;
using System.Text.Json;
using System.Text.Json.Serialization;

public sealed class Bar
{
    [JsonPropertyName("t")] public long T { get; init; }
    [JsonPropertyName("o")] public double O { get; init; }
    [JsonPropertyName("h")] public double H { get; init; }
    [JsonPropertyName("l")] public double L { get; init; }
    [JsonPropertyName("c")] public double C { get; init; }
    [JsonPropertyName("v")] public double V { get; init; }
}

public sealed class BarsMeta
{
    [JsonPropertyName("symbol")] public string? Symbol { get; init; }
    [JsonPropertyName("interval")] public string? Interval { get; init; }
    [JsonPropertyName("as_of")] public string? AsOf { get; init; }
    [JsonPropertyName("next_cursor")] public string? NextCursor { get; init; }
}

public sealed class BarsResponse
{
    [JsonPropertyName("data")] public List<Bar> Data { get; init; } = new();
    [JsonPropertyName("meta")] public BarsMeta? Meta { get; init; }
}

public static class MarketData
{
    public static HttpClient CreateClient(string apiKey)
    {
        var handler = new HttpClientHandler
        {
            AutomaticDecompression = DecompressionMethods.GZip
        };
        var http = new HttpClient(handler)
        {
            BaseAddress = new Uri("https://api.sifting.io")
        };
        http.DefaultRequestHeaders.Add("X-API-Key", apiKey);
        return http;
    }

    public static async Task<List<Bar>> GetBarsAsync(
        HttpClient http, string pair, string interval, string start,
        CancellationToken ct = default)
    {
        var bars = new List<Bar>();
        string path = $"/v1/hist/forex/{pair}/bars?interval={interval}";
        string url = $"{path}&start={Uri.EscapeDataString(start)}";
        int retries = 0;

        while (true)
        {
            using var resp = await http.GetAsync(url, ct);

            if (resp.StatusCode == HttpStatusCode.TooManyRequests && retries < 3)
            {
                retries++;
                TimeSpan wait = resp.Headers.RetryAfter?.Delta ?? TimeSpan.FromSeconds(5);
                await Task.Delay(wait, ct);
                continue;
            }

            if (!resp.IsSuccessStatusCode)
            {
                string body = await resp.Content.ReadAsStringAsync(ct);
                throw new HttpRequestException(
                    $"{(int)resp.StatusCode} for {pair}: {body}");
            }

            await using var stream = await resp.Content.ReadAsStreamAsync(ct);
            BarsResponse page =
                await JsonSerializer.DeserializeAsync<BarsResponse>(stream, cancellationToken: ct)
                ?? throw new InvalidOperationException("Empty response body.");

            bars.AddRange(page.Data);

            string? cursor = page.Meta?.NextCursor;
            if (string.IsNullOrEmpty(cursor)) break;
            url = $"{path}&cursor={Uri.EscapeDataString(cursor)}";
        }

        return bars;
    }
}

The error branch prints the response body because the API's error bodies name the problem. An unknown pair returns 404 with not_found, and an interval outside the list returns 400 with the allowed values in the message. A 429 carries a Retry-After header in seconds, which the loop honors up to three times before giving up.

Prices are parsed as double. For a stored price or a ledger amount you would want decimal, but indicators are averages and ratios, and double keeps the math simple and fast. The library section below converts to decimal because its quote type requires it.

Technical indicators in C# without a library#

Each function takes closes in oldest-first order and returns an array of the same length, with null wherever the indicator does not exist yet. Keeping the output aligned with the input means index i of every result refers to bar i.

public static class Indicators
{
    // Simple moving average: mean of the last n closes.
    public static double?[] Sma(IReadOnlyList<double> v, int n)
    {
        if (n < 1) throw new ArgumentOutOfRangeException(nameof(n));
        var result = new double?[v.Count];
        double sum = 0;
        for (int i = 0; i < v.Count; i++)
        {
            sum += v[i];
            if (i >= n) sum -= v[i - n];
            if (i >= n - 1) result[i] = sum / n;
        }
        return result;
    }

    // Exponential moving average, seeded with the SMA of the first n closes.
    public static double?[] Ema(IReadOnlyList<double> v, int n)
    {
        if (n < 1) throw new ArgumentOutOfRangeException(nameof(n));
        var result = new double?[v.Count];
        if (v.Count < n) return result;

        double k = 2.0 / (n + 1);
        double ema = 0;
        for (int i = 0; i < n; i++) ema += v[i];
        ema /= n;
        result[n - 1] = ema;

        for (int i = n; i < v.Count; i++)
        {
            ema += k * (v[i] - ema);
            result[i] = ema;
        }
        return result;
    }

    // Relative strength index with Wilder's smoothing.
    public static double?[] Rsi(IReadOnlyList<double> v, int n = 14)
    {
        if (n < 1) throw new ArgumentOutOfRangeException(nameof(n));
        var result = new double?[v.Count];
        if (v.Count <= n) return result;

        double avgGain = 0, avgLoss = 0;
        for (int i = 1; i <= n; i++)
        {
            double change = v[i] - v[i - 1];
            if (change > 0) avgGain += change; else avgLoss -= change;
        }
        avgGain /= n;
        avgLoss /= n;
        result[n] = ToRsi(avgGain, avgLoss);

        for (int i = n + 1; i < v.Count; i++)
        {
            double change = v[i] - v[i - 1];
            double gain = change > 0 ? change : 0;
            double loss = change < 0 ? -change : 0;
            avgGain = (avgGain * (n - 1) + gain) / n;
            avgLoss = (avgLoss * (n - 1) + loss) / n;
            result[i] = ToRsi(avgGain, avgLoss);
        }
        return result;
    }

    private static double ToRsi(double avgGain, double avgLoss) =>
        avgLoss == 0 ? 100 : 100 - 100 / (1 + avgGain / avgLoss);
}

The worked checks below all use one fixture: sixteen synthetic closes, invented for this post and shaped like EURUSD so the arithmetic is easy to follow. They are not market data.

double[] fixture =
{
    1.1650, 1.1662, 1.1655, 1.1671, 1.1680, 1.1668, 1.1659, 1.1675,
    1.1690, 1.1684, 1.1697, 1.1705, 1.1693, 1.1688, 1.1702, 1.1716
};

SMA: the formula and a worked check#

The SMA over n bars is the arithmetic mean of the last n closes: SMA = (c1 + c2 + ... + cn) / n. The first value exists at index n - 1.

With n = 5, the first window is 1.1650, 1.1662, 1.1655, 1.1671 and 1.1680. The sum is 5.8318, so the SMA at index 4 is 1.16636. One bar later the window drops 1.1650 and gains 1.1668. The sum becomes 5.8336 and the SMA at index 5 is 1.16672.

EMA: the formula and a worked check#

The EMA weights recent closes more heavily through a smoothing factor k = 2 / (n + 1). Each new value moves the previous EMA a fraction k of the way toward the new close: EMA today = EMA yesterday + k * (close - EMA yesterday). The recursion needs a starting value. This implementation seeds it with the SMA of the first n closes, a common convention.

With n = 5, k is 1/3 and the seed at index 4 is the SMA from above, 1.16636. At index 5 the close is 1.1668, so the EMA is 1.16636 + (1.1668 - 1.16636) / 3 = 1.16651 (1.1665067 before rounding). At index 6 the close is 1.1659 and the EMA is 1.1665067 + (1.1659 - 1.1665067) / 3 = 1.16630.

RSI: the formula and a worked check#

RSI compares the average size of up moves with the average size of down moves. For each bar, the gain is the rise from the previous close (or zero) and the loss is the fall (or zero). The first average gain and average loss are simple means over the first n changes. After that, Wilder's smoothing applies: avg = (previous avg * (n - 1) + current value) / n. Then RS = average gain / average loss and RSI = 100 - 100 / (1 + RS). The first value exists at index n, because n changes need n + 1 closes. When the average loss is zero this function returns 100, including for a completely flat series. Other implementations make a different choice for the flat case.

With n = 14, the first fourteen changes of the fixture, in units of 0.0001, are +12, -7, +16, +9, -12, -9, +16, +15, -6, +13, +8, -12, -5 and +14. The gains sum to 103 and the losses to 51. The average gain is 103 / 14 = 7.3571 and the average loss is 51 / 14 = 3.6429, so RS = 2.0196 and the RSI at index 14 is 100 - 100 / 3.0196 = 66.88.

The last change is +14. The smoothed average gain is (7.3571 * 13 + 14) / 14 = 7.8316 and the smoothed average loss is (3.6429 * 13 + 0) / 14 = 3.3827. RS is 2.3152 and the RSI at index 15 is 69.84.

You can turn the three checks into a test that runs before any network call:

Console.WriteLine($"{Indicators.Sma(fixture, 5)[5]:F5}");   // expect 1.16672
Console.WriteLine($"{Indicators.Ema(fixture, 5)[6]:F5}");   // expect 1.16630
Console.WriteLine($"{Indicators.Rsi(fixture, 14)[14]:F2}"); // expect 66.88
Console.WriteLine($"{Indicators.Rsi(fixture, 14)[15]:F2}"); // expect 69.84

Run the indicators on EURUSD bars#

The top-level program ties the pieces together. In a single Program.cs, the using lines go first, these statements second, and the class declarations from the earlier sections after them.

string key = Environment.GetEnvironmentVariable("SIFTING_KEY")
    ?? throw new InvalidOperationException("Set SIFTING_KEY first.");

using HttpClient http = MarketData.CreateClient(key);

string start = DateTime.UtcNow.AddDays(-45)
    .ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);

List<Bar> bars = await MarketData.GetBarsAsync(http, "EURUSD", "1h", start);

// Drop a last bar whose hour has not finished yet.
const long hourMs = 3_600_000;
long nowMs = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
if (bars.Count > 0 && bars[^1].T + hourMs > nowMs) bars.RemoveAt(bars.Count - 1);

if (bars.Count == 0)
{
    Console.WriteLine("No bars in this window.");
    return;
}

double[] closes = bars.Select(b => b.C).ToArray();
double?[] sma = Indicators.Sma(closes, 20);
double?[] ema = Indicators.Ema(closes, 20);
double?[] rsi = Indicators.Rsi(closes, 14);

int last = closes.Length - 1;
DateTimeOffset opened = DateTimeOffset.FromUnixTimeMilliseconds(bars[last].T);

Console.WriteLine($"EURUSD 1h, {closes.Length} bars, last bar opened {opened:yyyy-MM-dd HH:mm} UTC");
Console.WriteLine($"close {closes[last]:F5}  SMA20 {sma[last]:F5}  EMA20 {ema[last]:F5}  RSI14 {rsi[last]:F2}");

Three things about the input deserve attention before you trust the output.

The period counts bars. The docs state that closed market periods may have no bars, so twenty hourly bars that straddle a weekend span far more than twenty clock hours. That is the normal convention for indicators on FX data, and it means you should never fill the gap with invented bars just to make the timeline even.

The docs don't say whether a bar that is still forming is included when end defaults to now. The program removes any last bar whose hour hasn't ended, so the indicators only see completed bars. If you want a value that moves during the hour, keep the bar and label the result as provisional.

EMA and RSI are recursive, so their values depend on where the history starts. Two programs that load different amounts of history will print slightly different EMA and RSI values for the same bar until enough bars have passed for the starting point to fade. The 45-day window above yields several hundred hourly bars, which is far more than a 20-bar EMA or a 14-bar RSI needs to settle. The SMA has no such memory: it depends only on its own window.

The result is a set of computed numbers. Nothing here treats an RSI level or a moving-average crossing as a signal to buy or sell, and the fair values in the bars are reference prices, not executable quotes.

The same indicators with Skender.Stock.Indicators#

If you'd rather not maintain indicator code, the community package Skender.Stock.Indicators covers these three and many more. At the time of writing, its NuGet page lists version 2.7.3, targets .NET 8 and .NET Standard 2.0, and carries a notice that version 3 continues under the new package name FacioQuo.Stock.Indicators, with maintenance updates for version 2 ending at the end of 2026. The snippet below uses the version 2 API. Version 3 renames the methods (ToSma, ToEma, ToRsi), so check the package's documentation for the line you install.

dotnet add package Skender.Stock.Indicators

Add using Skender.Stock.Indicators; to the top of the file, then map the bars to the library's Quote type, which uses decimal for prices:

List<Quote> quotes = bars.Select(b => new Quote
{
    Date = DateTimeOffset.FromUnixTimeMilliseconds(b.T).UtcDateTime,
    Open = (decimal)b.O,
    High = (decimal)b.H,
    Low = (decimal)b.L,
    Close = (decimal)b.C,
    Volume = (decimal)b.V
}).ToList();

SmaResult smaLib = quotes.GetSma(20).Last();
EmaResult emaLib = quotes.GetEma(20).Last();
RsiResult rsiLib = quotes.GetRsi(14).Last();

Console.WriteLine($"library  SMA20 {smaLib.Sma:F5}  EMA20 {emaLib.Ema:F5}  RSI14 {rsiLib.Rsi:F2}");

Print this line under the hand-rolled one and compare. The SMA should agree to the printed precision, since both paths average the same twenty closes. For EMA and RSI, agreement depends on both implementations starting the recursion the same way and on how much history you loaded. The library's documentation is explicit about this: it asks for at least 2×N or N+100 quotes for an EMA and at least N+100 for RSI, and warns that early values carry convergence errors that shrink as more history is processed. That is the same start-of-history effect described above, and it applies to any implementation, including yours.

Which path to keep is a maintenance decision. The hand-rolled functions are about sixty lines with no dependency, and you control the seeding and the edge cases. The library gives you a large catalog of indicators and a tested implementation in exchange for a package reference and its versioning.

Several pairs, and where the WebSocket feed fits#

Running the calculation across a watchlist is a loop over the same call. Keep it sequential so a burst of parallel requests doesn't run into the rate limit:

string[] pairs = { "EURUSD", "GBPUSD", "USDJPY", "AUDUSD" };

foreach (string pair in pairs)
{
    List<Bar> b = await MarketData.GetBarsAsync(http, pair, "1h", start);
    if (b.Count == 0) continue;

    double[] c = b.Select(x => x.C).ToArray();
    int i = c.Length - 1;

    Console.WriteLine(
        $"{pair}  close {c[i]:G6}  SMA20 {Indicators.Sma(c, 20)[i]:G6}  " +
        $"EMA20 {Indicators.Ema(c, 20)[i]:G6}  RSI14 {Indicators.Rsi(c, 14)[i]:F2}");

    await Task.Delay(250);
}

The G6 format prints six significant digits, which suits both EURUSD (around 1.1) and USDJPY (around 150) without a per-pair format table. Every response carries X-RateLimit-Remaining, so a longer watchlist can read that header and slow down before a 429 arrives. The request limits depend on your plan, so check the pricing page for the current values.

Hourly bars only change once an hour, so a scheduled job that runs shortly after each hour is enough for most dashboards and research scripts. If you need the indicator to move between bar closes, the WebSocket feed at wss://stream.sifting.io/ws/v1 publishes forex ticks under the product code fx, and you can apply the latest tick price as a provisional close for the bar in progress. Building that client is outside the scope of this post. The mechanics of snapshots and streams are covered in Real-time FX and crypto quotes: REST snapshots and WebSocket streams, and the handling of bid, ask and tick timestamps in Live bid and ask price API: build a correct EURUSD and BTCUSD quote client. One caution if you combine the two: the historical docs note that the price basis can differ across sources, so test for a small step between the last historical close and the first streamed price before you blend them into one series.

The parameters, error codes and response fields for every bars endpoint are in the API reference. Read the docs

Keep reading

Related posts