QUIK# (.NET Port of QLUA)

repository·master·Indexed 42 days ago

https://github.com/finsight/quiksharp

A .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.

Tokens
6.7K
Snippets
14
Records
27
Agent score
53%

What's inside QUIK#

  1. Overview of QUIK#

    master
    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).
  2. Overview of the TradeWind Robot

    master

    The 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

    1. SMA (Short Moving Average): Period of 4-6. Used to detect immediate price changes.
    2. LMA (Long Moving Average): Period of 20-30. Used to identify the medium-term trend.
    3. 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.
  3. TradeWind Robot Signal Types

    master

    The 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 SELL signals for higher reliability.

  4. How the Begemot trading strategy works

    master

    The 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

    1. Monitoring: The robot monitors the order book for a large bid (volume) exceeding a user-defined threshold.
    2. Entry: Once a large bid is detected, the robot places a buy order exactly one step (tick) above that large order.
    3. 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.
    4. 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).
    5. 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).

  5. Configure network access for Lua scripts

    master

    By default, scripts listen on 127.0.0.1 (localhost). To allow connections from other devices on your local WiFi network, set both responseHostname and callbackHostname to 0.0.0.0.

    Security Warning: Setting the hostname to 0.0.0.0 makes 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.

  6. Risk Management and Stop-Loss Behavior

    master

    The TradeWind Robot includes built-in risk management features:

    • Max Loss (maxloss): If the accumulated loss for a specific ticker reaches the defined .maxloss value, the robot will stop trading that ticker and set its status to DISABLED.
    • Stop-Loss Mechanism: The robot uses .stop_steps to manage exits. If the robot enters a STOPPED state, it will not resume trading until manually reset or re-enabled.
    • Brake (brake): A coefficient used to adjust the sensitivity of the trading logic.
  7. Use the Spreader Robot for spread trading strategies

    master

    The 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:

    1. From Bid: Trading based on the bid side.
    2. From Ask: Trading based on the ask side.
    3. 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_spread value, 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 by n price steps (defined by wait_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 m price steps (defined by alert_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.
  8. Use the BollingerBandsBreakout strategy

    master

    The BollingerBandsBreakout strategy 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, where X is 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.
  9. Connect to multiple QUIK terminals using Lua scripts

    master

    You can work with multiple QUIK terminals simultaneously by configuring additional Lua scripts and server entries in config.json.

    To connect to a second terminal:

    1. Configure config.json: Locate the servers section. Find the scriptName option and set it to the name of your second Lua file (e.g., Quik_2). Note: Do not include the .lua extension in the scriptName value.
    2. Set unique ports: Ensure responsePort and callbackPort for the new server do not conflict with existing ports in config.json. By default, these are 34132 (request-response) and 34133 (callbacks) on 127.0.0.1.
    3. Deploy the script: Add the corresponding .lua file (e.g., Quik_2.lua) to QUIK and run it. You can run both QuikSharp.lua and 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
      }
    ]
  10. Add additional QUIK servers

    master

    To add more than two servers, follow these steps:

    1. 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.
    2. Update config.json: In the servers array, add a new object containing the configuration for the new script.
    3. Required fields:
      • scriptName: The name of your new file without the extension (e.g., MyBroker).
      • responsePort and callbackPort: Must be unique and not conflict with any other server in the configuration.
      • responseHostname and callbackHostname: Usually 127.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
      }
    ]
  11. Setup and use QUIK# with the QUIK terminal

    master

    QUIK# is a connector for the QUIK trading terminal that exposes Lua functionality to .NET (C#). To set up the environment:

    1. Build the solution: Open the project and build it in Release mode. 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).
    2. Prepare Lua files: Copy the contents of the \bin\lua folder to a separate directory that is accessible to the QUIK application.
    3. Run the Lua script: In the QUIK terminal, open the Lua script dialog and run QuikSharp.lua from the directory you prepared in step 2.
    4. Prerequisites: You may need to install LuaForWindows and restart your computer for the script to function correctly.

    Note: For learning the syntax and capabilities, you can use the QuikSharpDemo application found in the \Examples folder, or examine the RobotDemo example (a simple trading robot) in the same folder.

    # No specific command provided, follow the manual steps above.
  12. Install QUIK# via NuGet

    master

    The 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