Need help with a piece of code regarding Account.Equity

Created at 23 Mar 2013, 21:00
How’s your experience with the cTrader Platform?
Your feedback is crucial to cTrader's development. Please take a few seconds to share your opinion and help us improve your trading experience. Thanks!
kricka's avatar

kricka

Joined 13.03.2013

Need help with a piece of code regarding Account.Equity
23 Mar 2013, 21:00


 

Hi, need help with a piece of code regarding Account.Equity.

If Account.Equity reach a certain amount in a variable and then retrace to a variable that has less value it will close all positions and cancel all orders and stop the robot and other robots running.

Variable

target2   =   10.300.00       When "target2" hits and retrace to "stopout2", close all positions, orders and stop  the robot and other robots.                                                          

stopout2  =   9.500.00   

target1   =   10.100.00       When "target1" hits and retrace to "stopout1", before reaching "target2" close all positions, orders and stop  the robot and other robots

stopout1  =   9.000.00   

Account Equity 10.000.00 when the robot starts.

 

Thanks, if you can help me with this.


@kricka
Replies

cAlgo_Fanatic
26 Mar 2013, 17:49

It will be possible to close all positions and stop the robot but not other robots.

Set a flag(bool) assigned true when the equity reaches the target and if that flag is true check if the equity reached the stopout.
Please clarify the relationship between the two targets/stopouts, are you just giving two different examples?

@cAlgo_Fanatic

kricka
28 Mar 2013, 08:07

Hi,

thanks for your quick reply. 

The scenario I describe is in the same code, trying to lock in profits and limit drawdowns on different levels, when it comes to account protection.

This is what the code looks like but I  cannot get it to work the way it should. Hope you have some ideas how to code it right.


bool targetlevel1 = Account.Equity >= target1; bool targetlevel2 = Account.Equity >= target2; if ( targetlevel1 == true && Account.Equity <= stopout1 ) if (targetlevel2 == true && Account.Equity <= stopout2 ) { Trade.Close(position); } } } }




@kricka

cAlgo_Fanatic
28 Mar 2013, 11:50

Try this and let us know if it is what you are intending:

        protected override void OnTick()
        {
            //Reached targetStop2
            if(targetStop2)
                Trade.Close(position);
            else if(targetlevel2)
                targetStop2 = Account.Equity <= Stopout2;
            else if(targetStop1)
                targetlevel2 = Account.Equity >= Target2;
            else if(targetlevel1)
                targetStop1 = Account.Equity <= Stopout1;
            else
                targetlevel1 = Account.Equity >= Target1;
        }




@cAlgo_Fanatic

kricka
29 Mar 2013, 08:36

Hi,

I tried the above code and it gave alot of error messages. Tried also different ELSE IF and could not get any to work.

Maybe ELSE IF is not kompatible with cAlgo. Anyways maybe you have some other ways to get around the else if.  

Thanks...


@kricka

cAlgo_Fanatic
29 Mar 2013, 10:04

The boolean variables need to be declared on an outer scope. 

I probably misunderstood the logic intended. Please try this code:

 

private bool targetlevel1;
private bool targetlevel2;
//...

protected override void OnTick()
{
    if (Account.Equity >= Target1)
        targetlevel1 = true;
    if (Account.Equity >= Target2)
        targetlevel2 = true;

    if (targetlevel1 && Account.Equity <= Stopout1)
    {
        Trade.Close(position);
    }

    if (targetlevel2 && Account.Equity <= Stopout2)
    {
        Trade.Close(position);
    }
}

 

 


@cAlgo_Fanatic

kricka
29 Mar 2013, 23:36

Hi,

I'm working on somehing very close to your latest suggestion and after the weekend when the market is in full action again I'll have a chance to test it out. Just one thought though. The Target1 and Target2 needs only to be fullfilled once to be "True". Then the purpose of the bool maybe needs to be broken to save the first "True" as a fact. A break of the loop maybe be the right answer at that time, continuing  the looop will give it a "False" statement before reaching the Stopout1 and Stopout2. Hope you understand my logic.. :).

Thanks you for you support so far, just great in my opinion!

 


@kricka

kricka
02 Apr 2013, 01:47

Hi,

I've tried the different suggestion during the long weekend and so far I have not been able to get it working to my satisfaction.

Maybe by renaming the Target1 and Target2 to "Trigger1" and "Trigger2" will make it more clear what I'm after, namely when some of these triggers is hit the Stopout1 and Stopout2 will come in action. The triggers are not a means to close the positions, just a trigger that when hit  and then retrace to Stopout1 and Stopout2, they will take care of closing the positions.

Thanks..


@kricka

cAlgo_Fanatic
02 Apr 2013, 11:07

Hello,

Thank you for your kind words.

If it hits Trigger1, it will close positions if it retraces to Stopout1 before it reaches Trigger2. 
If it hits Trigger2, without/before retracing to Stopout1, close all positions if it retraces to Stopout2.
If this is correct then you are correct, you would have to set Trigger1 to false if Trigger2 becomes true.

private bool targetlevel1;
private bool targetlevel2;
//...

protected override void OnTick()
{
    if (Account.Equity >= Target1)
        targetlevel1 = true;
    if (Account.Equity >= Target2)
    {
        targetlevel2 = true;
        targetlevel1 = false;
    }
    if (targetlevel2 && Account.Equity <= Stopout2)
    {
        Trade.Close(position);
    }
    else if (targetlevel1 && Account.Equity <= Stopout1)
    {
        Trade.Close(position);
    }
}




@cAlgo_Fanatic

kricka
03 Apr 2013, 01:13

Hi, I will respond to your last logic with these lines.

 

1.Going through or equal to "Trigger1", it will close the positions if it retraces to "Stopout1" before it reaches "Trigger2". close all positions at Stopout1, 100% correct.

2. Going through "Trigger1" without retracing to "Stopout1" and going through or equal to "Trigger2" then retracing to Stopout2, close all positions at Stopout2.

 

Tried the latest code suggestion and I do get 2 error message saying.

A local variable that has not been submittet is used: targetlevel1

A local variable that has not been submittet is used: targetlevel2

On these 2 lines in the code:

bool targetlevel1; 

bool targetlevel2;

If I use private I'll get maybe 10 error messages.

The following code works though and can compile without errors but the code then is not carring out the stopouts.

bool targetlevel1 = (Account.Equity >= Target1);

bool targetlevel2 = (Account.Equity >= Target2);

 

Hope you have some more ideas of writing the code.

If I just use one line of code like: if (Account.Equity <= Stopout1) it works 100%, so my code before this instance is correct.

Thanks..


@kricka

cAlgo_Fanatic
04 Apr 2013, 16:04

Those  variables need to be declared in the outer scope:

for instance:

namespace cAlgo.Robots
{
    [Robot]
    public class NewRobot : Robot
    {
        private Position position;
        private bool targetlevel1;
        private bool targetlevel2;

        [Parameter]
        public double Target1 { get; set; }

        [Parameter]
        public double Stopout1 { get; set; }

        [Parameter]
        public double Target2 { get; set; }

        [Parameter]
        public double Stopout2 { get; set; }

        protected override void OnStart()
        {
            Trade.CreateBuyMarketOrder(Symbol, 10000);
        }

        protected override void OnTick()
        {
            if (Account.Equity >= Target1)
                targetlevel1 = true;
            if (Account.Equity >= Target2)
                targetlevel2 = true;

            if (targetlevel2 && Account.Equity <= Stopout2)
                Trade.Close(position);
            else if (targetlevel1 && Account.Equity <= Stopout1)
                Trade.Close(position);
        }

        protected override void OnPositionOpened(Position openedPosition)
        {
            position = openedPosition;
        }

        protected override void OnPositionClosed(Position closedPosition)
        {
            Stop();
        }
    }
}
 

@cAlgo_Fanatic

kricka
09 Apr 2013, 23:10

Hi,

I have implented the above code suggestions and after a few modification to fit my code and after some trial and erros, I got it to work in the backtesting. I also have tested in in rela time and it worked as well there too. Thanks for understanding my logic! Excellent coding from your side!

I have  a question about traling the Account..Equity if that is possible. I'll Give you my logic below.

if (Account.Equity >= Target3)

trail the Account..Equity with the distance of the variable in "traildistance". With other words it will trail up with Account..Equity until it will retrace and then the "traildistance" will stop out and close positions.

Thanks once again for your superb support!

 


@kricka

cAlgo_Fanatic
10 Apr 2013, 14:55

So, for instance if Target3 = 50100 and TrailDistance = 200

Start:      equity = 50000
Trigger:   equity = 50100
Trail:       equity = 50300
Trail:       equity = 50500
Retrace: equity = 50300

If the above is correct please, try this code:

protected override void OnTick()
{
    if (!isTriggered)
    {
        if( Account.Equity >= Target3)
        {
            isTriggered = true;
            trailingEquity = Account.Equity;
            Print("Triggered at {0}", Account.Equity);                                    
        }
    }        
    else 
    {
        if (Account.Equity - trailingEquity >= TrailDistance)
        {
            trailingEquity = Account.Equity;
            Print("Trailing Equity {0}", trailingEquity);                    
        }
        else if (Account.Equity - trailingEquity <= -TrailDistance)
        {
            Print("Retraced equity = {0}", Account.Equity);
            Trade.Close(position);
        }
    }
}



 

 

 


@cAlgo_Fanatic

kricka
18 Apr 2013, 21:03

Hi,

the above is correct but I could not get the code itself to work. got the first to print to log ok.

Print("Triggered at {0}", Account.Equity);

the logic in the code seems to be right but only the first piece is triggered.

 

protected override void OnTick()
{
    if (!isTriggered)
    {
        if( Account.Equity >= Target3)
        {
            isTriggered = true;
            trailingEquity = Account.Equity;
            Print("Triggered at {0}", Account.Equity);                                    
        }
    } 

Hope you have some more suggestions. Thanks..


@kricka

cAlgo_Fanatic
19 Apr 2013, 18:04 ( Updated at: 21 Dec 2023, 09:20 )

Please show us an example of your results.

These are the results in our backtesting:


@cAlgo_Fanatic

kricka
20 Apr 2013, 05:26

Hi,

your backtesting result sounds promising. Why do I not get the same result? Please give me your complete code.

Thanks..


@kricka

cAlgo_Fanatic
22 Apr 2013, 09:53

    public class NewRobot : Robot
    {
        private bool isTriggered;
        private Position position;
        private double trailingEquity;

        [Parameter(DefaultValue = 50100)]
        public double Target3 { get; set; }

        [Parameter(DefaultValue = 200)]
        public double TrailDistance { get; set; }


        protected override void OnStart()
        {
            Trade.CreateBuyMarketOrder(Symbol, 100000);
        }

        protected override void OnTick()
        {
            if (!isTriggered)
            {
                if (Account.Equity >= Target3)
                {
                    isTriggered = true;
                    trailingEquity = Account.Equity;
                    Print("Triggered at {0}", Account.Equity);
                }
            }
            else
            {
                if (Account.Equity - trailingEquity >= TrailDistance)
                {
                    trailingEquity = Account.Equity;
                    Print("Trailing Equity {0}", trailingEquity);
                }
                else if (Account.Equity - trailingEquity <= -TrailDistance)
                {
                    Print("Retraced equity = {0}", Account.Equity);
                    Trade.Close(position);
                }
            }
        }

        protected override void OnPositionOpened(Position openedPosition)
        {
            position = openedPosition;
        }

        protected override void OnPositionClosed(Position closedPosition)
        {
            Stop();
        }
    }

 


@cAlgo_Fanatic

kricka
24 Apr 2013, 00:10

Hi,

thanks for the complete code. I've implanted it and tested it for several days, and came to this conclusion, it works perfectly! 

Great coding for sure! 

Thanks..

 


@kricka

kricka
05 Nov 2013, 01:00

Hi,

if I would like the draw text to be static on the screen when the if statement have been true once, even if it retrace under the true statement. Whats the right code?

if (Account.Equity >= Target1)
                    {
                        targetlevel1 = true;
                        if (targetlevel1 && Account.Equity >= Target1)
                            ChartObjects.DrawText(" Level reached: ",  + levelreached, StaticPosition.TopLeft, Colors.Red);
                    }

Thanks..


@kricka

Spotware
05 Nov 2013, 17:04

If this is correct:

  • Call the method DrawText once, when the targetlevel1 is set to true
  • Set the targetlevel1 to true if it is false and equity >= Target1 
  • Do not reset targetlevel1  back to false if the equity falls below the Target1. 

Then the code should be:

if (!targetlevel1 && Account.Equity >= Target1)
{
    targetlevel1 = true;
    ChartObjects.DrawText("objectName", " Level reached: {0}" + levelreached, StaticPosition.TopLeft, Colors.Red);
}

 


@Spotware

kricka
06 Nov 2013, 01:29

RE:

Spotware said:

If this is correct:

  • Call the method DrawText once, when the targetlevel1 is set to true
  • Set the targetlevel1 to true if it is false and equity >= Target1 
  • Do not reset targetlevel1  back to false if the equity falls below the Target1. 

Then the code should be:

if (!targetlevel1 && Account.Equity >= Target1)
{
    targetlevel1 = true;
    ChartObjects.DrawText("objectName", " Level reached: {0}" + levelreached, StaticPosition.TopLeft, Colors.Red);
}

 

Tried it but it does not work..nothing printed.

When the "targetlevel1" is reached the draw text should be printed on the screen and stay there permanently, even if equity retrace below "targetlevel1".

Any more ideas how to solve it?


@kricka

atrader
07 Nov 2013, 17:55

Are you trying to print to the log or draw text on the chart?
Once you draw something on the chart with ChartObjects it will stay on the screen unless you call RemoveObject or RemoveAllObjects. 
If it didn't work it means the equity didn't reach the target or you set the bool targetlevel1 to true previously in the code.


@atrader

kricka
07 Nov 2013, 19:10

RE:

atrader said:

Are you trying to print to the log or draw text on the chart?
Once you draw something on the chart with ChartObjects it will stay on the screen unless you call RemoveObject or RemoveAllObjects. 
If it didn't work it means the equity didn't reach the target or you set the bool targetlevel1 to true previously in the code.

Thanks atrader for your input.

I'm drawing text on the chart and as you said it should stay on the chart visible when the "targetlevel1" is true but when it turns to false it vanish from the chart. Which in it self it should.

The problem I'm having is I want it to be true even if it turn false, later on. When it comes to the targetlevel1 not reached, its reached 100%.


@kricka

kricka
07 Nov 2013, 19:24

Whats makes it somewhat complicated is that I have several "targetlevels" not just one.

 


@kricka