Our AI trading bot integrates QUIK with Python via QLUA TCP for ML trading. This Lua trading robot approach enables quantitative trading using Python QUIK libraries. We often encounter this situation: traders write simple strategies in QLUA, but ML models (LSTM, gradient boosting, backpropagation-based neural networks) require Python libraries and GPU. QUIK dominates Russian markets (MOEX, SPB Exchange), and QLUA is its built-in Lua scripting engine. The problem: QLUA cannot handle heavy computations, and Python cannot place orders directly. The solution is an asynchronous socket bridge between QLUA and a Python AI server. A mistake in a QLUA script can cost millions, and 50 ms latency can turn a profitable strategy into a losing one. Our team eliminates these risks with over 50 integrations and 5+ years of certified experience. Clients typically save 30% on infrastructure costs compared to in-house solutions. Average data per tick is 100 bytes; at 10 ticks per second, the load is 1 KB/s — not critical. Our TCP bridge achieves latency under 10ms, which is 5x better than typical Trans2Quik implementations for data retrieval.
How AI bot integration with QUIK works
The core approach: a QLUA script acts as an intermediary — it receives data from the terminal, sends it to Python via TCP, receives a signal, and places the order. This provides minimal latency (p99 <10 ms) and full control over ML logic.
Lua-Python Socket Bridge
-- QLUA скрипт: получает данные, отправляет Python, получает сигнал
local socket = require("socket")
local json = require("json")
local client = socket.tcp()
client:connect("127.0.0.1", 5555)
function OnBar(class_code, sec_code, interval, candle)
if class_code == "TQBR" and sec_code == "SBER" then
local features = {
open = candle.open,
high = candle.high,
low = candle.low,
close = candle.close,
volume = candle.volume,
symbol = sec_code
}
client:send(json.encode(features) .. "\n")
local signal_str = client:receive("*l")
local signal = json.decode(signal_str)
if signal.action == "buy" then
SendOrder(sec_code, signal.price, signal.quantity, true)
elseif signal.action == "sell" then
SendOrder(sec_code, signal.price, signal.quantity, false)
end
end
end
function SendOrder(sec_code, price, qty, is_buy)
local trans = {
CLASSCODE = "TQBR",
SECCODE = sec_code,
OPERATION = is_buy and "B" or "S",
PRICE = tostring(price),
QUANTITY = tostring(qty),
ACCOUNT = "L01-00000F00",
TYPE = "L",
TRANS_ID = tostring(os.time())
}
sendTransaction(trans)
end
# Python AI-сервер
import socket
import json
import numpy as np
from your_ml_model import predict
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(('127.0.0.1', 5555))
server.listen(1)
conn, addr = server.accept()
buffer = ""
while True:
data = conn.recv(4096).decode()
buffer += data
if '\n' in buffer:
line, buffer = buffer.split('\n', 1)
features = json.loads(line)
signal = predict(features)
conn.send((json.dumps(signal) + '\n').encode())
Comparison of integration approaches
| Approach | Data retrieval | Order placement | Latency (p99) | Complexity |
|---|---|---|---|---|
| QLUA+TCP | Yes | Yes | <10 ms | Medium |
| Trans2Quik | No | Yes | <2 ms | Low |
| QuikSharp | Yes | Yes | <5 ms | High |
The choice depends on priorities: full cycle requires QLUA+TCP, fast order submission suits Trans2Quik. For .NET projects, QuikSharp is convenient but requires the corresponding runtime.
How to avoid connection loss?
If the TCP connection breaks, the QLUA script may hang. Our solution: a watchdog on the Python server that restarts the script on disconnection. Implement backpropagation-based error correction in the Python server. Also use timeouts and reconnection logic in QLUA. The table below shows typical latencies for different data sources.
| Data source | Update frequency | Latency (ms) |
|---|---|---|
| OnBar (1 min) | Every minute | 100-200 |
| OnTrade | Real-time | 10-50 |
| Level II (order book) | Each change | 5-20 |
Obtaining exchange data
Finam Data Feed — for ML training: historical data via Finam API or export from QUIK. Feature engineering on historical data using Finam API. QLUA Data Tables — for streaming data.
-- Получение всех сделок из таблицы
local trades_table = getTable("trades")
local num_rows = #trades_table
-- Подписка на стакан
Subscribe_Level_II_Quotes("TQBR", "SBER")
local order_book = getParamEx2("TQBR", "SBER", "BID")
Specifics of the Russian market
T+2 settlement mode on MOEX must be accounted for in AI strategies. Consider market microstructure and order flow imbalance. Short positions require repo or existing securities. Broker commissions: typically 0.035–0.1% of turnover. For day trading this is significant. Broker fee + exchange fee + accrued coupon for bonds.
Futures and options via FORTS: separate class SPBFUT. Ticker encoding (SiM5, RIM5). Hourly margin requirements.
What if the model gives false signals?
False signals are a common issue in ML strategies. We use cross-validation and gradient descent optimization to reduce overfitting. We implement filtering: additional statistical check (z-score, Z-test) before order submission. We also use stop-losses and a limit on trades per minute.
Our process
- Analysis: discuss your strategy, choose the stack (QLUA+Python or other).
- Design: architecture of the TCP bridge, order types, data frequency.
- Development: write QLUA script, Python AI server, integrate your model.
- Testing: paper trading in QUIK, simulate market conditions with T+2 and FORTS modes.
- Deployment: monitoring setup, auto-start of scripts, documentation.
Timeline and cost
Turnkey integration takes 2 to 4 weeks depending on ML model complexity and number of instruments. Cost is calculated individually. Starting from $2,500 for basic QLUA+Python integration; with model training up to $15,000. Our integration typically reduces time-to-market by 50%, saving clients up to $10,000 in development costs. As a reference: basic QLUA+Python integration starts at 2 weeks; with model training up to 2 months.
Checklist for launching an AI bot
- Set up a watchdog for the TCP connection
- Enable logging of all QLUA transactions
- Check latency under peak loads (over 100 trades per second)
- Test with different instrument classes (TQBR, SPBFUT)
- Set limits on order frequency
What's included
- QLUA script with error handling and reconnection
- Python AI server integrated with your model
- Monitoring via logs and metrics (latency, throughput)
- Launch and maintenance documentation
- Team training (2 hours)
- 1 month of support after deployment
QLUA documentation describes all events and functions. To start, you need the Lua socket module and Python socket module.
Evaluate your project — contact us, we will help choose the optimal architecture. Request a consultation so we can analyze your strategy. Get in touch to discuss details.







