Topics
22 Nov 2018, 23:48
 1261
 6
24 Oct 2016, 18:08
 2112
 1
14 Oct 2014, 20:45
 2516
 3
Replies

9718853
27 Nov 2018, 13:17

Hi Panagiotis,

Thank you for your quick reply. I can see that the obj argument would allow me to refer to the current positions away from OnPositionsClosed..

However, I can't work out how to refer to the last closed position?

Any sample code you could offer would be greatly appreciated...

Many thanks,

Ian


@9718853

9718853
23 Nov 2018, 15:57

Sorry Panagiotis, could you please offer an example of how to correectly use PendingOrders[0].TargetPrice 

How do I compare the PendingOrders[0].TargetPrice price to the Bid/Ask price ? 

My appologies, usually I can work these things out by looking at sample code but this one has me stumped!

Many thanks,

Ian


@9718853

9718853
23 Nov 2018, 13:01

Hi Panagiotis,

Thank you for you reply...

I'm trying to trail Stop orders behind the Bid/Ask price by a cosistant distance...

This is easy if I use a parameter eg var newTargetPrice = Symbol.Bid + X pips * Symbol.Pipsize

However, I'm using the MarketSeries High/Low to determine 'X' which is the current range of pips between the current High and Low...

Somehow I need my cBot to remember and refer to this range so that the orders can trail at a consitent distance while the MarketSeries High / Low fluctuates...

Is this possible with PendingOrders[0].TargetPrice?

Many Thanks, 

Ian


@9718853

9718853
09 Nov 2018, 11:13

Parameters:

BTCUSD 1hr chart

Commission = 30

Data = Tick Data from server

Dates = 28/08/17 - 07/11/18


@9718853

9718853
09 Nov 2018, 11:10

Morning Panagiotis,

I think I've found the issue, I've taken the same code and added a print statement on line 84, for some reason this seems to be causing the bug.. Why might this happen?!

 

 

using System;
using System.Linq;
using cAlgo.API;
using cAlgo.API.Indicators;
using cAlgo.API.Internals;
using cAlgo.Indicators;

namespace cAlgo
{
    [Robot(TimeZone = TimeZones.UTC, AccessRights = AccessRights.None)]
    public class FIBBOT : Robot
    {
        [Parameter("rangeCalcForTPandSL", DefaultValue = 1.4)]
        public double rangeCalcForTPandSL { get; set; }

        [Parameter("Look Back Period", DefaultValue = 20)]
        public int period { get; set; }

        string label = "618Bot";

        protected override void OnStart()
        {

        }

        private double smartVolume(double riskPercent, double stopLossPips)
        {
            double risked = Account.Balance * riskPercent / 100;
            double volume = risked / stopLossPips / Symbol.PipValue;
            return Symbol.NormalizeVolumeInUnits(volume, RoundingMode.ToNearest);
            //return Symbol.NormalizeVolume(volume, RoundingMode.ToNearest);
            // Smart volume calculates risk based on a percentage of the account balance and where the stop loss is placed.
            // When a StopOrder is placed in the code below smart volume states 'smartVolume(2, 100)' the 2 being 2% of the 
            // account balance and the 100 being a SL at 100 pips...
            // This is the initial stop placement, in actual fact our trailing stop of only 5 pips brings the risk to 0.01% for the avergage 2% risked position!
        }

        private int HighestBar(DataSeries series, int period)
        {
            for (int i = 0; i <= period; i++)
            {
                if (series[series.Count - 1 - i] == series.Maximum(period))
                {
                    return i;
                }
            }
            return -1;
        }
        private int LowestBar(DataSeries series, int period)
        {
            for (int i = 0; i <= period; i++)
            {
                if (series[series.Count - 1 - i] == series.Minimum(period))
                {
                    return i;
                }
            }
            return -1;
        }
        protected override void OnBar()
        {

            var longPosition = Positions.Find(label, Symbol, TradeType.Buy);
            var symbolSearch = Positions.FindAll(label, Symbol);
            int Hi = HighestBar(MarketSeries.High, period);
            int Lo = LowestBar(MarketSeries.Low, period);
            var maxHigh = MarketSeries.High.Maximum(period);
            var minLow = MarketSeries.Low.Minimum(period);
            var UpPatternfib618 = minLow + (maxHigh - minLow) * 0.382;
            var TP = ((maxHigh - minLow) / Symbol.PipSize) / rangeCalcForTPandSL;
            var SL = TP / 2;

            {
                bool UplongO = false;
                foreach (var order in PendingOrders)
                {
                    if (order.TradeType == TradeType.Buy && order.Label == label && order.SymbolCode == Symbol.Code)
                    {
                        UplongO = true;
                    }
                }

                if (UplongO == false && longPosition == null)
                    Print("1");
                {
                    PlaceLimitOrder(TradeType.Buy, Symbol, smartVolume(2, SL), UpPatternfib618, label, SL, TP, null);

                }
                if (Symbol.Bid + (2 * Symbol.PipSize) > maxHigh)
                {
                    foreach (var order in PendingOrders)
                    {
                        if (order.TradeType == TradeType.Buy && order.Label == label && order.SymbolCode == Symbol.Code)
                        {
                            CancelPendingOrder(order);
                        }
                    }
                }

                var DownshortPosition = Positions.Find(label, Symbol, TradeType.Sell);
                var DownPatternfib618 = minLow + (maxHigh - minLow) * 0.618;

                {
                    bool DownshortO = false;
                    foreach (var order in PendingOrders)
                    {
                        if (order.TradeType == TradeType.Sell && order.Label == label && order.SymbolCode == Symbol.Code)
                        {
                            DownshortO = true;
                        }
                    }
                    if (DownshortO == false && DownshortPosition == null)
                    {
                        PlaceLimitOrder(TradeType.Sell, Symbol, smartVolume(2, SL), DownPatternfib618, label, SL, TP, null);
                        Print("TP = " + TP + " SL = " + SL);
                    }
                    if (Symbol.Ask - (2 * Symbol.PipSize) < minLow)
                    {
                        foreach (var order in PendingOrders)
                        {
                            if (order.TradeType == TradeType.Sell && order.Label == label && order.SymbolCode == Symbol.Code)
                            {

                                CancelPendingOrder(order);
                            }
                        }
                    }
                }
            }
        }
    }
}

 


@9718853

9718853
07 Nov 2018, 18:41 ( Updated at: 21 Dec 2023, 09:20 )

Hi Panagiotis,

Thank you for the quick response, much appreciated...

The bool should prevent multiple pending orders (of the same label, symbol & TradeType)... This works with all currencies in both backtesting and live trading... 

However, in oil, bitcoin and indices there are lots of orders placed despite the bool...

My Broker is IC Markets...

 

Here's the code with a few entry parmeters removed to keep it concise:

using System;
using System.Linq;
using cAlgo.API;
using cAlgo.API.Indicators;
using cAlgo.API.Internals;
using cAlgo.Indicators;

namespace cAlgo
{
    [Robot(TimeZone = TimeZones.UTC, AccessRights = AccessRights.None)]
    public class FIBBOT : Robot
    {
        [Parameter("rangeCalcForTPandSL", DefaultValue = 1.4)]
        public double rangeCalcForTPandSL { get; set; }

        [Parameter("Look Back Period", DefaultValue = 20)]
        public int period { get; set; }

        string label = "618Bot";

        protected override void OnStart()
        {

        }

        private double smartVolume(double riskPercent, double stopLossPips)
        {
            double risked = Account.Balance * riskPercent / 100;
            double volume = risked / stopLossPips / Symbol.PipValue;
            return Symbol.NormalizeVolumeInUnits(volume, RoundingMode.ToNearest);
            //return Symbol.NormalizeVolume(volume, RoundingMode.ToNearest);
            // Smart volume calculates risk based on a percentage of the account balance and where the stop loss is placed.
            // When a StopOrder is placed in the code below smart volume states 'smartVolume(2, 100)' the 2 being 2% of the 
            // account balance and the 100 being a SL at 100 pips...
            // This is the initial stop placement, in actual fact our trailing stop of only 5 pips brings the risk to 0.01% for the avergage 2% risked position!
        }

        private int HighestBar(DataSeries series, int period)
        {
            for (int i = 0; i <= period; i++)
            {
                if (series[series.Count - 1 - i] == series.Maximum(period))
                {
                    return i;
                }
            }
            return -1;
        }
        private int LowestBar(DataSeries series, int period)
        {
            for (int i = 0; i <= period; i++)
            {
                if (series[series.Count - 1 - i] == series.Minimum(period))
                {
                    return i;
                }
            }
            return -1;
        }
        protected override void OnBar()
        {

            var longPosition = Positions.Find(label, Symbol, TradeType.Buy);
            var symbolSearch = Positions.FindAll(label, Symbol);
            int Hi = HighestBar(MarketSeries.High, period);
            int Lo = LowestBar(MarketSeries.Low, period);
            var maxHigh = MarketSeries.High.Maximum(period);
            var minLow = MarketSeries.Low.Minimum(period);
            var UpPatternfib618 = minLow + (maxHigh - minLow) * 0.382;
            var TP = ((maxHigh - minLow) / Symbol.PipSize) / rangeCalcForTPandSL;
            var SL = TP / 2;

            {
                bool UplongO = false;
                foreach (var order in PendingOrders)
                {
                    if (order.TradeType == TradeType.Buy && order.Label == label && order.SymbolCode == Symbol.Code)
                    {
                        UplongO = true;
                    }
                }

                if (UplongO == false && longPosition == null)
                {
                    PlaceLimitOrder(TradeType.Buy, Symbol, smartVolume(2, SL), UpPatternfib618, label, SL, TP, null);

                }
                if (Symbol.Bid + (2 * Symbol.PipSize) > maxHigh)
                {
                    foreach (var order in PendingOrders)
                    {
                        if (order.TradeType == TradeType.Buy && order.Label == label && order.SymbolCode == Symbol.Code)
                        {
                            CancelPendingOrder(order);
                        }
                    }
                }

                var DownshortPosition = Positions.Find(label, Symbol, TradeType.Sell);
                var DownPatternfib618 = minLow + (maxHigh - minLow) * 0.618;

                {
                    bool DownshortO = false;
                    foreach (var order in PendingOrders)
                    {
                        if (order.TradeType == TradeType.Sell && order.Label == label && order.SymbolCode == Symbol.Code)
                        {
                            DownshortO = true;
                        }
                    }
                    if (DownshortO == false && DownshortPosition == null)
                    {
                        PlaceLimitOrder(TradeType.Sell, Symbol, smartVolume(2, SL), DownPatternfib618, label, SL, TP, null);
                        Print("TP = " + TP + " SL = " + SL);
                    }
                    if (Symbol.Ask - (2 * Symbol.PipSize) < minLow)
                    {
                        foreach (var order in PendingOrders)
                        {
                            if (order.TradeType == TradeType.Sell && order.Label == label && order.SymbolCode == Symbol.Code)
                            {

                                CancelPendingOrder(order);
                            }
                        }
                    }
                }
            }
        }
    }
}




 

 

 

 


@9718853

9718853
21 Sep 2015, 13:16

 

Thank you so much for such a concise answer.... I'm currently going through the logic and running new tests, I'll post results if they are worth posting!

Thanks again...


@9718853

9718853
07 May 2015, 00:41

RE:

In OnStart() the indicator is defined...

In OnBar() the last result of the indicator is used to trigger an action...

If you wanted anything to happen on tick you would have to use OnTick() 

.ics said:

Hi all,

Having a question about some code present in Sample Breakout cBot.

In the below code we see the initialisation of bollingerBands in the OnStarrt(). In the OnBar() we request the top and bottom values of the BB.

My questions:

  • why is this initialisation of bollingerBands done in the OnStart() and not in the OnBar()?
  • is bollingerBands updated every tick even if it is defined in the OnStart()?

Thanks in advance.

        protected override void OnStart()
        {
            bollingerBands = Indicators.BollingerBands(Source, Periods, Deviations, MAType);
        }

        protected override void OnBar()
        {

            var top = bollingerBands.Top.Last(1);
            var bottom = bollingerBands.Bottom.Last(1);

            if (top - bottom <= BandHeightPips * Symbol.PipSize)
            {
                consolidation = consolidation + 1;
            }


           

 


@9718853

9718853
19 Apr 2015, 22:40

RE:

This will give you a calculation to manipulate volume with whole numbers...

var smartVolume = Volume * (int)(Account.Equity / openingBalance)

 

markstewie said:

Hello,

I'm trying to make a cBot that enters positions at with a certain percentage of the account balance at risk.

For example, if I wanted to risk 2.5% of account balance per trade and I've worked out I need a stop loss of 60 pips for the current trade, how would I calculate the position size taking account base currency, the symbol being traded and the pip value etc?

I have all the variables I need to place a limit order except volume... this is what I'm trying to calculate.

// This is where I've got to but it's clearly not right.
var volume = (Account.Balance * RiskPercentage / 100) / (stopLossPips * Symbol.PipValue);

TradeResult result = PlaceLimitOrder( TradeType.Buy, Symbol, volume, entryPrice, label, stopLossPips, takeProfitPips);

Any help would be greatly appreciated.

 

 


@9718853

9718853
04 Apr 2015, 12:05

cAlgo doesn't support multi symbol back testing... There are lots of requests for it so hopefully it is in development...

 


@9718853

9718853
22 Mar 2015, 14:25

Ok I've just ordered a 6 core overclocked 3.6GHZ PC...

I'll post some pictures here once it's all set up...


@9718853

9718853
09 Mar 2015, 14:32

Fixed it, all good... : )


@9718853

9718853
07 Mar 2015, 23:33 ( Updated at: 21 Dec 2023, 09:20 )

The results log states that the OverAllPipTP (take profit) level was met at 2501.7 so closed all positions at a loss of -48805 ?

 

 


@9718853

9718853
07 Mar 2015, 23:06 ( Updated at: 21 Dec 2023, 09:20 )

And now it actually posts a loss!!!

Now the same code is actually closing at a loss!!! How is this possible??

If the code only closes positions when the overall pip count is +2500 how on earth are the results below even possible?

 

 

 


@9718853

9718853
27 Feb 2015, 00:57

I'll be happy to share the code once it's developed, it's still full of comments and unused snippets at the minute....

Right now I'd just like to know if anyone has produced similar results and had to abandon development for some reason that I haven't factored in...?

For example, in the results chart you can see that up to 130 trades can be open at a time... Does anyone have any thoughts on this type of exposure?

 


@9718853

9718853
31 Jan 2015, 01:03

RE: RE:

Hi Amanev,

 

 

 

I started coding cBots without any coding knowledge and I found that printing some code onto paper and then making notes helped...

EG: notes on where brackets should be placed and why...

There's plenty of help online with C# forums or tutorials. This forum is a good resource too, even if the replies take a while to come through!

I would advise that you continue to post your code. The more you try to learn, the happier people will be to help. 

Keep at it and things will just start to click... 

 

 

amanev said:

Apologies for my typo's and gramma, spell checker was not working well..... Just correcting some typo errors...

 

Though I add this line to the code in order to build with no errors, (but I like to omit the line, have it so it follows through with the next trade according to the RSI parameters).

         private Random random = new Random();

After executing and testing, the first part works well, when a certain RSI value is reached, it opens a trade, but it continues, does not close with a takeprofit or stoploss values and the next trade opens, it does not apply the martingale options. Can anyone please help me correcting this code, much appreciated in advance..

My second and shorter question is - is there any Books for Dummies on how to code cBots in cAlgo besides the API reference and Guide section of this site (though helpful a more detail explanation in to the code be nice) ??

amanev said:

Though I have to add this line to the code in order to build with no errors, (but I like omit this line, have it so it follows through with the next trade according to the RSI parameters).

         private Random random = new Random();

After executing the and testing, well first part works, when a certain RSI value is reached, it opens a trade, but it continues does not close a the takeprofit or stoploss values and the next trade it opens it does not apply the martingale options. CAn anyone please help me correcting this code, much appreciated in advance..

My second and shorter question is there any Books for Dummies on how to code cBots in cAlgo besides the API reference and Guide section of this site (though helpful a more detail explanation in to the code be nice) ??

 

 


@9718853

9718853
31 Jan 2015, 00:14

RE:

Thank you, but I don't have MT4, only cBots... I'm to much of a coder but have been trading for a while... 

 

breakermind said:

Hi,

If you have some good bot version for MT4 (min earn 50% per month no scalping no HFT) I can connect to my vps on (breakermind.com) and made available for copying :)

Bye.

 


@9718853

9718853
31 Jan 2015, 00:11

RE:

If your backtest is modest then it wouldn't take 3 hours... A backtest should complete hundreds, even thousands of trades in minutes...

 

Presumably you are testing a simple system that doesn't close trades often? 

Or you are referring to an optimisation test which can take hours? I leave mine over night to complete and sometimes longer....

Are you running a backtest or optimisation?

cjdduarte said:

My computer has 4GB of RAM. I'm trying to make a modest backtest, expected to 3h to complete, however the application consumes all memory and is catching, being necessary to finalize the application.

Do you have any way to optimize this?
The same robo run on a notebook (only slower) with 3GB of RAM without problems.

 

Sds,

Carlos

 

 


@9718853

9718853
31 Jan 2015, 00:04

can you share the code? 

Is it the same cBot as your other code? Maybe a pending order happens to fall on the same price as another?


@9718853

9718853
30 Jan 2015, 23:59

if your trailing stop or move to break even logic is flawed then you will close positions in this way...


@9718853