### Deribit Example Script for TSLab Source: https://doc.tslab.pro/tslab/postavshiki-dannykh Provides a ready-to-use script for starting with Deribit on TSLab. This script likely demonstrates basic functionality for data retrieval or trading operations. ```TSLab Script /* This is a placeholder for the actual TSLab script code. The actual script would contain TSLab-specific functions and logic for interacting with the Deribit exchange. */ // Example of a potential function within the script: function InitializeDeribitProvider() { // Code to initialize the Deribit data provider // This might involve setting API keys, endpoints, etc. console.log("Initializing Deribit data provider..."); } // Example of another function: function FetchDeribitData(symbol, timeframe) { // Code to fetch historical or real-time data from Deribit // Returns data in a format TSLab can understand console.log("Fetching data for " + symbol + " with timeframe " + timeframe); return []; // Placeholder for actual data } // Example of how these functions might be called: InitializeDeribitProvider(); const historicalData = FetchDeribitData("BTC-PERPETUAL", "1m"); ``` -------------------------------- ### TSLab API Examples Source: https://doc.tslab.pro/tslab/rabota-s-programmoi/tslab-api This section provides examples and guidance on using the TSLab API, including managing orders, optimizing script performance, and general API usage. ```APIDOC ## TSLab API Examples This section covers practical examples and tips for using the TSLab API. ### Example: Script with Independent Order Management * **Description**: Demonstrates how to manage orders independently within a script. * **Link**: https://doc.tslab.pro/tslab/rabota-programmoi/tslab-api/api-primery/primer-skripta-s-samostoyatelnym-upravleniem-zayavkami ### Example: Optimizing Script Processing Speed * **Description**: Provides methods and techniques to accelerate the processing of scripts using the API. * **Link**: https://doc.tslab.pro/tslab/rabota-programmoi/tslab-api/api-primery/api-kak-uskorit-obrabotku-skripta-na-api ### Example: Links to Other Examples * **Description**: A collection of links to various other API examples. * **Link**: https://doc.tslab.pro/tslab/rabota-programmoi/tslab-api/api-primery/api-ssylki-na-primery ``` -------------------------------- ### Buy and Set Stop/Profit Orders Example (C#) Source: https://doc.tslab.pro/tslab/rabota-s-programmoi/tslab-api/napisanie-skriptov-na-api/api-rabota-s-poziciyami An example TSLab script in C# that demonstrates buying a security at market after a bullish candle and setting a stop-loss 200 points below entry and a take-profit 400 points above entry. It handles checking for existing positions before placing new orders. ```csharp using TSLab.Script; using TSLab.Script.Handlers; namespace MyLib { public class ExampleBuy : IExternalScript { public void Execute(IContext ctx, ISecurity sec) { for (int i = 0; i < ctx.BarsCount; i++) { var signalBuy = sec.Bars[i].Close > sec.Bars[i].Open; // определяем растущую свечу var longPos = sec.Positions.GetLastActiveForSignal("LE", i); // получаем активную позицию if (longPos == null) { // если нет позиции, то проверяем сигнал if (signalBuy) { // если есть сигнал на покупку, то покупаем по рынку sec.Positions.BuyAtMarket(i + 1, 1, "LE"); } } else { // если есть позиция, то ставим стоп-лосс и тейк-профит longPos.CloseAtStop(i + 1, longPos.EntryPrice - 200, "LXS"); longPos.CloseAtProfit(i + 1, longPos.EntryPrice + 400, "LXP"); } } } } } ``` -------------------------------- ### Get All Agent Runtime Info in C# Source: https://doc.tslab.pro/tslab/rabota-s-programmoi/tslab-api/api-vopros-otvet/poluchit-dannye-vsekh-agentov Retrieves runtime information for all agents using the `ctx.Runtime.GetAllAgentRuntimeInfo()` method. This method returns data equivalent to the 'Agents' table. The example iterates through each agent and its source items, logging detailed information to the message window. Dependencies include the TSLab.Script namespace. ```csharp using System.Linq; using System.Text; using TSLab.Script; using TSLab.Script.Handlers; namespace MyLib { public class TestAgentsInfo : IExternalScript { public void Execute(IContext ctx, ISecurity sec) { // В переменной agents будут данные по агентам. var agents = ctx.Runtime.GetAllAgentRuntimeInfo().ToList(); var sb = new StringBuilder(); foreach (var agent in agents) { sb.AppendLine($"Агент: {agent.AgentName}"); sb.AppendLine($"Скрипт: {agent.ScriptName}"); sb.AppendLine($"Работает: {agent.IsStarted}"); foreach (var sourceItem in agent.SourceItems) { sb.AppendLine($" Поставщик: {sourceItem.ProviderName}"); sb.AppendLine($" Счет: {sourceItem.AccountName}"); sb.AppendLine($" Валюта счета: {sourceItem.CurrencyName}"); sb.AppendLine($" Инструмент: {sourceItem.SecurityName}"); sb.AppendLine($" Позиция (лоты): {sourceItem.PositionInLots}"); sb.AppendLine($" Позиция (деньги): {sourceItem.PositionInMoney}"); sb.AppendLine($" Длинные поз. (лоты): {sourceItem.PositionLong}"); sb.AppendLine($" Короткие поз. (лоты): {sourceItem.PositionShort}"); sb.AppendLine($" Учетная цена: {sourceItem.BalancePrice}"); sb.AppendLine($" П/У: {sourceItem.Profit}"); sb.AppendLine($" П/У (дн): {sourceItem.DailyProfit}"); sb.AppendLine($" НП/У: {sourceItem.ProfitVol}"); sb.AppendLine($" Комиссия: {sourceItem.Commission}"); sb.AppendLine($" Текущая цена: {sourceItem.LastPrice}"); sb.AppendLine($" Оценочная цена: {sourceItem.AssessedPrice}"); sb.AppendLine(); } } ctx.Log(sb.ToString(), toMessageWindow: true); } } } ``` -------------------------------- ### C# Array Pool Usage Example Source: https://doc.tslab.pro/tslab/eng/working-with-the-program/tslab-api/api-additional-features/api-optimizaciya-pul-massivov This C# code demonstrates how to use the array pool in TSLab to retrieve and release arrays for optimization purposes. It shows how to get an array from the pool, populate it with data, and then log the hash code to verify array reuse. The example compares the performance with and without array pooling. ```csharp public class TestArrayPool : IExternalScript { public IntOptimProperty Param = new IntOptimProperty(1, 1, 5, 1); public void Execute(IContext ctx, ISecurity sec) { var bars = sec.Bars; var arr = new double[bars.Count]; for (int i = 0; i < bars.Count; i++) arr[i] = (bars[i].High + bars[i].Low) / 2; ctx.Log($"hash: {arr.GetHashCode()}", MessageType.Info, true); } } ``` -------------------------------- ### Открытие позиций (C#) Source: https://doc.tslab.pro/tslab/rabota-s-programmoi/tslab-api/napisanie-skriptov-na-api/api-rabota-s-poziciyami Примеры использования методов BuyXXX и SellXXX для открытия позиций по рынку, лимитной заявкой или условным ордером. Требуется объект 'sec' для доступа к методам управления позициями. ```csharp sec.Positions.BuyAtMarket(i + 1, 2, "LE"); // Купить два контракта по рынку на следующем баре. sec.Positions.BuyAtPrice(i + 1, 2, 65000, "LE"); // Выставить лимитную заявку на покупку двух контрактов на следующем баре по цене 65000. sec.Positions.BuyIfGreater(i + 1, 2, 65000, "LE"); // Выставить условный ордер на покупку двух контрактов на следующем баре если цена будет выше 65000. sec.Positions.BuyIfLess(i + 1, 2, 65000, "LE"); // Выставить условный ордер на покупку двух контрактов на следующем баре если цена будет ниже 65000. ``` ```csharp sec.Positions.SellAtMarket(i + 1, 2, "LE"); // Продать два контракта по рынку на следующем баре. sec.Positions.SellAtPrice(i + 1, 2, 65000, "LE"); // Выставить лимитную заявку на продажу двух контрактов на следующем баре по цене 65000. sec.Positions.SellIfGreater(i + 1, 2, 65000, "LE"); // Выставить условный ордер на продажу двух контрактов на следующем баре если цена будет 65000. sec.Positions.SellIfLess(i + 1, 2, 65000, "LE"); // Выставить условный ордер на продажу двух контрактов на следующем баре если цена будет ниже 65000 ``` -------------------------------- ### Configure QuikLua Data Provider in TSLab Source: https://doc.tslab.pro/tslab/postavshiki-dannykh This guide details the configuration of the QuikLua data provider for TSLab, ensuring compatibility with specific TSLab versions. It addresses common connection issues and provides solutions for initial setup problems. ```en This instruction is relevant for TSLab version 2.2.11 and later. ```