QUIK# (.NET Port of QLUA)
repository·master·Indexed 42 days ago
https://github.com/finsight/quiksharpA .NET port of the QUIK Lua interface (QLUA) that allows developers to interact with the QUIK trading terminal using C# async functions and events. It provides low-latency access to QLUA functions, including order management for Spot and Futures markets, chart data analysis, and native UI table management via the QTable class.
What's inside QUIK#
- QUIK# (QUIK Sharp) is a .NET port of the QUIK Lua interface (QLUA). It exposes all functions and events available in QLUA as C# asynchronous functions and events. It is designed to abstract away the idiosyncrasies of the QUIK terminal, providing a modern .NET development experience with low latency (approximately 60 microseconds roundtrip time for Ping/Pong benchmarks).
Overview of the TradeWind Robot
masterThe TradeWind Robot is an automated trading strategy designed for the QUIK platform. It uses a combination of three moving averages to identify trends and generate signals. The strategy operates on a trend-following principle, entering positions when moving averages align and exiting when the trend weakens or reverses.
Core Logic: Triple Moving Average Strategy
- SMA (Short Moving Average): Period of 4-6. Used to detect immediate price changes.
- LMA (Long Moving Average): Period of 20-30. Used to identify the medium-term trend.
- HMA (High Moving Average): Period of 100-150. Used to identify the long-term trend.
Signal Generation:
- A signal is triggered when the SMA crosses the LMA, provided the price is on the correct side of the HMA.
- The robot monitors the relationship between these averages to determine entry and exit points.
TradeWind Robot Signal Types
masterThe robot emits several signal levels to indicate the strength of a trend:
BUY/SELL: Standard entry signals based on moving average crossovers.STRONG BUY/STRONG SELL: High-confidence signals where the trend is strongly established.EXTRA BUY/EXTRA SELL: Signals indicating an intensification of the existing trend.
Note: Users should prioritize
STRONG BUY/STRONG SELLsignals for higher reliability.How the Begemot trading strategy works
masterThe Begemot (Бегемот) strategy is a liquidity-following algorithm designed to trade alongside large orders (referred to as 'Begemots') in the order book. The strategy is split into two main phases: monitoring favorable conditions and managing orders once they are placed.
Core Logic for Long Positions
- Monitoring: The robot monitors the order book for a large bid (volume) exceeding a user-defined threshold.
- Entry: Once a large bid is detected, the robot places a buy order exactly one step (tick) above that large order.
- Dynamic Adjustment:
- If the large order is removed, the robot cancels its own order and returns to monitoring mode.
- If the large order moves (price changes), the robot moves its order to maintain its position one step above the large order.
- Exit (Take Profit): Once the buy order is filled, the robot places a sell order at a profit target (defined as a constant number of points from the entry price).
- Emergency Protection (Stop Loss): If a trade occurs at one step below the large order that triggered the entry, it indicates the large order has been consumed or removed. The robot must immediately exit by placing the best possible sell order in the book and maintaining that 'best' position until the position is closed.
Order Management and Conflict Avoidance
- Conflict Check: Before placing a bid, the robot checks if there is another large order on the offers (asks) that is lower than the intended take profit. If such an order exists, the robot avoids the trade to prevent being trapped.
- Defensive Maneuvering: If a large sell order (a 'hostile Begemot') appears on the offers while the robot is holding a long position, the robot moves its sell order to be one point better than that large order to exit the position quickly.
- Handling Disappearing Liquidity: If the large order disappears or is partially consumed:
- Scenario A (Order moved lower): The robot moves its sell order lower, maintaining the take profit distance from the new price of the large order, but not lower than the best available offer.
- Scenario B (Order gone): The robot enters 'emergency exit' mode, placing a sell order one point ahead of the current best offer and continuously adjusting to remain the best seller until the position is closed.
Short Positions
The algorithm for short positions follows the exact same logic but is applied mirror-imaged (looking at offers instead of bids, and selling instead of buying).
Configure network access for Lua scripts
masterBy default, scripts listen on
127.0.0.1(localhost). To allow connections from other devices on your local WiFi network, set bothresponseHostnameandcallbackHostnameto0.0.0.0.Security Warning: Setting the hostname to
0.0.0.0makes the socket accessible to the entire network. Since the socket connection does not use passwords or encryption, this can expose your QUIK terminal to unauthorized access if your router is not properly secured. It is recommended to use specific local IP addresses or ensure strict router firewall rules if you enable external access.Risk Management and Stop-Loss Behavior
masterThe TradeWind Robot includes built-in risk management features:
- Max Loss (
maxloss): If the accumulated loss for a specific ticker reaches the defined.maxlossvalue, the robot will stop trading that ticker and set its status toDISABLED. - Stop-Loss Mechanism: The robot uses
.stop_stepsto manage exits. If the robot enters aSTOPPEDstate, it will not resume trading until manually reset or re-enabled. - Brake (
brake): A coefficient used to adjust the sensitivity of the trading logic.
- Max Loss (
Use the Spreader Robot for spread trading strategies
masterThe Spreader Robot is a Lua-based trading robot designed to profit from the difference between the best bid and best ask (the spread). It is suitable for low to medium liquidity instruments, including stocks, futures, and options.
Trading Modes
The robot can operate in three distinct modes:
- From Bid: Trading based on the bid side.
- From Ask: Trading based on the ask side.
- Simultaneous: Trading from both bid and ask sides at the same time.
Core Algorithm (Bid Mode Example)
- Entry: If the spread is greater than the configured
work_spreadvalue, the robot places the best bid. It continuously updates the bid to remain the best. If the spread falls below the threshold, the robot moves the order deeper into the book bynprice steps (defined bywait_slippage) to wait for a large market order. - Exit: Once a bid is accepted, the robot attempts to become the best ask, ensuring the price is at least the entry price plus the
minprofit. - Protection Mechanism: If a trade occurs within
mprice steps (defined byalert_slippage) of the entry price, the exit order will always stay at the top of the book (the best ask) until it is filled to protect against adverse price movements.
Use the BollingerBandsBreakout strategy
masterThe
BollingerBandsBreakoutstrategy is a trading logic based on breakouts of Bollinger Bands.Trading Logic:
- Buy (Long): When the price breaks below the lower Bollinger Band (calculated as
Lower Band - X, whereXis a specified offset in points). - Sell (Short): When the price breaks above the upper Bollinger Band (calculated as
Upper Band + X). - Exit: Positions are closed based on predefined Take Profit or Stop Loss levels, specified in points.
- Buy (Long): When the price breaks below the lower Bollinger Band (calculated as
Connect to multiple QUIK terminals using Lua scripts
masterYou can work with multiple QUIK terminals simultaneously by configuring additional Lua scripts and server entries in
config.json.To connect to a second terminal:
- Configure
config.json: Locate theserverssection. Find thescriptNameoption and set it to the name of your second Lua file (e.g.,Quik_2). Note: Do not include the.luaextension in thescriptNamevalue. - Set unique ports: Ensure
responsePortandcallbackPortfor the new server do not conflict with existing ports inconfig.json. By default, these are34132(request-response) and34133(callbacks) on127.0.0.1. - Deploy the script: Add the corresponding
.luafile (e.g.,Quik_2.lua) to QUIK and run it. You can run bothQuikSharp.luaand your new script simultaneously if they use different ports.
// Example config.json snippet for a second server "servers": [ { "scriptName": "Quik_2", "responseHostname": "127.0.0.1", "responsePort": 34132, "callbackHostname": "127.0.0.1", "callbackPort": 34133 } ]- Configure
Add additional QUIK servers
masterTo add more than two servers, follow these steps:
- Duplicate the script: Copy an existing script (like
Quik_2.lua) and save it with a new name (e.g.,MyBroker.lua) in the Lua folder. - Update
config.json: In theserversarray, add a new object containing the configuration for the new script. - Required fields:
scriptName: The name of your new file without the extension (e.g.,MyBroker).responsePortandcallbackPort: Must be unique and not conflict with any other server in the configuration.responseHostnameandcallbackHostname: Usually127.0.0.1.
// Example of adding a third server named 'MyBroker' "servers": [ { "scriptName": "Quik_1", ... }, { "scriptName": "Quik_2", ... }, { "scriptName": "MyBroker", "responseHostname": "127.0.0.1", "responsePort": 34134, "callbackHostname": "127.0.0.1", "callbackPort": 34135 } ]- Duplicate the script: Copy an existing script (like
Setup and use QUIK# with the QUIK terminal
masterQUIK# is a connector for the QUIK trading terminal that exposes Lua functionality to .NET (C#). To set up the environment:
- Build the solution: Open the project and build it in
Releasemode. If compilation errors occur on the first attempt, try building again (this is because demonstration projects reference the compiled library which may not exist yet). - Prepare Lua files: Copy the contents of the
\bin\luafolder to a separate directory that is accessible to the QUIK application. - Run the Lua script: In the QUIK terminal, open the Lua script dialog and run
QuikSharp.luafrom the directory you prepared in step 2. - Prerequisites: You may need to install
LuaForWindowsand restart your computer for the script to function correctly.
Note: For learning the syntax and capabilities, you can use the
QuikSharpDemoapplication found in the\Examplesfolder, or examine theRobotDemoexample (a simple trading robot) in the same folder.# No specific command provided, follow the manual steps above.- Build the solution: Open the project and build it in
Install QUIK# via NuGet
masterThe recommended way to integrate QUIK# into your .NET project is by installing the official NuGet package. This provides access to the ported QLUA functions and events as C# async functions and events.
PM> Install-Package QUIKSharp