Topics

Forum Topics not found

Replies

Invalid
29 Jul 2014, 17:52

RE:

Could you provide full code? 

Most probably position variable is not initialized.

apresau said:

Hi,

I'm having trouble with a crashing cBot.

The log message reads -

Crashed in OnTick with NullReferenceException: Object reference not set to an instance of an object.

The offending code is associated with the array -

        private double[] ExitPrice = new double[20];


        protected override void OnTick()
        {

// trade entry ---------
<>
               SetExitPriceArray();


// trade exit ---------
            if (Positions.Count > 0)
            {
                TradeCnt = Positions.Count;

                if (position.TradeType == TradeType.Buy)
                {
                    if (Ask <= ExitPrice[TradeCnt - 1])
                    {
                        CloseAllTrades();
                        return;
                    }
                }

                if (position.TradeType == TradeType.Sell)
                {
                    if (Bid >= ExitPrice[TradeCnt - 1])
                    {
                        CloseAllTrades();
                        return;
                    }
                }
            }
        }



// FUNCTIONS ------------------------------------------------------------------------------

<< other functions>>

        private void SetExitPriceArray()
        {
            double RefPrice;
            if (position.TradeType == TradeType.Buy)
            {
                RefPrice = Symbol.Ask;

                for (int i = 1; i < 4; i++)
                {
                    ExitPrice[i] = RefPrice;
                }
                for (int i = 4; i < 20; i++)
                {
                    ExitPrice[i] = RefPrice + (PipStep * Symbol.TickSize) * (i - 3);
                }
            }


            if (position.TradeType == TradeType.Sell)
            {
                RefPrice = Symbol.Bid;

                for (int i = 1; i < 4; i++)
                {
                    ExitPrice[i] = RefPrice;
                }
                for (int i = 4; i < 20; i++)
                {
                    ExitPrice[i] = RefPrice + (PipStep * Symbol.TickSize) * (i - 3);
                }
            }
        }
    }
}

I don't understand enough to be able to interpret the log entry.

If someone could help I'd be most grateful.

apresau

 


@Invalid

Invalid
25 Jul 2014, 11:21

RE:

I appreciate you work. Would be better to have comments in English in your solution for those who cares about comments. 

Abdallah_Hacid said:

Je propose une librairie encore au stade du développement pour aider à la programmation d'indicateurs et de robots de trading avec la plateforme cAlgo :

Solution Visual studio  :    https://calgorobots.codeplex.com/SourceControl/latest

Author : https://www.facebook.com/ab.hacid

Si vous avez des idées d'amélioration ou souhaitez y ajouter des méthodes utiles, dites le dans le fil de discussion.

Cordialement

translation for those who do not read French :

I propose a bookstore still in the development stage to help with the programming of indicators and trading robots with cAlgo platform: 

Visual Studio Solution: https://calgorobots.codeplex.com/SourceControl/latest 

Author: https://www.facebook.com/ab.hacid 

If you have ideas for improvement or wish to add useful methods, say it in the thread. 

best regards

 

 

 


@Invalid

Invalid
25 Jul 2014, 09:18

RE: RE:

ExecuteMarketOrder has 5 overloads. Oneof them is

ExecuteMarketOrder(tradeType, Symbol, Volume, "SampleRSI", stopLissPips, takeProfitPips);

Ancalagon said:

Ancalagon said:

 

stop los need to be a take proift sorry i cannot setup a take profit can someone please helpe me

hallo how can i had a stop los with this mod?

 

// -------------------------------------------------------------------------------------------------
//
//    This code is a cAlgo API sample.
//
//    This cBot is intended to be used as a sample and does not guarantee any particular outcome or
//    profit of any kind. Use it at your own risk.
//
//    The "Sample RSI cBot" will create a buy order when the Relative Strength Index indicator crosses the  level 30, 
//    and a Sell order when the RSI indicator crosses the level 70. The order is closed be either a Stop Loss, defined in 
//    the "Stop Loss" parameter, or by the opposite RSI crossing signal (buy orders close when RSI crosses the 70 level 
//    and sell orders are closed when RSI crosses the 30 level). 
//
//    The cBot can generate only one Buy or Sell order at any given time.
//
// -------------------------------------------------------------------------------------------------

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 SampleRSIcBot : Robot
    {
        [Parameter("Source")]
        public DataSeries Source { get; set; }

        [Parameter("Periods", DefaultValue = 14)]
        public int Periods { get; set; }

        [Parameter("Volume", DefaultValue = 10000, MinValue = 1000)]
        public int Volume { get; set; }

        private RelativeStrengthIndex rsi;

        protected override void OnStart()
        {
            rsi = Indicators.RelativeStrengthIndex(Source, Periods);
        }

        protected override void OnTick()
        {
            if (rsi.Result.LastValue < 30)
            {
                Close(TradeType.Sell);
                Open(TradeType.Buy);
            }
            else if (rsi.Result.LastValue > 70)
            {
                Close(TradeType.Buy);
                Open(TradeType.Sell);
            }
        }

        private void Close(TradeType tradeType)
        {
            foreach (var position in Positions.FindAll("SampleRSI", Symbol, tradeType))
                ClosePosition(position);
        }

        private void Open(TradeType tradeType)
        {
            var position = Positions.Find("SampleRSI", Symbol, tradeType);

            if (position == null)
                ExecuteMarketOrder(tradeType, Symbol, Volume, "SampleRSI");
        }
    }
}

 

 


@Invalid

Invalid
23 Jul 2014, 11:02

RE: RE: RE: RE:

Hi hiba7rain.

CBots are run on the client side (your machine), not on server. You can use VPS in order to keep cbot running on the server (but it will cost some money). Take a look here.

If you need to get some idea about C# language than you can read this post. You don't have to read everything there, just what you consider to be useful for you.

 

 

 

hiba7rain said:

Hi Invalid,

Thanks again, yes its working fine now after i have change it as you advise me  :) it was helpful to point the missing functions to me , for the moment I will do some modifications and additions before testing the robot live and ill update you , by the way why robots stop functioning once you log out form calgo or ctrader platforms?

 


@Invalid

Invalid
22 Jul 2014, 09:33

RE: RE:

Hi hiba7rain.

You don't understand smth fundamental yet.

Positions - it's a collection of all of your positions.

if you execute next code:

 foreach (var position in Positions)
{
      ClosePosition(position); 
}

it will close all your positions. If you need to close specific positions, than do as you did to get them and pass them to ClosePosition method.

        protected override void OnTick()
        {
            CheckForEMA();
        }

        private void CheckForEMA()
        {
            if (ema1.Result.LastValue > Symbol.Ask)
            {
                var positionsToClose = Positions.FindAll("calgooob", Symbol, TradeType.Buy);
                foreach (var position in positionsToClose)
                {
                    ClosePosition(position);
                }
            }
        }

hiba7rain said:

hanks for your reply  in fact I also got some help for friends here and I used the following method but am still having a problem that if i use the method all other positions will be closed which i dont want it to happen

the method I use is

protected override void OnTick()
        {
            CheckForEMA();
            var positions = Positions.FindAll("calgooob", Symbol, TradeType.Buy);
        }

        private void CheckForEMA()
        {
            if (ema1.Result.LastValue > Symbol.Ask)
            {
                foreach (var position in Positions)
                {
                    ClosePosition(position); 

MRSV said:

 

This was an example of how to use the Close() method.

If(SMA.Result.LastValue > 1)

Close();

 

It is the same as the method for opening a position, but insted of opening a position it closes it.

So you have for your criteria for closing a position that is the IF("something") then close.

 

In the example i used all positions would close when the Simple Moving Average hit 1.

If you want the position to close when EMA is equal or less the the as you write it like this:

If(EMA.Result.LastValue <= Symbol.Ask)
Close();

 

 

 

 

 


@Invalid

Invalid
21 Jul 2014, 15:58

RE: RE: RE: RE: RE: RE:

Take a look at guide. ExecuteMarketOrder returns an object with Position inside.

Quick sample:

        private Position _position;

        protected override void OnStart()
        {
           //....initialize ema1
            _position = ExecuteMarketOrder(TradeType.Sell, Symbol, 20000).Position;
        }

        protected override void OnTick()
        {
            CheckForEMA();
        }

        private void CheckForEMA()
        {
            if (ema1.Result.LastValue > Symbol.Ask)
            {
                _position=null;
            }
        }

 

hiba7rain said:

 Thanks but how to make it (close position) assigned to a specific  executed market order trade type , I have tried to do it using closepositions.Find but I think I done something wrong and its not working with me 


@Invalid

Invalid
21 Jul 2014, 10:14

RE: RE: RE: RE:

The code is the same for EMA

       private ExponentialMovingAverage ema;

        protected override void OnStart()
        {
            ema = Indicators.ExponentialMovingAverage(MarketSeries.Close, 14);
        }

        protected override void OnBar()
        {
            if (MarketSeries.Close.Last(1) < ema.Result.Last(1))
                ClosePosition(_position);
        }

 

hiba7rain said:

Invalid said:

Thank Invalid,

is the EMA codes and variables different from using SMA?


@Invalid

Invalid
21 Jul 2014, 09:51

RE: RE:

Hi. May be next could help to get an idea

        private SimpleMovingAverage sma;

        protected override void OnStart()
        {
            sma = Indicators.SimpleMovingAverage(MarketSeries.Close, 14);
        }

        protected override void OnBar()
        {
            if (MarketSeries.Close.Last(1) < sma.Result.Last(1))
                ClosePosition(_position);
        }

 

hiba7rain said:

modarkat said:

 

hey modarkat

thank you for the comment, I have a question with regards to using bars, is it possible to close opened position if for example the bar value became less than for example moving average?

if yes how to do it?

thanks

here you go:

        int GetBarsAgo(Position position)
        {
            for (var i = MarketSeries.OpenTime.Count - 1; i >= 0; i--)
            {
                if (position.EntryTime > MarketSeries.OpenTime[i])
                    return MarketSeries.OpenTime.Count - 1 - i;
            }
            return -1;
        }

        protected override void OnTick()
        {
            var barsAgo = GetBarsAgo(position);

            if (barsAgo > 5)
            {
                ClosePosition(position);
            }
        }

 

 

 


@Invalid

Invalid
21 Jul 2014, 09:13

you can do smth like:

    [Robot(TimeZone = TimeZones.UTC, AccessRights = AccessRights.FullAccess)]
    public class TrailCutII : Robot
    {
        protected override void OnStart()
        {
            var name = this.GetName();
        }
    }

    public static class AlgoExtensions
    {
        public static string GetName(this Robot robot)
        {
            return robot.GetType().Name;
        }
    }

 


@Invalid

Invalid
17 Jul 2014, 14:19

RE: RE: RE:
using Newtonsoft.Json;
using cAlgo.API;

namespace cAlgo
{
    [Robot(TimeZone = TimeZones.UTC, AccessRights = AccessRights.FullAccess)]
    public class JSON : Robot
    {
        protected override void OnStart()
        {
            var position = ExecuteMarketOrder(TradeType.Sell, Symbol, 40000).Position;
            var json = JsonConvert.SerializeObject(position, Formatting.Indented);
            
        }
    }
}

 

will produce:

{
  "SymbolCode": "EURUSD",
  "TradeType": 1,
  "Volume": 40000,
  "Id": 2646492,
  "Profit": -2.66,
  "GrossProfit": -2.66,
  "EntryPrice": 1.35275,
  "EntryTime": "2014-07-17T11:16:25.942Z",
  "Pips": -0.9,
  "Label": "",
  "Comment": "",
  "StopLoss": null,
  "TakeProfit": null,
  "NetProfit": -5.06,
  "Swap": 0.0,
  "Commissions": -1.2
}

 

 

MarsBarsLars said:

 

Do you have a simple example?


@Invalid

Invalid
17 Jul 2014, 10:40

RE:

Hi MarsBarsLars.

You can use this one http://james.newtonking.com/json. Just download and reference it using reference manager

or reference "System.Runtime.Serialization"  from .Net Framework. http://msdn.microsoft.com/en-us/library/bb410770(v=vs.100).aspx.

MarsBarsLars said:

Hi,

How do I include JSON serialization?

Is there an included library?

MarsBarsLars

 


@Invalid

Invalid
16 Jul 2014, 09:27

RE:

Probably memory is growing because you add message to log every 20ms. 

I've answered you about timer in another thread.

 

mistica87 said:

void process()
        {
            while (true)
            {
                try
                {                   
                  Print("Test");                   
                } catch (System.Exception e)
                {
                    Print(e.Message);
                }
                Thread.Sleep(20);
            }
        }

        protected override void OnStart()
        {          
            ThreadStart ts = delegate { process(); };
            Thread th = new Thread(ts);
            th.Start();
        }

When I run this code. CTrader not cope, RAM is overloaded, growing and CTrader freezes. Help solve the problem.

I need cycle with 20 miliseconds interval. I can`t use timer, becouse now it only in seconds.

 


@Invalid

Invalid
16 Jul 2014, 09:26

RE: millisecondtimer

Timer.Start has one overload with TimeSpan parameter.

 

Timer.Start(TimeSpan.FromMilliseconds(111));

 

mistica87 said:

Hello! Please add miliseconds timer. Now it only in seconds!!! Please!!!!!

In MetaTrader has a similar function 

http://www.mql5.com/en/docs/eventfunctions/eventsetmillisecondtimer 

 


@Invalid

Invalid
11 Jul 2014, 10:41 ( Updated at: 21 Dec 2023, 09:20 )

RE:

Either case normailizedVolume to int or change return type to long

1. 

return (int)normalizedVolume;

2. 

long lotsoptimized(){

RootFX said:

why show Long volume .?

 

 


@Invalid

Invalid
09 Jul 2014, 15:07

RE:

What do you mean live file? updated frequently?

You can check the file in OnTimer method in order to see if there's any change in the Excel File. If so - process these changes.

WinningTrader said:

Invalid,

 

The Excel file is a live file - rates change real time - will EPPLUS still support - 

 


@Invalid

Invalid
09 Jul 2014, 09:50

Hi WinningTrader.

You can use Epplus library to access your data from Excel file. But it should be saved in xlsx format. Here you can find how to read data: http://blog.fryhard.com/archive/2010/10/28/reading-xlsx-files-using-c-and-epplus.aspx

 

 

 


@Invalid

Invalid
27 Jun 2014, 12:37

Hi Balena. It works fine for me. Do you always face this problem? May be you use any special characters?


@Invalid

Invalid
27 Jun 2014, 12:02

Why not to use VS instead of Print?


@Invalid

Invalid
30 May 2014, 17:36

RE: RE: RE: RE:

Try to debug in VS - it will be much faster

breakermind said:

I see this in logs when start cbot when i have no open positions.

I look for it later...or write again from the beginning.

 

 

Invalid said:

Which line gives you this exception?

breakermind said:

if i have open position error gone!

if not a see this above

 

 

 

 


@Invalid

Invalid
30 May 2014, 17:08

Some of your fields are initialized only in specific scenarios. Initialize the field in declaration or change the usage code


@Invalid