Variables in your Kryll.io Bots: Concrete Examples and Applications

We know how important customization and flexibility are in the world of algorithmic trading. That's why we recently introduced a major new feature in the Kryll editor to give you even more control and opportunities to customize your trading strategies: personalized variables.

We've received a lot of positive feedback on these new features. However, we've also heard your requests for concrete examples and explanations on how these new features can be used to develop more effective and personalized trading strategies.

That's why we decided to create this detailed guide to show you how you can fully exploit the potential of personalized variables to improve your trading bots. Whether you're looking to set up simplified Dollar Cost Averaging (DCA) strategies, manage your capital more efficiently, find breakeven points more easily, create 'for' loops or something else, this guide is for you.

Get ready to discover a world of new possibilities for your trading bots on Kryll.io. Let's embark together on this detailed exploration of the applications of our new features. Let's get started!

Table of contents

  1. Creating a DCA Strategy in 4 Blocks on Kryll
  2. Creating a Smart DCA Bot on Kryll in 2 Minutes
  3. Creating a 'for' loop in Kryll
  4. Adjusting risk according to RoE
  5. Calculating your win/loss Ratio
  6. Taking fees into account for your breakeven point (BE)
  7. Creating a Trailing Stop
  8. Adjusting Your Stop-Loss According to Leverage
  9. Creating Functions in your Kryll bot
  10. Go even further with your Kryll.io bots

Kryll Bot Source Codes

All the strategies presented here are provided by Kryll for educational purposes. They aim to illustrate the functionalities of our platform and to help you understand how you can use them to create and enhance your own trading strategies.

Find the sources of these examples for free on GitHub, to use them as a basis for your own developments and improvements in trading strategies. It is important to note that trading involves risks and past performance does not guarantee future performance.

Creating a DCA Strategy in 4 Blocks on Kryll

The Dollar Cost Averaging method is a well-known investment strategy for its simplicity and effectiveness. It involves investing a fixed amount at regular intervals, allowing for buying more assets when prices are low and less when they're high. This approach minimizes the risk associated with market fluctuations and impulsive decisions, making investment more accessible and less stressful.

Using our new calendar block tool and the options of the Buy blocks on Kryll, setting up a DCA strategy is a piece of cake. Let's say we want to create a bot that will do a DCA every Friday for a year, it would suffice to do as follows:

DCA strategy buying every friday in 4 blocks

The calendar block is set to Friday at 00:00 and is completed by the balance block thanks to the AND block to validate that there are indeed funds left to allocate before making a new purchase. The Buy block is set to 2% of the starting capital to make 50 purchases during the year. After each purchase, the strategy waits one day and starts again.

Details of the settings of the DCA strategy blocks on Kryll.io

Note: Beware, most exchanges have minimum purchase limits (around $10). For this strategy to be able to make about 50 orders on Binance for example, it will need to be launched with a little more than $500.

Here is what it looks like if we had launched the strategy on January 1, 2022.

Results of the Kryll DCA strategy between January 2022 and June 2023

Source code: Find the source code for this strategy on GitHub or on our Marketplace.

Create a Smart DCA Bot on Kryll in 2 Minutes

DCA is good, but Smart DCA is even better! What does this mean? Smart DCA involves adapting the investment pace according to market conditions. A simple and effective way to create a Smart DCA bot is to invest at a fixed date only if the Bitcoin price is lower than our average purchase price, to avoid over-investing during rebound phases.

How to implement such a strategy on Kryll?
Nothing could be easier! With the introduction of variables on Kryll, you can easily configure your trading algorithm to react to market fluctuations.

To do this, let's quickly modify our DCA strategy to add in our test a Variable Test block that will allow us to validate the purchase only if the price is strictly lower than the average price we have bought at so far.

Example of Smart DCA strategy on Kryll.io

As we can see during our tests of this new version of our bot, this approach allows us not only to significantly increase the performance of the strategy in terms of return on investment, but also to significantly reduce the drawdown of our bot.

Results of the Kryll Smart DCA bot between January 2022 and June 2023

Source code: Find the source code for this strategy on GitHub or on our Marketplace.

Creating a 'for' loop on Kryll

In the world of programming, 'for' loops are an essential element to perform repetitive actions simply. Thanks to the 'Variables Operation' and 'Variables Test' blocks, you now have the ability to reproduce these loops in your trading bots on Kryll. This feature offers a new dimension to the customization of our strategies, allowing certain actions to be executed in an iterative and controlled manner.

To illustrate the creation of a 'for' loop on Kryll, let's take the example of a task that we want to repeat 20 times: systematically buying the next 20 bullish SuperTrend 4h signals with 5% of our starting capital at each iteration, as long as our positions do not capitalize a 10% gain.

  1. Start by using the 'Variable Operation' block in 'Assignment' mode to initialize a variable, which we will call counter, to 0.
  2. Create an AND condition with a SuperTrend block and a 'Variables Test' block to check if counter is less than 20.
  3. If this combination of blocks is valid it means we have a buy signal. We can therefore buy or implement any other action you want to repeat.
  4. After performing this action, use another 'Variable Operation' block in 'Operation' mode to increment counter by 1.
  5. Finally, connect the output of this operation to the 'Variables Test' block to loop the action.

With this structure, as long as 'counter' is less than or equal to 20, the action we have defined is repeated. This method can be particularly useful for accomplishing repetitive actions and for mastering the progress of your strategy with increased precision.
Here is what the strategy looks like in action over a little more than a year.

Source code: Find the source code for this strategy on GitHub or on our Marketplace.

Adjusting risk according to RoE

Taking into account the Return on Equity (RoE) in managing your risks is a key method to optimize the trading operations of your strategy, particularly in terms of the risk it can afford to take. The RoE represents the return on your invested capital and allows you to evaluate the current performance of your bot. Adjusting your level of risk based on the RoE can help you maximize your gains while preserving your capital.

On Kryll, this can be simply accomplished by using the Variable Test block, with the RoE option (or RoE without Piggy if you are using this option). You will thus be able to dynamically adapt the behavior of your trading strategy according to your bot's capital, taking into account the gains generated by your previous operations.

In the example below, the strategy will adapt the size of its purchase orders according to the current RoE:

  • Low risk if the strategy is not in profit: the bot will use only 40% of the starting capital
  • Greater risk if the strategy is in profit: the bot will use 70% of the available capital.
Example of adjusting the bot's position sizes based on the RoE

Calculating your win/loss ratio

To go even further, we could add to our strategy the calculation and use of the win/loss ratio for its decision-making. This metric would allow us to refine the assessment of our bot's effectiveness and adjust its behavior.

The win/loss ratio is simply the ratio of the total number of winning trades to the total number of losing trades. For example, if you have made 80 winning trades and 20 losing trades, your win/loss ratio is 80/20 = 4. This means that for every losing trade, you have on average 4 winning trades. A ratio greater than 1 indicates that you have more winning trades than losing trades, which is generally a good sign for your strategy if your losing trades do not impact your performance too significantly (hence the interest in managing your stop-loss and your move to Breakeven, points we will discuss right after).

With the introduction of variables in Kryll, it is now easy to calculate the win/loss ratio for your trading bot. Just create two variables, let's say "winning_trades" and "losing_trades", and increment each of them each time a corresponding trade is made.

Increment variables to count winning or losing trades on Kryll

Then, you can use an "Variable Operation" block to divide "winning_trades" by "losing_trades" and get your win/loss ratio.

Division operation to update the win/loss ratio in your Kryll bot

The win/loss ratio is a useful tool to steer the behavior of your strategy. For example, if your win/loss ratio is too low, this could indicate that your strategy is taking too many risks or that it is not effective enough to take advantage of opportunities in the current market setup. In this case, you might decide to reduce the size of your positions or target less risky trading opportunities to temporarily make your strategy more conservative. Conversely, a high win/loss ratio may indicate that your strategy is currently performing well, but you might decide to take more risks to try to increase your potential gains.

In the end, the win/loss ratio can serve as a flexible measure to allow us to balance the risks in our trading strategy, especially if it is coupled with performance analysis (RoE). For example, it is possible for us to implement 3 different risk modes in our strategy:

  • Low risk if the strategy is not in profit: only use 40% of the starting capital
  • Medium risk if the strategy is in profit but the win/loss ratio is less than one (more losing trades than winning): only use 60% of the starting capital.
  • High risk if the strategy is in profit AND the win/loss ratio is greater than one: use 80% of the available capital.
Implementation of risk management in a Kryll bot

As an example, let's create a strategy that seeks to exploit small rebounds in BTC during bearish phases. To do this; we will try to capture the crossings between the K and D line on the 4h Stochastic RSI if it is in the oversell zone (set at 30) and the SuperTrend is low. Here is the strategy and its result without risk exposure management based on the win/loss ratio over the last year (June 2022-June 2023).

Kryll strategy without risk management based on the win/loss ratio

By integrating the calculation of the win/loss ratio and using it to adjust our market exposure, it becomes possible to modulate the aggressiveness of our strategy. This approach then allows us to adjust the level of risk based on the performance of the strategy by analyzing the Return on Investment (RoE) and win/loss ratio. Thus, we can limit our risk when the strategy is not performing well enough, and amplify our audacity during profitable periods.

Kryll strategy with risk management based on the win/loss ratio 

By introducing this simple modification, without even touching the trading signals, we observe that our strategy becomes significantly more efficient and less risky. Despite the volatile movements of BTC over these last 12 months, it has managed to extract performance while drastically limiting its risk.

Source code: Find the source code for this strategy on GitHub or on our Marketplace.

Taking into account fees for your breakeven point (BE)

Implementing stop loss in your trading strategies is a crucial tool for limiting potential losses. It's a sell order that's triggered when the price of an asset reaches the maximum loss level acceptable as defined by a trader or bot. The main advantage of stop loss is that it allows trading strategies to automatically exit an unfavorable trade.

The breakeven point is another key trading concept. It refers to the point at which a trade moves from the stage of unrealized loss to that of unrealized gain, meaning that the price of the asset equals the entry price of the trade plus the entry and exit fees. The idea behind the move to BE is to secure your position as soon as possible in order to limit the risk of loss.

It's essential to implement these mechanisms in winning trades, especially when the gains are not yet realized (and the bot is waiting for a profit-taking signal). Indeed, markets can be very volatile and a profitable trade can quickly turn into a loss. It's also crucial to take into account trading fees (or at least a safety margin) when setting up such security mechanisms. In fact, transaction fees can significantly reduce your profits and can even make a profitable trade "losing". If you buy an asset at 100€ and the transaction fees are 1%, then your real entry price is 101€. Therefore, to reach BE, the price of the asset has to reach 101€ and not 100€.

Thanks to the variable blocks on Kryll, you can easily calculate these levels by incorporating the consideration of fees into your trading strategy and optimize your trades accordingly.

As an example, we will implement a strategy that will accumulate BTC every 48 hours if we are on a downtrend on a 2h SuperTrend. As soon as our return on investment exceeds 2%, we will take 25% of our profits and cut our position if the SuperTrend becomes bearish or if the current price is at our breakeven level to limit our risks.

To handle our BE point, we will first update our break_even pivot point after each purchase using the average purchase price to which we will add 0.5% trading fees (0.25% on purchase and 0.25% on sale).

Updating the Breakeven point after each DCA of the Kryll bot

Once the strategy is in 2% profit, we will test the price value to verify that it does not fall below (or is not equal to) our break_even price. If this is the case, we will exit our trade.

Setting up the breakeven test block of the Kryll strategy

Such a strategy allows for generating a return of more than 34% on BTC between June 2022 and June 2023 for a max drawdown of 22.3% in a market that ends at -15.3% over the same period with a correction of over 50.9% of drawdown! Enough to whet the appetite in the middle of a bear market!

Source code: Find the source code for this strategy on GitHub or on our Marketplace.

Creating a Trailing Stop

As we continue our exploration of the capabilities offered by Kryll's variable blocks (and to stay within the theme of "Stop-loss"), we would like to introduce another effective concept that can be easily implemented on the strategy editor: the Trailing Stop.

Unlike a classic stop-loss, a trailing stop is dynamic. It allows you to follow the market's upward trend and set a new stop-loss level with each profit realization: each time you make a profit, your stop-loss is raised to the level of the previous profit-taking (or to the breakeven point if it's the first profitable trade). Thus, if the market turns around, you have already secured your profits and limited your risk exposure.

Setting up a Trailing Stop on Kryll is fairly simple thanks to the use of variables. By creating a variable that updates with each profit-taking, you can configure your Stop-Loss to follow this stair-step motion, thus creating a tiered effect.

To do this, let's create a trailing_stop variable that will contain the value of the current stop-loss. Before each new profit-taking, it will be sufficient to update the trailing_stop variable with the value of the previous order and add a safety margin to take into account the fees (2 x 0.25% in this example) to raise our stop-loss to the value of the previous profit-taking.

Example of a Bot with Trailing-Stop on Kryll

This mechanism offers you more flexible control of your trades, allowing you to optimize your profits during bullish trends while protecting your capital in case of market reversal. It's a risk management technique that can significantly improve the effectiveness of your trading strategies.

Results of the Trailing-Stop strategy between 2021 and 2023

Source code: Find the source code of this strategy on GitHub or on our Marketplace.

Adjusting your Stop-Loss according to leverage

The adaptation of the Stop-Loss according to the leverage is another possibility introduced by Kryll's variable blocks. This flexibility ensures consistent and homogeneous risk management, regardless of the level of leverage deployed.

Let's consider a scenario where we want to develop a trading bot that follows SuperTrend signals on a 6-hour timeframe. With each trade, we would like to apply a 10% profit-taking and place a Stop-Loss at 5% while ensuring a maximum risk of 1% of the capital in our money management plan. Thanks to Kryll's basic tools, the implementation of such a strategy would look like this:

The bot buys 20% of the initial stake with a stop-loss at 5% (it therefore risks 5% of 20% of the initial capital, i.e., 1% of the starting bet each time)

However, when we change the strategy's leverage, the fixed Stop-Loss that we defined no longer allows us to respect our fund management rule. For example, with a leverage of 2, the risk rises to 2% of the capital. If the leverage reaches 4, the risk climbs to 4% and so on.

In lever x4 our strategy lost more than 3% of the initial capital on a single trade


To keep a risk at 1% of the initial capital as an unchangeable rule of our money management, we must adjust the level of the Stop-Loss according to the leverage used. This is where variable blocks come into play. By performing a division operation between the variable corresponding to the value of your initial Stop-Loss (5%) and the system 'leverage' variable, you can calculate the price differential between the current price and the Stop-Loss level that will keep the risk at 1% of the initial capital.

Here is how to implement such logic in your Kryll futures trading robot:

  • First, we initialize a STOP_VALUE variable in which we adjust the value of our Stop-Loss according to the leverage used, i.e., 5% divided by the leverage (0.05 / leverage).
  • Once the position is open, we calculate in another variable stop_gap the amount of potential loss on the asset that would trigger our Stop-Loss, i.e., STOP_VALUE  multiplied by the asset price
  • Finally, we determine the value of the price that would trigger our Stop-Loss in a third variable stop_loss, i.e., purchase price minus stop_gap
Kryll Strategy with Leverage-Adjusted Stop-Loss Calculation

By proceeding in this way, our Stop-Loss adapts to the leverage used, allowing us to limit the risk to 1% of the capital per trade, rather than 1% multiplied by the leverage.

Let's look at the comparison between our example strategy, without money management adjustment, and with adjustment, over the year 2023. It is clear that without the adaptation of the Stop-Loss, the strategy struggles to manage risk effectively. Its yield and Max Drawdown are affected.

Result of the Bot without adaptive stop-loss on 2023 at lever 4

On the other hand, with the introduction of the adaptive Stop-Loss, the performance of this basic strategy is practically doubled, while the risk is significantly reduced. This clearly demonstrates the importance of effective risk management and how simply adapting the Stop-Loss according to the leverage used can improve the overall performance of a strategy, while preserving the initial capital from undesirable market fluctuations.

Result of the Bot with adaptive stop-loss on 2023 at leverage 4

To go further

Using this reasoning, it is possible to use the same system for shorts. It will be enough to add stop_gap to the purchase price to have an upward Stop-Loss, which also depends on the leverage used.

Source code: Find the source code of this strategy on GitHub or on our Marketplace.

Creating functions in your Kryll bot

A useful concept in programming is the notion of a "function". A function is a set of instructions grouped together to perform a specific task. Once defined, a function can be called at any point in your program, thereby allowing you to reuse portions of code without having to rewrite them each time.

In simple terms, you can imagine a function as a mini-program within your main program. This mini-program performs a specific task and returns a result to your main program. This can be very useful for organizing your code and making it more readable and easier to maintain.

By coupling "GoTo" blocks and the new "Variable Operation" blocks on Kryll, you can create something resembling a function in your bot. So how does it work? By using these blocks, you can define a specific area of your bot to perform a particular task.

For example, if you've defined a portion of your bot to update your stop-loss, you can configure your bot to go to this portion of the strategy when certain conditions are met (for instance, after each trade) and update the stop-loss. You can then use this variable elsewhere in your bot to make trading decisions.

Simple example of a strategy with leverage-adapted money management and a Trailing Stop system using Goto and variable blocks. 

It's important to note that, just like in traditional programming, setting up "functions" in your bot may require some planning and organization. However, once properly set up, they can make your bot more flexible, more readable, and easier to maintain, allowing you to focus on optimizing your trading strategies rather than managing the details of your code.

Source code: Find the source code of this strategy on GitHub or on our Marketplace.

Go even further with your Kryll.io bots

Manage your function returns

You can go even further in the concept of a function and simulate behavior similar to the CALL and RET instructions in assembly language. The CALL instruction is used to call a function and the RET instruction is used to return to the place where the function was called.

To achieve such a structure in Kryll, you can use a variable to record the place from where you call a "function". Once the task of the function is completed, you can use the "Test on Variables" block to guide your bot to the location previously recorded.

Here is an example of a "Hello World" strategy with 2 functions called from 4 different places:

Kryll Bot "Hello World" with 2 functions and 4 call zones

Here's how the strategy behaves when it runs:

Source code: Find the source code of this strategy on GitHub or on our Marketplace.

State machines in your bots

Another new possibility is to set up a state machine in your bot. A state machine, in computer science, is a design pattern that allows a program to change its behavior based on its internal state. Imagine a state machine like a navigation system. You have a starting point (your initial state), a destination (your final state), and a series of intermediate steps (your other states). At each step, you make a decision on which direction to go based on the current state and the conditions of the moment.

In the context of a Kryll bot, a state machine could be implemented using a variable (say status) that represents the current state of your bot, and "Operation on Variable" and "Test on Variables" blocks to control the execution flow of your bot based on this state variable. You can think of this as a large switching system (switch/case) where each possible path represents one of the states of your bot.

"Hello world" example of a 4-state machine

Source code: Find the source code of this strategy on GitHub or on our Marketplace.


Happy Trading,

Website: https://kryll.io
Twitter: @Kryll_io
Telegram EN: https://t.me/kryll_io
Telegram FR: https://t.me/kryll_fr
Telegram ES: https://t.me/kryll_es
Discord: https://discord.gg/PDcHd8K
Reddit: https://reddit.com/r/Kryll_io
Facebook: https://www.facebook.com/kryll.io
Support: support@kryll.io