Execute code when Take Profit Hit

Created at 28 Aug 2022, 14:20
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!
CT

ctid3999979

Joined 05.07.2021

Execute code when Take Profit Hit
28 Aug 2022, 14:20


Hi

Been looking at the following API reference about using a switch for code execution when a position is closed for various reasons

Is shows Positions.Closed += Position_Closed is in the OnStart() funtion. Doesn't the OnStart() funtion only run when the cBot starts though? Shouldn't I put it on the onTick if I want it run after the cBot has started?

I'm confused when the Position_Closed function runs. I would hope that a Take Profit being hit would just simply be a method in and of itself that you can execute code against in the same way the onBar() is run whenever a new bar is created,

 

Ignore this...Just did some basic testing and its printing output in the log for every trade.


@ctid3999979
Replies

firemyst
29 Aug 2022, 11:15

RE:

ctid3999979 said:

Hi

Been looking at the following API reference about using a switch for code execution when a position is closed for various reasons

Is shows Positions.Closed += Position_Closed is in the OnStart() funtion. Doesn't the OnStart() funtion only run when the cBot starts though? Shouldn't I put it on the onTick if I want it run after the cBot has started?

I'm confused when the Position_Closed function runs. I would hope that a Take Profit being hit would just simply be a method in and of itself that you can execute code against in the same way the onBar() is run whenever a new bar is created,

 

Ignore this...Just did some basic testing and its printing output in the log for every trade.

I know you said "ignore this", but wanted to provide some clarity as it doesn't seem all your original questions had been answered.

> Positions.Closed += Position_Closed is in the OnStart() funtion

This sets up the _event method_ called "Position_Closed" which will be executed everytime the ".Closed" event happens. Eg, when _any_ (and this is very important) position is closed. So if you have a GBPUSD bot instance running and an AUDUSD bot instance running, and an AUDUSD position is closed, the event will fire and both bot instances will execute the "Position_Closed" method. So if you're going to run multiple instances of the same bot, you need to check that the position that was closed is the one related to your bot instance.

And yes, you only want it in your "OnStart" method because it's an event handler, and you register it with the C# runtime, you don't want to keep registering it every time a tick comes through, hence why it's in OnStart and not "OnTick".

 

Hope that helps. :-)

 


@firemyst