>_ DevTrendsen

Language

Home

Languages

Sections

Frontend Backend Mobile DevOps AI / ML GameDev Blockchain Embedded Security
Python

How to Build a Trading Bot in Python Without Reinventing the Wheel

When a programmer first decides to try algorithmic trading, everything usually starts with creating their own script. The script requests candles via REST API, calculates a couple of indicators, and sends orders. A month passes, and the project turns into a cumbersome construction of network error handling, socket desynchronization, and chaotic workarounds for order control.

Instead of writing everything from scratch, it makes more sense to take a ready-made framework. The VeighNa project (formerly known as VN.py) appeared back in 2015. It has over 43 thousand stars on GitHub, and active development continues to this day.

What the Platform Is

VeighNa is an open-source framework for algorithmic trading in Python. The internal architecture is built around an event engine. The system doesn't need to run endless waiting loops—it reacts to incoming ticks, order status changes, and system timer signals.

The project has an institutional focus. In China, it's used by futures brokers, asset management companies, and private hedge funds. This leaves a certain imprint on the codebase.

Most built-in connectors out of the box are tailored for the Chinese financial market (CTP, XTP, HTS). Nevertheless, there is an adapter for Interactive Brokers for working with international exchanges. If the required exchange or crypto platform isn't on the list, you'll need to write your own gateway by inheriting from the base Gateway class.

Modules for Solving Practical Tasks

The system architecture consists of three main parts: the core, trading applications (apps), and data adapters.

For strategies, various specialized engines are provided:

  • CTA Strategy handles standard trend and counter-trend trading on single instruments.
  • Spread Trading helps implement pair trading and spatial arbitrage.
  • Option Master contains tools for option valuation, volatility curve construction, and Greeks calculation.
  • Portfolio Strategy is focused on strategies trading a basket of assets at once.

Among the nice touches is the presence of ready-made interfaces for backtesting. To test an idea on historical data, you don't necessarily need to open Jupyter Notebook. The system has a built-in graphical interface based on PyQt, where you can run parameter optimization and immediately view the equity curve and drawdown charts.

For storing history, regular relational databases like SQLite and MySQL are supported, as well as specialized columnar stores QuestDB and TDengine, optimized for fast time series input and output.

Machine Learning in Release 4.0

The fourth generation of the framework introduced module vnpy.alpha. The developers honestly admit they were inspired by Microsoft's Qlib project.

The module closes the development cycle for ML strategies:

  • Feature generation and processing based on the Alpha158 factor expression set.
  • Training prediction models using LightGBM, Lasso, or multilayer perceptron (MLP).
  • Quick transition from research notebook to execution on a live or simulated account.

The repository contains ready-made Jupyter notebooks with examples, so getting acquainted with the data preparation and training pipeline won't be difficult.

What the Code Looks Like

Launching a trading terminal with the required set of modules can be done in literally a dozen lines. In the example below, we assemble an application with a CTP gateway connection and two modules: CTA strategy execution and historical testing.

from vnpy.event import EventEngine
from vnpy.trader.engine import MainEngine
from vnpy.trader.ui import MainWindow, create_qapp

from vnpy_ctp import CtpGateway
from vnpy_ctastrategy import CtaStrategyApp
from vnpy_ctabacktester import CtaBacktesterApp


def main():
    qapp = create_qapp()

    event_engine = EventEngine()
    main_engine = MainEngine(event_engine)
    
    main_engine.add_gateway(CtpGateway)
    main_engine.add_app(CtaStrategyApp)
    main_engine.add_app(CtaBacktesterApp)

    main_window = MainWindow(main_engine, event_engine)
    main_window.showMaximized()

    qapp.exec()


if __name__ == "__main__":
    main()

After launching, a full desktop window will open with order tables, positions, logs, and candlestick charts.

Is It Worth Using in Production

VeighNa is a massive platform. If you just need to send a couple of orders to the spot market once a day via REST API, the framework will seem overcomplicated.

However, the tool will definitely come in handy if you're looking for a time-tested architecture for event-driven trading, planning to write your own connectors, or want a ready-made desktop terminal with risk management and backtesting capabilities. The main thing is to be prepared for the fact that some of the documentation and community comments are translated from Chinese via a translator.

Related projects