Automating your trading strategy frees you from constantly monitoring the market, removes emotions from trading and grows your portfolio. The latter is possible only with proper risk management. To better understand this, consider risking 10% of your equity on each trade. When you win, you win big and when you lose, you lose big as well. This can be construed as gambling.

Starting small and increasing risk as your portfolio grows while letting profits run for as long as possible are sustainable capital management techniques. By implementing dynamic lots, you will be risking a predetermined percentage of your account and the lots only increase or decrease relative to the growth of your equity. When using a trailing profit, you will rake in more pips should the market rally in your favor.

The following is part of a large strategy, which I cannot cover in full in this article. However, the component can be successfully attached to any VJForex based strategy. Let’s get started.

Strategy Basics
  • We will be risking 1% of 10K account on each trade,
  • Instead of taking a preset profit, the trailing profit will be triggered at 25% of the 20-day Average True Range (ATR),
  • While not covered in this article due to length limitations, instead of a fixed stop loss, we could implement a hedge trigger at 60% 20-day ATR.

Creating and Debugging 1% Dynamic Lot

This might seem straightforward since its equity*(1/100). Let’s look into that. Drag the Calculation Expression block to the workspace and feed the variables as shown in the image below:

The result field should be a1*a2, translating to 10000*0.01 = 100. If we were to trade this, it would be 100lots as seen on the following debug image.

Note: We will cover debugging later.

While 100 is 1% of the equity, 100lots are wrong since lots should be in the form 1 for 1 million with 0.001 as the minimum. So, if 1lot = 1M what is the ratio? 1/1000000 = 0.000001. Multiplying 0.000001 with 10000 gives us 0.01 (1% of 10000).

Note: JavaScript will convert 0.000001 to the scientific notation (E notation) 1.0E-6.

Edit the dynamicLots variable and declare it as 0.000001. Next, edit and delete the default trade amount (0.001) from the defaultTradeAmount variable. This will turn the variable to dynamic, which rises or falls relative to account’s equity.

Use a simple calculation block to multiply dynamicLots with equity and output the defaultTradeAmount variable.

The next debug message shows the correct lots.

Creating Trailing Profit Using 20-Day ATR

As stated on the strategy basics, the trailing profit should be triggered when the price moves 25% of the 20-day ATR in the profit direction. The trailing profit is actually a custom trailing stop that gets triggered only when the price is already in profits. When triggered, it will cancel the previous (initial) stop-loss.

Start by creating an ATR block in VJForex with the following, the period should be daily, Shift 1 and Time period 20, name the output values variable atr20Day.

Note: JavaScript variables cannot start with a number so, 20DayAtr is wrong.

Converting ATR Data to Pips

As seen on the following image, the data output of the ATR block is not in pips and cannot be used as an integer (INT) for trailing stops or in our case trailing profit.

To convert ATR data into pips, create a calculation expression with the following data:
  • A1 = atr20Day (simply drag and drop from the first block),
  • A2 = 10000
  • A3 = 2
Result field should be (a1*a2)*a3 and name the result of calculation variable atr20dayPips.

Debugging the atr20DayPips variable gives us ATR in pips.

After getting the ATR in pips, creating a trailing profit is easy. We do not use a take profit when entering a trade. Make this work by right clicking on the defaultTakeProfit under Default Variables and then on edit. On the dialog box, delete the 50 then save.

To get 25% ATR, we use a calculation block and multiply the atr20DayPips with 0.25 (25/100). The output of the calculation is the traillingTrigger.

Next, we use a Positions Viewer block to check for open positions and if an open position profit in pips is equal to or greater than 25% ATR, we start trailing the profits using a custom trailing stop block. This variable is named currentPosition.

Take note of the Current Position is Long block and the last block Pending Position Amount block.

Debugging the trailingTrigger

The last block acts as garbage collection in case the initial stop loss is not canceled by the trailing profit. It is also vital in preventing losses when hedging.

The Current Position is Long block enables the trailing profit to work on JForex. If you test without it on VJForex it works but fails on JForex and the contest platform. Orders are closed immediately on open as it can be seen in my contest profile.

Note: By using dynamic lots, lots keep decreasing as the equity decreases.

The same on VJForex shows profits.

How to Debug Variables in a VJForex Strategy

As visible on the debug images in this article, it’s possible to see the output of variables in case a strategy is not working as it should. A common pitfall on VJForex is addition or subtraction of pips from the price.

Take a look at the following; the logic is getting the price after subtracting 50pips from the open price.

Without debugging, one might not notice the error above until the strategy is in production or it might lead to time wastage evaluating other variables.

The fix to the above is multiplying 50pips with pipsSize before subtracting from the open price as shown in the image below:

To debug variables, open the strategy in JForex. This is by clicking tools and then strategies in JForex. On the dialog box that opens, select the strategy to debug. You cannot edit a strategy from VJForex directly so click on the "copy to editor" icon. Save and compile the strategy locally.

There are two options, you can log to console or print to chart. Logging to console requires the “Show messages” option to be checked on the historical tester. While printing debug messages on the chart needs the chart package.

Debugging Using Console

On the code block that you wish to debug, paste the following:

console.getOut().println("Debug Message =" +variableToDebug);


Printing Debug Messages on Charts

This uses the comment function to print on the chart. Example:

This will print the variables on the chart as seen on the images above. However, it requires the following:

import java.awt.Color;
private IChart chart;chart = this.context.getChart(defaultInstrument);
chart = this.context.getChart(defaultInstrument);

The import color function goes on the same block as import com.dukascopy.api.*;. Place the IChart function after private IUserInterface userInterface;. The last two should be placed in the strategy's onStart event. If you don’t set the comment color, the default is used.

Next time we will look at building some form of intelligence by allowing a strategy to validate a signal based on distance to pivot levels, ATR balance (from historical candles), current volumes, time of day and day of week and hedging on high impact news releases.

Lastly a chart from backtesting the full bot which is still in development.

You can use this piece of code for free: or download it from my contest profile.

To make code execution faster, I have added the conditional check that only runs the profit trailing block if at least 1 order is open. Your indicators and the rest of the code should run if no open position is present, after the dynamicLots calculation block.
Translate to English Show original