Replies

v.fiodorov83
22 Aug 2023, 10:02

RE: How to get n-Bars ago ClosePrices

PanagiotisChar said: 

Hi there,

Try this

            var last50bars = Bars.ClosePrices.Reverse().Take(50);

Aieden Technologies

Need help? Join us on Telegram


 

Thank you! It works as expected


@v.fiodorov83

v.fiodorov83
26 Jul 2023, 14:04 ( Updated at: 21 Dec 2023, 09:23 )

RE: How to use/implement events OnBarClose/Open in cBot

PanagiotisChar said: 

Hi there,

Are you using 4.8.15?

Aieden Technologies

Need help? Join us on Telegram


 

 


@v.fiodorov83

v.fiodorov83
30 Apr 2023, 14:40 ( Updated at: 21 Dec 2023, 09:23 )

Solved

Ive solved this task using canvas

private Canvas _canvas;
private TextBlock _equityTextBlock;
private TextBlock _balanceTextBlock;

protected override void OnStart()
{
_canvas = new Canvas
            {
                HorizontalAlignment = HorizontalAlignment.Right,
                VerticalAlignment = VerticalAlignment.Top,
                Width = 300,
                Height = 200,
                //BackgroundColor = Color.DarkGray,
                Opacity = 0.5
            };

            _equityTextBlock = new TextBlock
            {
                Text = "Account equity: ",
                FontSize = 14,
                Margin = new Thickness(10, 50, 0, 0),
                FontWeight = FontWeight.Normal
            };
            // Create a new TextBlock instance for "Account Balance"

            _balanceTextBlock = new TextBlock
            {
                Text = "Account Balance: ",
                FontSize = 14,
                Margin = new Thickness(10, 70, 0, 0), // we place the inscription below the first inscription
                FontWeight = FontWeight.Normal
            };
            _canvas.AddChild(_balanceTextBlock);
            _canvas.AddChild(_equityTextBlock);
            Chart.AddControl(_canvas);

}

protected override void OnTick()
{

            // get the current value of equity and balance
            var equity = Account.Equity;
            var balance = Account.Balance;

            // update the text block with the new equity and balance value
            _equityTextBlock.Text = $"Account equity: {equity:F2}";
            _balanceTextBlock.Text = $"Account Balance: {balance:F2}";


}


@v.fiodorov83

v.fiodorov83
20 Apr 2023, 17:08

Ohh, thank you all good people. I will try


@v.fiodorov83

v.fiodorov83
04 Nov 2022, 17:23

RE:

Sorry/ Admins, you can delete this post, this is my stupidity because I mixed up the long and short periods in places


@v.fiodorov83

v.fiodorov83
03 Nov 2022, 22:58

RE: RE: https://ctrader.com/forum/calgo-support/39249 have a look here

Alwin123 said:

v.fiodorov83 said: 

Hello!

I want cBot to trade on the m1 timeframe, but make calculations based on the MacdHistogram indicator with the ability to select a timeframe, for example h1


        private MacdHistogram mcd;
     
        private Bars source;



        protected override void OnStart()

        {
            
            source = MarketData.GetBars(TimeFrame.Hour, SymbolName);

            mcd = Indicators.MacdHistogram(source.ClosePrices,shortCycle, longCycle, signalPeriod);
            
        }

I did it. OK. But then, when trying to use the MASD () data in the OnBar and OnTick methods, he doesn't care, he counts by closing the bar of the current timeframe/tick. Seems I need to create some kind of "dancing with a tambourine" so that he, like, waits until 12 M5 bars are collected, for example, in order to calculate the closing price of an hourly bar?

 

Yes. I saw this post, and thats my correct code for this task here in my post - Intitialize on start. But then begins bugs which I described


@v.fiodorov83

v.fiodorov83
14 Jan 2022, 10:27

RE: RE: RE: RE: RE:

Hi,

Can you please post the raw full JSON response, so I will be able to deserialize it on my system and see what's wrong.


If you don't mind, then let's continue our conversation in the telegram, because if I insert data here, it will be just a mess and it will be hard for you to dig into it. In the telegram, I will send you a direct link and you will have a look. And if we manage to fix it, then we will write in this thread of the forum. How do you like this idea?


@v.fiodorov83

v.fiodorov83
13 Jan 2022, 20:17 ( Updated at: 13 Jan 2022, 20:27 )

RE: RE: RE:

amusleh said:

v.fiodorov83 said:

amusleh said:

Hi,

You don't have to use this library for sending alerts to Telegram, you can use the Telegram .NET library that I mentioned on my first post.

You can also code the whole API interaction by yourself, you don't have to use any library, but they will make it much easier for you.

Well, you see, it turns out that if somewhere you have some library or dependency has the wrong version, different in x.x.x.x.1, then all this will not work and find where exactly the problem is unrealistic to find.

Nevertheless, thank you for your help and have a nice day.

Hi,

Telegram.Bot library can't deserialize the conversation updates, because one of the fields that must be integer comes as an empty string.

Either its the error code or the update ID, those are integers.

To find what's causing this issue, open the Telegram Bot API getUpdates on your browser: api.telegram.org/bot<your Bot Token>/getUpdates

Replace "your Bot Token" with your bot token, and post the response here.


 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Well, here's a screenshot for an example. Here is the log of my conversation with the bot and there is also a log of his entry into the group. He has no messages from the terminal or any requests ..

 

What else is interesting. In the "Alerts" window you can write any nonsense in Username/Chanel form, if the token is correct, then it does not display the error "wrong group name or username", and then it also crashes

 

 

 

 

 


@v.fiodorov83

v.fiodorov83
13 Jan 2022, 18:05

RE:

amusleh said:

Hi,

You don't have to use this library for sending alerts to Telegram, you can use the Telegram .NET library that I mentioned on my first post.

You can also code the whole API interaction by yourself, you don't have to use any library, but they will make it much easier for you.

Well, you see, it turns out that if somewhere you have some library or dependency has the wrong version, different in x.x.x.x.1, then all this will not work and find where exactly the problem is unrealistic to find.

Nevertheless, thank you for your help and have a nice day.


@v.fiodorov83

v.fiodorov83
13 Jan 2022, 17:28

RE: RE: RE: RE:

v.fiodorov83 said:

amusleh said:

v.fiodorov83 said:

amusleh said:

Hi,

Just tested it with the code you posted, worked fine on my system, the popup showed up and I got a message on Telegram.

Did you made any kind of change on the code? or you used the same exact posted code?

I noticed the following in the error text. In the very first line of the log

.....Culture=neutral, PublicKeyToken=null]]. The value '    ' cannot be parsed as the type 'Int32'.

It turns out that he passes NULL instead of a token, and then he tries to pass the value "  ", converting it to Int32 (Failed and an error is thrown )

No, that's not the case.

It looks like something is going wrong outside the scope of my code, it's something related to WPF.

I recorded a video that shows it's working fine on my system:

 

I believed you even before you posted your video. ) I will try to run it on another Windows machine.  It's just not clear what needs to be reinstalled, which library

I tried it on a different machine, and even with a different hardware, without success. I also tried to collect the sAlgo file, and run it on other machines, nothing. It seems unrealistic to me. Too uninformative error ((Are there any other ways to connect telegrams for alerts?


@v.fiodorov83

v.fiodorov83
13 Jan 2022, 15:08

RE: RE: RE:

amusleh said:

v.fiodorov83 said:

amusleh said:

Hi,

Just tested it with the code you posted, worked fine on my system, the popup showed up and I got a message on Telegram.

Did you made any kind of change on the code? or you used the same exact posted code?

I noticed the following in the error text. In the very first line of the log

.....Culture=neutral, PublicKeyToken=null]]. The value '    ' cannot be parsed as the type 'Int32'.

It turns out that he passes NULL instead of a token, and then he tries to pass the value "  ", converting it to Int32 (Failed and an error is thrown )

No, that's not the case.

It looks like something is going wrong outside the scope of my code, it's something related to WPF.

I recorded a video that shows it's working fine on my system:

 

I believed you even before you posted your video. ) I will try to run it on another Windows machine.  It's just not clear what needs to be reinstalled, which library


@v.fiodorov83

v.fiodorov83
13 Jan 2022, 13:37

RE:

amusleh said:

Hi,

Just tested it with the code you posted, worked fine on my system, the popup showed up and I got a message on Telegram.

Did you made any kind of change on the code? or you used the same exact posted code?

I noticed the following in the error text. In the very first line of the log

.....Culture=neutral, PublicKeyToken=null]]. The value '    ' cannot be parsed as the type 'Int32'.

It turns out that he passes NULL instead of a token, and then he tries to pass the value "  ", converting it to Int32 (Failed and an error is thrown )


@v.fiodorov83

v.fiodorov83
13 Jan 2022, 12:57

RE:

amusleh said:

Hi,

Just tested it with the code you posted, worked fine on my system, the popup showed up and I got a message on Telegram.

Did you made any kind of change on the code? or you used the same exact posted code?

Weird. I am using exactly the same code. NET Framework 4.5, as you have in the description. Local notifications in the pop-up window appear correctly and without problems. As soon as you enter the name of the telegram channel and the robot token, you press Add, it takes a couple of seconds and everything crashes. I also tried to enter my login and the login of the robot, the same thing


@v.fiodorov83

v.fiodorov83
13 Jan 2022, 12:21

RE:

amusleh said:

Hi,

No, I don't have such a code example, please use the Alert library I posted on my previously.

Read its documentation: Home · afhacker/ctrader-alert_popup Wiki (github.com)

You can send Telegram messages just with one line of code if you use the alert library.

Hello again. Only now I was able to do this and immediately got a crash. It occurs when a message is sent to the bot.

I just took that code from your link. I created a bot exactly according to your instructions. I don’t understand what is the problem? What can't he parse?


2022-01-13 09:51:28 => 
OS Version: Microsoft Windows NT 10.0.19042.0
System Type: 64-bit
Source: System.Runtime.Serialization
Message: There was an error deserializing the object of type TelegramBotApi.Types.ApiResponse`1[[TelegramBotApi.Types.Update[], TelegramBotApi, Version=1.1.3.0, Culture=neutral, PublicKeyToken=null]]. The value '    ' cannot be parsed as the type 'Int32'.
TargetSite: System.Object ReadObjectHandleExceptions(System.Runtime.Serialization.XmlReaderDelegator, Boolean, System.Runtime.Serialization.DataContractResolver)
Type: System.Runtime.Serialization.SerializationException
StackTrace:
    File:  | Line: 0 | Col: 0 | Offset: 129 | Method: System.Object ReadObjectHandleExceptions(System.Runtime.Serialization.XmlReaderDelegator, Boolean, System.Runtime.Serialization.DataContractResolver)
    File:  | Line: 0 | Col: 0 | Offset: 0 | Method: System.Object ReadObject(System.Xml.XmlDictionaryReader)
    File:  | Line: 0 | Col: 0 | Offset: 0 | Method: T Deserialize[T](System.String)
    File:  | Line: 0 | Col: 0 | Offset: 166 | Method: TelegramBotApi.Types.ApiResponse`1[TResponse] MakeRequest[TResponse](TelegramBotApi.Requests.Abstractions.IRequest`1[TResponse])
    File:  | Line: 0 | Col: 0 | Offset: 72 | Method: Void AddTelegramConversation()
    File:  | Line: 0 | Col: 0 | Offset: 81 | Method: Void CriticalExecuteCommandSource(System.Windows.Input.ICommandSource, Boolean)
    File:  | Line: 0 | Col: 0 | Offset: 25 | Method: Void OnClick()
    File:  | Line: 0 | Col: 0 | Offset: 26 | Method: Void OnClick()
    File:  | Line: 0 | Col: 0 | Offset: 83 | Method: Void OnMouseLeftButtonUp(System.Windows.Input.MouseButtonEventArgs)
    File:  | Line: 0 | Col: 0 | Offset: 7 | Method: Void InvokeHandler(System.Delegate, System.Object)
    File:  | Line: 0 | Col: 0 | Offset: 61 | Method: Void InvokeHandler(System.Object, System.Windows.RoutedEventArgs)
    File:  | Line: 0 | Col: 0 | Offset: 230 | Method: Void InvokeHandlersImpl(System.Object, System.Windows.RoutedEventArgs, Boolean)
    File:  | Line: 0 | Col: 0 | Offset: 109 | Method: Void ReRaiseEventAs(System.Windows.DependencyObject, System.Windows.RoutedEventArgs, System.Windows.RoutedEvent)
    File:  | Line: 0 | Col: 0 | Offset: 70 | Method: Void OnMouseUpThunk(System.Object, System.Windows.Input.MouseButtonEventArgs)
    File:  | Line: 0 | Col: 0 | Offset: 7 | Method: Void InvokeHandler(System.Delegate, System.Object)
    File:  | Line: 0 | Col: 0 | Offset: 61 | Method: Void InvokeHandler(System.Object, System.Windows.RoutedEventArgs)
    File:  | Line: 0 | Col: 0 | Offset: 230 | Method: Void InvokeHandlersImpl(System.Object, System.Windows.RoutedEventArgs, Boolean)
    File:  | Line: 0 | Col: 0 | Offset: 87 | Method: Void RaiseEventImpl(System.Windows.DependencyObject, System.Windows.RoutedEventArgs)
    File:  | Line: 0 | Col: 0 | Offset: 20 | Method: Void RaiseTrustedEvent(System.Windows.RoutedEventArgs)
    File:  | Line: 0 | Col: 0 | Offset: 495 | Method: Boolean ProcessStagingArea()
    File:  | Line: 0 | Col: 0 | Offset: 36 | Method: Boolean ProcessInput(System.Windows.Input.InputEventArgs)
    File:  | Line: 0 | Col: 0 | Offset: 53 | Method: Boolean ReportInput(System.Windows.Input.InputReport)
    File:  | Line: 0 | Col: 0 | Offset: 528 | Method: Boolean ReportInput(IntPtr, System.Windows.Input.InputMode, Int32, System.Windows.Input.RawMouseActions, Int32, Int32, Int32)
    File:  | Line: 0 | Col: 0 | Offset: 588 | Method: IntPtr FilterMessage(IntPtr, MS.Internal.Interop.WindowMessage, IntPtr, IntPtr, Boolean ByRef)
    File:  | Line: 0 | Col: 0 | Offset: 84 | Method: IntPtr InputFilterMessage(IntPtr, Int32, IntPtr, IntPtr, Boolean ByRef)
    File:  | Line: 0 | Col: 0 | Offset: 48 | Method: IntPtr WndProc(IntPtr, Int32, IntPtr, IntPtr, Boolean ByRef)
    File:  | Line: 0 | Col: 0 | Offset: 54 | Method: System.Object DispatcherCallbackOperation(System.Object)
    File:  | Line: 0 | Col: 0 | Offset: 119 | Method: System.Object InternalRealCall(System.Delegate, System.Object, Int32)
    File:  | Line: 0 | Col: 0 | Offset: 2 | Method: System.Object TryCatchWhen(System.Object, System.Delegate, System.Object, Int32, System.Delegate)
    File:  | Line: 0 | Col: 0 | Offset: 187 | Method: System.Object LegacyInvokeImpl(System.Windows.Threading.DispatcherPriority, System.TimeSpan, System.Delegate, System.Object, Int32)
    File:  | Line: 0 | Col: 0 | Offset: 304 | Method: IntPtr SubclassWndProc(IntPtr, Int32, IntPtr, IntPtr)
    File:  | Line: 0 | Col: 0 | Offset: -1 | Method: IntPtr DispatchMessage(System.Windows.Interop.MSG ByRef)
    File:  | Line: 0 | Col: 0 | Offset: 64 | Method: Void PushFrameImpl(System.Windows.Threading.DispatcherFrame)
    File:  | Line: 0 | Col: 0 | Offset: 280 | Method: System.Object ShowHelper(System.Object)
    File:  | Line: 0 | Col: 0 | Offset: 492 | Method: System.Nullable`1[System.Boolean] ShowDialog()
    File:  | Line: 0 | Col: 0 | Offset: 13 | Method: Void <Run>b__30_0()
    File:  | Line: 0 | Col: 0 | Offset: 153 | Method: Void Invoke(System.Action, System.Windows.Threading.DispatcherPriority, System.Threading.CancellationToken, System.TimeSpan)
    File:  | Line: 0 | Col: 0 | Offset: 28 | Method: Void Invoke(System.Action)
    File:  | Line: 0 | Col: 0 | Offset: 81 | Method: Void <ShowPopup>b__0()



    InnerException:
    Source: System.Runtime.Serialization
    Message: The value '    ' cannot be parsed as the type 'Int32'.
    TargetSite: Int32 ParseInt(System.String, System.Globalization.NumberStyles)
    Type: System.Xml.XmlException
    StackTrace:
        File:  | Line: 0 | Col: 0 | Offset: 40 | Method: Int32 ParseInt(System.String, System.Globalization.NumberStyles)
        File:  | Line: 0 | Col: 0 | Offset: 0 | Method: Char ParseChar(System.String, System.Globalization.NumberStyles)
        File:  | Line: 0 | Col: 0 | Offset: 83 | Method: Void ReadEscapedCharacter(Boolean)
        File:  | Line: 0 | Col: 0 | Offset: 346 | Method: Boolean Read()
        File:  | Line: 0 | Col: 0 | Offset: 207 | Method: System.String ReadContentAsString(Int32)
        File:  | Line: 0 | Col: 0 | Offset: 53 | Method: System.String ReadElementContentAsString()
        File:  | Line: 0 | Col: 0 | Offset: -1 | Method: System.Object ReadUserFromJson(System.Runtime.Serialization.XmlReaderDelegator, System.Runtime.Serialization.Json.XmlObjectSerializerReadContextComplexJson, System.Xml.XmlDictionaryString, System.Xml.XmlDictionaryString[])
        File:  | Line: 0 | Col: 0 | Offset: 7 | Method: System.Object ReadJsonValueCore(System.Runtime.Serialization.XmlReaderDelegator, System.Runtime.Serialization.Json.XmlObjectSerializerReadContextComplexJson)
        File:  | Line: 0 | Col: 0 | Offset: 16 | Method: System.Object ReadJsonValue(System.Runtime.Serialization.XmlReaderDelegator, System.Runtime.Serialization.Json.XmlObjectSerializerReadContextComplexJson)
        File:  | Line: 0 | Col: 0 | Offset: 0 | Method: System.Object ReadDataContractValue(System.Runtime.Serialization.DataContract, System.Runtime.Serialization.XmlReaderDelegator)
        File:  | Line: 0 | Col: 0 | Offset: 631 | Method: System.Object InternalDeserialize(System.Runtime.Serialization.XmlReaderDelegator, System.String, System.String, System.Type, System.Runtime.Serialization.DataContract ByRef)
        File:  | Line: 0 | Col: 0 | Offset: 49 | Method: System.Object InternalDeserialize(System.Runtime.Serialization.XmlReaderDelegator, Int32, System.RuntimeTypeHandle, System.String, System.String)
        File:  | Line: 0 | Col: 0 | Offset: -1 | Method: System.Object ReadMessageFromJson(System.Runtime.Serialization.XmlReaderDelegator, System.Runtime.Serialization.Json.XmlObjectSerializerReadContextComplexJson, System.Xml.XmlDictionaryString, System.Xml.XmlDictionaryString[])
        File:  | Line: 0 | Col: 0 | Offset: 7 | Method: System.Object ReadJsonValueCore(System.Runtime.Serialization.XmlReaderDelegator, System.Runtime.Serialization.Json.XmlObjectSerializerReadContextComplexJson)
        File:  | Line: 0 | Col: 0 | Offset: 16 | Method: System.Object ReadJsonValue(System.Runtime.Serialization.XmlReaderDelegator, System.Runtime.Serialization.Json.XmlObjectSerializerReadContextComplexJson)
        File:  | Line: 0 | Col: 0 | Offset: 0 | Method: System.Object ReadDataContractValue(System.Runtime.Serialization.DataContract, System.Runtime.Serialization.XmlReaderDelegator)
        File:  | Line: 0 | Col: 0 | Offset: 631 | Method: System.Object InternalDeserialize(System.Runtime.Serialization.XmlReaderDelegator, System.String, System.String, System.Type, System.Runtime.Serialization.DataContract ByRef)
        File:  | Line: 0 | Col: 0 | Offset: 49 | Method: System.Object InternalDeserialize(System.Runtime.Serialization.XmlReaderDelegator, Int32, System.RuntimeTypeHandle, System.String, System.String)
        File:  | Line: 0 | Col: 0 | Offset: -1 | Method: System.Object ReadUpdateFromJson(System.Runtime.Serialization.XmlReaderDelegator, System.Runtime.Serialization.Json.XmlObjectSerializerReadContextComplexJson, System.Xml.XmlDictionaryString, System.Xml.XmlDictionaryString[])
        File:  | Line: 0 | Col: 0 | Offset: 7 | Method: System.Object ReadJsonValueCore(System.Runtime.Serialization.XmlReaderDelegator, System.Runtime.Serialization.Json.XmlObjectSerializerReadContextComplexJson)
        File:  | Line: 0 | Col: 0 | Offset: 16 | Method: System.Object ReadJsonValue(System.Runtime.Serialization.XmlReaderDelegator, System.Runtime.Serialization.Json.XmlObjectSerializerReadContextComplexJson)
        File:  | Line: 0 | Col: 0 | Offset: 0 | Method: System.Object ReadDataContractValue(System.Runtime.Serialization.DataContract, System.Runtime.Serialization.XmlReaderDelegator)
        File:  | Line: 0 | Col: 0 | Offset: 631 | Method: System.Object InternalDeserialize(System.Runtime.Serialization.XmlReaderDelegator, System.String, System.String, System.Type, System.Runtime.Serialization.DataContract ByRef)
        File:  | Line: 0 | Col: 0 | Offset: 49 | Method: System.Object InternalDeserialize(System.Runtime.Serialization.XmlReaderDelegator, Int32, System.RuntimeTypeHandle, System.String, System.String)
        File:  | Line: 0 | Col: 0 | Offset: -1 | Method: System.Object ReadArrayOfUpdateFromJson(System.Runtime.Serialization.XmlReaderDelegator, System.Runtime.Serialization.Json.XmlObjectSerializerReadContextComplexJson, System.Xml.XmlDictionaryString, System.Xml.XmlDictionaryString, System.Runtime.Serialization.CollectionDataContract)
        File:  | Line: 0 | Col: 0 | Offset: 55 | Method: System.Object ReadJsonValueCore(System.Runtime.Serialization.XmlReaderDelegator, System.Runtime.Serialization.Json.XmlObjectSerializerReadContextComplexJson)
        File:  | Line: 0 | Col: 0 | Offset: 16 | Method: System.Object ReadJsonValue(System.Runtime.Serialization.XmlReaderDelegator, System.Runtime.Serialization.Json.XmlObjectSerializerReadContextComplexJson)
        File:  | Line: 0 | Col: 0 | Offset: 0 | Method: System.Object ReadDataContractValue(System.Runtime.Serialization.DataContract, System.Runtime.Serialization.XmlReaderDelegator)
        File:  | Line: 0 | Col: 0 | Offset: 631 | Method: System.Object InternalDeserialize(System.Runtime.Serialization.XmlReaderDelegator, System.String, System.String, System.Type, System.Runtime.Serialization.DataContract ByRef)
        File:  | Line: 0 | Col: 0 | Offset: 49 | Method: System.Object InternalDeserialize(System.Runtime.Serialization.XmlReaderDelegator, Int32, System.RuntimeTypeHandle, System.String, System.String)
        File:  | Line: 0 | Col: 0 | Offset: -1 | Method: System.Object ReadApiResponseOfArrayOfUpdateGM0objc9FromJson(System.Runtime.Serialization.XmlReaderDelegator, System.Runtime.Serialization.Json.XmlObjectSerializerReadContextComplexJson, System.Xml.XmlDictionaryString, System.Xml.XmlDictionaryString[])
        File:  | Line: 0 | Col: 0 | Offset: 7 | Method: System.Object ReadJsonValueCore(System.Runtime.Serialization.XmlReaderDelegator, System.Runtime.Serialization.Json.XmlObjectSerializerReadContextComplexJson)
        File:  | Line: 0 | Col: 0 | Offset: 16 | Method: System.Object ReadJsonValue(System.Runtime.Serialization.XmlReaderDelegator, System.Runtime.Serialization.Json.XmlObjectSerializerReadContextComplexJson)
        File:  | Line: 0 | Col: 0 | Offset: 0 | Method: System.Object ReadDataContractValue(System.Runtime.Serialization.DataContract, System.Runtime.Serialization.XmlReaderDelegator)
        File:  | Line: 0 | Col: 0 | Offset: 631 | Method: System.Object InternalDeserialize(System.Runtime.Serialization.XmlReaderDelegator, System.String, System.String, System.Type, System.Runtime.Serialization.DataContract ByRef)
        File:  | Line: 0 | Col: 0 | Offset: 44 | Method: System.Object InternalDeserialize(System.Runtime.Serialization.XmlReaderDelegator, System.Type, System.Runtime.Serialization.DataContract, System.String, System.String)
        File:  | Line: 0 | Col: 0 | Offset: 213 | Method: System.Object InternalReadObject(System.Runtime.Serialization.XmlReaderDelegator, Boolean)
        File:  | Line: 0 | Col: 0 | Offset: 116 | Method: System.Object ReadObjectHandleExceptions(System.Runtime.Serialization.XmlReaderDelegator, Boolean, System.Runtime.Serialization.DataContractResolver)



        InnerException:
        Source: mscorlib
        Message: Input string was not in a correct format.
        TargetSite: Void StringToNumber(System.String, System.Globalization.NumberStyles, NumberBuffer ByRef, System.Globalization.NumberFormatInfo, Boolean)
        Type: System.FormatException
        StackTrace:
            File:  | Line: 0 | Col: 0 | Offset: 92 | Method: Void StringToNumber(System.String, System.Globalization.NumberStyles, NumberBuffer ByRef, System.Globalization.NumberFormatInfo, Boolean)
            File:  | Line: 0 | Col: 0 | Offset: 32 | Method: Int32 ParseInt32(System.String, System.Globalization.NumberStyles, System.Globalization.NumberFormatInfo)
            File:  | Line: 0 | Col: 0 | Offset: 0 | Method: Int32 ParseInt(System.String, System.Globalization.NumberStyles)

And here is the source code:

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

using cAlgo.API.Alert.Utility;

namespace cAlgo.Robots
{
    [Robot(TimeZone = TimeZones.UTC, AccessRights = AccessRights.FullAccess)]
    public class Alerttester : Robot
    {
        [Parameter(DefaultValue = 0.0)]
        public double Parameter { get; set; }
        private int _barIndex;
        protected override void OnStart()
        {
            // Optional, if you want to see the alert library logs on cTrader logs tab then set this
            Logger.Tracer = Print;
        }
        protected override void OnBar()
        {
            int index = Bars.ClosePrices.Count - 1;
            if (_barIndex != index)
            {
                _barIndex = index;

                TradeType tradeType = Bars.ClosePrices[index - 1] > Bars.OpenPrices[index - 1] ? TradeType.Buy : TradeType.Sell;

                Notifications.ShowPopup(Bars.TimeFrame, Symbol, tradeType, "AlertTest cBot", Symbol.Bid, "No comment", Server.Time);
            }
        }
        protected override void OnTick()
        {
            // Put your core logic here
        }

        protected override void OnStop()
        {
            // Put your deinitialization logic here
        }
    }
}

 


@v.fiodorov83

v.fiodorov83
21 Dec 2021, 13:57

RE: Thanks! Maybe you just have a piece of working code that you post here, and I'll just replace your data with mine?

amusleh said:

Hi,

You can use Telegram API on your indicators/cBots, you can implement the API in .NET by your self or I recommend you to use the popular Telegram.Bot library: TelegramBots/Telegram.Bot: .NET Client for Telegram Bot API (github.com)

If you are looking for an example or a quick way you can use this library: afhacker/ctrader-alert_popup: Alert Popup For cTrader (github.com)

 


@v.fiodorov83

v.fiodorov83
19 Dec 2021, 23:05

RE: Sorry for taking so long to answer. But everything works, thanks for the help !

amusleh said:

Hi,

Try this:

using cAlgo.API;
using cAlgo.API.Indicators;
namespace cAlgo.Robots
{
    [Robot(TimeZone = TimeZones.UTC, AccessRights = AccessRights.None)]
    public class ExponentialMovingAverageSample : Robot
    {
        private ExponentialMovingAverage _ema;

        protected override void OnStart()
        {
            _ema = Indicators.ExponentialMovingAverage(Bars.ClosePrices, 20);
        }
        protected override void OnBar()
        {
            // This variable will have the cross price if there was any
            double maCrossPoint = double.NaN;
            
            // Bar close price crosses MA upward
            if (Bars.ClosePrices.Last(1) > _ema.Result.Last(1) && Bars.ClosePrices.Last(2) < _ema.Result.Last(2))
            {
                maCrossPoint = _ema.Result.Last(1);
            }
            // Bar close price crosses MA downward
            else if (Bars.ClosePrices.Last(1) < _ema.Result.Last(1) && Bars.ClosePrices.Last(2) > _ema.Result.Last(2))
            {
                maCrossPoint = _ema.Result.Last(1);
            }
        }
    }
}

 

 


@v.fiodorov83

v.fiodorov83
29 Sep 2021, 14:19 ( Updated at: 29 Sep 2021, 17:13 )

RE:

amusleh said:

Hi,

Try this:

using System;
using cAlgo.API;

namespace cAlgo
{
    [Indicator(IsOverlay = false, TimeZone = TimeZones.UTC, AccessRights = AccessRights.None)]
    public class NewIndicator : Indicator
    {
        protected override void Initialize()
        {
        }

        public override void Calculate(int index)
        {
            if (!IsLastBar) return;

            // Returns the min/max of last 10 bars
            var minMax = GetMinMax(Bars.OpenTimes[index - 10], Bars.OpenTimes[index]);

            Print("Min: {0} | Max: {1}", minMax.Item1, minMax.Item2);
        }

        /// <summary>
        /// Returns the minimum/maximum prices levels during an specific time period
        /// </summary>
        /// <param name="startTime">Start Time (Inclusive)</param>
        /// <param name="endTime">End Time (Inclusive)</param>
        /// <returns>Tuple<double, double> (Item1 will be minimum price and Item2 will be maximum price)</returns>
        private Tuple<double, double> GetMinMax(DateTime startTime, DateTime endTime)
        {
            var min = double.MaxValue;
            var max = double.MinValue;

            for (int barIndex = 0; barIndex < Bars.Count; barIndex++)
            {
                var bar = Bars[barIndex];

                if (bar.OpenTime < startTime || bar.OpenTime > endTime)
                {
                    if (bar.OpenTime > endTime) break;

                    continue;
                }

                min = Math.Min(min, bar.Low);
                max = Math.Max(max, bar.High);
            }

            return new Tuple<double, double>(min, max);
        }
    }
}

You have the full historical bars data of your chart time frame, and you can iterate over it to find highs/lows.

Thanks for your example. But it looks like an indicator. How can I use this class or data type MyIndicator in the body of my cBot? For example - use the obtained min, max values for opening positions from these levels?


@v.fiodorov83

v.fiodorov83
14 Sep 2021, 17:38

RE:

amusleh said:

There are Filled, Modified, and Canceled events for PendingOrders you can use, and there are similar events of positions like Closed, Modified, and Opened.

Thanks. Apparently I'll have to write a counter. If the buy-stop is full, then the counter will be 1, and a new buy-stop will open if the counter is 0


@v.fiodorov83

v.fiodorov83
13 Sep 2021, 13:15

RE:

amusleh said:

Hi,

You have to give the amount of time of that time frame and then you can check the amount of time passed since the bar opened:

using cAlgo.API;
using System;
using System.Globalization;

namespace cAlgo.Robots
{
    [Robot(TimeZone = TimeZones.UTC, AccessRights = AccessRights.None)]
    public class Test : Robot
    {
        private TimeSpan _barsTimeDiff;

        [Parameter("Bars Time Diff", DefaultValue = "04:00:00")]
        public string BarsTimeDiff { get; set; }

        protected override void OnStart()
        {
            if (!TimeSpan.TryParse(BarsTimeDiff, CultureInfo.InvariantCulture, out _barsTimeDiff))
            {
                Print("Invalid Bars Time Diff");
            }
            else
            {
                // Subtract 1 minute from your provided time amount
                _barsTimeDiff -= TimeSpan.FromMinutes(-1);

                Timer.Start(1);
            }
        }

        protected override void OnTimer()
        {
            Timer.Stop();

            foreach (var position in Positions)
            {
                var positionEntryBarIndex = Bars.OpenTimes.GetIndexByTime(position.EntryTime);

                // You can add more close conditions on this if statment if you want to by using && and ||
                if (Server.Time >= Bars.OpenTimes[positionEntryBarIndex].Add(_barsTimeDiff))
                {
                    ClosePosition(position);
                }
            }

            Timer.Start(1);
        }
    }
}

Ohh, cool!) Thank you. It woks!

Can I use a hardcoded parameter like (GetCurrentTimeFrime) instead of the user input 04:00:00? So that this timer is taken based on the currently selected timeframe on the chart.

[Parameter("Bars Time Diff", DefaultValue = "04:00:00")]
        public string BarsTimeDiff { get; set; }

@v.fiodorov83

v.fiodorov83
09 Sep 2021, 13:38

RE:

amusleh said:

Hi,

You can use timer and check if the position entry bar is closed or not, if a new bar is opened then you can close your position, here is an example:

using cAlgo.API;

namespace cAlgo.Robots
{
    [Robot(TimeZone = TimeZones.UTC, AccessRights = AccessRights.None)]
    public class Test : Robot
    {
        protected override void OnStart()
        {
            Timer.Start(1);
        }

        protected override void OnTimer()
        {
            Timer.Stop();

            var index = Bars.Count - 1;

            foreach (var position in Positions)
            {
                var positionEntryBarIndex = Bars.OpenTimes.GetIndexByTime(position.EntryTime);

                if (positionEntryBarIndex < index)
                {
                    ClosePosition(position);
                }
            }

            Timer.Start(1);
        }
    }
}

It iterates over all of your open positions every second.

Great thanks!

Almost everything works, but Can I add a conditions?

1. I have the logic of closing positions at a specific price also inside the current H4 candlestick, in the OnTick () method. And now they are ignored and only closed by timer

2. How to make the position close exactly at the end of the candle at 03:59:59, and not at the beginning of the next one. The problem is that the next one can open with a gap.


@v.fiodorov83