bytex README

The project's README from github.com/BYTEX-TRADE/bytex. As one markdown file: README.md.

BYTEX

An event-driven algorithmic trading engine for .NET — one strategy, from backtest to live.

BYTEX is an open-source trading platform written in C#. It lets you write a trading strategy once and run it unchanged against historical data, against live market data with simulated execution, and against real exchange accounts. The engine is deterministic, asset-class agnostic, and built around a small set of composable components that are the same in every environment.

Status: pre-release. APIs may change between minor versions until 1.0, and the venue adapters are beta until they complete verification against live venues. Backtesting and sandbox trading are fully functional today.

Why BYTEX

Capabilities

Area What is included
Strategy SDK Actor and Strategy base classes with lifecycle, data, order, and position handlers; typed configuration; order factory; cache and portfolio access; clock and timers; indicators
Orders market, limit, stop-market, stop-limit, market-if-touched, limit-if-touched, trailing stops, market-to-limit; GTC / IOC / FOK / GTD / DAY; post-only, reduce-only, iceberg display quantity; OCO / OTO / OUO contingencies; bracket orders
Backtesting simulated venues with a per-instrument matching engine, fill and slippage models, fee models, cash and margin accounts; bar, quote, and trade data; Parquet data catalog; performance reports
Live trading trading node with live clock, exchange adapters, startup reconciliation, sandbox execution (live data, simulated fills), optional Redis state persistence
Risk pre-trade validation of precision, size, notional, rate limits; trading state control
Adapters Binance (spot, USDⓈ-M futures), Bybit (spot, linear perpetuals); Tardis historical data; adapter SDK for new venues
Tooling bytex CLI for backtests, live nodes, and catalog management; Docker image; notebook support

See the roadmap for what is planned next.

Quick start

Build from source (NuGet packages are planned; until they are published, reference the projects directly):

git clone https://github.com/BYTEX-TRADE/bytex
cd bytex
dotnet build
dotnet run --project examples/Bytex.Examples -- backtest-ema-cross
public sealed class EmaCrossConfig : StrategyConfig
{
    public required InstrumentId InstrumentId { get; init; }
    public required BarType BarType { get; init; }
    public int FastPeriod { get; init; } = 10;
    public int SlowPeriod { get; init; } = 20;
    public decimal TradeSize { get; init; } = 1m;
}

public sealed class EmaCross : Strategy<EmaCrossConfig>
{
    private readonly ExponentialMovingAverage _fast;
    private readonly ExponentialMovingAverage _slow;

    public EmaCross(EmaCrossConfig config) : base(config)
    {
        _fast = new ExponentialMovingAverage(config.FastPeriod);
        _slow = new ExponentialMovingAverage(config.SlowPeriod);
    }

    protected override void OnStart()
    {
        RegisterIndicatorForBars(Config.BarType, _fast);
        RegisterIndicatorForBars(Config.BarType, _slow);
        SubscribeBars(Config.BarType);
    }

    protected override void OnBar(Bar bar)
    {
        if (!_fast.IsInitialized || !_slow.IsInitialized)
        {
            return;
        }

        var instrument = Cache.Instrument(Config.InstrumentId)!;
        var quantity = instrument.MakeQuantity(Config.TradeSize);

        if (_fast.Value > _slow.Value && Portfolio.IsFlat(Config.InstrumentId))
        {
            SubmitOrder(OrderFactory.Market(Config.InstrumentId, OrderSide.Buy, quantity));
        }
        else if (_fast.Value < _slow.Value && Portfolio.IsNetLong(Config.InstrumentId))
        {
            CloseAllPositions(Config.InstrumentId);
        }
    }
}

The same class runs in a BacktestEngine, in a sandbox, or in a live TradingNode. Full walkthroughs are in docs/getting-started.

Command line

The bytex tool runs backtests and trading nodes from JSON configuration (installable with dotnet tool install --global Bytex.Cli once packages are published; from source, use dotnet run --project src/Bytex.Cli --):

bytex catalog fetch-instruments --path ./catalog --venue BINANCE --quote USDT
bytex catalog import-csv --path ./catalog --file btcusdt-1m.csv --kind bars --instrument BTCUSDT.BINANCE --bar-type BTCUSDT.BINANCE-1-MINUTE-LAST-EXTERNAL
bytex --plugins ./plugins backtest --config examples/configs/backtest-ema-cross.json
bytex --plugins ./plugins run --config examples/configs/sandbox-binance-ema-cross.json

Strategies are referenced by type name in JSON and loaded from plugin assemblies, so one CLI runs any strategy. See docs/getting-started/cli.md.

Repository layout

src/Bytex.Core               domain model, messaging, clock, cache, portfolio, engines, Strategy SDK, adapter SDK, plugins
src/Bytex.Indicators         technical indicators
src/Bytex.Data               Parquet data catalog, CSV loaders
src/Bytex.Backtest           simulated venues, backtest engine and node, reports
src/Bytex.Live               trading node, kernel loop, network infrastructure, sandbox execution
src/Bytex.Adapters.*         Binance, Bybit, Tardis
src/Bytex.Persistence.Redis  Redis state persistence
src/Bytex.Cli                the bytex command-line tool
examples/                    example strategies and configurations
tests/                       unit, integration, and performance tests
docs/                        getting started, concepts, integrations, design notes, roadmap

Building from source

Requires the .NET 10 SDK.

dotnet build
dotnet run --project examples/Bytex.Examples -- backtest-ema-cross

Contributing

Contributions are welcome. Please read CONTRIBUTING.md first. Security issues should be reported as described in SECURITY.md.

License

BYTEX is licensed under the Apache License, Version 2.0. Third-party components are listed in THIRD-PARTY-NOTICES.md.

Disclaimer

BYTEX is software for building trading systems. It is not investment advice, and it does not guarantee any trading outcome. Trading financial instruments involves risk of loss. You are solely responsible for any strategy you run and any account you connect.

bytex (BYTEX-TRADE/bytex)

Searching Database…

886 ·GitHub
Что это?BYTEX — открытый событийно-ориентированный движок алгоритмической торговли для .NET, написанный на C#. Вы пишете торговую стратегию один раз и запускаете тот же код без изменений в бэктестинге, песочнице и реальной торговле на настоящих биржевых счетах.
Это фреймворк или библиотека?Это фреймворк: стратегия пишется как класс C# на основе базовых классов Strategy/Actor от BYTEX, а однопоточное ядро движка ведёт весь жизненный цикл событий — отдельного слоя скриптов или биндингов нет.
Как это запустить?Сейчас нужно собрать его из исходников и подключить проекты напрямую, так как NuGet-пакет Bytex.Cli ещё не опубликован; затем ваш класс стратегии запускается внутри BacktestEngine, песочницы или живого TradingNode без изменений.
Нужно ли что-то кроме .NET для сборки?Для сборки из исходников нужен .NET 10 SDK; Redis требуется, только если хотите опциональное сохранение состояния живого торгового узла.
Готово ли это к реальной торговле уже сегодня?Не полностью — BYTEX ещё до релиза, его API могут меняться до версии 1.0, а адаптеры площадок Binance/Bybit помечены как бета, пока не завершится их проверка на живых биржах. Бэктестинг и песочница (живые данные с симулированным исполнением) уже полностью работают.
На каких биржах можно торговать?BYTEX поставляется с адаптерами для Binance (спот и фьючерсы USDS-M) и Bybit (спот и линейные бессрочные контракты), плюс адаптер Tardis для исторических данных; новые площадки добавляются через adapter SDK без изменения движка.
Почему BYTEX не использует числа с плавающей запятой для денег?Цены, объёмы и балансы хранятся как десятичные числа с фиксированной точкой и явной точностью, а не как float, что исключает накопление ошибок округления и делает результаты бэктеста точно воспроизводимыми.
Что на самом деле делает режим песочницы?Режим песочницы прогоняет стратегию на живых рыночных данных, но исполняет симулированные сделки вместо реальных ордеров, так что можно тестировать в режиме реального времени, не рискуя настоящим биржевым счётом.
Что умеет CLI bytex?CLI bytex запускает бэктесты и живые торговые узлы из JSON-файлов конфигурации, загружая стратегии по имени типа из сборок плагинов, так что один бинарник CLI может выполнить любую стратегию; он также управляет каталогом данных Parquet.
Size
1.9 MB
Stars
886
Age
1mo
Commits · 90 Days