# Events

## Events <a href="#events" id="events"></a>

AgenaTrader is an *event-oriented* application by definition.

Programming in AgenaTrader using the various application programming interface (*API*) methods is based initially on the *Overwriting* of routines predefined for event handling.

The following methods can be used and therefore overwritten:

* [*OnBrokerConnect()*](#onbrokerconnect)
* [*OnBrokerDisconnect()*](#onbrokerdisconnect)
* [OnInit()](#oninit)
* [*OnCalculate()*](#oncalculate)
* [*OnChartPanelMouseDown()*](#onchartpanelmousedown)
* [*OnChartPanelMouseMove()*](#onchartpanelmousemove)
* [*OnDispose()*](#ondispose)
* [*OnLevel1()*](#onlevel1)
* [*OnLevel2()*](#onlevel2)
* [*OnOrderChanged()*](#onorderchanged)
* [*OnOrderExecution()*](#onorderexecution)
* [*OnStart()*](#onstart)
* [*OnStop()*](#onstop)

### OnBrokerConnect() <a href="#onbrokerconnect" id="onbrokerconnect"></a>

{% hint style="warning" %}
OnBrokerConnect() is only available for overwriting in **UserStrategies**!
{% endhint %}

#### Description <a href="#description" id="description"></a>

OnBrokerConnect() method is invoked each time the connection to the broker is established. With the help of OnBrokerConnect(), it is possible to reassign the existing or still open orders to the strategy in the event of a connection abort with the broker and thus allow it to be managed again.

More information can be found here: [*Events*.](#events)

#### Parameter <a href="#parameter" id="parameter"></a>

none

#### Usage <a href="#usage" id="usage"></a>

```csharp
protected override void OnBrokerConnect()
```

#### Example <a href="#example" id="example"></a>

```csharp
private IOrder _takeProfit = null;
private IOrder _trailingStop = null;


protected override void OnBrokerConnect()
{
   if (Trade != null && Trade.PositionType != PositionType.Flat)
   {
       _takeProfit = Orders.FirstOrDefault(o => o.Name == this.GetType().Name && o.OrderType ==OrderType.Limit);
       _trailingStop = Orders.FirstOrDefault(o => o.Name == this.GetType().Name && o.OrderType ==OrderType.Stop);
   }
}
```

### OnBrokerDisconnect() <a href="#onbrokerdisconnect" id="onbrokerdisconnect"></a>

{% hint style="warning" %}
OnBrokerDisconnect() is only available for overwriting in **UserStrategies**!
{% endhint %}

#### Description <a href="#description_1" id="description_1"></a>

OnBrokerDisconnect() method is invoked each time the connection to the broker is interrupted.

More information can be found here: [*Events*.](#events)

#### Parameter <a href="#parameter_1" id="parameter_1"></a>

An object from *TradingDatafeedChangedEventArgs*

#### Usage <a href="#usage_1" id="usage_1"></a>

```csharp
protected override void OnBrokerDisconnect(TradingDatafeedChangedEventArgs e)
```

#### Example <a href="#example_1" id="example_1"></a>

```csharp
protected override void OnBrokerDisconnect(TradingDatafeedChangedEventArgs e)
{
   if (e.Connected)
       Print("The connection to the broker will be disconnected.");
   else
       Print("The connection to the broker was disconnected.");
}
```

### OnInit() <a href="#oninit" id="oninit"></a>

#### Description <a href="#description_57" id="description_57"></a>

The OnInit() method is called up once at the beginning of an indicator or strategy calculation. This method can be used to set indicator properties, initialize your own variables, or add plots.

#### Parameter <a href="#parameter_30" id="parameter_30"></a>

none

#### Return Value <a href="#return-value_18" id="return-value_18"></a>

none

#### Usage <a href="#usage_42" id="usage_42"></a>

```csharp
protected override void OnInit()
```

#### Important Keywords <a href="#important-keywords" id="important-keywords"></a>

* [*Add()*](/keywords.md#addoutput)
* [*AllowRemovalOfChartDrawings*](/keywords.md#allowremovalofchartdrawings)
* *IsAutoScale*
* [*RequiredBarsCount*](/keywords.md#requiredbarscount)
* [*CalculateOnClosedBar*](/keywords.md#calculateonclosedbar)
* [*ClearTraceWindow()*](/keywords.md#cleartracewindow)
* [*Displacement*](/keywords.md#displacement)
* [*IsShowInDataBox*](/keywords.md#isshowindatabox)
* [*IsAddDrawingsToPricePanel*](/keywords.md#isadddrawingstopricepanel)
* [*InputPriceType*](/keywords.md#inputpricetype)
* [*IsOverlay*](/keywords.md#isoverlay)
* [*IsShowPriceMarkers*](/keywords.md#isshowpricemarkers)
* [*IsShowChartVerticalGrid*](/keywords.md#isshowchartverticalgrid)

**Additional Keywords for Strategies**

* [*DefaultOrderQuantity*](/strategy-programming.md#defaultorderquantity)
* *EntriesPerDirection*
* [*SetUpStopLoss()*](/strategy-programming.md#setupstoploss)
* [*SetUpProfitTarget()*](/strategy-programming.md#setupprofittarget)
* [*SetUpTrailStop()*](/strategy-programming.md#setuptrailstop)
* [*TimeInForce*](/strategy-programming.md#timeinforce)
* [*TraceOrders*](/strategy-programming.md#traceorders)

#### More Information <a href="#more-information_2" id="more-information_2"></a>

**Caution:** The OnInit() method is not only called up at the beginning of an indicator or strategy calculation, but also if the chart is reloaded unexpectedly or if the properties dialog of indicators is opened and so on. Developers of custom AgenaScripts should NOT use this method for running their own routines, opening forms, performing license checks, etc. The OnStart() method should be used for these kind of tasks.

#### Example <a href="#example_52" id="example_52"></a>

```csharp
protected override void OnInit()
{
AddOutput(new OutputDescriptor(Color.FromKnownColor(KnownColor.Orange), "Output1"));
ClearTraceWindow();
IsAutoScale = false;
IsOverlay = true;
IsShowPriceMarkers = false;
IsShowInDataBox = false;
CalculateOnClosedBar = true;
}
```

### OnCalculate() <a href="#oncalculate" id="oncalculate"></a>

#### Description <a href="#description_2" id="description_2"></a>

The OnCalculate() method is called up whenever a bar changes; depending on the variables of *CalculateOnClosedBar*, this will happen upon every incoming tick or when the bar has completed/closed. OnCalculate is the most important method and also, in most cases, contains the largest chunk of code for your self-created indicators or strategies. The editing begins with the oldest bar and goes up to the newest bar within the chart. The oldest bar has the number 0. The indexing and numbering will continue to happen; in order to obtain the numbering of the bars you can use the current bar variable. You can see an example illustrating this below.

**Caution:** **the numbering/indexing is different from the bar index – see** [***Bars*****.**](/handling-bars-and-instruments/bars.md)

More information can be found here: [*Events*.](#events)

#### Parameter <a href="#parameter_2" id="parameter_2"></a>

none

#### Usage <a href="#usage_2" id="usage_2"></a>

```csharp
protected override void OnCalculate()
```

#### Example <a href="#example_2" id="example_2"></a>

```csharp
protected override void OnCalculate()
{
    Print("Calling of OnCalculate for the bar number " + ProcessingBarIndex + " from " +Time[0]);
}
```

### OnChartPanelMouseDown() <a href="#onchartpanelmousedown" id="onchartpanelmousedown"></a>

#### Description <a href="#description_3" id="description_3"></a>

In an indicator, or strategy, the click event of the mouse can be processed. For this, it is necessary to program an EventHandler as a method and add this method to the Chart.ChartPanelMouseDown event.

#### Attention! <a href="#attention" id="attention"></a>

It is important to remove the EventHandler from the OnDispose() method, otherwise the EventHandler will still be executed even if the indicator has been removed from the chart.

#### Example <a href="#example_3" id="example_3"></a>

```csharp
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Xml;
using System.Xml.Serialization;
using AgenaTrader.API;
using AgenaTrader.Custom;
using AgenaTrader.Plugins;
using AgenaTrader.Helper;


namespace AgenaTrader.UserCode
{
       public class ChartPanelMouseDown : UserIndicator
       {
               protected override void OnInit()
               {
                       IsOverlay = true;
               }

               protected override void OnStart()
               {
                       // Add event listener
                       if (Chart != null)
                               Chart.ChartPanelMouseDown += OnChartPanelMouseDown;
               }


               protected override void OnDispose()
               {
                       // Remove event listener
                       if (Chart != null)
                               Chart.ChartPanelMouseDown -= OnChartPanelMouseDown;
               }


               private void OnChartPanelMouseDown(object sender,System.Windows.Forms.MouseEventArgs e)
               {
                       Print("X = {0}, Y = {1}", Chart.GetDateTimeByX(e.X),Chart.GetPriceByY(e.Y));
               }
       }
}
```

### OnChartPanelMouseMove() <a href="#onchartpanelmousemove" id="onchartpanelmousemove"></a>

#### Description <a href="#description_4" id="description_4"></a>

In an indicator, or strategy, the current position of the mouse can be evaluated and processed. For this, it is necessary to program an EventHandler as a method and add this method to the Chart.ChartPanelMouseMove event.

#### Attention! <a href="#attention_1" id="attention_1"></a>

It is important to remove the EventHandler from the OnDispose() method, otherwise the EventHandler will still be executed even if the indicator has been removed from the chart.

#### Example <a href="#example_4" id="example_4"></a>

```csharp
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Xml;
using System.Xml.Serialization;
using AgenaTrader.API;
using AgenaTrader.Custom;
using AgenaTrader.Plugins;
using AgenaTrader.Helper;


namespace AgenaTrader.UserCode
{
    public class ChartPanelMouseMove : UserIndicator
    {
        protected override void OnInit()
        {
            IsOverlay = true;
        }

        protected override void OnStart()
        {
            // Add event listener
            if (Chart != null)
                Chart.ChartPanelMouseMove += OnChartPanelMouseMove;
        }

        protected override void OnDispose()
        {
            // Remove event listener
            if (Chart != null)
                Chart.ChartPanelMouseMove -= OnChartPanelMouseMove;
        }

        private void OnChartPanelMouseMove(object sender, System.Windows.Forms.MouseEventArgs e)
        {
            Print("X = {0}, Y = {1}", Chart.GetDateTimeByX(e.X), Chart.GetPriceByY(e.Y));
        }
    }
}
```

### OnDispose() <a href="#ondispose" id="ondispose"></a>

#### Description <a href="#description_5" id="description_5"></a>

The OnDispose() method can also be overridden in order to once again free up all the resources used in the script.

See [*OnInit()*](/keywords.md#oninit) and [*OnStart()*.](#onstart)

More information can be found here: [*Events*.](#events)

#### Parameter <a href="#parameter_3" id="parameter_3"></a>

none

#### Usage <a href="#usage_3" id="usage_3"></a>

```csharp
protected override void OnDispose()
```

#### More Information <a href="#more-information" id="more-information"></a>

**Caution:** **Please do not override the Dispose() method since this can only be used much later within the script. This would lead to resources being used and held for an extended period and thus potentially causing unexpected consequences for the entire application.**

#### Example <a href="#example_5" id="example_5"></a>

```csharp
protected override void OnDispose()
{
    if (Window != null)
    {
        Window.Dispose();
        Window = null;
    }
}
```

### OnLevel1() <a href="#onlevel1" id="onlevel1"></a>

#### Description <a href="#description_6" id="description_6"></a>

The OnLevel1() method is called up when a change in level 1 data has occurred, meaning whenever there is a change in the bid price, ask price, bid volume, or ask volume, and of course in the last price after a real turnover has occurred. In a multibar indicator, the rocessingBarSeriesIndex property identifies the data series that was used for an information request for OnLevel1(). OnLevel1() will not be called up for historical data.&#x20;

More information can be found here: [*Events*.](#events)

**Notes regarding data from Yahoo (YFeed)**

The field "LastPrice" equals – as usual – either the bid price or the ask price, depending on the last revenue turnover.

The MarketDataType" field always equals the "last" value

The fields "Volume", "BidSize" and "AskSize" are always 0.

#### Usage <a href="#usage_4" id="usage_4"></a>

```csharp
protected override void OnLevel1(Level1Args e)
```

#### Parameter <a href="#parameter_4" id="parameter_4"></a>

```csharp
[*Level1Args*] e
```

#### Example <a href="#example_6" id="example_6"></a>

```csharp
protected override void OnLevel1(Level1Args e)
{
    Print("AskPrice "+e.AskPrice);
    Print("AskSize "+e.AskSize);
    Print("BidPrice "+e.BidPrice);
    Print("BidSize "+e.BidSize);
    Print("Instrument "+e.Instrument);
    Print("LastPrice "+e.LastPrice);
    Print("MarketDataType "+e.MarketDataType);
    Print("Price "+e.Price);
    Print("Time "+e.Time);
    Print("Volume "+e.Volume);
}
```

### OnLevel2() <a href="#onlevel2" id="onlevel2"></a>

#### Description <a href="#description_7" id="description_7"></a>

The OnLevel2() method is called up whenever there is a change in the level 2 data (market depth). In a multibar indicator, the ProcessingBarSeriesIndex property identifies the data series for which the OnLevel2() method is called up. OnLevel2 is not called up for historical data.

More information can be found here: [*Events*.](#events)

#### Usage <a href="#usage_5" id="usage_5"></a>

```csharp
protected override void OnLevel2(Level2Args e)
```

#### Parameter <a href="#parameter_5" id="parameter_5"></a>

An object from *Level2Args*

#### Example <a href="#example_7" id="example_7"></a>

```csharp
protected override void OnLevel2(Level2Args e)
{
    // Current Bit-Price
    if (e.MarketDataType == MarketDataType.Bit)
        Print("The current bit is " + e.Price );
}
```

### OnOrderChanged() <a href="#onorderchanged" id="onorderchanged"></a>

#### Description <a href="#description_8" id="description_8"></a>

The OnOrderChanged() method is called up whenever the status is changed by a strategy-managed order. A status change can therefore occur due to a change in the volume, price or status of the exchange (from “working” to “filled”). It is guaranteed that this method will be called up in the correct order for the relevant events.

**Important note:** **If a strategy is to be controlled by order executions, we highly recommend that you use OnOrderExecution() instead of OnOrderChanged(). Otherwise there may be problems with partial executions.**

More information can be found here: [*Events*.](#events)

#### Parameter <a href="#parameter_6" id="parameter_6"></a>

An order object of the type IOrder

#### Usage <a href="#usage_6" id="usage_6"></a>

```csharp
protected override void OnOrderChanged(IOrder order)
```

#### Example <a href="#example_8" id="example_8"></a>

```csharp
private IOrder entry = null;
protected override void OnCalculate()
{
    if (CrossAbove(EMA(14), SMA(50), 1) && IsSerieRising(ADX(20)))
        entry = OpenLong("EMACrossesSMA");

    if (entry != null && entry == order)
    {
        if (order.OrderState == OrderState.Filled)
        {
        PlaySound("OrderFilled.wav");
        entryOrder = null;
        }
    }
}
protected override void OnOrderChanged(IOrder order)
{

}
```

### OnOrderExecution() <a href="#onorderexecution" id="onorderexecution"></a>

#### Description <a href="#description_9" id="description_9"></a>

The OnOrderExecution() method is called up when an order is executed (filled). The status of a strategy can be changed by a strategy-managed order. This status change can be initiated by the changing of a volume, price or the status of the exchange (from “working” to “filled”). It is guaranteed that this method will be called up in the correct order for all events.

OnOrderExecution() will always be executed AFTER [*OnOrderChanged()*.](#onorderchanged)

More information can be found here: [*Events*.](#events)

#### Parameter <a href="#parameter_7" id="parameter_7"></a>

An execution object of the type *IExecution*

#### Usage <a href="#usage_7" id="usage_7"></a>

```csharp
protected override void OnOrderExecution(IExecution execution)
```

#### Example <a href="#example_9" id="example_9"></a>

```csharp
private IOrder entry = null;
protected override void OnCalculate()
{
    if (CrossAbove(EMA(14), SMA(50), 1) && IsSerieRising(ADX(20)))
            entry = OpenLong("EMACrossesSMA");
}
protected override void OnOrderExecution(IExecution execution)
{
    // Example
    if (entry != null && execution.Order == entry)
    {
        Print(execution.Price.ToString());
    Print(execution.Order.OrderState.ToString());
    }
}
```

### OnStart() <a href="#onstart" id="onstart"></a>

#### Description <a href="#description_10" id="description_10"></a>

The OnStart() method can be overridden to initialize your own variables, perform license checks or call up user forms etc. OnStart() is only called up once at the beginning of the script, after [*OnInit()* ](/keywords.md#oninit)and before [*OnCalculate()* ](#oncalculate)are called up which results in the following execution sequence:

**OnInit** **OnStart** **OnStop** **OnDispose**

See [*OnDispose()*.](#ondispose)

More information can be found here: [*Events*.](#events)

#### Parameter <a href="#parameter_8" id="parameter_8"></a>

none

#### Usage <a href="#usage_8" id="usage_8"></a>

```csharp
protected override void OnStart()
```

#### Example <a href="#example_10" id="example_10"></a>

```csharp
private myForm Window;
protected override void OnStart()
{
    if (Chart != null)
    {
    Window = new myForm();
    Window.Show();
    }
}
```

### OnStop() <a href="#onstop" id="onstop"></a>

#### Description <a href="#description_11" id="description_11"></a>

The OnStop() method is called up once a script is terminated. This can be when e.g. an indicator was removed from the chart or a column with an indicator / a scripted condition was removed from the scanner.

See [*OnDispose()*.](#ondispose)

More information can be found here: [*Events*.](#events)

#### Parameter <a href="#parameter_9" id="parameter_9"></a>

none

#### Usage <a href="#usage_9" id="usage_9"></a>

```csharp
protected override void OnStop()
```

#### Example <a href="#example_11" id="example_11"></a>

```csharp
protected override void OnStop()
{
    Log("Stop: " + this.ToString() + " | " + Instrument.Symbol, InfoLogLevel.Info);
}
```

<br>


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://script.agenatrader.com/events.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
