Trading Bot in C# — Part 1 — Basic Market Watching on Binance

·

Automated trading has revolutionized how investors interact with financial markets, especially in the fast-paced world of cryptocurrency. In this comprehensive guide, we’ll walk through building a foundational C# trading bot that connects to Binance, retrieves real-time and historical market data, and computes a key technical indicator — the Relative Strength Index (RSI) — to help assess market conditions.

This is the first part of a multi-phase series focused on creating a fully functional automated trading system using modern .NET tools. Here, our goal is simple: observe the market intelligently.


Understanding Automated Crypto Trading

Before diving into code, it's important to understand what we're building and why. Automated trading systems — or “bots” — execute trades based on predefined rules derived from technical indicators, price movements, or volume changes.

We’re focusing on cryptocurrency day-trading using technical analysis, specifically on the Binance exchange. This means:

Our bot today won’t place trades yet — that comes in later parts — but it will monitor market activity and interpret whether an asset like BTC/USDT is potentially overbought or oversold.

👉 Discover how real-time market data can power advanced trading strategies.


Prerequisites for Building Your C# Trading Bot

To follow along, you’ll need:

This library abstracts complex REST and WebSocket communications into clean, easy-to-use methods — ideal for developers who want to focus on logic, not infrastructure.

Install it via NuGet Package Manager or CLI:

dotnet add package WhalesSecret.ScriptApiLib

No Binance account is needed at this stage since we’re only accessing public market data.


Step 1: Create a New Console Application

Start by creating a new C# console project named MarketWatcher:

dotnet new console --name MarketWatcher
cd MarketWatcher

Alternatively, in Visual Studio:

  1. Select Create a new project.
  2. Choose Console App (.NET Core) with C#.
  3. Name the project MarketWatcher.
  4. Install WhalesSecret.ScriptApiLib via the NuGet Package Manager.

You now have a blank canvas for your trading bot.


Step 2: Connect to Binance Market Data

The first functional step is establishing a connection to Binance’s servers to stream market information. Since we’re only reading data (not placing orders), no API keys are required.

Add the following code to your Program.cs file:

using WhalesSecret.ScriptApiLib;
using WhalesSecret.TradeScriptLib.API.TradingV1;
using WhalesSecret.TradeScriptLib.API.TradingV1.MarketData;
using WhalesSecret.TradeScriptLib.Entities;
using WhalesSecret.TradeScriptLib.Entities.MarketData;

await using ScriptApi scriptApi = await ScriptApi.CreateAsync();
Console.WriteLine("Initializing Binance exchange.");

await scriptApi.InitializeMarketAsync(ExchangeMarket.BinanceSpot);
Console.WriteLine("Connecting...");

ConnectionOptions options = new(ConnectionType.MarketData);
await using ITradeApiClient tradeClient = await scriptApi.ConnectAsync(ExchangeMarket.BinanceSpot, options);

Console.WriteLine("Connection succeeded!");

This initializes the exchange context and opens a read-only WebSocket connection for market data. Once connected, your bot can begin requesting candlestick data.


Step 3: Retrieve Historical Price Data

To make informed decisions, bots analyze historical trends. On exchanges like Binance, price data is often represented in candlesticks, each summarizing four key values over a time interval:

Additionally, each candle includes volume — the amount traded during that period.

Let’s fetch 1-minute candles for BTC/USDT over the past three days:

await using ICandlestickSubscription subscription = 
    await tradeClient.CreateCandlestickSubscriptionAsync(SymbolPair.BTC_USDT);

DateTime endTime = DateTime.Now;
DateTime startTime = endTime.AddDays(-3);

CandlestickData candlestickData = await tradeClient.GetCandlesticksAsync(
    SymbolPair.BTC_USDT, 
    CandleWidth.Minute1, 
    startTime, 
    endTime);

This gives us thousands of data points to analyze — but raw prices aren't enough. We need insights.


Step 4: Compute RSI Using Skender.Stock.Indicators

One of the most popular technical indicators is the Relative Strength Index (RSI), which measures the speed and change of price movements. It helps identify:

To calculate RSI, we’ll use the open-source Skender.Stock.Indicators library:

dotnet add package Skender.Stock.Indicators

Then map Binance candle data to the format required by the library:

using Skender.Stock.Indicators;

List<Quote> quotes = new();
foreach (Candle candle in candlestickData.Candles)
    quotes.Add(QuoteFromCandle(candle));

// Get latest closed candle for ongoing monitoring
Candle lastClosedCandle = subscription.GetLatestClosedCandlestick(CandleWidth.Minute1);
Console.WriteLine($"Last closed candle: {lastClosedCandle}");
ReportRsi(quotes);

// Keep listening for new candles
while (true)
{
    Console.WriteLine("Waiting for the next closed candle...");
    try
    {
        lastClosedCandle = await subscription.WaitNextClosedCandlestickAsync(CandleWidth.Minute1);
    }
    catch (OperationCanceledException)
    {
        break;
    }

    Console.WriteLine($"New closed candle arrived: {lastClosedCandle}");
    quotes.Add(QuoteFromCandle(lastClosedCandle));
    ReportRsi(quotes);
}

static void ReportRsi(IEnumerable<Quote> quotes)
{
    var results = quotes.GetRsi();
    var lastRsi = results.Last();

    string interpretation = lastRsi.Rsi switch
    {
        < 30 => " (oversold!)",
        > 70 => " (overbought!)",
        _ => string.Empty
    };

    Console.WriteLine($"Current RSI: {lastRsi.Date:yyyy-MM-dd HH:mm} -> {lastRsi.Rsi:F2}{interpretation}");
}

static Quote QuoteFromCandle(Candle candle)
{
    return new Quote
    {
        Date = candle.Timestamp,
        Open = (decimal)candle.OpenPrice,
        High = (decimal)candle.HighPrice,
        Low = (decimal)candle.LowPrice,
        Close = (decimal)candle.ClosePrice,
        Volume = (decimal)candle.BaseVolume
    };
}

This loop continuously monitors for new 1-minute candles and recalculates RSI in real time.

👉 Learn how algorithmic signals can improve trading performance.


Frequently Asked Questions

What is RSI and how does it help in trading?

The Relative Strength Index (RSI) is a momentum oscillator that measures the magnitude of recent price changes to evaluate overbought or oversold conditions. Traders use it to anticipate reversals — for example, entering long positions when RSI drops below 30.

Do I need a Binance account to run this bot?

Not for this stage. Since we're only consuming public market data (like prices and candles), no authentication is required. However, executing actual trades will require API keys in future versions.

Can I use other technical indicators besides RSI?

Absolutely. Once you have candle data, you can compute SMA, EMA, MACD, Bollinger Bands, and more — many of which are also supported by Skender.Stock.Indicators.

Why use C# instead of Python for trading bots?

While Python dominates in data science, C# offers superior performance, strong typing, seamless integration with Windows systems, and robust async support — making it excellent for low-latency trading applications.

Is historical data accurate enough for strategy testing?

Yes, but granularity matters. For day-trading, 1-minute or 5-minute candles are typically sufficient. Always validate against multiple timeframes and consider slippage and order book depth in live environments.

How often does Binance update candlestick data?

For 1-minute candles, Binance finalizes each candle at the end of every minute. Our bot waits until a candle is fully closed before processing it, ensuring accuracy.

👉 See how professional traders leverage real-time analytics.


Conclusion

In this first installment, we’ve laid the foundation for a powerful C#-based trading bot capable of connecting to Binance, retrieving historical and live market data, and computing actionable insights using the RSI indicator.

Key takeaways:

In upcoming parts, we’ll expand this bot with notification systems, trade execution capabilities, risk management features, and backtesting frameworks.

Remember: This content does not constitute financial advice. Always test strategies in sandbox environments and conduct thorough research before deploying capital.

Now that your bot can see the market — what should it do next?