# AgenaScript - Let's start

### Welcome to the official AgenaScript documentation!&#x20;

Want to learn more about the AgenaTrader scripting language? We've got the resources to help you get started. Start by browsing the documentation on the list below.


# Introductory Words

AgenaScript is AgenaTrader’s integrated programming language. The syntax is derived from C# and thus closely resembles it.&#x20;

Because AgenaScript is part of AgenaTrader

The C# programming language is under constant improvement and development. Every year a new C# version will be relased by Microsoft. AgenaScript is based on the language version C# 7.3, so code words, functions and structures from C# 8 onwards are not yet possible.

AgenaScript allows you to execute any ideas/methods that are too complex for the ConditionEscort. From simple indicators to entire applications where AgenaTrader is only required to run in the background, anything that can be written in .NET can be implemented.

Information contained in this help document:

### [Drawing objects](/drawingobjects)

All drawing objects that can be used within the chart can also be accessed using AgenaScript. In this way, you can turn on/off certain lines, arrows, rectangles and other objects with specified conditions.

### [Events](/events)

AgenaScript is event-based and -driven. When (for example) a candle closes or a new candle opens, then an event has occurred. When a new price value is delivered by your data provider or a new order is executed by your broker, then these too are considered events. AgenaScript allows you to react to these events. You can read about the exact methodology in this and the following chapters.

### [Handling bars and instruments](/handling-bars-and-instruments)

You will find a detailed explanation of how AgenaScript reacts and interacts with individual bars or candles as well as various trading instruments.

### [Hints and advice](/hints-and-advice)

This section provides solutions to problems of an unusual nature. To solve such problems, you need to be able to trace and understand source code and programming. More advanced programmers and users may find solutions and suggestions that could help them in their own programming.

### [Keywords](/keywords)

Like every other programming language, AgenaTrader has a set of commands that can be converted and used via Scripts. You should be relatively well versed in these if you wish to create your own indicators or trading systems.

### [Strategy programming](/strategy-programming)

AgenaScript allows you to create your own trading strategies and execute them live within the market. Information pertaining to prerequisites and how orders are sent to the broker and managed internally can be found here.


# Handling bars and instruments

Data is understood as information that is retrieved externally and uploaded to AgenaTrader, or as data series that are created by AgenaScripts.

Further detailed information can be found using the appropriate shortcuts:

[Bars](/handling-bars-and-instruments/bars)

[Collections](/handling-bars-and-instruments/collections)

[Data series](/handling-bars-and-instruments/data-series)

[Instruments](/handling-bars-and-instruments/instruments)

[Multibars](/handling-bars-and-instruments/multibars)


# Bars

## Functionality&#x20;

A classical indicator calculates one or multiple values using an existing data series.

Data series can be anything from closing prices to daily lows or values of an hourly period etc.

Every period (meaning all candles of one day, one hour etc.) is assigned one or more indicator values. The following example is based on an indicator value, such as with a moving average, for example. To calculate a smoothed moving average, AgenaTrader needs a data series. In this example we will use the closing prices. All closing prices of a bar (candle) that are represented in the chart will be saved in a list and indexed.

The current closing price, meaning the closing price of the bar that is on the right-hand side of the chart, will be assigned an index of 0. The bar to the left of that will have an index of 1 and so on. The oldest bar displayed will have an index value of 500.

Whenever a new bar is added within a session it will become the new index 0; the bar to the left of it, which previously had an index of 0, will become index 1 and so on. The oldest bar will become index 501. Within a script (a self-created program/algorithm) the [*Close*](/handling-bars-and-instruments/data-series#close) will be representative for the array (list) of all closing prices. The last closing price is thus *Close \[0]*; the closing price previous to this will become *Close \[1]*, the value before that will become *Close \[2]* and the oldest bar will be *Close \[501]*. The number within the squared brackets represents the index. AgenaTrader allows you to use the „bars ago" expression for this in general cases.

Obviously, every bar will not only have a closing value but also a [*High*](/handling-bars-and-instruments/data-series#high), [*Low*](/handling-bars-and-instruments/data-series#low), [*Open*](/handling-bars-and-instruments/data-series#open), [*Median*](/handling-bars-and-instruments/data-series#median), [*Typical*](/handling-bars-and-instruments/data-series#typical), [*Weighted*](/handling-bars-and-instruments/data-series#weighted), [*Time*](/handling-bars-and-instruments/data-series#time) and [*Volume*](/handling-bars-and-instruments/data-series#volume). Thus, the high of the candle that occurred 10 days ago will be *High \[10]*, yesterday’s low *Low \[1]*...

**Important tip:**

The previous examples all assume that the calculations will occur at the end of a period. The value of the currently running index is not being taken into consideration.

If you wish to use the values of the currently forming candle then you will need to set the value of

*CalculateOnClosedBar* to „false".

In this case the currently running bar will have the value 0, the bar next to the current bar will have the value 1 and so on. The oldest bar (as in the example above) would now have the value 502.

With close \[0] you would receive the most recent value of the last price that your data provider transmitted to AgenaTrader. All values of the bar (high \[0], low \[0]…) may still change as long as the bar is not yet finished/closed and a new bar has not yet started. Only the open \[0] value will not change.

## Properties&#x20;

#### Properties of Bars <a href="#properties-of-bars" id="properties-of-bars"></a>

"Bars" represents a list of all bars (candles) within a chart (see [*Functionality*](#functionality), [*Bars*](/handling-bars-and-instruments/bars)).

Bars (**public** IBars Bars) can be used directly in a script and equates to BarsArray \[0] (see Bars.GetNextSessionTimeSpan for more information).

The list of bars itself has many properties that can be used in AgenaScript. Properties are always indicated by a dot before the objects (in this case bars, list of candles).

[*Bars.Count*](#bars.count)

[*Bars.CurrentSessionBeginTime*](#bars.currentsessionbegintime)

[*Bars.CurrentSessionEndTime*](#bars.currentsessionendtime)

[*Bars.GetBar*](#barsgetbar)

[*Bars.GetBarIndex*](#barsgetbarindex)

[*Bars.GetBarsAgo*](#barsgetbarsago)

[*Bars.GetByIndex*](#barsgetbyindex)

[*Bars.GetClose*](#barsgetclose)

[*Bars.GetHigh*](#barsgethigh)

[*Bars.GetLow*](#barsgetlow)

[*Bars.GetNextSessionTimeSpan*](#barsgetnextsessiontimespan)

[*Bars.GetOpen*](#barsgetopen)

[*Bars.GetSessionBegin*](#barsgetsessionbegin)

[*Bars.GetTime*](#barsgettime)

[*Bars.GetVolume*](#barsgetvolume)

[*Bars.Instrument*](#barsinstrument)

[*Bars.IsEod*](#barsiseod)

[*Bars.IsFalling*](#barsisfalling)

[*Bars.IsFirstBarInSession*](#barsisfirstbarinsession)

[*Bars.IsGrowing*](#barsisgrowing)

[*Bars.IsIntraday*](#barsisintraday)

[*Bars.IsNtb*](#barsisntb)

[*Bars.SessionBreak*](#barsissessionbreak)

[*Bars.LastBarCompleteness*](#barslastbarcompleteness)

[*Bars.NextSessionBeginTime*](#barsnextsessionbegintime)

[*Bars.NextSessionEndTime*](#barsnextsessionendtime)

[*Bars.TailBottom*](#barstailbottom)

[*Bars.TailTop*](#barstailtop)

[*Bars.TicksCountForLastBar*](#barstickscountforlastbar)

[*Bars.TicksCountInTotal*](#barstickscountintotal)

[*Bars.TimeFrame*](#barstimeframe)

[*BarsCountForSession*](#barscountforsession)

[*IsProcessingBarIndexLast*](#processingbarindexlast)

With the **OnCalculate()** method you can use any properties you want without having to test for a null reference. As soon as the function **OnCalculate()** is called up by AgenaScript, it is assumed that an object is also available. If you wish to use these properties outside of **OnCalculate()** then you should first perform a test for null references using **if** (Bars != **null**).

## Bars.Count&#x20;

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

Bars.Count gives you the amount of bars in a data series.

See [*Properties*](#properties) for additional information.

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

Type int Amount of Bars

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

Bars.Count

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

The value of *ProcessingBarIndex* can only be lesser than or equal to Bars.Count - 1

When you specify how many bars are to be loaded within AgenaTrader, then the value of Bars.Count is equal to this setting. In the following example, Bars.Count would give back a value of 500.

![](https://3984528791-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FSWsZPE35pbN2CTsq7pus%2Fuploads%2Fu6yiIY1iUGcfEmFPeZjm%2Fimage1.png?alt=media\&token=2b4725aa-2471-4ee8-be68-03b4f2c0740f)

#### Example

```csharp
Print ("There are a total of" + Bars.Count + "bars available.");
```

## Bars.CurrentSessionBeginTime

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

Bars.CurrentSessionBeginTime outputs the date and time for the beginning of the current trading session.

Date and time for the beginning of the current trading session will be displayed correctly when the function is used on a bar that has occurred in the past.

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

None

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

Type DateTime

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

Bars.GetSessionBegin

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

The time for the returned value will equal the starting time defined in the Market Escort for the specified exchange. The value itself is set within the Instrument Escort and can be called up in AgenaScript using the function [*Instrument.Exchange*](/handling-bars-and-instruments/instruments#instrumentexchange) .

![](https://3984528791-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FSWsZPE35pbN2CTsq7pus%2Fuploads%2FyhWZkkNHnKfnki4etzLr%2FTradingHour_TSE.jpg?alt=media\&token=03a7b9e4-9c85-4640-9063-ff04fb3d77e2)

#### Exchange:

```csharp
Print("The currently running trading session started at " + Bars.CurrentSessionBeginTime );
```

## Bars.CurrentSessionEndTime

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

Bars.CurrentSessionEndTime outputs the time for the end of the currently running trading session. Date and time for the end of the current trading session will, in this case, also be outputted correctly when the function is used on a previous bar.

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

None

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

Type DateTime

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

Bars.GetSessionEnd

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

The time for the returned value will correlate with the end time of the trading session defined in the Market Escort for the exchange. The value itself can be set within the Instrument Escort and can be called up with AgenaScript using the [*Instrument.Exchange*](/handling-bars-and-instruments/instruments#instrumentexchange) function.

![](https://3984528791-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FSWsZPE35pbN2CTsq7pus%2Fuploads%2F6efYvTOcyH7FtmWYbWq0%2FTradingHour_Nashdaq.jpg?alt=media\&token=cb351cd6-c2bf-404d-8db7-5dd8e4c8597d)

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

```csharp
Print("The currently running trading session started at " + Bars.CurrentSessionBeginTime );
```

## Bars.GetBar <a href="#barsgetbar" id="barsgetbar"></a>

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

Bars.GetBar outputs the first bars (from oldest to newest) that correspond to the specified date/time.

See [*Bars.GetBarsAgo*](#barsgetbarsago), [*Bars.GetByIndex*](#barsgetbyindex), [*Bars.GetBarIndex*](#barsgetbarindex).

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

Type DateTime

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

Type IBar Bar Object, for the bars corresponding to the timestamp

For a timestamp older than the oldest bar: 0 (null) For a timestamp younger than the newest bar: index of the last bar

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

```csharp
Bars.GetBar(DateTime time)
```

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

For the indexing of bars please see [*Functionality*](#functionality), [*Bars*](/handling-bars-and-instruments/bars)

For more information about using DateTime see <http://msdn.microsoft.com/de-de/library/system.datetime.aspx>

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

```csharp
Print ("The closing price for 01.03.2012 at 18:00:00 was " + Bars.GetBar(new DateTime(2012, 01, 03, 18, 0, 0)).Close);
```

## Bars.GetBarIndex <a href="#barsgetbarindex" id="barsgetbarindex"></a>

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

Bars.GetBarIndex outputs the index of a bar – you can input either a bar object or a date-time object using this method.

See [*Bars.GetBar*](#barsgetbar), [*Bars.GetBarsAgo*](#barsgetbarsago), [*Bars.GetByIndex*](#barsgetbyindex).

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

Type IBar bar or Type DateTime

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

Type int The bar index of the specified bar object or DateTime object

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

```csharp
Bars.GetBarIndex (IBar bar)
Bars.GetBarIndex (DateTime dt)
```

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

For more information about indexing see [*Functionality*](#functionality), [*Bars*](/handling-bars-and-instruments/bars)

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

```csharp
int barsAgo = 5;
IBar bar = Bars.GetBar(Time[barsAgo]);
Print(barsAgo + " and " + Bars.GetBarIndex(bar) + " are equal in this example.");
```

## Bars.GetBarsAgo <a href="#barsgetbarsago" id="barsgetbarsago"></a>

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

Bars.GetBarsAgo outputs the index of the first bars (from oldest to newest) that correspond to the specified date/time.

See: [*Bars.GetBar*](#barsgetbar), [*Bars.GetBarsAgo*](#barsgetbarsago), [*Bars.GetByIndex*](#barsgetbyindex).

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

Type DateTime

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

Type int Index of the bar that corresponds to the timestamp

With a timestamp older than the oldest bar: 0 (null) With a timestamp newer than the youngest bar: index of the last bar

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

```csharp
Bars.GetBarsAgo(DateTime time)
```

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

For more information about indexing please see [*Functionality*](#functionality), [*Bars*](/handling-bars-and-instruments/bars)

For more information about using DateTime see <http://msdn.microsoft.com/de-de/library/system.datetime.aspx>

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

```csharp
Print("The bar for 01.03.2012 at 18:00:00 O’clock has an index of " + Bars.GetBarsAgo(new DateTime(2012, 01, 03, 18, 0, 0)));
```

## Bars.GetByIndex <a href="#barsgetbyindex" id="barsgetbyindex"></a>

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

Bars.GetByIndex outputs the index for the specified bar object

See [*Bars.GetBar*](#barsgetbar), [*Bars.GetBarsAgo*](#barsgetbarsago), [*Bars.GetByIndex*](#barsgetbyindex).

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

Type int Index

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

Type IBar Bar object for the specified index

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

```csharp
Bars.GetByIndex (int Index)
```

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

For indexing of bars see [*Functionality*](#functionality), [*Bars*](/handling-bars-and-instruments/bars)

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

```csharp
Print(Close[0] + " and " + Bars.GetByIndex(ProcessingBarIndex).Close + " are equal in this example.");
```

## Bars.GetClose <a href="#barsgetclose" id="barsgetclose"></a>

Bars.GetClose(int index) – see [*Bars.GetOpen*](#barsgetopen).

## Bars.GetHigh <a href="#barsgethigh" id="barsgethigh"></a>

Bars.GetHigh(int index) – see [*Bars.GetOpen*](#barsgetopen).

## Bars.GetLow <a href="#barsgetlow" id="barsgetlow"></a>

Bars.GetLow(int index) – see [*Bars.GetOpen*](#barsgetopen).

## Bars.GetNextSessionTimeSpan <a href="#barsgetnextsessiontimespan" id="barsgetnextsessiontimespan"></a>

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

Bars.GetNextSessionTimeSpan outputs the date and time for the beginning and end of a trading session.

See [*Bars.CurrentSessionBeginTime*](#bars.currentsessionbegintime), [*Bars.CurrentSessionEndTime*](#bars.currentsessionendtime), [*Bars.NextSessionBeginTime*](#barsnextsessionbegintime), [*Bars.NextSessionEndTime*](#barsnextsessionendtime).

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

|          |         |                                                                                            |
| -------- | ------- | ------------------------------------------------------------------------------------------ |
| DateTime | time    | Date or time for which the data of the following trading session will be scanned/searched. |
| iBars    | bars    | Bar object for which the data will be scanned/searched.                                    |
| int      | barsago | Number of days in the past for which the data will be searched/scanned.                    |

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

DateTime session begin DateTime session end

**Note:** The date for the beginning and the end of a trading session are connected components. If the specified date corresponds to the end date of the current trading session then the returned value for the beginning of a trading session may already be in the past. In this case the date for the following trading session cannot be returned.

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

```csharp
Bars.GetNextSessionTimeSpan(Bars bars, int barsAgo, out DateTime sessionBegin, out DateTime sessionEnd)
Bars.GetNextSessionTimeSpan(DateTime time, out DateTime sessionBegin, out DateTime sessionEnd)
```

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

The two signatures will not necessarily output the same result. When using the bar signature, the supplied bar will be inspected for its session template association. The beginning and end of the next session will be taken from this template.

When using the time signature, the date and time of the supplied bar will be used to calculate the data for the current and the following sessions.

When using the time signature, a timestamp is transmitted that corresponds exactly to the beginning or the end time of a session.

More information can be found here [*http://msdn.microsoft.com/de-de/library/system.datetime.aspx*](http://msdn.microsoft.com/de-de/library/system.datetime.aspx)

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

```csharp
DateTime sessionBegin;
DateTime sessionEnd;
protected override void OnCalculate()
{
Bars.GetNextSessionTimeSpan(Bars, 0, out sessionBegin, out sessionEnd);
Print("Session Start: " + sessionBegin + " Session End: " + sessionEnd);
}
```

## Bars.GetOpen <a href="#barsgetopen" id="barsgetopen"></a>

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

For reasons of compatibility, the following methods are available.

* Bars.GetOpen(int index) outputs the open for the bars referenced with \<index>.
* Bars.GetHigh(int index) outputs the high for the bars referenced with \<index>.
* Bars.GetLow(int index) outputs the low for the bars referenced with \<index>.
* Bars.GetClose(int index) outputs the close for the bars referenced with \<index>.
* Bars.GetTime(int index) outputs the timestamp for the bars referenced with \<index>.
* Bars.GetVolume(int index) outputs the volume for the bars referenced with \<index>.

**Caution**: The indexing will deviate from the Indexing, *Bars* normally used. Here, the indexing will begin with 0 for the oldest bar (on the left of the chart) and end with the newest bar on the right of the chart (=Bars.Count-1).

The indexing can easily be recalculated:

```csharp
private int Convert(int idx)
{
return Math.Max(0,Bars.Count-idx-1-(CalculateOnClosedBar?1:0));
}
```

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

int index (0 .. Bars.Count-1)

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

Type double for GetOpen, GetHigh, GetLow, GetClose and GetVolume

Type DateTime for GetTime

## Bars.GetSessionBegin <a href="#barsgetsessionbegin" id="barsgetsessionbegin"></a>

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

Bars.GetSessionBegin provides the date and time of the particular session start. The date and time for the start of the current trading session are also correctly indicated when the function is called from a bar in the past. See also other [*Properties*](#properties) of bars.

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

None

#### Return value <a href="#return-value_9" id="return-value_9"></a>

Type DateTime

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

Bars.GetSessionBegin(DateTime dt)

#### Further Information <a href="#further-information" id="further-information"></a>

The time of the returned value corresponds to the start time of the trading session. The relevant trading center which is specified in the MarketEscort. The trading place used for the value is set in the Instrumet Escort and can be determined in AgenaSript with the Instrument.Exchange function.

![](https://3984528791-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FSWsZPE35pbN2CTsq7pus%2Fuploads%2FyhWZkkNHnKfnki4etzLr%2FTradingHour_TSE.jpg?alt=media\&token=03a7b9e4-9c85-4640-9063-ff04fb3d77e2)

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

```csharp
Print("Die Handelssitzung am 25.03.2015 hat um "+ Bars.GetSessionBegin(new DateTime(2015, 03, 25)) + " begonnen.");
}
```

## Bars.GetTime <a href="#barsgettime" id="barsgettime"></a>

Bars.GetTime(int index) – see [*Bars.GetOpen*](#barsgetopen).

## Bars.GetVolume <a href="#barsgetvolume" id="barsgetvolume"></a>

Bars.GetVolume(int index) – see [*Bars.GetOpen*](#barsgetopen).

## Bars.Instrument <a href="#barsinstrument" id="barsinstrument"></a>

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

Bars.Instrument outputs an instrument object for the trading instrument displayed within the chart.

See [*Properties*](#properties) for more information.

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

None

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

Type Instrument

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

Bars.Instrument

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

For more information regarding the trading instruments please see [*Instruments*](/handling-bars-and-instruments/instruments).

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

```csharp
// both outputs will provide the same result
Print("The currently displayed trading instrument has the symbol: " + Bars.Instrument);
Instrument i = Bars.Instrument;
Print("The currently displayed trading instrument has the symbol " + i.Symbol);
```

## Bars.IsEod <a href="#barsiseod" id="barsiseod"></a>

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

Bars.IsEod can be used to check whether they are end-of-day bars.

See [*Properties*](#properties) for more information.

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

None

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

Type bool

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

Bars.IsEod

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

Within [*OnCalculate()*](/events#oncalculate), this property can be used without having to test for null reference. As soon as the method OnCalculate () is called by AgenaScript, there is always a bar object.

If this property used outside of OnCalculate (), then a corresponding test should be set to zero reference, e.g. With if (bars! = Null).

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

```csharp
Print("The bars are EOD: " + Bars.IsEod);
```

## Bars.IsFalling <a href="#barsisfalling" id="barsisfalling"></a>

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

Bar properties used when Bar is falling down.

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

None

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

None

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

```csharp
Bars[0].IsFalling;
```

## Bars.IsFirstBarInSession <a href="#barsisfirstbarinsession" id="barsisfirstbarinsession"></a>

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

With Bars.IsFirstBarInSession you can determine whether the current bar is the first bar of the trading session.

See [*Properties*](#properties) of bars for more information.

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

Type bool

**true**: The bar is the first bar of the current trading session **false**: The bar is not the first bar of the current trading session

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

Bars.IsFirstBarInSession

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

With [*OnCalculate()*](/events#oncalculate) this property can be used without having to test for a null reference. As soon as the OnCalculate() method is called up, an object will become available. If this property is called up outside of OnCalculate() you should test for a null reference using if (Bars != null).

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

```csharp
if (Bars.IsFirstBarInSession)
Print ("The current trading session started at" + Time [0]);
```

## Bars.isGrowing <a href="#barsisgrowing" id="barsisgrowing"></a>

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

Bar properties used when Bar is growing up.

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

None

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

None

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

```csharp
Bars[0].isGrowing;
```

## Bars.IsIntraday <a href="#barsisintraday" id="barsisintraday"></a>

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

Bars.IsIntraday returns a boolean which indicates if the TimeFrame is intra-day.

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

**bool**

It returns "true" if TimeFrame is intra-day (e.g. 1 min, 15 min, 1 hour, etc.) and "false" in other cases.

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

```csharp
Bars.IsIntraday
```

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

```csharp
if(Bars.IsIntraday) {
    Print("TimeFrame is Intraday.");
} else {
    Print("TimeFrame is not Intraday.");
}
```

## Bars.IsNtb <a href="#barsisntb" id="barsisntb"></a>

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

With Bars.IsNtb it can be checked whether it is not-time-based bars. For example Ntb bars are Point & Figure or Renko Charts.

See [*Properties*](#properties) for more information.

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

None

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

Type bool

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

Bars.IsNtb

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

[*OnCalculate()*](/events#oncalculate) property can be used without having to test for null reference first. As soon as the method OnCalculate() is called by AgenaScript, there is always a bar object. If this property is used outside of OnCalculate(), then a corresponding test should be set to zero reference, e.g. With if (bars! = Null).

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

```csharp
Print("The bars are Ntb: " + Bars.IsNtb);
```

### Bars.IsSessionBreak <a href="#barsissessionbreak" id="barsissessionbreak"></a>

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

Bars.IsSessionBreak can be used to determine whether the bars are within the commercial trading session in the commercial breaks defined in the marketplace escort.

See [*Properties*](#properties) for more information.

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

None

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

Type bool

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

Bars.IsSessionBreak

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

![](https://3984528791-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FSWsZPE35pbN2CTsq7pus%2Fuploads%2F6efYvTOcyH7FtmWYbWq0%2FTradingHour_Nashdaq.jpg?alt=media\&token=cb351cd6-c2bf-404d-8db7-5dd8e4c8597d)

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

```csharp
if (Bars.IsSessionBreak)
{
    Print("The stock exchange Xetra has just a trade pause.");
}
```

## Bars.LastBarCompleteness <a href="#barslastbarcompleteness" id="barslastbarcompleteness"></a>

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

Bars.LastBarCompleteness outputs the value that displays what percentage a bar has already completed. A bar with a period of 10 minutes has completed 50% after 5 minutes.

For non-time-based charts (Kagi, LineBreak, Renko, Range, P\&F etc.) this will output 0 during backtesting.

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

**double**

A percentage value; 30% will be outputted as 0.3

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

Bars.LastBarCompleteness

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

With [*OnCalculate()*](/events#oncalculate) this property can be used without having to test for a null reference. As soon as the OnCalculate() method is called up by AgenaScript, the object will become available.

If this property is used outside of OnCalculate() you should test for a null reference before executing it. You can test using *if* (Bars != *null*)

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

```csharp
// A 60 minute chart is looked at from an intraday perspective
// every 5 minutes before the current bar closes
// an acoustic signal shall be played
// 55 min. equals 92%
bool remind = false;
protected override void OnCalculate()
{
if (FirstTickOfBar) remind = true;
    if (remind && Bars.LastBarCompleteness >= 0.92)
    {
    remind = false;
    PlaySound("Alert1");
    }
}
```

## Bars.NextSessionBeginTime <a href="#barsnextsessionbegintime" id="barsnextsessionbegintime"></a>

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

Bars.NextSessionBeginTime outputs the date and time for the start of the next trading session. Date and time for the next session will be correctly outputted when the function is used on a bar in the past.

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

None

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

Type DateTime

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

Bars.GetSessionNextBegin

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

The time for the returned value will correlate to the value displayed in the MarketEscort. The value can be set within the Instrument Escort and can be called up using the [*Instrument.Exchange*](/handling-bars-and-instruments/instruments#instrumentexchange) function.

![](https://3984528791-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FSWsZPE35pbN2CTsq7pus%2Fuploads%2FyhWZkkNHnKfnki4etzLr%2FTradingHour_TSE.jpg?alt=media\&token=03a7b9e4-9c85-4640-9063-ff04fb3d77e2)

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

```csharp
Print("The next trading session starts at " + Bars.NextSessionBeginTime);
```

## Bars.NextSessionEndTime <a href="#barsnextsessionendtime" id="barsnextsessionendtime"></a>

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

Bars.NextSessionEndTime outputs the date and time for the end of the next session. See [*Properties*](#properties) for more information.

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

None

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

Type DateTime

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

Bars.GetSessionNextEnd

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

The time for the returned value will correlate with the value specified within the MarketEscort. The value itself can be set within the Instrument Escort and can be called up with AgenaScript using the [*Instrument.Exchange*](/handling-bars-and-instruments/instruments#instrumentexchange) function.

![](https://3984528791-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FSWsZPE35pbN2CTsq7pus%2Fuploads%2F6efYvTOcyH7FtmWYbWq0%2FTradingHour_Nashdaq.jpg?alt=media\&token=cb351cd6-c2bf-404d-8db7-5dd8e4c8597d)

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

```csharp
Print("The next trading session ends at " + Bars.NextSessionEndTime);
```

## Bars.TailBottom <a href="#barstailbottom" id="barstailbottom"></a>

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

With this property you are able to get the height of the bottom candle tail.

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

None

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

None

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

```csharp
Bars[0].TailBottom;
```

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

```csharp
Print("The height of the bottom candle tail is: " + Bars.TailBottom);
```

## Bars.TailTop <a href="#barstailtop" id="barstailtop"></a>

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

With this property you are able to get the height of the top candle tail.

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

None

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

None

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

```csharp
Bars[0].TailTop;
```

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

```csharp
Print("The height of the top candle tail is: " + Bars.TailTop);
```

## Bars.TicksCountForLastBar <a href="#barstickscountforlastbar" id="barstickscountforlastbar"></a>

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

Bars.TicksCountForLastBar outputs the total numbers of ticks contained within a bar.

More information can be found in [*Properties*](#properties) of bars.

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

None

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

Type int

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

Bars.TicksCountForLastBar

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

With [*OnCalculate()*](/events#oncalculate) this property can be used without having to test for a null reference. As soon as the OnCalculate() method is called up by AgenaScript, the object will become available.

If this property is used outside of OnCalculate(), you should test for a null reference before executing it. You can test using *if* (Bars != *null*)

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

```csharp
Print("The current bar consists of " + Bars.TicksCountForLastBar + " Ticks.");
```

## Bars.TicksCountInTotal <a href="#barstickscountintotal" id="barstickscountintotal"></a>

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

Bars.TicksCountInTotal outputs the total number of ticks from the moment the function is called up.

More information can be found here: [*Properties*](#properties).

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

None

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

Type int

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

Bars.TicksCountInTotal

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

The data type int has a positive value range of 2147483647. When you assume 10 ticks per second, there will be no overlaps within 2 trading months with a daily runtime of 24 hours.

With [*OnCalculate()*](/events#oncalculate) this property can be used without having to test for a null reference. As soon as the OnCalculate() method is called up by AgenaScript, the object will become available.

If this property is used outside of OnCalculate(), you should test for a null reference before executing it. You can test using *if* (Bars != *null*)

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

```csharp
Print("The total amount of ticks is " + Bars.TicksCountInTotal);
```

## Bars.TimeFrame <a href="#barstimeframe" id="barstimeframe"></a>

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

Bars.TimeFrame outputs the timeframe object containing information regarding the currently used timeframe.

More information can be found here: [*Properties*](#properties)

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

None

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

Type ITimeFrame

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

Bars.TimeFrame

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

For more information about timeframe objects please see [*TimeFrame*](/handling-bars-and-instruments/data-series#timeframe).

With [*OnCalculate()*](/events#oncalculate) this property can be used without having to test for a null reference. As soon as the OnCalculate() method is called up by AgenaScript, the object will become available.

If this property is used outside of OnCalculate(),you should test for a null reference before executing it. You can test using *if* (Bars != *null*)

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

```csharp
//Usage within a 30 minute chart
TimeFrame tf = (TimeFrame) Bars.TimeFrame;
Print(Bars.TimeFrame); // outputs "30 Min"
Print(tf.Periodicity); // outputs "Minute"
Print(tf.PeriodicityValue); // outputs "30"
```

## BarsCountForSession <a href="#barscountforsession" id="barscountforsession"></a>

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

Bars.BarsCountForSession outputs the amount of bars that have occurred since the beginning of the current trading session.

See further [*Properties*](#properties) of bars.

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

Type int Amount of Bars

A value of -1 indicates a problem with referencing the correct session beginning.

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

Bars.BarsCountForSession

#### Further Information <a href="#further-information_1" id="further-information_1"></a>

Within *OnCalculate()* this property can be used without having to test for a null reference. As soon as the OnCalculate() method is called up by AgenaScript, the object will become available.

If this property is used outside of OnCalculate() then you should test for a null reference before executing it. You can test using *if* (Bars!= *null*) .

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

```csharp
Print("Since the start of the last trading session there have been" + Bars.BarsCountForSession + "bars.");
```

## ProcessingBarIndexLast <a href="#processingbarindexlast" id="processingbarindexlast"></a>

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

Indicates if current bar is last in calculation.

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

none

#### Return value <a href="#return-value_27" id="return-value_27"></a>

Type bool

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

ProcessingBarIndexLast

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

used for complicated calculation on a last bar

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

```csharp
protected override void OnCalculate()
        {
            base.OnCalculate();
            if (!IsProcessingBarIndexLast)
                return;
            bool isUpdated;
}
```


# Collections

## ChartDrawings <a href="#chartdrawings" id="chartdrawings"></a>

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

ChartDrawings is a collection containing all drawing objects within the chart. The property hold all drawings which were generated by the script. The index for ChartDrawings is the explicit name for the drawing object (string tag).

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

ChartDrawings \[string tag]

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

**Note:** To be able to use the interface definitions you must use the using method.

```csharp
using AgenaTrader.Plugins;
// Output number of drawing objects within the chart and their tags
Print("The chart contains " + ChartDrawings.Count + " drawing objects.");
foreach (IDrawObject draw in ChartDrawings) Print(draw.Tag);
//Draw a black trend line...
AddChartLine("MyLine", true, 10, Close[10], 0, Close[0], Color.Black, DashStyle.Solid, 3);
// ... and change the color to red
ITrendLine line = (ITrendLine) ChartDrawings["MyLine"];
if (line != null) line.Pen.Color = Color.Red;
// Set all lines within the chart to a line strength of 3,
// and lock it so that it cannot be edited or moved
foreach (IDrawObject draw in ChartDrawings)
if (draw is IVerticalLine)
{
    IVerticalLine vline = (IVerticalLine) draw;
    vline.IsLocked = true;
    vline.Editable = false;
    vline.Pen.Width = 3;
}
```

## InSeries <a href="#inseries" id="inseries"></a>

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

InSeries is a [*DataSeries*](/handling-bars-and-instruments/data-series) object in which the input data for an indicator or strategy is stored.

If the indicator is used without any explicit instructions for the input data, then the closing price for the current market prices will be used.

When calling up the SMA(20) the smoothing average is calculated on the basis of the closing prices for the current chart price data (this is equivalent to SMA(close,20).

InSeries\[0] = Close\[0].

When calling up the SMA(high, 20) the high price values are loaded and used for the calculation of the smoothing average.

InSeries\[0] = High\[0].

This way you can select which data series should be used for the calculation of the indicator.

**double** d = **RSI**(**SMA**(20), 14, 3)\[0]; calculates the 14 period RSI using the SMA(20) as the input data series. InSeries\[0] = SMA(20)\[0].

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

```csharp
InSeries
InSeries[int barsAgo]
```

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

```csharp
Print("The input data for the indicators are " + Input[0]);
```

## Lines <a href="#lines" id="lines"></a>

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

Lines is a collection that contains all LevelLine objects of an indicator.

When a line object is added to the indicator using the [*Add()*](/keywords#addline) method, this line is automatically added to the "lines" collection.

The order of the add commands determines how these lines are sorted. The first information request of Add() will create Lines\[0], the next information request will be Lines\[1] etc.

See [*OutputDescriptor*](#outputdescriptor).

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

```csharp
Lines[int index]
```

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

```csharp
// Add "using System.Drawing.Drawing2D;" for DashStyle
protected override void OnInit()
{
Add(new LevelLine(Color.Blue, 70, "Upper")); // saves into Lines[0]
Add(new LevelLine(Color.Blue, 30, "Lower")); // saves into Lines[1]
}
protected override void OnCalculate()
{
// When the RSI is above 70, properties of the lines will be changed
if (RSI(14 ,3)[0] >= 70)
{
    Lines[0].Width = 3;
    Lines[0].Color = Color.Red;
    Lines[0].DashStyle = DashStyle.Dot;
}
else
{
    Lines[0].Width = 1;
    Lines[0].Color = Color.Blue;
    Lines[0].DashStyle = DashStyle.Solid;
}
}
```

## PlotColors <a href="#plotcolors" id="plotcolors"></a>

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

PlotColors is a collection that contains all color series of all plot objects.

When a plot is added using the [*Add()*](/keywords#addline) method it automatically creates a color series object and is added to the PlotColors collection.

The order of the add commands determines how the plot colors are sorted. The first information request of Add() will create PlotColors\[0], the following information request will create PlotColors\[1] etc.

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

```csharp
PlotColors[int PlotIndex][int barsAgo]
```

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

More information regarding the collection class: [*http://msdn.microsoft.com/en-us/library/ybcx56wz%28v=vs.80%29.aspx*](http://msdn.microsoft.com/en-us/library/ybcx56wz%28v=vs.80%29.aspx)

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

```csharp
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using AgenaTrader.API;
namespace AgenaTrader.UserCode
{
    [Description("PlotColor Demo")]
    public class PlotColorsDemo : UserIndicator
{
    public DataSeries SMA20 { get {return Outputs[0];} }
    public DataSeries SMA50 { get {return Outputs[1];} }
    public DataSeries SMA100 { get {return Outputs[2];} }
    private Pen pen;
    protected override void OnInit()
{
// Set line strength (width) to 4
pen = new Pen(Color.Empty, 4);
// Add three plots with the defined line strength to the chart
Add(new OutputDescriptor(pen, OutputSeriesDisplayStyle.LevelLine, "SMA20" )); //attached to PlotColors[0]
Add(new OutputDescriptor(pen, OutputSeriesDisplayStyle.LevelLine, "SMA50" )); //attached to PlotColors[1]
Add(new OutputDescriptor(pen, OutputSeriesDisplayStyle.LevelLine, "SMA100")); //attached to PlotColors[2]
IsOverlay = true;
}
    protected override void OnCalculate()
{
// Add values to the three plots
SMA20.Set (SMA(20) [0]);
SMA50.Set (SMA(50) [0]);
SMA100.Set(SMA(100)[0]);
// Change colors depending on the trend
if (IsSerieRising(Close))
{
    PlotColors[0][0] = Color.LightGreen;
    PlotColors[1][0] = Color.Green;
    PlotColors[2][0] = Color.DarkGreen;
}
else if (IsSerieFalling(Close))
{
    PlotColors[0][0] = Color.LightSalmon;
    PlotColors[1][0] = Color.Red;
    PlotColors[2][0] = Color.DarkRed;
}
else
{
    PlotColors[0][0] = Color.LightGray;
    PlotColors[1][0] = Color.Gray;
    PlotColors[2][0] = Color.DarkGray;
}
}
}
}
```

## OutputDescriptor <a href="#outputdescriptor" id="outputdescriptor"></a>

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

OutputDescriptor is a collection that contains the plot objects of an indicator.

When a plot object is added to an indicator using the Add() method, it is also automatically added to the "plots" collection.

The order of the add commands determines how the plots are sorted. The first Add() information request will create Plots\[0], the following information request will create OutputDescriptor\[1] etc.

See [*Lines*](#lines).

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

```csharp
OutputDescriptor[int index]
```

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

```csharp
protected override void OnInit()
{
    Add(new OutputDescriptor(Color.FromKnownColor(KnownColor.Blue), "MySMA 20")); // saved to OutputDescriptor[0]
}
protected override void OnCalculate()
{
Value.Set(SMA(20)[0]);
// If the market price is above the SMA colorize it green, otherwise red
if (Close[0] > SMA(20)[0])
    OutputDescriptor[0].PlotColor = Color.Green;
else
    OutputDescriptor[0].PlotColor = Color.Red;
}
```

## Values <a href="#values" id="values"></a>

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

Values are a collection that contains the data series objects of an indicator.

When a plot is added to an indicator using the Add() method, a value object is automatically created and added to the "values" collection.

The order of the add commands determines how the values are sorted. The first information request will create Values\[0], the next information request will create Values\[1], etc.

**Value** is always identical to Values\[0].

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

```csharp
Outputs[int index]
Outputs[int index][int barsAgo]
```

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

The methods known for a collection, Set() Reset() and Count(), are applicable for values.

Information on the class collection: [*http://msdn.microsoft.com/en-us/library/ybcx56wz%28v=vs.80%29.aspx*](http://msdn.microsoft.com/en-us/library/ybcx56wz%28v=vs.80%29.aspx)

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

```csharp
// Check the second indicator value of one bar ago and set the value of the current indicator value based on it.
if (Instrument.Compare(Outputs[1][1], High[0] - Low[0]) < 0)
    Value.Set(High[0] - Low[0]);
else
    Value.Set(High[0] - Close[0]);
```


# Data Series

Data series are interpreted as freely usable data storage containers for your programs. Additionally, they an integrated component of AgenaTrader that saves the price changes for individual bars. We will be focusing on the latter function here. In the following section, the concept of data series will be explained in detail and understandably. All price data for the individual bars are organized and saved within data series. The following are available:

[*Open*](#open)

[*High*](#high)

[*Low*](#low)

[*Close*](#close)

[*Median*](#median)

[*Typical*](#typical)

[*Weighted*](#weighted)

[*Time*](#time)

[*TimeFrame*](#timeframe)

[*Volume*](#volume)

## Open <a href="#open" id="open"></a>

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

Open is a [*DataSeries*](/handling-bars-and-instruments/data-series) of the type [*DataSeries*](/handling-bars-and-instruments/data-series), in which the historical opening prices are saved.

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

BarsAgo Index Value (see [*Bars*](/handling-bars-and-instruments/bars))

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

```csharp
Open
Open[int barsAgo]
```

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

The returned value is dependent upon the property of [*CalculateOnClosedBar*](/keywords#calculateonclosedbar).

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

```csharp
// Opening price for the current period
Print(Time[0] + " " + Open[0]);
// Opening price for the bars of 5 periods ago
Print(Time[5] + " " + Open[5]);
// Current value for the SMA 14 that is based on the opening prices (rounded)
Print("SMA(14) calculated using the opening prices: " + Instrument.Round2TickSize(SMA(Open, 14)[0]));
```

## Opens <a href="#opens" id="opens"></a>

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

Opens is an array of data series that contains all open data series.

This array is only useful or meaningful for indicators or strategies that use multiple data from multiple timeframes. A new entry is entered into the array whenever a new timeframe is added to an indicator or strategy.

With **\[TimeFrameRequirements(("1 Day"), ("1 Week"))]** the array will contain 3 entries:

Opens\[0] The open data series of the chart timeframe Opens\[1] The open data series of all bars in a daily timeframe Opens\[2] The open data series of all bars in a weekly timeframe

Opens\[0]\[0] is equivalent to Open\[0].

In addition, please see [*MultiBars*](/handling-bars-and-instruments/multibars) for more information.

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

barsAgo Index value for the individual bars within the data series (see [*Bars*](/handling-bars-and-instruments/bars)) barSeriesIndex Index value for the various timeframes

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

```csharp
Opens[int barSeriesIndex]
Opens[int barSeriesIndex][int barsAgo]
```

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

The returned value is dependent upon the property of [*CalculateOnClosedBar*](/keywords#calculateonclosedbar).

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

See example: [*Multibars*](/handling-bars-and-instruments/multibars).

## High <a href="#high" id="high"></a>

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

High is a [*Data Series*](/handling-bars-and-instruments/data-series) of the type [*Data Series*](/handling-bars-and-instruments/data-series), in which the historical high prices are saved.

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

barsAgo IndexValue (see [*Bars*](/handling-bars-and-instruments/bars))

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

```csharp
High
High[int barsAgo]
```

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

The returned value is dependent upon the property of [*CalculateOnClosedBar*](/keywords#calculateonclosedbar).

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

```csharp
// High values of the current period
Print(Time[0] + " " + High[0]);
// High values of the bar from 5 periods ago
Print(Time[5] + " " + High[5]);
// the current value for the SMA 14 calculated on the basis of the high prices
Print("SMA(14) Calculated using the high prices: " + Instrument.Round2TickSize(SMA(High, 14)[0]));
```

## Highs <a href="#highs" id="highs"></a>

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

Highs is an array of \[*DataSeries*]\[1] that contains all high data series.

This array is only of value for indicators or strategies that use data from multiple timeframes.

A new entry is added to the array whenever a new time unit is added to an indicator or strategy.

With **\[TimeFrameRequirements(("1 Day"), ("1 Week"))]** the array will contain 3 entries:

Highs\[0] the high data series of the chart timeframe Highs\[1] the high data series of all bars in a daily timeframe Highs\[2] the high data series of all bars in a weekly timeframe

Highs\[0]\[0] is equivalent to High\[0].

See [*MultiBars*](/handling-bars-and-instruments/multibars).

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

barsAgo Index value for the individual bars within the data series (see [*Bars*](/handling-bars-and-instruments/bars)) barSeriesIndex Index value for the various timeframes

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

```csharp
Highs[int barSeriesIndex]
Highs[int barSeriesIndex][int barsAgo]
```

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

The returned value is dependent upon the property of [*CalculateOnClosedBar*](/keywords#calculateonclosedbar).

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

Please see examples under [*Multibars*](/handling-bars-and-instruments/multibars).

## Low <a href="#low" id="low"></a>

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

Low is a [*DataSeries*](/handling-bars-and-instruments/data-series) of the type [*DataSeries*](/handling-bars-and-instruments/data-series), in which the historical low prices are saved.

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

barsAgo IndexValue (see [*Bars*](/handling-bars-and-instruments/bars))

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

```csharp
Low
Low[int barsAgo]
```

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

The returned value is dependent upon the property of [*CalculateOnClosedBar*](/keywords#calculateonclosedbar).

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

```csharp
// Lowest value of the current period
Print(Time[0] + " " + Low[0]);
// Lowest value of the bar from 5 periods ago
Print(Time[5] + " " + Low[5]);
// The current value for the SMA 14 calculated on the basis of the low prices (smoothed)
Print("SMA(14) calculated using the high prices: " + Instrument.Round2TickSize(SMA(Low, 14)[0]));
```

## Lows <a href="#lows" id="lows"></a>

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

Lows is an array of \[*DataSeries*]\[1] that contains all [*Low*](#low) data series.

This array is only of value to indicators or strategies that use data from multiple time units.

A new entry is added whenever a new time unit is added to an indicator or strategy.

With **\[TimeFrameRequirements(("1 Day"), ("1 Week"))]** the array will contain 3 entries:

Lows\[0] the low data series for the chart timeframe Lows\[1] the low data series for all bars in a daily timeframe Lows\[2] the low data series for all bars in a weekly timeframe

Lows\[0]\[0] is equivalent to Low\[0].

See [*MultiBars*](/handling-bars-and-instruments/multibars).

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

barsAgo Index value for the individual bars within the data series barSeriesIndex Index value for the various timeframes

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

```csharp
Lows[int barSeriesIndex]
Lows[int barSeriesIndex][int barsAgo]
```

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

The returned value is dependent upon the property [*CalculateOnClosedBar*](/keywords#calculateonclosedbar).

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

See example [*Multibars*](/handling-bars-and-instruments/multibars).

## Close <a href="#close" id="close"></a>

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

Close is a [*DataSeries*](/handling-bars-and-instruments/data-series) of the type [*DataSeries*](/handling-bars-and-instruments/data-series), in which the historical closing prices are saved.

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

barsAgo Index value (see [*Bars*](/handling-bars-and-instruments/bars))

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

```csharp
Close
Close[int barsAgo]
```

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

The returned value is dependent upon the property [*CalculateOnClosedBar*](/keywords#calculateonclosedbar).

Indicators are usually calculated using the closing prices.

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

```csharp
// Closing price of the current period
Print(Time[0] + " " + Close[0]);
// Closing price of the bar from 5 periods ago
Print(Time[5] + " " + Close[5]);
// Current value for the SMA 14 based on the closing prices
Print("SMA(14) calculated using the closing prices: " + Instrument.Round2TickSize(SMA(Close, 14)[0]));
// Close does not need to be mentioned since it is used by default
Print("SMA(14) calculated using the closing prices: " + Instrument.Round2TickSize(SMA(14)[0]));
```

## Closes <a href="#closes" id="closes"></a>

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

Closes is an array of \[*DataSeries*]\[1] that contains all [*Low*](#low) data series.

This array is only of importance to indicators or strategies that use data from multiple time units.

A new entry is added to the array whenever a timeframe is added to an indicator or strategy.

With **\[TimeFrameRequirements(("1 Day"), ("1 Week"))]** the array will contain 3 entries:

Closes\[0] the close data series of the chart timeframe Closes\[1] the close data series of all bars in a daily timeframe Closes\[2] the close data series of all bars in a weekly timeframe

Closes\[0]\[0] is equivalent to Close\[0].

See [*MultiBars*](/handling-bars-and-instruments/multibars).

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

barsAgo Index value of the individual bars within the data series barSeriesIndex Index value for the various timeframes

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

```csharp
Closes[int barSeriesIndex]
Closes[int barSeriesIndex][int barsAgo]
```

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

The returned value is dependent upon the property [*CalculateOnClosedBar*](/keywords#calculateonclosedbar).

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

See example [*Multibars*](/handling-bars-and-instruments/multibars).

## Median <a href="#median" id="median"></a>

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

Median is a [*DataSeries*](/handling-bars-and-instruments/data-series) of the type [*DataSeries*](/handling-bars-and-instruments/data-series), in which the historical median values are saved.

The median price of a bar is calculated using (high + low) / 2

See [*Typical*](#typical) & [*Weighted*](#weighted).

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

barsAgo Index value (see [*Bars*](/handling-bars-and-instruments/bars))

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

```csharp
Median
Median[int barsAgo]
```

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

The returned value is dependent upon the property [*CalculateOnClosedBar*](/keywords#calculateonclosedbar).

Further information about median, typical und weighted: [*http://blog.nobletrading.com/2009/12/median-price-typical-price-weighted.html*](http://blog.nobletrading.com/2009/12/median-price-typical-price-weighted.html)

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

```csharp
// Median price for the current period
Print(Time[0] + " " + Median[0]);
// Median price of the bar from 5 periods ago
Print(Time[5] + " " + Median[5]);
// Current value for the SMA 14 calculated using the median prices
Print("SMA(14) calculated using the median prices: " + Instrument.Round2TickSize(SMA(Median, 14)[0]));
```

## Medians <a href="#medians" id="medians"></a>

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

Medians is an array of \[*DataSeries*]\[1] that contains all [*Median*](#median) data series.

This array is only of value to indicators or strategies that use data from multiple timeframes.

A new entry is added to the array whenever a new time frame is added to an indicator or strategy.

With **\[TimeFrameRequirements(("1 Day"), ("1 Week"))]** the array will contain 3 entries:

Medians\[0] the median data series of the chart timeframe Medians\[1] the median data series of all bars in a daily timeframe Medians\[2] the median data series of all bars in a weekly timeframe

Medians\[0]\[0] is equivalent to Medians\[0].

See [*MultiBars*](/handling-bars-and-instruments/multibars).

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

barsAgo Index value for the individual bars within a data series barSeriesIndex Index value for the various timeframes

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

```csharp
Medians[int barSeriesIndex]
Medians[int barSeriesIndex][int barsAgo]
```

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

The returned value is dependent upon the property [*CalculateOnClosedBar*](/keywords#calculateonclosedbar).

Further information on median: <http://www.investopedia.com/terms/m/median.asp>

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

See example in [*Multibars*](/handling-bars-and-instruments/multibars).

## Typical <a href="#typical" id="typical"></a>

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

Typical is a [*DataSeries*](/handling-bars-and-instruments/data-series) of the type [*DataSeries*](/handling-bars-and-instruments/data-series), in which the historical typical values are saved.

The typical price of a bar is calculated using (high + low + close) / 3.

See [*Median*](#median) and [*Weighted*](#weighted).

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

barsAgo Index value (see [*Bars*](/handling-bars-and-instruments/bars))

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

```csharp
Typical
Typical[int barsAgo]
```

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

The returned value is dependent upon the property [*CalculateOnClosedBar*](/keywords#calculateonclosedbar).

Further information on typical: [*https://technicianapp.com/resources/typical-price/*](https://technicianapp.com/resources/typical-price/)

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

```csharp
// Typical price for the current period
Print(Time[0] + " " + Typical[0]);
// Typical price of the bar from 5 periods ago
Print(Time[5] + " " + Typical[5]);
// Current value for the SMA 14 calculated using the typical price
Print("SMA(14) calculated using the typical price: " + Instrument.Round2TickSize(SMA(Typical, 14)[0]));
```

## Typicals <a href="#typicals" id="typicals"></a>

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

Typicals is an array of *DataSeries* that contains all [*Typical*](#typical) data series.

This array is only of value to indicators and strategies that make use of multiple timeframes.

A new entry is added to the array whenever a new timeframe is added to an indicator or strategy.

With **\[TimeFrameRequirements(("1 Day"), ("1 Week"))]** the array will contain 3 entries:

Typicals\[0] the typical data series of the chart timeframe Typicals\[1] the typical data series of all bars in a daily timeframe Typicals\[2] the typical data series of all bars in a weekly timeframe

Typicals\[0]\[0] is equivalent to Typicals\[0].

See [*MultiBars*](/handling-bars-and-instruments/multibars).

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

barsAgo Index value of the individual bars within a data series barSeriesIndex Index value of the various timeframes

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

```csharp
Typicals[int barSeriesIndex]
Typicals[int barSeriesIndex][int barsAgo]
```

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

The returned value is dependent upon the property [*CalculateOnClosedBar*](/keywords#calculateonclosedbar).

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

See example [*Multibars*](/handling-bars-and-instruments/multibars).

## Weighted <a href="#weighted" id="weighted"></a>

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

Weighted is a [*DataSeries*](/handling-bars-and-instruments/data-series) of the type [*DataSeries*](/handling-bars-and-instruments/data-series), in which the historical weighted values are saved.

The weighted price of a bar is calculated using the formula (high + low + 2\*close) / 4 and then weighted on the closing price.

See also [*Median*](#median) and [*Typical*](#typical).

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

barsAgo Index value (see [*Bars*](/handling-bars-and-instruments/bars))

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

## Weighted <a href="#weighted_1" id="weighted_1"></a>

```csharp
Weighted[int barsAgo]
```

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

The returned value is dependent upon the property [*CalculateOnClosedBar*](/keywords#calculateonclosedbar).

Information regarding weighted: [*http://www.stock-trading-infocentre.com/pivot-points.html*](http://www.stock-trading-infocentre.com/pivot-points.html)

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

```csharp
// Weighted price for the current period
Print(Time[0] + " " + Weighted[0]);
// Weighted price of the bar from 5 periods ago
Print(Time[5] + " " + Weighted[5]);
// Current value for the SMA 14 using the weighted price
Print("SMA(14) calculated using the weighted price: " + Instrument.Round2TickSize(SMA(Weighted, 14)[0]));
```

## Weighteds <a href="#weighteds" id="weighteds"></a>

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

Weighteds is an array of \[*DataSeries*]\[1] that contains all [*Weighted*](#weighted) data series.

The array is only of value for indicators and strategies that use data from multiple timeframes.

A new entry is added to the array whenever a new timeframe is added to an indicator or strategy.

With **\[TimeFrameRequirements(("1 Day"), ("1 Week"))]** the array will contain 3 entries:

Weighteds\[0] the weighted data series of the chart timeframe Weighteds\[1] the weighted data series of all bars in a daily timeframe Weighteds\[2] the weighted data series of all bars in a weekly timeframe

Weighteds\[0]\[0] is equivalent to Weighteds\[0].

See [*MultiBars*](/handling-bars-and-instruments/multibars).

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

barsAgo Index value of the individual bars within a data series barSeriesIndex Index value for the various timeframes

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

```csharp
Weighteds[int barSeriesIndex]
Weighteds[int barSeriesIndex][int barsAgo]
```

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

The returned value is dependent upon the property [*CalculateOnClosedBar*](/keywords#calculateonclosedbar).

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

See example under [*Multibars*](/handling-bars-and-instruments/multibars).

## Time <a href="#time" id="time"></a>

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

Time is a [*DataSeries*](/handling-bars-and-instruments/data-series) of the type [*DateTimeSeries*](/keywords#datetimeseries), in which the timestamps of the individual bars are saved.

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

barsAgo Index value (see [*Bars*](/handling-bars-and-instruments/bars))

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

```csharp
Time
Time[int barsAgo]
```

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

The returned value is dependent upon the property [*CalculateOnClosedBar*](/keywords#calculateonclosedbar).

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

```csharp
// Timestamp of the current period
Print(Time[0]);
// Timestamp of the bar from 5 periods ago
Print(Time[5]);
```

## Times <a href="#times" id="times"></a>

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

Times is an array of [*DataSeries*](/handling-bars-and-instruments/data-series) that contains all [*Time*](#time) data series.

This array is only of value to indicators and strategies that make use of multiple timeframes. A new entry is added to the array whenever a new timeframe is added to an indicator or strategy.

With **\[TimeFrameRequirements(("1 Day"), ("1 Week"))]** the array will contain 3 entries:

Times\[0] the time data series of the chart timeframe Times\[1] the time data series of all bars in a daily timeframe Times\[2] the time data series of all bars in a weekly timeframe

Times\[0]\[0] is equivalent to Times\[0].

See [*MultiBars*](/handling-bars-and-instruments/multibars).

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

barsAgo Index value for the individual bars within a data series barSeriesIndex Index value for the various timeframes

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

```csharp
Times[int barSeriesIndex]
Times[int barSeriesIndex][int barsAgo]
```

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

The returned value is dependent upon the property [*CalculateOnClosedBar*](/keywords#calculateonclosedbar).

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

See example [*Multibars*](/handling-bars-and-instruments/multibars).

## Volume <a href="#volume" id="volume"></a>

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

Volume is a [*DataSeries*](/handling-bars-and-instruments/data-series) of the type [*DataSeries*](/handling-bars-and-instruments/data-series), in which the historical volume information is saved.

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

barsAgo Index value (see [*Bars*](/handling-bars-and-instruments/bars))

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

Volume

Volume\[**int** barsAgo]

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

The returned value is dependent upon the property [*CalculateOnClosedBar*](/keywords).

The value returned by the *VOL()* indicator is identical with the volume described here; for example, Vol()\[3] will have the same value as Volume\[3].

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

```csharp
// Volume for the current period
Print(Time[0] + " " + Volume[0]);
// Volume of the bar from 5 periods ago
Print(Time[5] + " " + Volume[5]);
// Current value for the SMA 14 calculated using the volume
Print("SMA(14) calculated using the volume: " + Instrument.Round2TickSize(SMA(Volume, 14)[0]));
```

## Volumes <a href="#volumes" id="volumes"></a>

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

Volumes is an array of [*DataSeries*](/handling-bars-and-instruments/data-series) that contains all [*Volume*](#volume) data series.

This array is only of value for indicators or strategies that use data from multiple timeframes.

A new entry is added to the array whenever a new timeframe is added to an indicator or strategy.

With **\[TimeFrameRequirements(("1 Day"), ("1 Week"))]** the array will contain 3 entries:

Volumes\[0] the volume data series of the chart timeframe Volumes\[1] the volume data series of all bars in the daily timeframe Volumes\[2] the volume data series of all bars in the weekly timeframe

Volumes\[0]\[0] is equivalent to Volumes\[0].

See [*MultiBars*](/handling-bars-and-instruments/multibars).

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

barsAgo Index value of the individual bars within a data series

barSeriesIndex Index value of the various timeframes

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

```csharp
Volumes[int barSeriesIndex]
Volumes[int barSeriesIndex][int barsAgo]
```

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

The returned value is dependent upon the property [*CalculateOnClosedBar*.](/keywords#calculateonclosedbar)

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

See example [*Multibars*](/handling-bars-and-instruments/multibars).

## TimeFrame <a href="#timeframe" id="timeframe"></a>

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

TimeFrame is a timeframe object. This property is used to read the current TimeFrame and not to set it.

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

```
TimeFrame
```

## TimeFrames <a href="#timeframes" id="timeframes"></a>

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

TimeFrames is an array of timeframe objects that contains a timeframe object for each individual bar object.

This array is only of value for indicators or strategies that use data from multiple timeframes.

A new entry is added to the array whenever a new timeframe is added to an indicator or strategy.

With **\[TimeFrameRequirements(("1 Day"), ("1 Week"))]** the array will contain 3 entries:

TimeFrames \[0] Timeframe of the primary data series (chart timeframe) TimeFrames \[1] **Print**(TimeFrames\[1]); // returns "1 Day" TimeFrames \[2] **Print**(TimeFrames\[2]); // returns "1 Week"

TimeFrames \[0] is equivalent to [*TimeFrame*](#timeframe).

See [*MultiBars*](/handling-bars-and-instruments/multibars).

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

barSeriesIndex Index value for the various timeframes

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

```csharp
TimeFrames [int barSeriesIndex]
```

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

```csharp
if (ProcessingBarSeriesIndex == 0 && ProcessingBarIndex == 0)
for (int i = BarsArray.Count-1; i >= 0; i--)
Print("The Indicator " + this.Name + " uses Bars of the Timeframe " + TimeFrames[i]);
```

<br>


# Instruments

The term "instrument" denotes a tradable value such as a stock, ETF, future etc.

An instrument has various properties that can be used in AgenaScripts created by the user:

[*Instrument.Compare*](#instrumentcompare)

[*Instrument.Currency*](#instrumentcurrency)

[*Instrument.Digits*](#instrumentdigits)

[*Instrument.ETF*](#instrumentetf)

[*Instrument.Exchange*](#instrumentexchange)

[*Instrument.Expiry*](#instrumentexpiry)

[*Instrument.GetCurrencyFactor*](#instrumentgetcurrencyfactor)

[*Instrument.InstrumentType*](#instrumentinstrumenttype)

[*Instrument.MainSector*](#instrumentmainsector)

[*Instrument.Margin*](#instrumentmargin)

[*Instrument.Name*](#instrumentname)

[*Instrument.PointValue*](#instrumentpointvalue)

[*Instrument.Round2TickSize*](#instrumentround2ticksize)

[*Instrument.Symbol*](#instrumentsymbol)

[*Instrument.TickSize*](#instrumentticksize)

With the **OnCalculate()** method you can use any properties you wish without having to test for a null reference. As soon as the **OnCalculate()** function is called up by AgenaScript, an object will become available. If you wish to use these properties outside of **OnCalculate()**, you should first perform a test for null references using **if** (Bars != **null**)

## Instrument.Compare <a href="#instrumentcompare" id="instrumentcompare"></a>

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

The Instrument.Compare function compares two market prices whilst taking into account the correct number of decimal points. The smallest possible price change is displayed by the value TickSize. This function simplifies the otherwise time-consuming comparison using floating-point operations.

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

double value1 double value2

#### Return value <a href="#return-value_28" id="return-value_28"></a>

Type int

1 - value1 is bigger than value2 -1 - value1 is smaller than value2 0 - value1 and value2 are equal

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

```csharp
Instrument.Compare(double Value1, double Value2)
```

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

**Be aware this function compares prices based on TickSize.** If the ticksize of your instrument is 0.01 these prices will be rounded and compared on 2 decimal digits. If you want a regular comparation of two numbers, you should use the operator "greater than" (>) or the operator "smaller than" (<).

More infomation about [math.round()](https://msdn.microsoft.com/en-us//library/75ks3aby\(v=vs.110\).aspx)

If the tick size is 0,00001 – as it usually is with FX values – then the following will be displayed:

Compare(2, 1.99999) a 1, meaning 2 is bigger than 1.99999 Compare(2, 2.000001) a 0, meaning the values are equal Compare(2, 1.999999) a 0, meaning the values are equal Compare(2, 2.00001) a -1, meaning 2 is smaller than 2.00001

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

```csharp
Print(Instrument.Compare(2, 1.999999));
```

## Instrument.Currency <a href="#instrumentcurrency" id="instrumentcurrency"></a>

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

Instrument.Currency outputs a currency object that contains the corresponding currency in which the instrument is traded.

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

None

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

A constant of the type "public enum currencies"

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

Instrument.Currency

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

The common currencies are: AUD, CAD, EUR, GBP, JPY or USD.

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

```csharp
Print(Instrument.Name + " is traded in " + Instrument.Currency);
```

## Instrument.Digits <a href="#instrumentdigits" id="instrumentdigits"></a>

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

Instrument.Digits outputs the number of decimal points in which the market price of the instrument is traded.

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

none

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

int Digits

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

Instrument.Digits

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

Stocks are usually traded to two decimal points. Forex can be traded (depending on the data provider) with 4 or 5 decimal places.

This function is especially useful when formatting the output of various instruments that need rounding. Also see [*TickSize*](/keywords#ticksize) and [*Instrument.Round2Ticks*](#instrumentround2ticksize), [*Instrument.Round2TickSize*](#instrumentround2ticksize).

More information can be found here: *Formatting of Numbers*.

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

```csharp
Print("The value of " +Instrument.Name + " is noted with a precision of " + Instrument.Digits +" Decimal points.");
```

## Instrument.ETF <a href="#instrumentetf" id="instrumentetf"></a>

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

Instrument.ETF is used to differentiate between a stock and an ETF. This is necessary since ETFs are considered to be „stocks" by some exchanges.

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

none

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

Type bool

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

Instrument.ETF

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

What is an ETF?

Wikipedia: [*http://de.wikipedia.org/wiki/Exchange-traded\_fund*](http://de.wikipedia.org/wiki/Exchange-traded_fund*)

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

```csharp
if (Instrument.InstrumentType == InstrumentType.Stock)
if (Instrument.ETF)
Print("The value is an ETF.");
else
Print("The value is a stock.");
```

## Instrument.Exchange <a href="#instrumentexchange" id="instrumentexchange"></a>

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

Instrument.Exchange outputs the description/definition of the current exchange for the current instrument.

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

none

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

An exchange object of the type "public enum exchanges"

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

Instrument.Exchange

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

An overview of various exchange: *<https://en.wikipedia.org/wiki/List\\_of\\_stock\\_exchanges>*

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

```csharp
Print("The instrument " + Instrument.Name +" is traded on the " + Instrument.Exchange + " exchange.");
```

## Instrument.Expiry <a href="#instrumentexpiry" id="instrumentexpiry"></a>

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

Instrument.Expiry outputs the date (month and year) of the expiry of a financial instrument. Only derivative instruments such as options or futures will have an expiry date.

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

None

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

Type DateTime

For instruments without an expiry date the returned value is set to DateTime.MaxValue(= 31.12.9999 23.59:59)

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

Instrument.Expiry

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

The expiry date (expiry) can also be seen within the Instrument Escort:

![](https://3984528791-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FSWsZPE35pbN2CTsq7pus%2Fuploads%2FtzPMC5tadRDqHIb37geS%2FExpiry.jpg?alt=media\&token=4d4e09e6-cdeb-4e66-bfbb-a93ec84278fa)

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

```csharp
Print("The instrument " + Instrument.Name +" will expire on " + Instrument.Expiry);
```

## Instrument.GetCurrencyFactor <a href="#instrumentgetcurrencyfactor" id="instrumentgetcurrencyfactor"></a>

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

Instrument.GetCurrencyFactor returns a conversion factor that can be used to convert an instrument's currency to the account's currency.

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

Type Currencies

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

Type double

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

Instrument.GetCurrencyFactor(Currencies)

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

Common currencies are.B. AUD, CAD, EUR, GBP, JPY oder USD.

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

```csharp
Protected override void OnCalculate()
{
   double currFactor = Instrument.GetCurrencyFactor(Account.Currency);
   Print(Close[0] + " in " + Instrument.Currency.ToString() + " = " + (Close[0] * currFactor) + " in " + Account.Currency.ToString());
}
```

## Instrument.InstrumentType <a href="#instrumentinstrumenttype" id="instrumentinstrumenttype"></a>

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

Instrument.InstrumentType outputs a type object of the trading instrument.

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

none

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

Object of the type "public enum instrument"

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

Instrument.InstrumentType

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

Potential values are: future, stock, index, currency, option, CFD and unknown.

There is no ETF type. ETFs are considered to be of the type "stock" – see [*Instrument.ETF*](#instrumentetf).

The instrument type can also be viewed within the Instrument Escort:

![](https://3984528791-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FSWsZPE35pbN2CTsq7pus%2Fuploads%2FuMUAvL98no9BxGU5LyMC%2FInstrumentTypeFGBL.jpg?alt=media\&token=c0f0b225-97d5-4d5f-9101-f153045adb0d)

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

```csharp
Print("The instrument " + Instrument.Name + " is of the type " + Instrument.InstrumentType);
```

## Instrument.MainSector <a href="#instrumentmainsector" id="instrumentmainsector"></a>

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

Instrument.MainSector returns the main sector of the trading instrument.

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

none

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

String

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

Instrument.MainSector

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

The main sector is also visible in the instrument escort:

![](https://3984528791-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FSWsZPE35pbN2CTsq7pus%2Fuploads%2FuMUAvL98no9BxGU5LyMC%2FInstrumentTypeFGBL.jpg?alt=media\&token=c0f0b225-97d5-4d5f-9101-f153045adb0d)

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

```csharp
Print("Das Instrument " + Instrument.Name + " ist im Sektor " + Instrument.MainSector + " tätig.");
```

## Instrument.Margin <a href="#instrumentmargin" id="instrumentmargin"></a>

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

Instrument.MainSector returns the required margin of the trading instrument.

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

none

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

int

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

Instrument.Margin

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

Margin is also visible in the instrument escort:

![](https://3984528791-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FSWsZPE35pbN2CTsq7pus%2Fuploads%2F28x3441VQl66a6JS0zhY%2FMarginFGBL.jpg?alt=media\&token=4963e0ba-e85a-44b8-b109-c20d7e41d677)

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

```csharp
Print("Das Instrument " + Instrument.Name + " has a margin of " + Instrument.Margin);
```

## Instrument.Name <a href="#instrumentname" id="instrumentname"></a>

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

Instrument.Name outputs the name/description of the trading instrument.

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

none

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

Type string

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

Instrument.Name

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

The instrument name can also be seen within the Instrument Escort:

![](https://3984528791-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FSWsZPE35pbN2CTsq7pus%2Fuploads%2FMdNkgryys6mJQHtvd8Zd%2FName_Fdax.jpg?alt=media\&token=0e0986d5-3278-4693-88a7-83b1253481a0)

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

```csharp
Print("The currently loaded instrument inside the chart is named " + Instrument.Name);
```

## Instrument.PointValue <a href="#instrumentpointvalue" id="instrumentpointvalue"></a>

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

Instrument.PointValue outputs the monetary value for a full point movement of the instrument.

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

none

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

double – point value

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

Instrument.PointValue

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

**Example for various point values** (per amount, CFD, futures contract, lot etc.)

Stock: generally 1.00 Euro or 1.00 USD. EUR/USD: 100,000 USD DAX future: 25.00 Euro

**Tick Value**

The tick value can be calculated by multiplying the point value with the tick size.

For example, the E-mini S\&P 500 has a point value of $50. The tick size equals 0.25. This means that there are 4 ticks in one full point for the E-mini S\&P 500. Since 50 \* 0.25 = 50/4 this means that the tick value is $12.50.

The point value can also be viewed within the Instrument Escort:

![](https://3984528791-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FSWsZPE35pbN2CTsq7pus%2Fuploads%2FgIGzwbBnjcCtsUdt3UEM%2FFdax_PointValue.jpg?alt=media\&token=025d226d-fb24-4057-9f7e-e741a8ba63f2)

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

```csharp
Print("When " + Instrument.Name + " rises for one full point then this is equal to " + Instrument.PointValue + " " + Instrument.Currency);
```

## Instrument.Round2TickSize <a href="#instrumentround2ticksize" id="instrumentround2ticksize"></a>

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

The function Instrument.Round2TickSize rounds the supplied market price to the smallest value divisible by the tick size of the instrument.

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

double – market value

#### Return value <a href="#return-value_40" id="return-value_40"></a>

double

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

```csharp
Instrument.Round2TickSize(double MarketPrice)
```

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

The number of decimal places to which the price is rounded depends on the instrument. If, for example, an instrument is a stock, then the rounding will be performed to 2 decimal places. For a Forex instrument, it may be carried out to 4 or 5 decimal places.

See [*TickSize*](/keywords#ticksize) and [*Instrument.Digits*](#instrumentdigits).

Example of professional *Formatting*, *Formatting of Numbers*.

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

```csharp
double Price = 12.3456789;
Print(Price + " rounded for a " + Instrument.Name + " valid value is " + Instrument.Round2TickSize(Price));
```

## Instrument.Symbol <a href="#instrumentsymbol" id="instrumentsymbol"></a>

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

Instrument.Symbol outputs the symbol that identifies the trading instrument within AgenaTrader. Depending on the symbol, the mappings for the various data feed providers and brokers will be managed in different ways.

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

none

#### Return value <a href="#return-value_41" id="return-value_41"></a>

Type string

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

Instrument.Symbol

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

By using symbols, identical stocks being traded on different exchanges can be identified and separated from each other. The symbol BMW\.DE is the BMW stock on the XETRA exchange. BMW\.CFG is the CFD for the BMW stock.

The instrument symbol can also be viewed within the Instrument Escort:

![](https://3984528791-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FSWsZPE35pbN2CTsq7pus%2Fuploads%2FOs6rM4lWesU7UWcRwVLI%2FFdax_Symbol.jpg?alt=media\&token=7ef959b8-dc65-40f6-bd2e-8828cbba025f)

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

```csharp
Print("The instrument currently loaded within the chart has the symbol: " + Instrument.Symbol);
```

## Instrument.TickSize <a href="#instrumentticksize" id="instrumentticksize"></a>

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

The tick size is the smallest measurable unit that a financial instrument can move. This is usually called 1 tick.

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

none

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

double

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

Instrument.TickSize or simply TickSize

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

The keyword [*TickSize*](/keywords#ticksize) is equivalent to Instrument.TickSize. Both information requests will produce the same value and are thus interchangeable.

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

Stock: 0.01 ES future: 0.25 EUR/USD: 0.00001

See [*Instrument.PointValue*](#instrumentpointvalue) and [*Instrument.Digits*](#instrumentdigits).

Examples of professional *Formatting*, *Formatting of Numbers*.

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

```csharp
Print("The value of " + Instrument.Name + " can change for a minimum of " + Instrument.TickSize + " Tick(s).");
```


# Multibars

## Multibars

An indicator or a strategy will always have the same underlying timeframe-units as those units being displayed within the chart. The values of an SMA(14) indicator displayed in a 5 minute chart will be calculated based on the last fourteen 5 minute bars. A daily chart, on the other hand, would use the closing prices of the past 14 days in order to calculate this value. The same method applies for your self-programmed indicators. A 5 minute chart will call up the [*OnCalculate()*](/events#oncalculate) for each 5 minute bar. If you want your self-created indicator to use a different timeframe, this is possible using multibars.

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

```csharp
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
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
{
    [Description("Multibar Demo")]
    // The indicator requires daily and weekly data
    [TimeFrameRequirements("1 Day", "1 Week")]
    public class MultiBarDemo : UserIndicator
    {
        private static readonly TimeFrame TF_Day = new TimeFrame(DatafeedHistoryPeriodicity.Day, 1);
        private static readonly TimeFrame TF_Week = new TimeFrame(DatafeedHistoryPeriodicity.Week, 1);

        protected override void OnBarsRequirements()
        {
            Add(TF_Day);
            Add(TF_Week);
        }

        protected override void OnInit()
        {
            CalculateOnClosedBar = true;
        }
        protected override void OnCalculate()
        {
            // The current value for the SMA 14 in the timeframe of the chart
            Print("TF0: " + SMA(Closes[0], 14)[0]);
            // The current value for the SMA 14 in a daily timeframe
            Print("TF1: " + SMA(Closes[1], 14)[0]);
            // Current value for the SMA 14 in a weekly timeframe
            Print("TF2: " + SMA(Closes[2], 14)[0]);
        }
    }
}
```

#### Additional Notes <a href="#additional-notes" id="additional-notes"></a>

When using additional timeframes, a further entry with the respective data series for the bars of the new timeframe will be added to the arrays [*Opens*](/handling-bars-and-instruments/data-series#opens), [*Highs*](/handling-bars-and-instruments/data-series#highs), [*Lows*](/handling-bars-and-instruments/data-series#lows), [*Closes*](/handling-bars-and-instruments/data-series#closes), [*Medians*](/handling-bars-and-instruments/data-series#medians), [*Typicals*](/handling-bars-and-instruments/data-series#typicals), [*Weighteds*](/handling-bars-and-instruments/data-series#weighteds), [*Times*](/handling-bars-and-instruments/data-series#times) and [*Volumes*](/handling-bars-and-instruments/data-series#volumes). The indexing will occur in the order of the addition of the new timeframes. Closes\[0]\[0] is equivalent to Close\[0]. Closes\[1]\[0] equals the current closing price for the daily data series Closes\[2]\[0] equals the current closing price for the weekly data series

"Closes" is, of course, interchangeable with Opens, Highs, Lows etc.

See [*ProcessingBarIndexes*](#processingbarindexes), [*ProcessingBarSeriesIndex*](#processingbarseriesindex), [*TimeFrames*](/handling-bars-and-instruments/data-series#timeframes).

Additional syntax methods are available for multibars:

```csharp
// Declare the variable TF_DAY and define it
private static readonly TimeFrame TF_Day = new TimeFrame(DatafeedHistoryPeriodicity.Day, 1);
private static readonly TimeFrame TF_Week = new TimeFrame(DatafeedHistoryPeriodicity.Week, 1);
// The following instruction is identical to double d = Closes[1][0];
double d = MultiBars.GetBarsItem(TF_Day).Close[0];
// The following instruction is identical to double w = Closes[2][0];
double w = MultiBars.GetBarsItem(TF_Week).Close[0];
```

## ProcessingBarIndexes <a href="#processingbarindexes" id="processingbarindexes"></a>

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

ProcessingBarIndexes is an array of int values that contains the number of [*ProcessingBarIndex*](#processingbarindexes) for each bar.

This array is only of value for indicators or strategies that use data from multiple timeframes.

A new entry is added to the array whenever a new timeframe is added to an indicator or strategy.

With **\[TimeFrameRequirements(("1 Day"), ("1 Week"))]** the array will contain 3 entries:

ProcessingBarIndexes\[0] Current bar for the primary data series (chart timeframe) ProcessingBarIndexes\[1] Current bar for the daily bars ProcessingBarIndexes\[2] Current bar for the weekly bars

ProcessingBarIndexes\[0] is equivalent to [*ProcessingBarIndex*](#processingbarindexes).

Also see [*MultiBars*](#multibars).

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

barSeriesIndex Index value for the various timeframes

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

```csharp
ProcessingBarIndexes[int barSeriesIndex]
```

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

```csharp
//Ensure that a minimum of 20 bars is loaded
for (int i=0; i<ProcessingBarIndexes.Count; i++)
if (ProcessingBarIndexes[i] < 20) return;
```

## ProcessingBarSeriesIndex <a href="#processingbarseriesindex" id="processingbarseriesindex"></a>

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

Within a multibars script, multiple bars objects are available. The [*OnCalculate()*](/events#oncalculate) method will therefore also be called up for every bar within your script. In order to include/exclude events of specific data series, you can use the ProcessingBarSeriesIndex property.

ProcessingBarSeriesIndex is only of value for indicators or strategies that use data from multiple timeframes. With **\[TimeFrameRequirements("1 Day", "1 Week")]** two timeframes will be added to the primary chart timeframe.

If OnCalculate() is called up by the primary data series, then ProcessingBarSeriesIndex will equal zero. If OnCalculate() is called up by the daily bars, then ProcessingBarSeriesIndex will equal 1. Weekly bars will have a value of 2.

See [*Multibars*](#multibars) and [*ProcessingBarIndexes*](#processingbarindexes).

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

none

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

ProcessingBarSeriesIndex

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

Within a script that only works with primary timeframes, the value will always equal zero.

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

```csharp
// To demonstrate the methodology
// set CalculateOnClosedBar=false
Print(Time[0] + " " + ProcessingBarSeriesIndex);
// Calculate only for the chart timeframe
protected override void OnCalculate()
{
if (ProcessingBarSeriesIndex > 0) return;
// Logic for the primary data series
}

```


# 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#addoutput)
* [*AllowRemovalOfChartDrawings*](/keywords#allowremovalofchartdrawings)
* *IsAutoScale*
* [*RequiredBarsCount*](/keywords#requiredbarscount)
* [*CalculateOnClosedBar*](/keywords#calculateonclosedbar)
* [*ClearTraceWindow()*](/keywords#cleartracewindow)
* [*Displacement*](/keywords#displacement)
* [*IsShowInDataBox*](/keywords#isshowindatabox)
* [*IsAddDrawingsToPricePanel*](/keywords#isadddrawingstopricepanel)
* [*InputPriceType*](/keywords#inputpricetype)
* [*IsOverlay*](/keywords#isoverlay)
* [*IsShowPriceMarkers*](/keywords#isshowpricemarkers)
* [*IsShowChartVerticalGrid*](/keywords#isshowchartverticalgrid)

**Additional Keywords for Strategies**

* [*DefaultOrderQuantity*](/strategy-programming#defaultorderquantity)
* *EntriesPerDirection*
* [*SetUpStopLoss()*](/strategy-programming#setupstoploss)
* [*SetUpProfitTarget()*](/strategy-programming#setupprofittarget)
* [*SetUpTrailStop()*](/strategy-programming#setuptrailstop)
* [*TimeInForce*](/strategy-programming#timeinforce)
* [*TraceOrders*](/strategy-programming#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)

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#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#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>


# Strategy Programming

### Account <a href="#account" id="account"></a>

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

Account is an object containing information about the account with which the current strategy is working.

The individual properties are:

* **Account.AccountConnection** Name for the broker connection used (the name assigned under the account connection submenu)
* **Account.AccountType** Type of account (live account, simulated account etc.)
* **Account.Broker** Name/definition for the broker
* **Account.BuyingPower** The current account equity in consideration of the leverage provided by the broker (IB leverages your account equity by a factor of 4, meaning that with 10000€ your buying power is equal to 40000€)
* **Account.CashValue** Amount (double)
* **Account.Currency** Currency in which the account is held
* **Account.IsDemo** True, if the account is a demo account
* **Account.Name** Name of the account (should be identical to Account.AccountConnection)
* **Account.RealizedProfitLoss** Realized profits and losses (double)

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

```csharp
Print("AccountConnection " + Account.AccountConnection);
Print("AccountType " + Account.AccountType);
Print("Broker " + Account.Broker);
Print("BuyingPower " + Account.BuyingPower);
Print("CashValue " + Account.CashValue);
Print("Currency " + Account.Currency);
Print("InstrumentTypes " + Account.InstrumentTypes);
Print("IsDemo " + Account.AccountType == AccountType.Simulate);
Print("Name " + Account.Name);
Print("RealizedProfitLoss " + Account.RealizedProfitLoss);
```

### BarsCountFromTradeClose() <a href="#barscountfromtradeclose" id="barscountfromtradeclose"></a>

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

The property "BarsCountFromTradeClose" outputs the number of bars that have occurred since the last exit from the market.

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

```csharp
BarsCountFromTradeClose()
BarsCountFromTradeClose(string strategyName)
```

For multi-bar strategies

```csharp
BarsCountFromTradeClose(int multibarSeriesIndex, string strategyName, int exitsAgo)
```

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

|                     |                                                                                                                                                                                                                                                        |
| ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| strategyName        | The Strategy name (string) that has been used to clearly label the exit within the exit method.                                                                                                                                                        |
| multibarSeriesIndex | For \*[*MultiBars* ](/handling-bars-and-instruments/multibars#multibars)strategies. Index of the data series for which the exit order has been executed. See [*ProcessingBarSeriesIndex*](/handling-bars-and-instruments/bars#processingbarindexlast). |
| exitsAgo            | Number of exits that have occurred in the past. A zero indicates the number of bars that have formed after the last exit.                                                                                                                              |

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

```csharp
Print("The last exit was " + BarsCountFromTradeClose() + " bars ago.");
```

### BarsCountFromTradeOpen() <a href="#barscountfromtradeopen" id="barscountfromtradeopen"></a>

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

The property "BarsCountFromTradeOpen" returns the number of bars that have occurred since the last entry into the market.

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

```csharp
BarsCountFromTradeOpen()
BarsCountFromTradeOpen(string strategyName)
```

For multi-bar strategies

```csharp
BarsCountFromTradeOpen(int multibarSeriesIndex, string strategyName, int entriesAgo)
```

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

|                     |                                                                                                                                                                                                                                                        |
| ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| strategyName        | The strategy name (string) that has been used to clearly label the entry within an entry method.                                                                                                                                                       |
| multibarSeriesIndex | For \*[*MultiBars* ](/handling-bars-and-instruments/multibars#multibars)strategies. Index of the data series for which the exit order has been executed. See [*ProcessingBarSeriesIndex*](/handling-bars-and-instruments/bars#processingbarindexlast). |
| entriesAgo          | Number of entries in the past. A zero indicates the number of bars that have formed after the last entry.                                                                                                                                              |

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

```csharp
Print("The last entry was " + BarsCountFromTradeOpen() + " bars ago.");
```

### CancelAllOrders() <a href="#cancelallorders" id="cancelallorders"></a>

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

CancelAllOrders deletes all oders (cancel) managed by the strategy. A cancel request is sent to the broker. Whether an or there is really deleted, can not be guaranteed. It may happen that an order has received a partial execution before it is deleted. Therefore we recommend that you check the status of the order with [*OnOrderChanged()*](/events#onorderchanged).

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

```csharp
CancelAllOrders()
```

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

None

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

```csharp
protected override void OnCalculate()
{
   if (BarsCountFromTradeOpen() >= 30)
       CancelAllOrders();
}
```

### Order.CancelOrder() <a href="#ordercancel" id="ordercancel"></a>

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

Cancel order deletes an order.

A cancel request is sent to the broker. There is no guarantee that the order will actually be deleted there. It may occur that the order receives a partial execution before it is deleted. Therefore we recommend that you check the status of the order with [*OnOrderChanged()*](/events#onorderchanged).

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

```csharp
Order.CancelOrder()
```

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

An order object of the type "IOrder"

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

```csharp
private IOrder entryOrder = null;
private int barNumber = 0;
protected override void OnCalculate()
{
    // Place an entry stop at the high of the current bar
    if (entryOrder == null)
    {
         entryOrder=  SubmitOrder(new StrategyOrderParameters
                {
                    Direction = OrderDirection.Buy,
                    Type = OrderType.Stop,
                    StopPrice = High[0],
                    Quantity = 100,
                    SignalName = "strategyName",
                });
        
        barNumber = ProcessingBarIndex;
    }
    // Delete the order after 3 bars
    if (Position.PositionType == PositionType.Flat &&
    ProcessingBarIndex > barNumber + 3)
        entryOrder.CancelOrder();
}
```

### CreateIfDoneGroup() <a href="#createifdonegroup" id="createifdonegroup"></a>

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

If two orders are linked to one another via a CreateIfDoneGroup, it means that if the one order has been executed, the second linked order is activated.

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

```csharp
CreateIfDoneGroup(IEnumerable<IOrder> orders)
```

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

An order object of type IOrder as a list

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

```csharp
private IOrder oopenlong = null;
private IOrder osubmitbuy = null;


protected override void OnInit()
{
   IsAutoConfirmOrder = false;
}


protected override void OnCalculate()
{

 oopenlong =  SubmitOrder(new StrategyOrderParameters
                {
                    Direction = OrderDirection.Buy,
                    Type = OrderType.Market,
                    Quantity = DefaultOrderQuantity,
                    SignalName = "strategyName",
                });

osubmitbuy =  SubmitOrder(new StrategyOrderParameters
                {
                    Direction = OrderDirection.Sell,
                    Type = OrderType.Stop,
                    Quantity = DefaultOrderQuantity,
            StopPrice = Close[0] * 1.1,
                    SignalName = "strategyName",
                });

   CreateIfDoneGroup(new List<IOrder> { oopenlong, osubmitbuy });

   oopenlong.ConfirmOrder();
}
```

### CreateOCOGroup() <a href="#createocogroup" id="createocogroup"></a>

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

If two orders are linked via a CreateOCOGroup, it means that once the one order has been executed, the second linked order is deleted.

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

```csharp
CreateOCOGroup(IEnumerable<IOrder> orders)
```

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

An order object of type IOrder as a list

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

```csharp
private IOrder oopenlong = null;
private IOrder oEnterShort = null;


protected override void OnInit()
{
   IsAutoConfirmOrder = false;
}


protected override void OnCalculate()
{

oopenlong =  SubmitOrder(new StrategyOrderParameters
                {
                    Direction = OrderDirection.Buy,
                    Type = OrderType.Stop,
                    Quantity = DefaultOrderQuantity,
            StopPrice = Close[0] * 1.1,
                    SignalName = "strategyName",
                });


oEnterShort =  SubmitOrder(new StrategyOrderParameters
                {
                    Direction = OrderDirection.Sell,
                    Type = OrderType.Stop,
                    Quantity = DefaultOrderQuantity,
            StopPrice = Close[0] * -1.1,
                    SignalName = "strategyName",
                });



   CreateOCOGroup(new List<IOrder> { oopenlong, oEnterShort });

   oopenlong.ConfirmOrder();
   oEnterShort.ConfirmOrder();
}
```

### CreateOROGroup() <a href="#createorogroup" id="createorogroup"></a>

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

If two orders are linked via a CreateOROGroup, it means that once the one order has been executed, the order size of the second order is reduced by the order volume of the first order.

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

```csharp
CreateOROGroup(IEnumerable<IOrder> orders)
```

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

An order object of type IOrder as a list

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

```csharp
private IOrder oStopLong = null;
private IOrder oLimitLong = null;


protected override void OnInit()
{
   IsAutoConfirmOrder = false;
}


protected override void OnCalculate()
{

   oStopLong =  SubmitOrder(new StrategyOrderParameters
                {
                    Direction = OrderDirection.Buy,
                    Type = OrderType.Stop,
                    Quantity = DefaultOrderQuantity,
            StopPrice = Close[0] * -1.1,
                    SignalName = "strategyName",
                });




   oLimitLong =  SubmitOrder(new StrategyOrderParameters
                {
                    Direction = OrderDirection.Buy,
                    Type = OrderType.Limit,
                    Quantity = DefaultOrderQuantity*0.5,
            Price = Close[0] * 1.1,
                    SignalName = "strategyName",
                });

   CreateOROGroup(new List<IOrder> { oLimitLong, oStopLong });
}
```

### DataSeriesConfigurable <a href="#dataseriesconfigurable" id="dataseriesconfigurable"></a>

### DefaultOrderQuantity <a href="#defaultorderquantity" id="defaultorderquantity"></a>

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

Change order changes an order.

Default quantity defines the amount to be used in a strategy. Default quantity is set within the [*OnInit()*](/keywords#oninit) method.

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

```csharp
ReplaceOrder(IOrder iOrder, int quantity, double limitPrice, double stopPrice)
```

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

An int value containing the amount (stocks, contracts etc.)

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

```csharp
protected override void OnInit()
{
DefaultOrderQuantity = 100;
}
```

### ExcludeTradeHistoryInBacktest <a href="#excludetradehistoryinbacktest" id="excludetradehistoryinbacktest"></a>

### CloseLongTrade () <a href="#closelongtrade" id="closelongtrade"></a>

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

CloseLongTrade creates a sell order for closing a long position (sell).

See: [SubmitOrder()](#submitorder), [CloseShortTrade()](#closeshorttrade)

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

See [*StrategyOrderParameters*](#strategyorderparameters)

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

See [*StrategyOrderParameters*](#strategyorderparameters)

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

An order object of the type "IOrder"

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

```csharp
var order = CloseLongTrade(new StrategyOrderParameters
{
    Type = OrderType.Market
});
```

### ExitOnClose <a href="#exitonclose" id="exitonclose"></a>

### ExitOnCloseSeconds <a href="#exitoncloseseconds" id="exitoncloseseconds"></a>

### CloseShortTrade() <a href="#closeshorttrade" id="closeshorttrade"></a>

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

CloseShortTradecreates a buy-to-cover order for closing a short position (buy).

See: [SubmitOrder()](#submitorder), [*CloseLongTrade()*](#closelongtrade)

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

See [*StrategyOrderParameters*](#strategyorderparameters)

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

See [*StrategyOrderParameters*](#strategyorderparameters)

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

An order object of the type "IOrder"

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

```csharp
var order = CloseShortTrade(new StrategyOrderParameters
{
    Type = OrderType.Stop,
    Quantity = quantity,
    StopPrice = price
});
```

### Account.GetValue() <a href="#accountgetvalue" id="accountgetvalue"></a>

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

Get account value outputs information regarding the account for which the current strategy is being carried out.

See [*GetProfitLoss()*.](#getprofitloss)

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

```csharp
Account.GetValue(AccountItem accountItem)
```

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

Possible values for account item are:

AccountItem.BuyingPower

AccountItem.CashValue

AccountItem.RealizedProfitLoss

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

A double value for the account item for historical bars, a zero (0) is returned

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

```csharp
Print("The current account cash value is " + Account.GetValue(AccountItem.CashValue));
Print("The current account cash value with the leverage provided by the broker is " + Account.GetValue(AccountItem.BuyingPower));
Print("The current P/L already realized is " + Account.GetValue(AccountItem.RealizedProfitLoss));
```

### GetEntries() <a href="#getentries" id="getentries"></a>

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

This DataSeries is used in conditions and indicates multiple entry prices for entry orders

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

Overload in scripted condition for short and long signal indication

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

None

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

int

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

```csharp
public class MyTestEntry : UserScriptedCondition
    {

        double _percentage = 100;

        protected override void Initialize()
        {
            IsEntry = true;
            IsStop = false;
            IsTarget= false;
            Add(new OutputDescriptor(Color.FromKnownColor(KnownColor.Black), "Occurred"));
            Add(new OutputDescriptor(Color.FromArgb(255, 118, 222, 90), "Entry1"));
            Add(new OutputDescriptor(Color.FromArgb(255, 118, 222, 90), "Entry2"));
            Add(new OutputDescriptor(Color.FromArgb(255, 118, 222, 90), "Entry3"));
            Overlay = true;
            CalculateOnBarClose = true;
        }

        protected override void OnBarUpdate()
        {

            Calculate();

        }

        public override void Recalculate()
        {
            Calculate();
        }

        private void Calculate ()
        {

            if (TradeDirection == PositionType.Long)
            {
                Entry1.Set(Close[0] + 0.5);
                Entry2.Set(Close[0] + 1);
                Entry3.Set(Close[0] + 1.5);
            }
            else
            {
                Entry1.Set(Close[0] - 0.5);
                Entry2.Set(Close[0] - 1);
                Entry3.Set(Close[0] - 1.5);
            }
        }

        #region Properties

        [Browsable(false)]
        [XmlIgnore()]
        public DataSeries Occurred
        {
            get { return Values[0]; }
        }

        [Browsable(false)]
        [XmlIgnore()]
        public DataSeries Entry1
        {
            get { return Values[1]; }
        }

        [Browsable(false)]
        [XmlIgnore()]
        public DataSeries Entry2
        {
            get { return Values[2]; }
        }

        [Browsable(false)]
        [XmlIgnore()]
        public DataSeries Entry3
        {
            get { return Values[3]; }
        }

        public override IList<DataSeries> GetEntrys()
        {
            return new[] { Entry1, Entry2, Entry3 };
```

### GetProfitLoss() <a href="#getprofitloss" id="getprofitloss"></a>

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

Get profit loss outputs the currently unrealized profit or loss for a running position.

See [*Account.GetValue()*.](#accountgetvalue)

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

```csharp
GetProfitLoss(int pLType);
```

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

Potential values for the P/L type are:

0 – Amount: P/L as a currency amount

1 – Percent: P/L in percent

2 – Risk: P/L in Van Tharp R-multiples [*www.vantharp.com*](http://www.vantharp.com/tharp-concepts/risk-and-r-multiples.asp)

3 – P/L in ticks

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

A double value for the unrealized profit or loss

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

```csharp
Print("The current risk for the strategy " + this.Name + " is " + GetProfitLoss(1) + " " + Instrument.Currency);
Print("This equals "+ string.Format( "{0:F1} R.", GetProfitLoss(3)));
```

### GetProfitLossAmount() <a href="#getprofitlossamount" id="getprofitlossamount"></a>

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

GetProfitLossAmount () provides the current unrealized gain or loss of a current position as the currency amount.

See [*Account.GetValue()*.](#accountgetvalue)

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

```csharp
GetProfitLossAmount(double profitLoss);
```

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

Double

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

A double value for the unrealized profit or loss

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

```csharp
Print("the current P&L " + this.Name + " is " + GetProfitLossAmount(Position.OpenProfitLoss) + " " + Instrument.Currency);
```

### GetProfitLossRisk() <a href="#getprofitlossrisk" id="getprofitlossrisk"></a>

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

GetProfitLossRisk () returns the current unrealized gain or loss of a current position in R-multiples.

See [*Account.GetValue()*.](#accountgetvalue)

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

```csharp
GetProfitLossRisk();
```

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

None

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

A double value for the R-Multiple

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

```csharp
Print("the current P&L " + this.Name + " is " + string.Format( "{0:F1} R.", GetProfitLossRisk()));
```

### GetScriptedCondition() <a href="#getscriptedcondition" id="getscriptedcondition"></a>

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

This method allows user to communicate between scripts.

### IsAutoConfirmOrder <a href="#isautoconfirmorder" id="isautoconfirmorder"></a>

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

IsAutoConfirmOrder determines whether orders are activated automatically. IsAutoConfirmOrder is specified in the [*OnInit()* ](/keywords#oninit)method.

If IsAutoConfirmOrder = true, then orders are automatically activated (default). If IsAutoConfirmOrder is assigned the value false, the corresponding order must be activated with order.

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

Bool value

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

```csharp
protected override void OnInit()
{
   IsAutoConfirmOrder = false;
}
```

### Order <a href="#order" id="order"></a>

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

IOrder is an object that contains information about an order that is currently managed by a strategy.

The individual properties are:

* Action **One of four possible positions in the market:**
  * OrderDirection.Buy
  * OrderDirection.Sell
* **AveragePrice** **The average purchase or selling price of a position.For positions without partial executions, this corresponds to the entry price.**
* **FilledQuantity** For partial versions
* **LimitPrice**
* **Name**    The unique SignalName (maybe mistake SignalName)
* **OrderId** The unique OrderId
* **OrderMode** One of three possible positions in the market:
  * OrderMode.Direct
  * OrderMode.Dynamic
  * OrderMode.Synthetic
* **OrderState** The current status of the order can be queried (see *OnOrderExecution* and *OnOrderChanged*)
  * OrderState.Accepted
  * OrderState.Cancelled
  * OrderState.CancelRejected
  * OrderState.FilledQuantity
  * OrderState.PartFilled
  * OrderState.PendingCancel
  * OrderState.PendingReplace
  * OrderState.PendingSubmit
  * OrderState.Rejected
  * OrderState.ReplaceRejected
  * OrderState.Unknown
  * OrderState.Working
* **OrderType** Possible order types:
  * OrderType.Limit
  * OrderType.Market
  * OrderType.Stop
  * OrderType.StopLimit
* **Quantity** The quantity to be ordered
* **StopPrice**
* **Timestamp** Time stamp
* **TimeFrame** The TimeFrame, which is valid for the order.
* **TimeFrame**

Possible Methods:

* **order Order.Cancel()** Delete the Order
* **order.ConfirmOrder()** Confirm the order. This method have to be executed if IsAutoConfirmOrder is set to false and you want to run the order automatically. This is, for example, the case when an OCO or IfDone fabrication is to be produced.

### Performance <a href="#performance" id="performance"></a>

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

Performance is an object containing information regarding all trades that have been generated by a strategy.

The trades are sorted into multiple lists. With the help of these lists it is easier to create a performance evaluation.

See Performance Characteristics.

The individual lists are:

* **Performance.AllTrades** A [*Trade*](#trade) collection object containing all trades generated by a strategy.
* **Performance.LongTrades** A [*Trade*](#trade) collection object containing all long trades generated by a strategy.
* **Performance.ShortTrades** A [*Trade*](#trade) collection object containing all short trades generated by a strategy.
* **Performance.WinningTrades** A [*Trade*](#trade) collection object containing all profitable trades generated by a strategy.
* **Performance.LosingTrades** A [*Trade*](#trade) collection object containing all loss trades generated by a strategy.

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

```csharp
// When exiting a strategy, create a performance evaluation
protected override void OnDispose()
{
Print("Performance evaluation of the strategy : " + this.Name);
Print("----------------------------------------------------");
Print("Amount of all trades: " + Performance.AllTrades.Count);
Print("Amount of winning trades: " + Performance.WinningTrades.Count);
Print("Amount of all loss trades: " + Performance.LosingTrades.Count);
Print("Amount of all long trades: " + Performance.LongTrades.Count);
Print("Amount of short trades: " + Performance.ShortTrades.Count);
Print("Result: " + Account.RealizedProfitLoss + " " + Account.Currency);
}
```

### Position <a href="#position" id="position"></a>

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

Position is an object containing information regarding the position currently being managed by a strategy.

The individual properties are:

* **Position.AvgPrice** The average buy or sell price of a position. For positions without partial executions, this is equal to the entry price.
* **Position.CreatedDateTime** Date and time at which the position was opened.
* **Position.Instrument** The trading instrument in which the position exists. See *Instruments*.
* **Position.PositionType** One of three possible positions in the market:
  * PositionType.Flat
  * PositionType.Long
  * PositionType.Short
* **Position.OpenProfitLoss** The currently not yet realized profit or loss. See [*GetProfitLoss()*.](#getprofitloss)
* **Position.ProfitCurrency** Profit (or loss) displayed as a currency amount.
* **Position.ProfitPercent** Profit (or loss) displayed in percent.
* **Position.ProfitPoints** Profit (or loss) displayed in points or pips.
* **Position.Quantity** Amount of stocks, contracts, CFDs etc. within a position.

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

```csharp
if (Position.PositionType != PositionType.Flat)
{
Print("Average price " + Position.AvgPrice);
Print("Opening time " + Position.CreatedDateTime);
Print("Instrument " + Position.Instrument);
Print("Current positioning " + Position.PositionType);
Print("Unrealized P/L " + Position.OpenProfitLoss);
Print("P/L (currency) " + Position.ProfitCurrency);
Print("P/L (in percent) " + Position.ProfitPercent);
Print("P/L (in points) " + Position.ProfitPoints);
Print("Pieces " + Position.Quantity);
}
```

### PositionType <a href="#positiontype" id="positiontype"></a>

See ***Position.PositionType*****.**

### TraceOrders <a href="#traceorders" id="traceorders"></a>

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

The trace orders property is especially useful for keeping track of orders generated by strategies. It also provides an overview of which orders were generated by which strategies. Trace orders can be specified with the [*OnInit()*](/keywords#oninit) method.

When TraceOrders is activated, each order will display the following values in the output window:

* Instrument
* Time frame
* Action
* Type
* Limit price
* Stop price
* Quantity
* Name

This information is useful when creating and debugging strategies.

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

TraceOrders

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

none

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

**true** Tracing is currently switched on **false** Tracing is switched off

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

```csharp
protected override void OnInit()
{
ClearTraceWindow();
TraceOrders = true;
}
```

### Quantity <a href="#quantity" id="quantity"></a>

See ***Position.Quantity***, ***Position.PositionType*****.**

### ReplaceOrder() <a href="#replaceorder" id="replaceorder"></a>

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

Change order, as the name suggests, changes an order.

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

```csharp
ReplaceOrder(IOrder iOrder, int quantity, double limitPrice, double stopPrice)
```

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

|            |                                          |
| ---------- | ---------------------------------------- |
| iOrder     | An order object of the type "IOrder"     |
| quantity   | Number of units to be ordered            |
| limitPrice | Limit price. Set this to 0 if not needed |
| stopPrice  | Stop price. Set this to 0 if not needed  |

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

```csharp
private IOrder stopOrder = null;
protected override void OnCalculate()
{
// If the position is profiting by 10 ticks then set the stop to break-even
if (stopOrder != null
    && Close[0] >= Position.AvgPrice + (10 * TickSize)
        && stopOrder.StopPrice < Position.AvgPrice)
ReplaceOrder(stopOrder, stopOrder.Quantity, stopOrder.LimitPrice, Position.AvgPrice);
}
```

### SetUpProfitTarget() <a href="#setupprofittarget" id="setupprofittarget"></a>

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

Set profit target immediately creates a "take profit" order after an entry order is generated. The order is sent directly to the broker and becomes active immediately. If the profit target is static, you can also define SetUpProfitTarget() with the OnInit() method.

See [*SetUpStopLoss()*](#setupstoploss), [*SetUpTrailStop()*](#setuptrailstop).

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

```csharp
SetUpProfitTarget(double currency)
SetUpProfitTarget(CalculationMode mode, double value)
SetUpProfitTarget(string fromEntry signal, CalculationMode mode, double value)
```

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

|                  |                                                                                                                                                                         |
| ---------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| currency         | Sets the profit target in a currency, for example 500€.                                                                                                                 |
| mode             | Potential values can be: CalculationMode.Percent (display in percent); CalculationMode.Price (display as price value); CalculationMode.Ticks (display in ticks or pips) |
| value            | The distance between entry price and profit target. This is dependent upon the „mode" but generally refers to a monetary value, a percentage or a value in ticks.       |
| fromEntry signal | The name of the entry signal for which the profit target is to be generated. The amount is taken from the entry order referenced.                                       |

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

```csharp
protected override void OnInit()
{
// Creates a Target Order 20 ticks above the market
SetUpProfitTarget(CalculationMode.Ticks, 20);
}
```

### SetUpStopLoss() <a href="#setupstoploss" id="setupstoploss"></a>

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

Set stop loss creates a stop loss order after an entry order is placed. The order is sent directly to the broker and becomes effective immediately.

If the stop loss is static, then SetUpStopLoss() can be defined with the OnInit() method.

See [*SetUpProfitTarget()*](#setupprofittarget), [*SetUpTrailStop()*](#setuptrailstop).

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

```csharp
SetUpStopLoss(double currency)
SetUpStopLoss(double currency, bool simulated)
SetUpStopLoss(CalculationMode mode, double value)
SetUpStopLoss(string fromEntry signal, CalculationMode mode, double value, bool simulated)
```

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

|                  |                                                                                                                                                                                                             |
| ---------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| currency         | The difference between the stop loss and the entry price (=risk) in a currency, such as 500€                                                                                                                |
| mode             | Potential values can be: CalculationMode.Percent (display in percent); CalculationMode.Price (display as price value); CalculationMode.Ticks (display in ticks or pips)                                     |
| simulated        | When set to "true," the stop order does not go live (as a market order) until the price has „touched" it for the first time (meaning that it is executed just as it would be under real market conditions). |
| value            | The distance between stop price and profit target. This is dependent upon the „mode" but generally refers to a monetary value, a percentage or a value in ticks.                                            |
| fromEntry signal | The name of the entry signal for which the stop order is to be generated. The amount is taken from the entry order referenced.                                                                              |

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

```csharp
protected override void OnInit()
{
// Sets profitTarget 15 Ticks above the market
SetUpStopLoss("MACDEntry", CalculationMode.Ticks, 15, true);
}
```

### SetUpTrailStop() <a href="#setuptrailstop" id="setuptrailstop"></a>

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

Set trail stop creates a trail stop order after an entry order is generated. Its purpose is to protect you from losses, and after reaching break-even, to protect your gains.

The order is sent directly to the broker and becomes effective immediately.

If the stop loss price and the offset value are static, you can define SetUpTrailStop() with the OnInit() method.

If you use SetUpTrailStop() within the[ *OnCalculate()*](/events#oncalculate) method, you must make sure that the parameters are readjusted to the initial value, otherwise the most recently used settings will be used for the new position.

**Functionality:**

Assuming that you have SetUpTrailStop(CalculationMode.Ticks, 30) selected:

In a long position, the stop will be 30 ticks from the previously reached high. If the market makes a new high, the stop will be adjusted. However, the stop will no longer be moved downwards.

In a short position, this behavior starts with the most recent low.

**Tips:**

It is not possible to use SetUpStopLoss and SetUpTrailStop for the same position at the same time within one strategy. The SetUpStopLoss() method will always have precedence over the other methods.

However, it is possible to use both variants parallel to each other in the same strategy if they are referencing different entry signals.

Partial executions of a single order will cause a separate trading stop for each partial position.

If a SetUpProfitTarget() is used in addition to a SetUpTrailStop(), then both orders will be automatically linked to form an OCO order.

It is always a stop market order that is generated, and not a stop limit order.

If a position is closed by a different exit order within the strategy, then the TrailingStopOrder is automatically deleted.

See [*SetUpStopLoss()*](#setupstoploss), [*SetUpTrailStop()*](#setuptrailstop).

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

```csharp
SetUpTrailStop(double currency)
SetUpTrailStop(double currency, bool simulated)
SetUpTrailStop(CalculationMode mode, double value)
SetUpTrailStop(string fromEntry signal, CalculationMode mode, double value, bool simulated)
```

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

|                  |                                                                                                                                                                                                             |
| ---------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| currency         | The distance between the stop loss and the entry price                                                                                                                                                      |
| mode             | Possible values are: CalculationMode.Percent; CalculationMode.Ticks                                                                                                                                         |
| simulated        | When set to "true," the stop order does not go live (as a market order) until the price has „touched" it for the first time (meaning that it is executed just as it would be under real market conditions). |
| value            | The distance between stop price and profit target. This is dependent upon the „mode" but generally refers to a monetary value, a percentage or a value in ticks.                                            |
| fromEntry signal | The name of the entry signal for which the stop order is to be generated. The amount is taken from the entry order referenced.                                                                              |

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

```csharp
protected override void OnInit()
{
// Sets a trailing at the low of the last candle
    SetUpTrailStop(CalculationMode.Price, Low[0]);
}
```

### StrategyOrderParameters <a href="#strategyorderparameters" id="strategyorderparameters"></a>

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

This class aggregates all properties needed to submit the order.

See [*SubmitOrder()*](#submitorder), [*CloseLongTrade()*](#closelongtrade), [*CloseShortTrade()*](#closeshorttrade).

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

```csharp
public class StrategyOrderParameters
    {
        public OrderDirection Direction { get; set; }
        public OrderMode Mode { get; set; } = OrderMode.Direct;
        public OrderType Type { get; set; }
        public bool LiveUntilCancelled { get; set; }
        public int Quantity { get; set; }
        public double Price { get; set; }
        public double StopPrice { get; set; }
        public string SignalName { get; set; } = String.Empty;
        public IInstrument Instrument { get; set; }
        public ITimeFrame TimeFrame { get; set; }
        public string FromEntrySignal { get; set; } = String.Empty;
    }
```

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

|                    |                                                                                                                                                                                                   |
| ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| OrderDirection     | Possible values are: **orderDirection.Buy** (Buy order for a long entry); **orderDirection.Sell** (Sell order for closing a long position)                                                        |
| OrderMode          | One of three possible positions in the market: Direct, Dynamic, Synthetic                                                                                                                         |
| OrderType          | Possible values: OrderType.Limit, OrderType.Market, OrderType.Stop, OrderType.StopLimit                                                                                                           |
| LiveUntilCancelled | The order will not be deleted at the end of the bar, but will remain active until removed with [*Order.Cancel*](#ordercancel) or until it reaches its expiry (see [*TimeInForce*](#timeinforce)). |
| Quantity           | Amount                                                                                                                                                                                            |
| Price              | Limit value. Inputting a 0 makes this parameter irrelevant                                                                                                                                        |
| StopPrice          | Stop value. Inputting a 0 makes this parameter irrelevant                                                                                                                                         |
| SignalName         | An unambiguous signal name (string)                                                                                                                                                               |
| Instrument         | The trading instrument in which the position exists.                                                                                                                                              |
| TimeFrame          | The TimeFrame, which is valid for the order.                                                                                                                                                      |
| FromEntrySignal    | The name of the attached entry signal                                                                                                                                                             |

### SubmitOrder() <a href="#submitorder" id="submitorder"></a>

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

Submit order creates a user-defined order. For this order, no stop or limit order is placed in the market. All AgenaTrader control mechanisms are switched off for this order type. The user is responsible for managing the various stop and target orders, including partial executions.

See [*OnOrderChanged()*](/events#onorderchanged), [*OnOrderExecution()*.](/events#onorderexecution)

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

See [*StrategyOrderParameters*](#strategyorderparameters)

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

See [*StrategyOrderParameters*](#strategyorderparameters)

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

an order object of the type "IOrder"

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

```csharp
// Limit Long order
Submit Limit Buy
var order = SubmitOrder(new StrategyOrderParameters
                {
                    Direction = OrderDirection.Buy,
                    Type = OrderType.Limit,
                    Mode = orderMode,
                    Price = limitPrice,
                    Quantity = quantity,
                    SignalName = entryName,
                    Instrument = Instrument,
                    TimeFrame = TimeFrame,
                    LiveUntilCancelled = true
                });

// Short Market order
Submit Sell Market
var order = SubmitOrder(new StrategyOrderParameters
            {
                Direction = OrderDirection.Sell,
                Type = OrderType.Market,
                Mode = ordermode,
                Quantity = quantity,
                SignalName = entryName,
                Instrument = Instrument,
                TimeFrame = TimeFrame
            });
```

### TimeInForce <a href="#timeinforce" id="timeinforce"></a>

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

The time in force property determines how long an order is valid for. The validity period is dependent upon which values are accepted by a broker.

For orders submitted with `LiveUntilCancelled = true`, the `TimeInForce` setting is always ignored.\
`TimeInForce` will only be applied when `LiveUntilCancelled` is set to `false`.

TimeInForce is specified with the [*OnInit()*](/keywords#oninit) method.

Permitted values are: TimeInForce.day TimeInForce.loc TimeInForce.gtc (GTC = good till canceled) TimeInForce.gtd

**Default:** TimeInForce.GTC

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

**TimeInForce**

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

```csharp
protected override void OnInit()
{
TimeInForce = TimeInForce.Day;
}
```

### Trade <a href="#trade" id="trade"></a>

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

Trade is an object containing information about trades that have been executed by a strategy or are currently running.

The individual properties are:

* **Trade.AvgPrice** Average entry price
* **Trade.ClosedProfitLoss** Profit or loss already realized
* **Trade.Commission** Commissions
* **Trade.CreatedDateTime** Time at which the trade was created
* **Trade.EntryReason** Description of the entry signal For strategies: signal entry name
* **Trade.ExitDateTime** Time at which the trade was closed
* **Trade.ExitPrice** Exit price
* **Trade.ExitReason** Description of the exit signal For strategies: name of the strategy
* **Trade.Instrument** Description of the trading instrument
* **Trade.PositionType** Positioning within the market
  * PositionType.Flat
  * PositionType.Long
  * PositionType.Short
* **Trade.OpenProfitLoss** Unrealized profit/loss of a running position
* **Trade.ProfitCurrency** Profit or loss in the currency that the account is held in
* **Trade.ProfitLoss** Profit or loss
* **Trade.ProfitPercent** Profit or loss in percent
* **Trade.ProfitPercentWithCommission** Profit or loss in percent with commissions
* **Trade.ProfitPoints** Profit or loss in points/pips
* **Trade.Quantity** Quantity of stocks/contracts/ETFs/etc.
* **Trade.TimeFrame** Timeframe in which the trade was opened
* **Trade.Url** URL for the snapshot of the chart at the moment of creation

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

```csharp
protected override void OnDispose()
{

  foreach (ITradeState tradeState in Performance.AllTrades)
  {
  ITrade trade = tradeState.Trade;
  if (trade == null) continue;

    Print("Trade #"+trade.Id);
    Print("--------------------------------------------");
    Print("Average price " + trade.AvgPrice);
    Print("Realized P/L " + trade.ClosedProfitLoss);
    Print("Commissions " + trade.Commission);
    Print("Time of entry " + trade.CreatedDateTime);
    Print("Entry reason " + trade.EntryReason);
    Print("Time of exit " + trade.ExitDateTime);
    Print("Exit price " + trade.ExitPrice);
    Print("Exit reason " + trade.ExitReason);
    Print("Instrument " + trade.Instrument);
    Print("Positioning " + trade.PositionType);
    Print("Unrealized P/L " + trade.OpenProfitLoss);
    Print("P/L (currency) " + trade.ProfitCurrency);
    Print("P/L " + trade.ProfitLoss);
    Print("P/L (in percent) " + trade.ProfitPercent);
    Print("P/L (% with commission)" + trade.ProfitPercentWithCommission);
    Print("PL (in points) " + trade.ProfitPoints);
    Print("Quantity " + trade.Quantity);
    Print("Timeframe " + trade.TimeFrame);
    Print("URL for the snapshot " + trade.Url);
  }
}
```

### Unmanaged <a href="#unmanaged" id="unmanaged"></a>

## Backtesting and Optimization <a href="#backtesting-and-optimization" id="backtesting-and-optimization"></a>

### Performance Characteristics <a href="#performance-characteristics" id="performance-characteristics"></a>

Performance characteristics are the various factors that can be calculated for a list of trades. The trades can be generated by a strategy in real-time or based on a backtest.

The following are available:

* all trades
* all long trades
* all short trades
* all winning trades
* all losing trades

See [*Performance*.](#performance)

The individual factors are:

**AvgEtd** The average drawdown at the end of a trade \<TradeCollection>.TradesPerformance.\<TradesPerformanceValues>.AvgEtd

```csharp
Print("Average ETD of all trades is: " + Performance.AllTrades.TradesPerformance.Currency.AvgEtd);
```

**AvgMae** Average maximum adverse excursion \<TradeCollection>.TradesPerformance.\<TradesPerformanceValues>.AvgMae

```csharp
Print("Average MAE of all trades is: " + Performance.AllTrades.TradesPerformance.Currency.AvgMae);
```

**AvgMfe** Average maximum favorable excursion \<TradeCollection>.TradesPerformance.\<TradesPerformanceValues>.AvgMfe

```csharp
Print("Average MFE of all trades is: " + Performance.AllTrades.TradesPerformance.Currency.AvgMfe);
```

**AvgProfit** Average profit for all trades \<TradeCollection>.TradesPerformance.\<TradesPerformanceValues>.AvgProfit

```csharp
Print("Average profit of all trades is: " + Performance.AllTrades.TradesPerformance.Currency.AvgProfit);
```

**CumProfit** The cumulative winnings over all trades \<TradeCollection>.TradesPerformance.\<TradesPerformanceValues>.CumProfit

```csharp
Print("Average cumulative profit of all trades is: " + Performance.AllTrades.TradesPerformance.Currency.CumProfit);
```

**DrawDown** The drawdown for all trades \<TradeCollection>.TradesPerformance.\<TradesPerformanceValues>.DrawDow

```csharp
Print("Drawdown of all trades is: " + Performance.AllTrades.TradesPerformance.Currency.DrawDown);
```

**LargestLoser** The largest losing trade \<TradeCollection>.TradesPerformance.\<TradesPerformanceValues>.LargestLoser

```csharp
Print("Largest loss of all trades is: " + Performance.AllTrades.TradesPerformance.Currency.LargestLoser);
```

**LargestWinner** The largest winning trade \<TradeCollection>.TradesPerformance.\<TradesPerformanceValues>.LargestWinner

```csharp
Print("Largest win of all trades is: " + Performance.AllTrades.TradesPerformance.Currency.LargestWinner);
```

**ProfitPerMonth** The total performance (wins/losses) for the month (also in percent) \<TradeCollection>.TradesPerformance.\<TradesPerformanceValues>.ProfitPerMonth

```csharp
Print("Profit per month of all trades is: " + Performance.AllTrades.TradesPerformance.Currency.ProfitPerMonth);
```

**StdDev** The standard deviation for the wins/losses. With this, you are able to identify outliers. The smaller the standard deviation, the higher the expectation of winnings.

**All factors are double values.**

![Performance Characteristics](https://agenatrader.github.io/AgenaScript-documentation/media/image10.png)

[Next ](https://agenatrader.github.io/AgenaScript-documentation/keywords/)[ Previous](https://agenatrader.github.io/AgenaScript-documentation/events/)

***

Built with [MkDocs](https://www.mkdocs.org/) using a [theme](https://github.com/snide/sphinx_rtd_theme) provided by [Read the Docs](https://readthedocs.org/).


# Keywords

### AddOutput() <a href="#addoutput" id="addoutput"></a>

### AddLine() <a href="#addline" id="addline"></a>

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

The add method allows you to add plots or line objects to the chart. When a new plot object is added using Add(), this automatically creates a data series of the type DataSeries, which is attached to this object. The value collection allows you to reference and access this data series. Add() can be used with the OnInit() and the OnCalculate() methods.

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

plot – a *OutputDescriptor* object line – a *LevelLine* object

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

```csharp
AddOutput(new OutputDescriptor(Color.FromKnownColor(KnownColor.Black), "MyPlot1"));
Add(LevelLine line)
```

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

```csharp
#region Usings
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Linq;
using System.Xml;
using System.Xml.Serialization;
using AgenaTrader.API;
using AgenaTrader.Custom;
using AgenaTrader.Plugins;
using AgenaTrader.Helper;
#endregion
namespace AgenaTrader.UserCode
{
  [Description("Enter the description for the new custom indicator here")]
  public class MyIndicator : UserIndicator
  {
    protected override void OnInit()
    {
    // Two blue lines will be placed into the chart, one at 70 and the other at 30
    AddLine(new LevelLine(Color.Blue, 70, "UpperLine"));
    AddLine(new LevelLine(Color.Blue, 30, "LowerLine"));

    // Add 2 plots
    AddOutput(new OutputDescriptor(Color.FromKnownColor(KnownColor.Red), "FastSMA"));
    AddOutput(new OutputDescriptor(Color.FromKnownColor(KnownColor.Blue), "SlowSMA"));
    }

    protected override void OnCalculate()
    {
    //The set method is assigned to the value of the current bar
    FastSMA.Set( SMA(8)[0] ); // is identical with Outputs[0].Set( SMA(8)[0] );
    SlowSMA.Set( SMA(50)[0] ); // is identical with Outputs[1].Set( SMA(50)[0] );
    }

    // Two data series are made available here
    // These are not necessary for the display of the indicator // With the help of these series, one indicator can access the other
    // For example: double d = MyIndicator.FastSMA[0] - MyIndicator.SlowSMA[0];
    [Browsable(false)]
    [XmlIgnore()]
    public DataSeries FastSMA
    {
      get { return Outputs[0]; }
    }

    [Browsable(false)]
    [XmlIgnore()]
    public DataSeries SlowSMA
    {
      get { return Outputs[1]; }
    }
  }
}
```

### AllowRemovalOfChartDrawings <a href="#allowremovalofchartdrawings" id="allowremovalofchartdrawings"></a>

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

"AllowRemovalOfChartDrawings" is a property of indicators that can be set under [*OnInit()*](#oninit).

**AllowRemovalOfChartDrawings = true**

Drawing objects that are drawn by an indicator or a strategy can be manually removed from the chart.

**AllowRemovalOfChartDrawings = false (default)**

Drawing objects that have been created by a strategy or indicator CANNOT be manually removed from the chart. They are removed once the indicator or strategy is removed.

This property can be queried and will return "true" or "false".

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

```csharp
AllowRemovalOfChartDrawings
```

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

```csharp
protected override void OnInit()
{
AddOutput(new OutputDescriptor(Color.FromKnownColor(KnownColor.Black), "MyPlot1"));
//Drawing objects can be manually removed from the chart
AllowRemovalOfChartDrawings = true;
}
```

### Attribute <a href="#attribute" id="attribute"></a>

Attribute is a component of the C# language. Within AgenaScript, indicators, and strategies, you can use these attributes in the same manner as you would in C#. Information regarding the usage of attributes can be found here:

<https://learn.microsoft.com/de-de/dotnet/csharp/advanced-topics/reflection-and-attributes/>

The most commonly used attributes in AgenaScript are:

* [*Browsable*](#browsable)
* [*Category*](#category)
* [*ConditionalValue*](#conditionalvalue)
* [*Description*](#description_2)
* [*DisplayName*](#displayname)
* [*TimeFrameRequirements*](#timeframerequirements)
* [*XmlIgnore*](#xmlignore)

### Browsable <a href="#browsable" id="browsable"></a>

Browsable is an [Attribute](#attribute) within AgenaScript.

AgenaScript uses public variables for entering parameters for indicators (such as periods for the SMA) and for outputting events and calculations within indicators (for example, data series). Variables used for entering parameters must be displayed in the properties dialog. Data series are exempt from this. Public variables with the browsable attribute set to false are not displayed within the properties dialog.

By default, browsable is set to true. Therefore, within a variable containing an entry parameter, the attribute does not need to be specified.

**Example for a parameter:**

The parameter should be displayed and queried in the properties window. Therefore browsable should be set to true.

```csharp
[Description("Numbers of bars used for calculations")]
[Category("InputParameter")]
public int Period
{
get { return period; }
set { period = Math.Max(1, value); }
}
```

**Example for a data series:**

```csharp
[Browsable(false)]
[DisplayName("Lower band")]
[XmlIgnore]
public DataSeries Lower
{
get { return Outputs[0]; }
}
```

### Category <a href="#category" id="category"></a>

Category is an [Attribute](#attribute) in AgenaScript and can be used on properties and classes.

The category attribute on properties defines under which category in the properties dialog the parameter is shown. If this attribute is missing, the parameters category is accepted as the standard.

The following example shows how to create the new category "My InputParameter" in the properties dialog:

```csharp
[Category("My InputParameter")]
[DisplayName("Period number")]
public double _period
{
get { return _period; }
set { _period = value; }
}
```

![Category](https://agenatrader.github.io/AgenaScript-documentation/media/image11.png)

If you use the category [Attribute](#attribute) on classes you are able to create subcategories for your scripts and group them all in one category. This is pretty useful if you are creating a package and you want to group a few indicators in a group with one name.

The following example shows how to create a subfolder "My Package":

```csharp
namespace AgenaTrader.UserCode
{
    [Description("Description what this indicator doing.")]
    [Category("My Package")]
    public class MyHolyGrail_Indicator : UserIndicator
    {
      /* your code here */
    }
}
```

### ConditionalValue <a href="#conditionalvalue" id="conditionalvalue"></a>

Conditional value is an [Attribute](#attribute) in AgenaScript.

Normally, when making comparisons within the ConditionEscort, the data series generated by indicators are used. One such example would be checking whether a moving average lies above or below a specific price value. An indicator can also yield values that are not contained within data series, such as values of the type int, double, char, Boolean, string, etc. To use these values within the scanner or ConditionEscort, they have to be labeled with the conditional value attribute.

```csharp
[Browsable(false)]
[XmlIgnore]
[ConditionalValue]
public int PublicVariable
{
get
{
Update();
return _internVariable;
}
}
```

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

Description is an [Attribute](#attribute) in AgenaScript.

The description attribute is used in AgenaScript for classes and public variables. As an attribute of the class, the text is a description of the function of the entire indicator.

```csharp
[Description("Displays the tick count of a bar.")]
public class TickCounter : UserIndicator
{
//As an attribute of a public variable, the text is a description of the function of the parameter.
[Description("Number of standard deviations")]
[DisplayName("# of std. dev.")]
public double NumStdDev
{
get { return numStdDev; }
set { numStdDev = Math.Max(0, value); }
}
}
```

The descriptions are displayed in the relevant properties dialog.

### DisplayName <a href="#displayname" id="displayname"></a>

Display name is an [Attribute](#attribute) in AgenaScript.

The display name attribute defines the text shown in the properties dialog for the parameter.

If this attribute is not specified, the name of the public variable is used.

```csharp
[Description("Number of standard deviations")]
[DisplayName("# of std. dev.")]
public double NumStdDev
{
get { return numStdDev; }
set { numStdDev = Math.Max(0, value); }
}
```

### TimeFrameRequirements <a href="#timeframerequirements" id="timeframerequirements"></a>

Timeframe requirements is an [Attribute](#attribute) in AgenaScripts.

If you want a script to use data from various timeframes, the class requires the attribute „TimeFrameRequirements". You can specify multiple timeframes here:

```csharp
[TimeFrameRequirements("1 day")]
[TimeFrameRequirements("15 minutes", "1 day", "1 week")]
```

The amount of data provided for the other timeframes will always be the same as the number of actual candles loaded into the chart. If there are 500 candles for a 5-minute chart, then 500 candles of another timeframe will also be loaded. In the first example above, 500 daily candles will be loaded. In the second example, 500 15-minute candles, 500 daily candles and 500 weekly candles will be loaded. The amount of data can become rather large very quickly, thus you should take precautions when using this attribute.

See [*MultiBars*.](/handling-bars-and-instruments/multibars#multibars)

**Important:**

If a class uses a different indicator that requires one or more secondary timeframes, then the "TimeFrameRequirements" attribute must be set for the class retrieving the data. An example for this can be seen here: *GetDayBar*.

### XMLIgnore <a href="#xmlignore" id="xmlignore"></a>

XML ignore is an [Attribute](#attribute) in AgenaScript.

AgenaTrader saves all parameter settings for the indicators in a template. The template files are saved in an XML format. In order to avoid a parameter being saved as part of the template, the attribute XML ignore can be set.

To save parameters in an XML file, the values must be serialized. Under most circumstances, AgenaTrader performs this automatically. Self-defined data types cannot be serialized automatically, so in this case the programmer is responsible for the correct serialization. In the following example, the color and font are used as parameters of an indicator. AgenaTrader has two methods for serializing color and font information (TextColorSerialize and TextFontSerialize). Both parameters – TextColor and TextFont – thus need to be marked with the XML ignore parameter.

```csharp
private Color _textColor = Color.Blue;
private Font _textFont = new Font("Arial", 12, FontStyle.Bold);
[XmlIgnore]
[Description("Textcolor")]
public Color TextColor
{
get { return _textColor; }
set { _textColor = value; }
}
[Browsable(false)]
public string TextColorSerialize
{
get { return SerializableColor.ToString(_textColor); }
set { _textColor = SerializableColor.FromString(value); }
}
[XmlIgnore()]
[Description("TextFont")]
public Font TextFont
{
get { return _textFont; }
set { _textFont = value; }
}
[Browsable(false)]
public string TextFontSerialize
{
get { return SerializableFont.ToString(_textFont); }
set { _textFont = SerializableFont.FromString(value); }
}
```

### CalculateOnClosedBar <a href="#calculateonclosedbar" id="calculateonclosedbar"></a>

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

The property "CalculateOnClosedBar" determines the events for which AgenaTrader can call up the OnCalculate() method.

```csharp
CalculateOnClosedBar = true
```

**OnCalculate()** is called up when a bar is closed and the next incoming tick creates a new bar.

```csharp
CalculateOnClosedBar = false
```

OnCalculate() is called up for each new incoming tick. If you are running AgenaTrader on older hardware, this may cause performance issues with instruments that are highly liquid. The property can be queried in the script and will return a value of the type Boolean (true or false). CalculateOnClosedBar can be used within OnInit() and also within OnCalculate(). OnCalculate() is only called up for the closing price of each bar with historical data, even if CalculateOnClosedBar is set to false. When an indicator is called up by another indicator, the CalculateOnClosedBar property of the retrieved indicator overwrites the indicator performing the retrieving.

The default value of this property is true so in default setup your script does not use tick data.

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

CalculateOnClosedBar

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

See [*Bars*.](/handling-bars-and-instruments/bars)

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

```csharp
protected override void OnInit()
{
//Indicator calculation should only occur when a bar has closed/finished
CalculateOnClosedBar = true;
}
```

### Chart <a href="#chart" id="chart"></a>

Chart control is an object that provides reading access of various properties for the chart.

The important properties are:

* ChartFontColor, BackColor
* UpColor, DownColor
* Font
* BarMarginLeft, BarMarginRight
* BarSpace, BarWidth
* BarsPainted
* FirstBarPainted, LastBarPainted
* BarsVisible
* FirstBarVisible, LastBarVisible
* GetXByBarIdx, GetYByValue

An example can be seen here: [*PlotMethod*](#plotmethod).

**BarsPainted und BarsVisible:**

BarsPainted contains the number of bars that a chart *could* display from the left to right border with the current width and distance of the candles. BarsVisible contains the number of bars actually visible.

**FirstBarPainted und FirstBarVisible:**

FirstBarPainted contains the number of the bar that *would* be displayed on the left border of the chart.

FirstBarVisible contains the number of the bar that is actually shown as the first bar on the left side of the chart area.

Example: the chart has been moved so that the first bar of the chart is now in the middle of the chart.

FirstBarPainted would be negative.

FirstBarVisible would be 0.

**LastBarPainted und LastBarVisible:**

LastBarPainted contains the number of the bar that *would* be displayed on the right border of the chart.

LastBarVisible contains the number of the bar that is actually displayed on the right side of the chart.

Example: the chart has been moved so that the last bar of the chart is displayed in the middle section.

LastBarPainted would be larger than Bars.Count.

LastBarVisible would be Bars.Count -1.

### ClearTraceWindow() <a href="#cleartracewindow" id="cleartracewindow"></a>

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

The ClearTraceWindow() method empties the output window. The method can be used within OnInit() as well as within OnCalculate(). The output window contains all outputs that have been created with the [*Print()*](#print) command. Using the output window is a great method for code debugging.

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

```csharp
ClearTraceWindow()
```

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

none

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

none

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

```csharp
protected override void OnInit()
{
// Delete the content of the output window
ClearTraceWindow();
}
```

### Colors <a href="#colors" id="colors"></a>

AgenaScript provides you with the following commands for defining colors and making color changes to the chart:

[*BarColor*](#barcolor) Color of a bar

[*BackColor*](#backcolor) Background color of the chart

[*BackColorAll*](#backcolorall) Background color of the chart and all panels

Chart.UpColor Color of up ticks (up bars) Chart.DownColor Color of down ticks (down bars)

For each bar, its colors are saved in the following data series. If these data series are written in, the color of the referenced bar will change.

[*BarColorSeries*](#barcolorseries)

[*CandleOutlineColorSeries*](#candleoutlinecolorseries)

[*BackColorSeries*](#backcolorseries)

[*BackColorAllSeries*](#backcolorallseries)

### BackColor <a href="#backcolor" id="backcolor"></a>

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

Back color changes the background color of a bar or gives the current background color of a bar when queried.

See [*Colors*](#colors), [*BarColor*](#barcolor), [*BackColor*](#backcolor),[ *BackColorAll*](#backcolorall), [*BarColorSeries*](#barcolorseries),[ *BackColorAll*](#backcolorall), [*CandleOutlineColor*](#candleoutlinecolor).

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

A color object of the type "public struct color"

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

BackColor

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

```csharp
// Every Monday, change the bar background color to blue
if (Time[0].DayOfWeek == DayOfWeek.Monday)
BackColor = Color.Blue;
```

![BackColor](https://agenatrader.github.io/AgenaScript-documentation/media/image16.png)

```csharp
// Changing the bar background color depending on a smoothing average
// Market price above the SMA(14) to green
// Market price below the SMA(14) to maroon
BackColor = SMA(14)[0] >= Close[0] ? Color.Maroon : Color.LimeGreen;
```

![BackColor](https://agenatrader.github.io/AgenaScript-documentation/media/image17.png)

### BackColorAll <a href="#backcolorall" id="backcolorall"></a>

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

Back color all changes the background color of a bar within the chart window and in all subcharts.

See [*Colors*](#colors), [*BarColor*](#barcolor), [*BackColor*](#backcolor),[ *BackColorAll*](#backcolorall), [*BarColorSeries*](#barcolorseries),[ *BackColorAll*](#backcolorall), [*CandleOutlineColor*](#candleoutlinecolor).

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

A color object of the type "public struct color"

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

BackColorAll

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

```csharp
// Every Monday, change the bar background color to blue
if (Time[0].DayOfWeek == DayOfWeek.Monday)
BackColorAll = Color.Blue;
```

![BackColorAll](https://agenatrader.github.io/AgenaScript-documentation/media/image18.png)

### BackColorAllSeries <a href="#backcolorallseries" id="backcolorallseries"></a>

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

Back color all series is a data series containing the background color for each bar. The difference to BackColorSeries is that the background color of the subchart is included.

See [*Colors*](#colors), [*BarColor*](#barcolor), [*BackColor*](#backcolor),[ *BackColorAll*](#backcolorall), [*BarColorSeries*](#barcolorseries),[ *BackColorAll*](#backcolorall), [*CandleOutlineColor*](#candleoutlinecolor).

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

a color object of the type "public struct color"

int barsAgo

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

```csharp
BackColorAllSeries
BackColorAllSeries[int barsAgo]
```

When using the method with an index \[**int** barsAgo] the background color for the referenced bar will be changed or returned.

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

See [*BackColorSeries*](#backcolorseries).

### BackColorSeries <a href="#backcolorseries" id="backcolorseries"></a>

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

Back color series is a data series containing the background color for each bar. If the background color for the subcharts is to be included, please use "BackColorAllSeries" instead.

See [*Colors*](#colors), [*BarColor*](#barcolor), [*BackColor*](#backcolor),[ *BackColorAll*](#backcolorall), [*BarColorSeries*](#barcolorseries),[ *BackColorAll*](#backcolorall), [*CandleOutlineColor*](#candleoutlinecolor).

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

a color object of the type "public struct color"

int barsAgo

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

```csharp
BackColorSeries
BackColorSeries[int barsAgo]
```

When using this method with an index \[**int** barsAgo] the background color for the referenced bar will be outputted.

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

```csharp
// Which background color does the current bar have?
Print (BackColorSeries[0]);
// Set the current bar’s background color to blue
// This is identical to BackColor = Color.Blue
BackColorSeries[3] = Color.Blue;
// Set background color for the previous bar to green
BackColorSeries[1] = Color.Green;
```

### BarColor <a href="#barcolor" id="barcolor"></a>

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

Bar color changes the color of a bar.

See [*Colors*](#colors), [*BarColor*](#barcolor), [*BackColor*](#backcolor),[ *BackColorAll*](#backcolorall), [*BarColorSeries*](#barcolorseries),[ *BackColorAll*](#backcolorall), [*CandleOutlineColor*](#candleoutlinecolor).

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

a color object of the type "public struct color"

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

BarColor

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

```csharp
// If the closing price is above the SMA(14), color the bar orange
if (Close[0] > SMA(14)[0]) BarColor = Color.Orange;
```

![BarColor](https://agenatrader.github.io/AgenaScript-documentation/media/image15.png)

### BarColorSeries <a href="#barcolorseries" id="barcolorseries"></a>

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

Bar color series is a data series containing the color for each bar.

See [*Colors*](#colors), [*BarColor*](#barcolor), [*BackColor*](#backcolor),[ *BackColorAll*](#backcolorall), [*BarColorSeries*](#barcolorseries),[ *BackColorAll*](#backcolorall), [*CandleOutlineColor*](#candleoutlinecolor).

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

a color object of the type "public struct color"

int barsAgo

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

BarColorSeries

BarColorSeries\[**int** barsAgo]

When using the method with an index \[**int** barsAgo] the color for the referenced bar will be changed or returned.

**Caution: Only the color of a bar whose color has been explicitly changed beforehand will be returned. In all other cases, the "Color.Empty" value will be returned.**

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

```csharp
protected override void OnCalculate()
{
if (ProcessingBarIndex == Bars.Count-1-(CalculateOnClosedBar?1:0))
{
// Color the current bar blue
// This is identical to BarColor = color.Blue
BarColorSeries[0] = Color.Blue;
// Color the previous bars green
BarColorSeries[1] = Color.Orange;
// Color the third bar yellow
BarColorSeries[2] = Color.Yellow;
}
}
```

![BarColorSeries](https://agenatrader.github.io/AgenaScript-documentation/media/image19.png)

### CandleOutlineColor <a href="#candleoutlinecolor" id="candleoutlinecolor"></a>

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

Candle outline color changes the border/outline color (including the wick) of a bar.

If the color of the bar is changed using BarColor and the outline is not changed using CandleOutlineColor, the outline color is adjusted to match the color of the bar.

See [*Colors*](#colors), [*BarColor*](#barcolor), [*BackColor*](#backcolor),[ *BackColorAll*](#backcolorall), [*BarColorSeries*](#barcolorseries),[ *BackColorAll*](#backcolorall), [*CandleOutlineColor*](#candleoutlinecolor).

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

a color object of the type "public struct color"

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

CandleOutlineColor

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

```csharp
if (SMA(14)[0] > SMA(200)[0])
CandleOutlineColor = Color.LimeGreen;
else
CandleOutlineColor = Color.Red;
```

![CandleOutlineColor](https://agenatrader.github.io/AgenaScript-documentation/media/image20.png)

### CandleOutlineColorSeries <a href="#candleoutlinecolorseries" id="candleoutlinecolorseries"></a>

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

Candle outline color series is a data series that saves the outline color for each bar.

See [*Colors*](#colors), [*BarColor*](#barcolor), [*BackColor*](#backcolor),[ *BackColorAll*](#backcolorall), [*BarColorSeries*](#barcolorseries),[ *BackColorAll*](#backcolorall), [*CandleOutlineColor*](#candleoutlinecolor).

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

a color object of the type "public struct color"

int barsAgo

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

```csharp
CandleOutlineColorSeries
CandleOutlineColorSeries[int barsAgo]
```

When using this method with an index \[**int** barsAgo] the border color for the referenced bar will be outputted.

**Caution: Color.Empty will be outputted for a bar unless it has been previously changed.**

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

```csharp
// Set the outline color of the current bar to blue
CandleOutlineColorSeries[0] = Color.Blue;
// Change the outline color to the chart default value
CandleOutlineColorSeries[0] = Color.Empty;
```

### CrossAbove() <a href="#crossabove" id="crossabove"></a>

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

The CrossAbove() method allows you to check whether a crossing of two values has occurred (from bottom to top) within a predefined number of periods. The values can be a market price, an indicator, a data series or a constant value.

See [*CrossAbove()*](#crossabove), [*CrossBelow()*](#crossbelow), [*IsSerieRising()*](#isserierising), [*IsSerieFalling()*](#isseriefalling).

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

```csharp
CrossAbove(IDataSeries series1, double value, int lookBackPeriod)
CrossAbove(IDataSeries series1, IDataSeries series2, int lookBackPeriod)
```

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

**true** a cross has occurred **false** a cross has not occurred

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

|                     |                                                          |
| ------------------- | -------------------------------------------------------- |
| lookBackPeriod      | Number of bars within which a cross will be searched for |
| series1 und series2 | A data series such as an indicator, close, high, etc.    |
| value               | A constant value of the type double                      |

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

```csharp
// Puts out a notice if the SMA(20) crosses above the SMA(50)
if (CrossAbove(SMA(20), SMA(50), 1))
Print("SMA(20) has risen above SMA(50)!");
// Puts out a notice if the SMA(20) crosses above the value of 40
if (CrossAbove(SMA(20), 40, 1))
Print("SMA(20) has risen above 40!");
// Put out a notice for a long entry if the SMA(20) has crossed above the SMA(50) within the last 5 bars.
if (CrossAbove(SMA(20), SMA(50), 1) && Close[0] > Close[1])
Print("Long entry !!!");
```

### CrossBelow() <a href="#crossbelow" id="crossbelow"></a>

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

Using the CrossBelow() method, you can test whether or not a cross below has occurred within a predefined number of periods. The values can be the market price, an indicator, any data series, or a constant value.

See [*CrossAbove()*](#crossabove), [*CrossBelow()*](#crossbelow), [*IsSerieRising()*](#isserierising), [*IsSerieFalling()*](#isseriefalling).

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

```csharp
CrossBelow(IDataSeries series1, double value, int lookBackPeriod)
CrossBelow(IDataSeries series1, IDataSeries series2, int lookBackPeriod)
```

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

**true** a cross has occurred **false** a cross has not occurred

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

|                     |                                                          |
| ------------------- | -------------------------------------------------------- |
| lookBackPeriod      | Number of Bars within which a cross will be searched for |
| series1 und series2 | A data series such as an indicator, close, high etc.     |
| value               | A constant value of the type double                      |

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

```csharp
// Puts out a notice if the SMA(20) crosses below the SMA(50)
if (CrossBelow(SMA(20), SMA(50), 1))
Print("SMA(20) has fallen below SMA(50)!");
// Puts out a notice if the SMA(20) falls below the value of 40
if (CrossBelow(SMA(20), 40, 1))
Print("SMA(20) has fallen below 40!");
// Puts out a notice for a short entry if a crossing of the SMA(20) below the SMA(50) has occurred within the last 5 bars.
.
if (CrossBelow(SMA(20), SMA(50), 1) 
&& Instrument.Compare(Close[1], Close[0]) > 1)
Print("Short entry !!!");
```

### DatafeedHistoryPeriodicity <a href="#datafeedhistoryperiodicity" id="datafeedhistoryperiodicity"></a>

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

Datafeed history periodicity is a data type.

#### Definition <a href="#definition" id="definition"></a>

public enum DatafeedHistoryPeriodicity - DatafeedHistoryPeriodicity.Tick - DatafeedHistoryPeriodicity.Second - DatafeedHistoryPeriodicity.Minute - DatafeedHistoryPeriodicity.Hour - DatafeedHistoryPeriodicity.Day - DatafeedHistoryPeriodicity.Week - DatafeedHistoryPeriodicity.Month - DatafeedHistoryPeriodicity.Volume - DatafeedHistoryPeriodicity.Range - DatafeedHistoryPeriodicity.Quarter - DatafeedHistoryPeriodicity.Year - DatafeedHistoryPeriodicity.HeikinAshi - DatafeedHistoryPeriodicity.Renko - DatafeedHistoryPeriodicity.LineBreak - DatafeedHistoryPeriodicity.Kagi - DatafeedHistoryPeriodicity.PointAndFigure - DatafeedHistoryPeriodicity.Custom

See *TimeFrame*, *TimeFrames*.

### DataSeries <a href="#dataseries" id="dataseries"></a>

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

Data series (data rows) are an easy yet powerful method of saving additional values for individual bars. For example, when calculating the smoothing average, each bar is assigned the value calculated for this bar. A data series is an array that contains as many elements as there are bars displayed in a chart. AgenaTrader ensures that data series are correctly synchronized with the bars. Data series are used in exactly the same way as the close or time series. They can therefore also be used for the input data for various indicators. In the table below you will find 4 newly created data series (highlighted). Each data series has exactly one value of a special data type (int, bool, string) attached to it per bar. The indexing with barsAgo is thus identical to the data series provided by the system.

![DataSeries](https://agenatrader.github.io/AgenaScript-documentation/media/image12.png)

#### Usable Data Series in AgenaTrader <a href="#usable-data-series-in-agenatrader" id="usable-data-series-in-agenatrader"></a>

[*BoolSeries*](#boolseries)

[*DataSeries*](#dataseries)

[*DateTimeSeries*](#datetimeseries)

[*FloatSeries*](#floatseries)

[*IntSeries*](#intseries)

[*LongSeries*](#longseries)

[*StringSeries*](#stringseries)

In addition, there are also data series such as ColorSeries, although these are only used for internal purposes and should not be used directly. To change the color of plots, please use [*PlotColors*](https://agenatrader.github.io/AgenaScript-documentation/keywords/#plotcolors).

#### Set(), Reset() und ContainsValue() <a href="#set-reset-und-containsvalue" id="set-reset-und-containsvalue"></a>

Each data series contains a **Set()**, **Reset()** and **ContainsValue()** method. With Set(value) or Set(int barsAgo, value) you can place values into the data series for the current position, or in this case into the barsAgo position. With Reset() or Reset(int barsAgo) you can delete a value from the data series for the current position or for the barsAgo position. This has the result that no valid value exists at this position any more. Programming with the help of the reset method can simplify otherwise complex logic. This is especially true for Boolean series, where only "true" or "false" values can be included. The ContainsValue() checks whether a data series has a value for a specific position.

#### Information about Data Types <a href="#information-about-data-types" id="information-about-data-types"></a>

<https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/built-in-types>

### BoolSeries <a href="#boolseries" id="boolseries"></a>

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

Bool series is a data series that contains a Boolean value for each bar. The number of elements in this series correlates with the exact number of bars within the chart.

#### Create New Bool Series <a href="#create-new-bool-series" id="create-new-bool-series"></a>

In the area for the declaration of variables, simply declare a new variable:

```csharp
//Variable declaration
private BoolSeries myBoolSeries;
```

With the OnInit() method, this variable assigns a new instance of the Bool series:

```csharp
protected override void OnInit()
{
myBoolSeries = new BoolSeries(this);
CalculateOnClosedBar = true;
}
```

#### Assign Values <a href="#assign-values" id="assign-values"></a>

Assigning a value to the data series for the current position:

```csharp
myBoolSeries.Set(true);
```

Writing a value in the past into the data series:

```csharp
myBoolSeries.Set(int barsAgo, bool Value);
```

#### Delete Values <a href="#delete-values" id="delete-values"></a>

Removing the current value for the data series:

```csharp
myBoolSeries.Reset();
```

Removing a value in the past from the data series:

```csharp
myBoolSeries.Reset(int barsAgo);
```

#### Check Values for their Validity <a href="#check-values-for-their-validity" id="check-values-for-their-validity"></a>

```csharp
myBoolSeries.ContainsValue(int barsAgo);
```

#### Read Value <a href="#read-value" id="read-value"></a>

```csharp
Print ("For the bar of " + Time[0] + " ago the value of the data series is: " + myBoolSeries[0]);
```

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

```csharp
protected override void OnCalculate()
{
if (Close[0] > Open[0])
myBoolSeries.Set(true);
else
myBoolSeries.Set(false);
}
```

### DataSeries <a href="#dataseries_1" id="dataseries_1"></a>

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

Data series is a [*DataSeries*](#dataseries) that can contain a double value for each bar. The number of elements in this series corresponds to the exact number of bars within the charts.

Data series for double values are the data series most commonly used for indicators.

#### Create a New Data Series <a href="#create-a-new-data-series" id="create-a-new-data-series"></a>

In the declaration area for variables:

```csharp
//Variable declaration
private DataSeries myDataSeries;
```

With the OnInit() method, this variable is assigned a new instance:

```csharp
protected override void OnInit()
{
myDataSeries = new DataSeries(this);
CalculateOnClosedBar = true;
}
```

#### Assign Values <a href="#assign-values_1" id="assign-values_1"></a>

Assigning a value to the data series for the current position:

```csharp
myDataSeries.Set(Bars[0].Close);
```

Writing a value in the past into the data series:

```csharp
myDataSeries.Set(int barsAgo, double Value);
```

#### Delete Values <a href="#delete-values_1" id="delete-values_1"></a>

Removing the current value from the data series:

```csharp
myDataSeries.Reset();
```

Removing a value in the past from the data series:

```csharp
myDataSeries.Reset(int barsAgo);
```

#### Check Values for their Validity <a href="#check-values-for-their-validity_1" id="check-values-for-their-validity_1"></a>

```csharp
myDataSeries.ContainsValue(int barsAgo);
```

#### Read Value <a href="#read-value_1" id="read-value_1"></a>

```csharp
Print ("For the bar from " + Time[0] + " ago the value for the data series is: " + myDataSeries[0]);
```

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

```csharp
//Saves the span between the high and low of a bar
myDataSeries.Set(Math.Abs(High[0]-Low[0]));
```

### DateTimeSeries <a href="#datetimeseries" id="datetimeseries"></a>

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

Date time series is a [*DataSeries*](#dataseries) that can record a date time value for each bar. The number of elements in this series corresponds to the number of bars in the chart.

#### Create a New Data Series <a href="#create-a-new-data-series_1" id="create-a-new-data-series_1"></a>

Create a new variable in the declaration area:

```csharp
//Variable declaration
private DateTimeSeries myDataSeries;
```

Assign a new instance of DateTimeSeries for the variable with the OnInit() method:

```csharp
protected override void OnInit()
{
myDataSeries = new DateTimeSeries(this);
CalculateOnClosedBar = true;
}
```

#### Assign Values <a href="#assign-values_2" id="assign-values_2"></a>

Assigning a value to the current position of the data series:

```csharp
myDataSeries.Set(DateTime Value);
```

Writing a value from the past into the data series:

```csharp
myDataSeries.Set(int barsAgo, DateTime Value);
```

#### Delete Values <a href="#delete-values_2" id="delete-values_2"></a>

Removing the current value from the data series:

```csharp
myDataSeries.Reset();
```

Remove a past value from the data series:

```csharp
myDataSeries.Reset(int barsAgo);
```

#### Check Values for their Validity <a href="#check-values-for-their-validity_2" id="check-values-for-their-validity_2"></a>

```csharp
myDataSeries.ContainsValue(int barsAgo);
```

#### Read Value <a href="#read-value_2" id="read-value_2"></a>

```csharp
Print ("For the bar from " + Time[0] + " ago the value of the data series is: " + myDataSeries[0]);
```

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

```csharp
//Saves the difference of -6 hours (eastern time, New York) for a time zone conversion
myDataSeries.Set(Time[0].AddHours(-6));
```

### FloatSeries <a href="#floatseries" id="floatseries"></a>

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

Float series is a [*DataSeries*](#dataseries) that contains a float value for each bar in the chart. The number of elements in this series corresponds to the number of bars within the chart.

#### Create a New Data Series <a href="#create-a-new-data-series_2" id="create-a-new-data-series_2"></a>

Create a new variable in the declaration area:

```csharp
//Variable declaration
private FloatSeries myDataSeries;
```

Assign a new instance of the FloatSeries to the variable with the OnInit() method:

```csharp
protected override void OnInit()
{
myDatatSeries = new FloatSeries(this);
CalculateOnClosedBar = true;
}
```

#### Assign Values <a href="#assign-values_3" id="assign-values_3"></a>

Assigning a value to the current position of the data series

```csharp
myDataSeries.Set(float Value);
```

Writing a value from the past into the data series:

```csharp
myDataSeries.Set(int barsAgo, float Value);
```

#### Delete Values <a href="#delete-values_3" id="delete-values_3"></a>

Removing the current value from the data series:

```csharp
myDataSeries.Reset();
```

Removing a value located in the past from the data series:

```csharp
myDataSeries.Reset(int barsAgo);
```

#### Check Values for their Validity <a href="#check-values-for-their-validity_3" id="check-values-for-their-validity_3"></a>

```csharp
myDataSeries.ContainsValue(int barsAgo);
```

#### Read Value <a href="#read-value_3" id="read-value_3"></a>

```csharp
Print ("For the bar from " + Time[0] + " ago the value for the data series is: " + myDataSeries[0]);
```

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

```csharp
//Saves the span between the high and the low of a bar
myDataSeries.Set(Math.Abs((float) High[0] - (float) Low[0]));
```

### IntSeries <a href="#intseries" id="intseries"></a>

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

Int series is a [*DataSeries*](#dataseries) that can assign an integer value for each bar. The number of elements in this series corresponds to the number of bars within the chart.

#### Create a New Data Series <a href="#create-a-new-data-series_3" id="create-a-new-data-series_3"></a>

Create a new variable in the declaration area:

```csharp
//Variable declaration
private IntSeries myDataSeries;
```

Assign an instance of the int series to the variable with the OnInit() method:

```csharp
protected override void OnInit()
{
myDataSeries = new IntSeries(this);
CalculateOnClosedBar = true;
}
```

#### Assign Values <a href="#assign-values_4" id="assign-values_4"></a>

Assigning a value to the current position of the data series

```csharp
myDataSeries.Set(int Value);
```

Writing a value from the past into the data series:

```csharp
myDataSeries.Set(int barsAgo, int Value);
```

#### Delete Values <a href="#delete-values_4" id="delete-values_4"></a>

Removing the current value from the data series:

```csharp
myDataSeries.Reset();
```

Removing a value located in the past from the data series:

```csharp
myDataSeries.Reset(int barsAgo);
```

#### Check Values for their Validity <a href="#check-values-for-their-validity_4" id="check-values-for-their-validity_4"></a>

```csharp
myDataSeries.ContainsValue(int barsAgo);
```

#### Read Value <a href="#read-value_4" id="read-value_4"></a>

```csharp
Print (For the bar from + Time[0] + the value of the data series is:+ myDataSeries[0]);
```

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

```csharp
//Saves the span in ticks between high and low for each bar
myDataSeries.Set((int) ((High[0] - Low[0]) / TickSize));
```

### LongSeries <a href="#longseries" id="longseries"></a>

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

Long series is a [*DataSeries*](#dataseries) that can include an integer value for each bar. The number of elements in this series corresponds to the number of bars within the chart.

#### Create a New Data Series <a href="#create-a-new-data-series_4" id="create-a-new-data-series_4"></a>

Create a new variable in the declaration area:

```csharp
//Variable declaration
private LongSeries myDataSeries;
```

Assign a new instance of the long series to the variable with the OnInit() method:

```csharp
protected override void OnInit()
{
myDataSeries = new LongSeries(this);
CalculateOnClosedBar = true;
}
```

#### Assign Values <a href="#assign-values_5" id="assign-values_5"></a>

Assigning a value to the current position of the data series:

```csharp
myDataSeries.Set(long Value);
```

Writing a value from the past into the data deries:

```csharp
myDataSeries.Set(int barsAgo, long Value);
```

#### Delete Values <a href="#delete-values_5" id="delete-values_5"></a>

Removing the current value from the data series:

```csharp
myDataSeries.Reset();
```

Removing a value located in the past from the data series:

```csharp
myDataSeries.Reset(int barsAgo);
```

#### Check Values for their Validity <a href="#check-values-for-their-validity_5" id="check-values-for-their-validity_5"></a>

```csharp
myDataSeries.ContainsValue(int barsAgo);
```

#### Read Value <a href="#read-value_5" id="read-value_5"></a>

```csharp
Print (For the bar from + Time[0] + the value of the data series is:+ myDataSeries[0]);
```

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

```csharp
//Saves the span of ticks between high and low for each bar
myDataSeries.Set((long) ((High[0] - Low[0]) / TickSize));
```

### StringSeries <a href="#stringseries" id="stringseries"></a>

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

String series is a [*DataSeries*](#dataseries) for string values that are saved for each bar. The number of elements in this series corresponds to the number of bars within the chart.

#### Create a New Data Series <a href="#create-a-new-data-series_5" id="create-a-new-data-series_5"></a>

Create a new variable in the declaration area:

```csharp
//Variable declaration
private StringSeries myDataSeries;
```

Assign an instance of string series to the variable with the OnInit() method:

```csharp
protected override void OnInit()
{
myDataSeries = new StringSeries(this);
CalculateOnClosedBar = true;
}
```

#### Assign Values <a href="#assign-values_6" id="assign-values_6"></a>

Assigning a value to the current position of the data series:

```csharp
myDataSeries.Set(string Value);
```

Writing a value from the past into the data series:

```csharp
myDataSeries.Set(int barsAgo, string Value);
```

#### Delete Values <a href="#delete-values_6" id="delete-values_6"></a>

Remove the current value from the data series:

```csharp
myDataSeries.Reset();
```

Remove a value located in the past from the data series:

```csharp
myDataSeries.Reset(int barsAgo);
```

#### Check Values for their Validity <a href="#check-values-for-their-validity_6" id="check-values-for-their-validity_6"></a>

```csharp
myDataSeries.ContainsValue(int barsAgo);
```

#### Read Value <a href="#read-value_6" id="read-value_6"></a>

```csharp
Print (For the bar from + Time[0] + the value of the data series is:+ myDataSeries[0]);
```

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

```csharp
//Save the current calendar day for each bar (Monday… Tuesday etc.)
myDataSeries.Set(string.Format("{0:dddd}", Time[0]));
```

### DayOfWeek <a href="#dayofweek" id="dayofweek"></a>

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

"DayOfWeek" outputs the date-time value (such as a timestamp) for each bar.

Of course, all other methods defined within the C# language for usage of date-time objects are also available, such as day, month, year, hour, minute, second, day of week etc.

See <https://learn.microsoft.com/en-us/dotnet/api/system.datetime.dayofweek?view=net-8.0>

#### Definition <a href="#definition_1" id="definition_1"></a>

Property DayOfWeek

public enum DayOfWeek - DayOfWeek.Monday - DayOfWeek.Tuesday - DayOfWeek.Wednesday - DayOfWeek.Thursday - DayOfWeek.Friday - DayOfWeek.Saturday - DayOfWeek.Sunday

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

```csharp
//Outputs the weekday for each bar
Print(Time[0].DayOfWeek);
//Do not execute trades on a Friday
if (Time[0].DayOfWeek == DayOfWeek.Friday)
return;
```

### Displacement <a href="#displacement" id="displacement"></a>

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

By implementing "Displacement", you can shift a drawn indicator line right or left along the x-axis. This property can be queried within the script and will return an int value.

Blue line: Displacement = 0 (Original) Red line: Displacement = -5 Green line: Displacement = +5

![Displacement](https://agenatrader.github.io/AgenaScript-documentation/media/image13.png)

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

Displacement

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

int Offset Number of bars by which the indicator is to be moved.

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

```csharp
protected override void OnInit()
{
AddOutput(new OutputDescriptor(Color.FromKnownColor(KnownColor.Black), "MyPlot1"));
//Displacement of the plot by one bar to the right
Displacement = 1;
}
```

### Email function <a href="#email-function" id="email-function"></a>

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

Override method which allows to send mail.

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

None

#### Return value <a href="#return-value_3" id="return-value_3"></a>

string

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

used for complicated calculation on a last bar

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

```csharp
protected override void OnOrderExecution(IExecution execution)
{
if (execution.Order != null && execution.Order.OrderState == OrderState.FilledQuantity)
{
if (oEnter != null && execution.Name == oEnter.Name)
{
// Enter-Order gefüllt
if (_sendMail) this.SendEmail(Core.AccountManager.Core.Settings.MailDefaultFromAddress, Core.PreferenceManager.DefaultEmailAddress,
execution.Instrument.Symbol + " order " + execution.Name + " executed.", "The order for " + execution.Instrument.Name + " was executed. Invest: " + (Trade.Quantity * Trade.AvgPrice).ToString("F2"));
}
else if (oTStop != null && execution.Name == oTStop.Name)
{
OrderStatus = 0; // Trend-Stopp-Order gefüllt
if (_sendMail) this.SendEmail(Core.AccountManager.Core.Settings.MailDefaultFromAddress, Core.PreferenceManager.DefaultEmailAddress,
execution.Instrument.Symbol +" order " + execution.Name + " executed.",
execution.Instrument.Symbol +" order " + execution.Name + " executed. Profit:" + Trade.ClosedProfitLoss.ToString("F2"));
}
}
}
```

### FirstTickOfBar <a href="#firsttickofbar" id="firsttickofbar"></a>

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

FirstTickOfBar is a property of the type "bool" that returns "true" if the currently incoming tick is associated with a new bar. This means that this tick is the first tick of a new bar. This property can only be meaningfully applied when the indicator or strategy is running in the tick-by-tick mode, meaning that CalculateOnClosedBar = false and the data feed is able to output real-time values. When using end-of-day data in a daily chart, the "FirstTickOfBar" is always true for the last bar. FirstTickOfBar should not be used outside of the OnCalculate() method. See [*Bars.TicksCountForLastBar*.](/handling-bars-and-instruments/bars#barstickscountforlastbar)

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

FirstTickOfBar

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

```csharp
// Within a tick-by-tick strategy, execute one part bar-by-bar only
if (FirstTickOfBar)
{
if (CCI(20)[1] < -250)
OpenLong();
return;
}
```

### FirstTickOfBarMtf <a href="#firsttickofbarmtf" id="firsttickofbarmtf"></a>

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

FirstTickOfBarMtf is the **multi-time frame** variant of the [*FirstTickOfBar* ](#firsttickofbar)property.

The setting of CalculateOnClosedBar only affects the primary timeframe (chart timeframe). When working with multi-bars, the ticks of the secondary timeframes are provided on a tick-by-tick basis independently of the CalculateOnClosedBar setting. With the help of FirstTickOfBarMtf, it is possible to determine when a new bar has begun in a secondary timeframe.

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

FirstTickOfBarMtf(ProcessingBarSeriesIndex)

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

FirstTickOfBarMtf(ProcessingBarSeriesIndex).

See [*ProcessingBarSeriesIndex*.](#processingbarindex)

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

```csharp
if (FirstTickOfBarMtf(ProcessingBarSeriesIndex))
Print("A new bar has begun.");
```

### GetCurrentAsk() <a href="#getcurrentask" id="getcurrentask"></a>

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

The GetCurrentAsk() method returns the current value of the ask side of the order book. If no level 1 data is available to AgenaTrader, then this function simply outputs the last trade value.

See [*GetCurrentBid()*](#getcurrentbid) and [*OnLevel1()*](/events#onlevel1).

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

GetCurrentAsk()

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

double value

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

none

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

```csharp
If an entry condition is fulfilled, then 1 contract should be sold at the current ask price:
private IOrder entryOrder = null;
protected override void OnCalculate()
{
// Entry condition
if (Close[0] < SMA(20)[0] && entryOrder == null)
// Sell 1 contract at the current ask price

    SubmitOrder(new StrategyOrderParameters
                {
                    Direction = OrderDirection.Sell,
                    Type = OrderType.Limit,
                    Mode = OrderMode.Direct,
                    Price = GetCurrentAsk(),
                    Quantity = 1,
                    SignalName = "Enter short",
                    Instrument = Instrument,
                    TimeFrame = TimeFrame,
                    LiveUntilCancelled = true
                });
}
```

### GetCurrentAskVolume() <a href="#getcurrentaskvolume" id="getcurrentaskvolume"></a>

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

The GetCurrentAskVolume () method returns the current volume on the Ask page of the order book. This function is only executable if the data provider provides level 2 data.

See [*GetCurrentBidVolume()*](#getcurrentbidvolume), [*GetCurrentBid()* ](#getcurrentbid)and [*OnLevel1()*](/events#onlevel1).

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

GetCurrentAskVolume()

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

Long value

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

none

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

```csharp
protected override void OnCalculate()
{
   if (GetCurrentAskVolume() < GetCurrentBidVolume())
       Print("AskVolume {0} < BidVolume {1}", GetCurrentAskVolume(), GetCurrentBidVolume());
}
```

### GetCurrentBid() <a href="#getcurrentbid" id="getcurrentbid"></a>

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

The GetCurrentBid() method returns the current value of the bid side of the order book. If no level 1 data is available to AgenaTrader, then the function outputs the last traded price.

See [*GetCurrentAsk()*](#getcurrentask) and [*OnLevel1()*](/events#onlevel1).

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

GetCurrentBid()

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

double value

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

none

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

If an entry condition is fulfilled, then 1 contract should be sold at the current bid price:

```csharp
private IOrder entryOrder = null;
protected override void OnCalculate()
{
// Entry condition
if (Instrument.Compare(Close[0], SMA(20)[0]) > 0 && entryOrder == null)
// Sell 1 contract at the current bid price

  SubmitOrder(new StrategyOrderParameters
                {
                    Direction = OrderDirection.Buy,
                    Type = OrderType.Limit,
                    Mode = OrderMode.Direct,
                    Price = GetCurrentBid(),
                    Quantity = 1,
                    SignalName = "Enter long",
                    Instrument = Instrument,
                    TimeFrame = TimeFrame,
                    LiveUntilCancelled = true
                });
}
```

### GetCurrentBidVolume() <a href="#getcurrentbidvolume" id="getcurrentbidvolume"></a>

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

The GetCurrentBidVolume () method returns the current volume on the Bid page of the order book. This function is only executable if the data provider provides level 2 data.

See [*GetCurrentAskVolume*](#getcurrentaskvolume), [*GetCurrentBid()*](#getcurrentbid) and [*OnLevel1()*](/events#onlevel1).

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

GetCurrentBidVolume()

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

Long value

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

none

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

```csharp
protected override void OnCalculate()
{
   if (GetCurrentAskVolume() < GetCurrentBidVolume())
       Print("AskVolume {0} < BidVolume {1}", GetCurrentAskVolume(), GetCurrentBidVolume());
}
```

### GetCurrentPrice() <a href="#getcurrentprice" id="getcurrentprice"></a>

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

The GetCurrentPrice() method returns the current price (Latest). If AgenaTrader does not have Level1 data, the function returns the price of the last sales

See [*GetCurrentAsk*](#getcurrentask), [*GetCurrentBid()*](#getcurrentbid) and [*OnLevel1()*](/events#onlevel1).

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

GetCurrentPrice()

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

none

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

double

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

If an initial condition is fulfilled, 1 contract should be purchased at the current exchange rate.

```csharp
private IOrder entryOrder = null;

protected override void OnCalculate()
{

   .....

   // Einstiegsbedingung
   if (Instrument.Compare(Close[0], SMA(20)[0]) > 0 && entryOrder == null)
       // Kauf 1 Kontrakt zum aktuellen BidKurs
       entryOrder = SubmitOrder(new StrategyOrderParameters
                {
                    Direction = OrderDirection.Buy,
                    Type = OrderType.Limit,
                    Mode = OrderMode.Direct,
                    Price = GetCurrentBid(),
                    Quantity = 1,
                    SignalName = "EntryLong",
                    Instrument = Instrument,
                    TimeFrame = TimeFrame,
                    LiveUntilCancelled = true
                });
}
```

### GetCurrentSpread() <a href="#getcurrentspread" id="getcurrentspread"></a>

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

The GetCurrentSpare () method returns the current spread.

See [*GetCurrentAsk*](#getcurrentask), [*GetCurrentBid()*](#getcurrentbid) and [*OnLevel1()*](/events#onlevel1).

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

GetCurrentSpread()

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

none

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

double

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

If an initial condition is fulfilled, 1 contract should be purchased at the current exchange rate.

```csharp
protected override void OnCalculate()
{
       Print("Der aktuelle Spread ist {0}", GetCurrentSpread());
}
```

### GetDayAsInt() <a href="#getdayasint" id="getdayasint"></a>

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

To day is a method specifically suited for inexperienced programmers who have problems with the potentially complex .net date-time structure of C#. Experienced programmers can continue using the date-time function directly.

To day outputs an int representation in the format of yyyymmdd. (yyyy = year, mm = month, dd = day)

13.08.2012 would thus be 20120813.

See [*GetTimeAsInt*.](#gettimeasint)

Help with date-time: <https://learn.microsoft.com/de-de/dotnet/api/system.datetime?view=net-8.0>

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

GetDayAsInt(DateTime time)

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

```csharp
// Do not trade on the 11<sup>th</sup> of September
if (GetDayAsInt(Time[0]) = 20130911)
return;
```

### GetSeriesHighestValue <a href="#getserieshighestvalue" id="getserieshighestvalue"></a>

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

The GetSeriesHighestValue() method searches within a predetermined number of periods for the highest bar and outputs how many bars ago it can be found.

See [*GetSeriesLowestValue()*.](#getserieslowestvalue)

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

period Number of bars within which the bar is searched for

series Every data series, such as close, high, low, etc.

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

```csharp
int barsAgo How many bars ago the high occurred
```

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

```csharp
GetSeriesHighestValue(IDataSeries series, int period)
```

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

```csharp
// How many bars ago was the highest high for the current session?
Print(GetSeriesHighestValue(High, Bars.BarsCountForSession - 1));
// What value did the market price have at the highest high of the session?
Print("The highest price for the session was: " + Open[GetSeriesHighestValue(High, Bars.BarsCountForSession - 1)]);
```

### GetSeriesLowestValue <a href="#getserieslowestvalue" id="getserieslowestvalue"></a>

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

The GetSeriesLowestValue() method attempts to find the lowest bar within a predefined number of periods.

See [*GetSeriesHighestValue()*.](#getserieshighestvalue)

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

period Number of bars that will be searched for the lowest bar

series Every data series, such as close, high, low etc.

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

**int** barsAgo How many bars ago the low occurred

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

```csharp
GetSeriesLowestValue(IDataSeries series, int period)
```

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

```csharp
// How many bars ago was the lowest low of the session?
Print(GetSeriesLowestValue(Low, Bars.BarsCountForSession - 1));
// Which price did the lowest open of the current session have?
Print("The lowest open price of the current session was: " + Open[GetSeriesLowestValue(Low, Bars.BarsCountForSession - 1)]);
```

### GetTimeAsInt() <a href="#gettimeasint" id="gettimeasint"></a>

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

To time is a method specifically suited for inexperienced programmers who have problems with the potentially complex .net date-time structure of C#.

To time outputs an int representation in the format hhmmss. (hh = hour, mm = minute, ss = seconds)

The time 07:30 will be displayed as 73000 and 14:15:12 will become 141512.

See [*GetDayAsInt*](#getdayasint).

Help with date-time: [*http://msdn.microsoft.com/de-de/library/system.datetime.aspx*](http://msdn.microsoft.com/de-de/library/system.datetime.aspx)

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

GetTimeAsInt(DateTime time)

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

```csharp
// Only enter trades between 08:15 and 16:35
if (GetTimeAsInt(Time[0]) >= 81500 && GetTimeAsInt(Time[0]) <= 163500)
{
// Any trading technique
}
```

### Historical <a href="#historical" id="historical"></a>

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

Historical allows you to check whether AgenaScript is working with historical or real-time data. As long as OnCalculate() is called up for historical data, then historical = true. As soon as live data is being used, then historical = false. During a backtest, historical is always true.

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

Historical

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

**true** when using historical data **false** when using real-time data

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

```csharp
protected override void OnCalculate()
{
// only execute for real-time data
if (IsHistoricalMode) return;
// Trading technique
}
```

### InputPriceType <a href="#inputpricetype" id="inputpricetype"></a>

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

The input price type property determines which price series is used by default when calculating an indicator, if no other data series is explicitly stated. InputPriceType can be set with the OnInit() method; this specification is then valid for all further calculations. If InputPriceType is in OnCalculate(), these changes are only valid starting with the next instruction. Every further appearance of InputPriceType will be ignored!

See [*PriceType*](#pricetype)

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

```csharp
InputPriceType
```

#### Example1 <a href="#example1" id="example1"></a>

```csharp
protected override void OnInit()
{
ClearTraceWindow();
InputPriceType = PriceType.Low;
}
protected override void OnCalculate()
{
// The input data series for the indicator (InSeries) is low
Print(Low[0] + " " + InSeries[0] + " " + InputPriceType);
}
```

#### Example2 <a href="#example2" id="example2"></a>

```csharp
protected override void OnCalculate()
{
// These values are identical
// since close is used as the input data series by default
Print(SMA(20)[0] + " " + SMA(Close, 20)[0]);
InputPriceType = PriceType.Low;
// From here on out, low is used instead of close
// Both values are identical
Print(SMA(20)[0] + " " + SMA(Low, 20)[0]);
InputPriceType = PriceType.High;
// The instructions will be ignored
// InSeries = low is still in effect
}
```

### Instrument <a href="#instrument" id="instrument"></a>

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

With "instrument", information concerning the trading instrument (stock, future etc.) is made available.

Detailed information can be found here: *Instruments*.

### IsAddDrawingsToPricePanel <a href="#isadddrawingstopricepanel" id="isadddrawingstopricepanel"></a>

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

The property "IsAddDrawingsToPricePanel" determines the panel in which the drawing objects are drawn.

```csharp
IsAddDrawingsToPricePanel = true (default)
```

Drawing objects are shown in the price chart

```csharp
IsAddDrawingsToPricePanel = false
```

Drawing objects are drawn in the panel (subchart) assigned to the indicator

If the indicator is already assigned to the price chart (overlay = true) then this property has no effect, meaning that no additional subchart is opened. The property can be queried within the script and returns a Boolean value.

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

IsAddDrawingsToPricePanel

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

```csharp
protected override void OnInit()
{
// Indicator is drawn in a new subchart
IsOverlay = false;
       AddOutput(new OutputDescriptor(Color.FromKnownColor(KnownColor.Black), "MyPlot1"));
// Drawing object is drawn in the price chart
IsAddDrawingsToPricePanel = true;
}
protected override void OnCalculate()
{
// Draws a vertical line in the price chart for the bar from 5 minutes ago
AddChartVerticalLine("MyVerticalLine", 5, Color.Black);
}
```

### IsAutoAdjustableScale <a href="#isautoadjustablescale" id="isautoadjustablescale"></a>

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

IsAutoAdjustableScale is a property of indicators that can be set within the OnInit() method.

```csharp
IsAutoAdjustableScale = true (default)
```

The price axis (y-axis) of the chart is set so that all plots and lines of an indicator are visible.

```csharp
IsAutoAdjustableScale = false
```

Plots and lines of an indicator or strategy are not accounted for in the scaling of the y-axis. Therefore they may lie outside of the visible chart area.

This property can be queried and will return either "true" or "false".

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

IsAutoAdjustableScale

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

```csharp
protected override void OnInit()
{
//Scale the chart so that all drawing objects are visible
IsAutoAdjustableScale = true;
}
```

### IsOverlay <a href="#isoverlay" id="isoverlay"></a>

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

The overlay property defines whether the indicator outputs are displayed in the price chart above the bars or whether a separate chart window is opened below the charting area.

This property can be queried within the script and outputs a value of the type Boolean (true or false).

Please bear in mind that this property is only set once during the first OnInit() method. You are not able to change the value later in your script. So if you have disabled the indicator output box below the charting area using this property during OnInit() you need to enable it manually.

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

```csharp
IsOverlay = true // -> The indicator is drawn in front of the price (e.g. the SMA indicator)
```

```csharp
IsOverlay = false // -> A separate window below the chart is opened (e.g. the RSI indicator)
```

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

```csharp
protected override void OnInit()
{
       AddOutput(new OutputDescriptor(Color.FromKnownColor(KnownColor.Black), "MyPlot1"));
       
       //The indicator should be displayed within a separate window
       IsOverlay = false;
}
```

### IsProcessingBarIndexLast <a href="#isprocessingbarindexlast" id="isprocessingbarindexlast"></a>

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

Indicates if current bar is last in calculation.

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

None

#### Return value <a href="#return-value_13" id="return-value_13"></a>

Type bool

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

used for complicated calculation on a last bar

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

```csharp
protected override void OnCalculate()
{
            base.OnCalculate();
            if (!IsProcessingBarIndexLast)
                return;
            bool isUpdated;
}
```

### IsSerieRising() <a href="#isserierising" id="isserierising"></a>

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

With this method you can check if an uptrend exists, i.e. if the current value is bigger than the previous bar’s value.

See [*CrossAbove()*](#crossabove), [*CrossBelow()*](#crossbelow), [*IsSerieRising()*](#isserierising), [*IsSerieFalling()*](#isseriefalling).

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

```csharp
IsSerieRising(IDataSeries series)
```

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

**true** If the data series is rising **false** If the data series is not rising

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

series A data series such as an indicator, close, high etc.

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

```csharp
// Check if SMA(20) is rising
if (IsSerieRising(SMA(20)))
Print("The SMA(20) is currently rising.");
```

### IsSerieFalling() <a href="#isseriefalling" id="isseriefalling"></a>

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

The IsSerieFalling() method allows you to test whether an "is falling" condition exists, i.e. whether the current value is smaller than the value of the previous bar.

See [*CrossAbove()*](#crossabove), [*CrossBelow()*](#crossbelow), [*IsSerieRising()*](#isserierising), [*IsSerieFalling()*](#isseriefalling).

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

```csharp
IsSerieFalling(IDataSeries series)
```

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

**true** If the data series is falling **false** If the data series is not falling

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

series a data series such as an indicator, close, high etc.

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

```csharp
// Check whether SMA(20) is falling
if (IsSerieFalling(SMA(20)))
Print("The SMA(20) is currently falling.");
```

### IsShowChartVerticalGrid <a href="#isshowchartverticalgrid" id="isshowchartverticalgrid"></a>

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

The property IsShowChartVerticalGrid defines whether or not the regularly spaced vertical lines (the so-called grid) are shown within the charting area.

**IsShowChartVerticalGrid = true (default)**

Vertical grid lines are shown

**IsShowChartVerticalGrid = false**

Vertical grid lines are not shown

This property can be queried within the script and returns a value of the type Boolean (true or false).

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

IsShowChartVerticalGrid

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

```csharp
protected override void OnInit()
{
       AddOutput(new OutputDescriptor(Color.FromKnownColor(KnownColor.Black), "MyPlot1"));
// Vertical grid lines shall not be shown within the chart
IsShowChartVerticalGrid = false;
}
```

### IsShowInDataBox <a href="#isshowindatabox" id="isshowindatabox"></a>

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

The property "IsShowInDataBox" states whether the value of an indicator is contained in the data box of the chart or not.

The property can be queried in the script and returns a value of the type Boolean (true or false).

```csharp
IsShowInDataBox = true (default)
```

The indicator values are displayed in the data box.

```csharp
IsShowInDataBox = false
```

The indicator values are not displayed in the data box.

The following image displays the values of 3 smoothed averages in the data box.

![IsShowInDataBox](https://agenatrader.github.io/AgenaScript-documentation/media/image14.png)

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

IsShowInDataBox

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

```csharp
protected override void OnInit()
{
 AddOutput(new OutputDescriptor(Color.FromKnownColor(KnownColor.Black), "MyPlot1"));
//Values will not be shown in the data box
IsShowInDataBox = false;
}
```

### IsShowPriceMarkers <a href="#isshowpricemarkers" id="isshowpricemarkers"></a>

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

The paint price markers property defines whether the so-called price markers for the indicator outputs are displayed on the right-hand chart border (in the price axis) or not. In some cases it makes sense to switch these off for a better overview in the chart. **IsShowPriceMarkers = true (default)**

Price markers are shown in the price axis

**IsShowPriceMarkers = false**

Price markers are not shown in the price axis

This property can be queried within the script and returns a value of the type Boolean (true or false).

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

IsShowPriceMarkers

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

```csharp
protected override void OnInit()
{

AddOutput(new OutputDescriptor(Color.FromKnownColor(KnownColor.Black), "MyPlot1"));
//Do not show price markers in the price axis
IsShowPriceMarkers = false;
}
```

### Level1Args <a href="#level1args" id="level1args"></a>

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

The data type Level1Args represents a change in the level 1 data and is used as a parameter of the OnLevel1() function.

|                |                                                                                                                                                          |
| -------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- |
| AskSize        | Current order volume on the ask side                                                                                                                     |
| AskPrice       | Current ask price                                                                                                                                        |
| BidSize        | Current order volume on the bid side                                                                                                                     |
| BidPrice       | Current bid price.                                                                                                                                       |
| Instrument     | An object of the type instrument that contains the trading instrument for which the level 1 data is outputted. See *Instruments*                         |
| LastPrice      | Last traded price                                                                                                                                        |
| MarketDataType | Potential values are: MarketDataType.Ask, MarketDataType.AskSize, MarketDataType.Bid, MarketDataType.BidSize, MarketDataType.Last, MarketDataType.Volume |
| Price          | This is equal to last price. This field only exists for compatability reasons                                                                            |
| Time           | A date-time value containing the timestamp of the change                                                                                                 |
| Volume         | A long value that shows the volume                                                                                                                       |

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

See [*OnLevel1()*](/events#onlevel1).

### Level2Args <a href="#level2args" id="level2args"></a>

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

The data type Level2Args represents a change in the level 2 data (market depth) and is used as a parameter within OnLevel2().

|                |                                                                                                                                 |
| -------------- | ------------------------------------------------------------------------------------------------------------------------------- |
| MarketDataType | Potential values are: MarketDataType.Ask, MarketDataType.Bid                                                                    |
| MarketMaker    | A string value containing the market maker ID                                                                                   |
| Position       | An int value that defines the position within the market depth                                                                  |
| Operation      | Represents the action caused by a change in the order book. Values can be: Operation.Insert, Operation.Remove, Operation.Update |
| Price          | A double value that displays the bid/ask price                                                                                  |
| Time           | A date-time value containing the timestamp of the change                                                                        |
| Volume         | A long value that shows the volume                                                                                              |

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

See [*OnLevel2()*](/events#onlevel2).

### LevelLine() <a href="#levelline" id="levelline"></a>

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

A line object is used for drawing a horizontal line in the chart. Usually, these are upper and lower trigger lines for indicators such as the RSI (70 and 30). The lines described here are not to be confused with lines from the drawing objects (see "AddChartHorizontalLine"). LevelLine objects can be added to an indicator with the help of the Add() method, and with this, added to the lines collection.

See [*OutputDescriptor*](#outputdescriptor).

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

|       |                                                              |
| ----- | ------------------------------------------------------------ |
| Color | LevelLine color                                              |
| Name  | Description                                                  |
| Pen   | A pen object                                                 |
| Value | Defines which value on the y-axis the line will be drawn for |

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

```csharp
LevelLine(Color color, double value, string name)
LevelLine(Pen pen, double value, string name)
```

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

Information on the pen class: <https://learn.microsoft.com/de-de/dotnet/api/system.drawing.pen?view=dotnet-plat-ext-8.0>

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

```csharp
// Example 1
// A new line with standard values drawn at the value of 70
Add(new LevelLine(Color.Black, 70, "Upper"));
// Example 2
// A new line with self-defined values
private LevelLine line;
private Pen pen;
protected override void OnInit()
{
// Define a red pen with the line strength 1
pen = new Pen(Color.Red, 1);
// Define a horizontal line at 10
line = new LevelLine(pen, 10, "MyLine");
// add the defined line to the indicator
Add(line);
}
// Example 3
// Short form for the line in example 2
Add(new LevelLine(new Pen(Color.Red, 1), 10, "MyLine"));
```

### Log() <a href="#log" id="log"></a>

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

Log() allows you to write outputs in the AgenaTrader log file (log tab). 5 different log levels are supported.

Note: If the log tab is not viewable, it can be displayed using the tools log.

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

```csharp
**Log**(string message, LogLevel logLevel)
```

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

|          |                                                                                                                                |
| -------- | ------------------------------------------------------------------------------------------------------------------------------ |
| message  | Text (message)                                                                                                                 |
| logLevel | Possible values are: InfoLogLevel.Info, InfoLogLevel.Message, InfoLogLevel.Warning, InfoLogLevel.ShowAlert, InfoLogLevel.Error |

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

```csharp
//Tab protocol
Log("This is information.", InfoLogLevel.Info); //white
Log("This is a message.", InfoLogLevel.Message); // white
Log("This is a warning.", InfoLogLevel.Warning); // blue
Log("This is an alarm.", InfoLogLevel. ShowAlert); //green
Log("This is a mistake.", InfoLogLevel.Error); // red
//Tab messags
Log("This is a message (messages).", InfoLogLevel.Message); //white
//PopUp & protocoll
Log("This is an alert popup window.", InfoLogLevel.ShowAlert); //green

//Output-Tab:
//InfoLogLevel.Message = send to Tab "Messages" not "Log"

//Action:
/*
InfoLogLevel.Error: also the AT-Status-Line is red and flashes
InfoLogLevel.ShowAlert: opens also a modeless messagebox
*/

/*
Summary: * - InfoLogLevel.ShowAlert Color: green Tab: Log Action: modeless Messagebox * - InfoLogLevel.Warning Color: blue Tab: Log * - InfoLogLevel.Info Color: white Tab: Log * - InfoLogLevel.Error Color: red Tab: Log Action: AT-Status-Line: red + flashing (Error) * - InfoLogLevel.Message Color: white Tab: Messages
*/
```

Crossreference: a crossreference to Print() and ShowAlert()

### Occurred <a href="#occurred" id="occurred"></a>

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

This DataSeries is used in conditions and indicates if signal occurred (1-long, -1 short, 0- no signal )

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

None

#### Return value <a href="#return-value_16" id="return-value_16"></a>

Int

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

In scripted condition for short, long, none signal indication

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

```csharp
protected override void OnCalculate()
{
if ( ProcessingBarIndex %2 == 0 )
Occurred.Set(1); // Long
else if ( ProcessingBarIndex %3 == 0 )
Occurred.Set(-1); // Short
else
Occurred.Set(0);
}
```

### OnBarsRequirements() <a href="#onbarsrequirements" id="onbarsrequirements"></a>

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

The OnBarsRequirements() method is called up once at the beginning of an indicator and/or strategy calculation. This method is only necessary when using multi-bars. Within OnBarsRequirements, no other programming commands are executed. For initializing, the OnInit() or OnStart() method should be used.

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

none

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

none

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

```csharp
protected override void OnBarsRequirements()
{
Add(DatafeedHistoryPeriodicity.Day, 1);
Add(DatafeedHistoryPeriodicity.Week, 1);
}
```

### 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()*](#addoutput)
* [*AllowRemovalOfChartDrawings*](#allowremovalofchartdrawings)
* *IsAutoScale*
* [*RequiredBarsCount*](#requiredbarscount)
* [*CalculateOnClosedBar*](#calculateonclosedbar)
* [*ClearTraceWindow()*](#cleartracewindow)
* [*Displacement*](#displacement)
* [*IsShowInDataBox*](#isshowindatabox)
* [*IsAddDrawingsToPricePanel*](#isadddrawingstopricepanel)
* [*InputPriceType*](#inputpricetype)
* [*IsOverlay*](#isoverlay)
* [*IsShowPriceMarkers*](#isshowpricemarkers)
* [*IsShowChartVerticalGrid*](#isshowchartverticalgrid)

**Additional Keywords for Strategies**

* [*DefaultOrderQuantity*](/strategy-programming#defaultorderquantity)
* *EntriesPerDirection*
* [*SetUpStopLoss()*](/strategy-programming#setupstoploss)
* [*SetUpProfitTarget()*](/strategy-programming#setupprofittarget)
* [*SetUpTrailStop()*](/strategy-programming#setuptrailstop)
* [*TimeInForce*](/strategy-programming#timeinforce)
* [*TraceOrders*](/strategy-programming#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;
}
```

### OutputDescriptor() <a href="#outputdescriptor" id="outputdescriptor"></a>

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

A plot (drawing) is used to visually display indicators in a chart. OutputDescriptor objects are assigned to an indicator with the help of the Add() method and attached to the plots collection. See [*LevelLine*](#levelline).

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

|                          |                                                                                                                                                                                                                                                                                                                            |
| ------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Color                    | Drawing color                                                                                                                                                                                                                                                                                                              |
| Pen                      | Pen object                                                                                                                                                                                                                                                                                                                 |
| OutputSeriesDisplayStyle | LevelLine type: OutputSeriesDisplayStyle.Bar, OutputSeriesDisplayStyle.Block, OutputSeriesDisplayStyle.Cross, OutputSeriesDisplayStyle.Dot, OutputSeriesDisplayStyle.Hash, OutputSeriesDisplayStyle.LevelLine, OutputSeriesDisplayStyle.Square, OutputSeriesDisplayStyle.TriangleDown, OutputSeriesDisplayStyle.TriangleUp |
| Name                     | Description                                                                                                                                                                                                                                                                                                                |

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

```csharp
OutputDescriptor(Color color, string name)
OnPOutputDescriptoraint(Pen pen, string name)
OutputDescriptor(Color color, OutputSeriesDisplayStyle plotStyle, string name)
OutputDescriptor(Pen pen, OutputSeriesDisplayStyle plotStyle, string name)
```

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

Information on the pen class: [*http://msdn.microsoft.com/de-de/library/system.drawing.pen.aspx*](http://msdn.microsoft.com/de-de/library/system.drawing.pen.aspx)

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

```csharp
// Example 1
// OutputDescriptor with standard values (line with line strength 1)
AddOutput(new OutputDescriptor(Color.FromKnownColor(KnownColor.Orange), "Output1"));
// Example 2
// user-defined values for pen and plot style
private OutputDescriptor plot;
private Pen pen;
protected override void OnInit()
{
// a red pen with the line strength of 6 is defined
pen = new Pen(Color.Blue, 6);
// a point line with a thick red pen from above is defined
paint = new OutputDescriptor(pen, OutputSeriesDisplayStyle.Dot, "MyPlot");
// The defined plot is to be used as a representation for an indicator
Add(paint);
}
// Example 3
// Abbreviation of example 2
protected override void OnInit()
{
Add(new OutputDescriptor(new Pen(Color.Blue, 6), OutputSeriesDisplayStyle.Dot, "MyPlot"));
}
```

### InputParameter() <a href="#inputparameter" id="inputparameter"></a>

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

Attribute which used for indicator customization

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

None

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

None

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

```csharp
[Description("Period for the medium mean average")]
[InputParameter]
[DisplayName("MA Medium")]
public int MA_Medium
{
    get 
    { 
        return _ma_medium; 
    }
    set
    {
        _ma_medium = value;
    }
}
```

### PlaySound() <a href="#playsound" id="playsound"></a>

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

This method allows you to play a wav file.

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

**PlaySound**(wavFile)

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

none

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

wavFile File name of the wav file to be played

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

```csharp
using System.IO;
string path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
string file = "\\\\AgenaTrader\\\\Sounds\\\\Alert1.wav";
PlaySound(path + file);
```

### PlotMethod <a href="#plotmethod" id="plotmethod"></a>

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

In each indicator, the plot method can be overridden in order to add your own graphics (GDI+) to the price chart with the help of the graphics class (System.Drawing).

See [*http://msdn.microsoft.com/de-de/library/system.drawing.graphics.aspx*](http://msdn.microsoft.com/de-de/library/system.drawing.graphics.aspx).

The *Chart* object offers several parameters.

More examples: *Bar Numbering*, *PlotSample*, *Chart Background Image*.

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

graphics The graphics object of the price chart (context)

rectangle The size of the drawing area (type "public struct rectangle")

double min The smallest price in the y-axis

double max The biggest price in the y-axis

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

none

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

```csharp
public override void OutputDescriptor(Graphics graphics, Rectangle r, double min, double max)
```

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

```csharp
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Drawing2D;
using AgenaTrader.API;
using AgenaTrader.Custom;
using AgenaTrader.Plugins;
namespace AgenaTrader.UserCode
{
[Description("Example for the usage of the plot method.")]
public class PlotSample : UserIndicator
{
private StringFormat stringFormat = new StringFormat();
private SolidBrush brush = new SolidBrush(Color.Black);
private Font font = new Font("Arial", 10);
protected override void OnInit()
{
IsChartOnlyIndicator = true;
IsOverlay = true;
}
protected override void OnCalculate()
{}
protected override void OnDispose()
{
brush.Dispose();
stringFormat.Dispose();
}
public override void OutputDescriptor(Graphics graphics, Rectangle r, double min, double max)
{
// Fill a rectangle
SolidBrush tmpBrush = new SolidBrush(Color.LightGray);
graphics.FillRectangle(tmpBrush, new Rectangle (0, 0, 300, 300));
tmpBrush.Dispose();
// Draw a red line from top left to bottom right
Pen pen = new Pen(Color.Red);
graphics.AddChartLine(pen, r.X, r.Y, r.X + r.Width, r.Y + r.Height);
// Draw a red line from bottom left to top right
// Use anti-alias (the line appears smoother)
// The current settings for the smoothing are saved
// Restore after drawing
SmoothingMode oldSmoothingMode = graphics.SmoothingMode; //Save settings
graphics.SmoothingMode = SmoothingMode.AntiAlias; // Use higher smoothing settings
graphics.AddChartLine(pen, r.X, r.Y + r.Height, r.X + r.Width, r.Y);
graphics.SmoothingMode = oldSmoothingMode; // Settings restored
pen.Dispose();
// Text in the upper left corner (position 10,35)
stringFormat.Alignment = StringAlignment.Near; // Align text to the left
brush.Color = Color.Blue;
graphics.DrawString("Hello world!", font, brush, r.X + 10, r.Y + 35, stringFormat);
// Text in the left lower corner and draw a line around it
brush.Color = Color.Aquamarine;
graphics.FillRectangle(brush, r.X + 10, r.Y + r.Height - 20, 140, 19);
// Draw outside line
pen = new Pen(Color.Black);
graphics.AddChartRectangle(pen, r.X + 10, r.Y + r.Height - 20, 140, 19);
pen.Dispose();
// Write text
brush.Color = Color.Red;
graphics.DrawString("Here is bottom left!", font, brush, r.X + 10, r.Y + r.Height - 20, stringFormat);
}
}
}
```

### PriceType <a href="#pricetype" id="pricetype"></a>

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

Price type describes a form of price data.

See [*InputPriceType*](#inputpricetype)

Following variables are available: - PriceType.Close - PriceType.High - PriceType.Low - PriceType.Median - PriceType.Open - PriceType.Typical - PriceType.Volume - PriceType.Weighted

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

PriceType

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

See [*InputPriceType*](#inputpricetype)

### Print() <a href="#print" id="print"></a>

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

The Print() method writes outputs in the AgenaTrader output window. See [*ClearTraceWindow()*](#cleartracewindow).

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

```csharp
Print(string message)
Print(bool value)
Print(double value)
Print(int value)
Print(DateTime value)
Print(string format, string message)
```

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

string Text an individual message text

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

none

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

Information regarding output formatting: *Formatting numbers*.

Hints about the String.Format() method: [*http://msdn.microsoft.com/de-de/library/fht0f5be%28v=vs.80%29.aspx*](http://msdn.microsoft.com/de-de/library/fht0f5be%28v=vs.80%29.aspx)

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

```csharp
// "Quick&Dirty" formatting of a number with 2 decimal points
Print(Close[0].ToString("0.00"));
// Output day of the week from the timestamp for the bar
Print(string.Format("{0:dddd}", Time[0]));
// An additional empty row with an escape sequence
Print("One empty row afterwards \\n");
```

### ProcessingBarIndex <a href="#processingbarindex" id="processingbarindex"></a>

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

Current bar is a method of indexing bars used in the OnCalculate() method. If a chart contains 500 bars and an indicator is to be calculated on the basis of these, then AgenaTrader will begin calculating from the oldest bar. The oldest bar receives the number 0. Once the calculation for this bar has been completed, the OnCalculate() method is called up for the next bar, which in turn receives the number 1. This continues until the last bar, which receives a value of 500.

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

none

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

Current bar is a variable of the type int, which always contains the number of the bar currently being used.

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

ProcessingBarIndex

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

The OnCalculate() method uses numbering different from that of ProcessingBarIndex in terms of the [*Barindex*](#processingbarindex) and [*Bars*](/handling-bars-and-instruments/bars). Understanding this difference is of great importance, which is why we ask you to please read the following paragraph carefully:

ProcessingBarIndex numbers continuously from the oldest to youngest bar starting with 0. The BarIndex for the youngest bar is always 0. In the example referenced below this paragraph, Time\[0] stands for the timestamp of the current bar. The index of the oldest bar always has 1 added to it. Thus a logical numbering of barsAgo is possible. The timestamp for the bar of 5 periods ago is Time\[5]. For using multiple timeframes (multi-bars) in an indicator, see ProcessingBarIndexes.

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

```csharp
protected override void OnCalculate()
{
Print("Call of OnCalculate for bar nr. " + ProcessingBarIndex + " of " + Time[0]);
}
```

### RemoveChartDrawing() <a href="#removechartdrawing" id="removechartdrawing"></a>

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

The RemoveChartDrawing() method removes a specific drawing object from the chart based on a unique identifier (tag). See [*RemoveChartDrawings()*](#removechartdrawings).

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

RemoveChartDrawings(string tag)

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

none

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

string tag The clearly identifiable name for the drawing object

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

```csharp
RemoveChartDrawings("My line");
```

### RemoveChartDrawings() <a href="#removechartdrawings" id="removechartdrawings"></a>

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

This method removes all drawings from the chart See [*RemoveChartDrawings()*](#removechartdrawings)*.*

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

RemoveChartDrawings()

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

none

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

```csharp
//Delete all drawings from the chart
RemoveChartDrawings();
```

### RequiredBarsCount <a href="#requiredbarscount" id="requiredbarscount"></a>

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

The property "RequiredBarsCount" determines how many historical bars are required for an indicator or a strategy to call up the OnCalculate() method for the first time and thus begin the calculations. Bars required should be set within the OnInit() method. The setting should be chosen carefully. If you require 100 days for the calculation of a moving average, then you should ensure that at least 100 days of historical data are loaded. The property can be queried in the script and will return an int value.

When OnCalculate is called up for the first time, the ProcessingBarIndex property is 0 regardless of the value of RequiredBarsCount.

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

RequiredBarsCount

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

```csharp
protected override void OnInit()
{
//The indicator requires a minimum of 50 bars loaded into the history
RequiredBarsCount = 50;
}
```

### ShowAlert() <a href="#showalert" id="showalert"></a>

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

The ShowAlert method creates an acoustic and/or visual alarm.

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

```csharp
ShowAlert(string message, bool showMessageBox, string soundLocation);
//Due to compatability reasons, an old signature is still used here. When using this method, the color settings and the "re-arm seconds" parameter are ignored.
ShowAlert(string id, AlertPriority priority, string message, string soundLocation, int rearmSeconds, Color backColor, Color forColor);
```

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

None

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

|                |                                                                                                                    |
| -------------- | ------------------------------------------------------------------------------------------------------------------ |
| message        | Alert text displayed within the messages tab                                                                       |
| soundLocation  | Name of a sound file in the \*.wav format. If no path is specified, then "My Documents\AgenaTrader\Sounds\ is used |
| showMessageBox | If set to "true", a message box will be displayed in addition to the sound                                         |

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

```csharp
// Message will be outputted if the SMA(20) crosses below the SMA(50)
if (CrossBelow(SMA(20), SMA(50), 1))
Alert("Check short signal!", true, "Alert4.wav");
```

To use music files in a different path, you need to specify the path:

```csharp
string pathOfSoundfile = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)+@"\\MyAlertSounds\\";
string nameOfSoundFile = "MyAlertSoundFile.wav";
Alert("Message text", true, pathOfSoundfile + nameOfSoundFile);
```

### TickSize <a href="#ticksize" id="ticksize"></a>

A tick is the smallest possible price change of a financial instrument within an exchange. If, for example, the trading prices are specified to 2 decimal places, then a tick equals 0.01. You can expect Forex instruments to be specified to within 4 or 5 decimal places. A tick is called a pip in Forex trading and usually equals 0.0001 or 0.00001. The tick value is usually predefined by the exchange and does not (usually) change. See [*Instrument.TickSize*](/handling-bars-and-instruments/instruments#instrumentticksize).

Usually, a tick is displayed as a decimal number. Historically speaking (especially in American exchanges) stocks have been noted with tick sizes of 1/16 of a dollar. This notation is still widespread within commodities. Corn futures (ZC) are noted in ¼ US cents/bushel (usually equals 12.50 US$ per contract). US treasury bonds are noted in a tick size of 1/32 points, which equals 31.25$. Notations are usually made with apostrophes, for example:

149'00 equals exactly 149, 149'01 equals 149 1/32 (meaning 149.03125), 149'31 equals 149 31/32 (149.96875), and the next value after this is 150’00

In the so-called T-Bond intermonth spreads, notations are specified in quarters of 1/32, resulting in point values of 7.8125 per contract.

Notations have a dash:

17-24 equals 17 24/32 points, 17-242 equals 17 24.25/32 points, 17-245 equals 17 24.5/32 points and 17-247 equals 17 24.75/32 points. The next notation after 17-247 is 17-25 and then 17-252, 17-255 etc. After 17-317 comes 18.

The individual contract specifications can be found on the websites of the respective exchanges.

CME: [*http://www.cmegroup.com*](http://www.cmegroup.com/) under Products & Trading Eurex (FDAX): [*http://www.eurexchange.com/exchange-en/products/idx/dax/17206/*](http://www.eurexchange.com/exchange-en/products/idx/dax/17206/)

See [*Instrument.TickSize*](https://agenatrader.github.io/AgenaScript-documentation/keywords/#instrumentticksize).

### TimeFrame <a href="#timeframe" id="timeframe"></a>

See [*Bars.TimeFrame*](/handling-bars-and-instruments/bars#barstimeframe).

When using multiple timeframes ([*Multibars*](/handling-bars-and-instruments/multibars#multibars)) in an indicator, please see [*TimeFrames*.](#timeframe)

### Update() <a href="#update" id="update"></a>

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

The Update() method calls up the OnCalculate method in order to recalculate the indicator values.

Update() is to be used with caution and is intended for use by experienced programmers.

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

```csharp
Update()
```

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

none

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

none

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

The effect of update can be illustrated with the help of 2 indicators. The first indicator, Ind1, uses a public variable from the indicator Ind2.

**Code from Ind1:**

```csharp
public class Ind1 : UserIndicator
{
protected override void OnCalculate()
{
Print( Ind2().MyPublicVariable );
}
}
```

**Code from Ind2:**

```csharp
private double myPublicVariable = 0;
protected override void OnCalculate()
{
myPublicVariable = 1;
}
public double MyPublicVariable
{
get
{
Update();
return myPublicVariable;
}
}
```

**Without Update() - Wrong** If Ind2 is called up by Ind1, the get-method of MyPublicVariable is called up in Ind2. Without Update(), the value of MyPublicVariable would be returned. In this case it would be 0.

**With Update() - Correct** By calling up Update(), OnCalculate() is initially executed by Ind2. This sets MyPublicVariable to 1. Lastly, the value 1 is passed on to the requesting indicator.

### Value <a href="#value" id="value"></a>

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

Value is a data series object containing the first data series of an indicator.

When the Add() method is called up, a value object is automatically created and added to the values collection.

Value is identical to Values\[0].

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

Value

Value\[**int** barsAgo]

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

The methods known for a collection, Set(), Reset(), and Count(), can be used for values.

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

See [*Values*](#value).


# DrawingObjects

### AddChartAndrewsPitchfork() <a href="#addchartandrewspitchfork" id="addchartandrewspitchfork"></a>

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

This drawing object draws an Andrew’s Pitchfork.

Information concerning its usage: - [*vtad.de*](http://vtadwiki.vtad.de/index.php/Andrews_Pitchfork) - [*hvolumen-analyse.de*](http://www.volumen-analyse.de/blog/?p=917) - [*Godmode-Trader.de*](http://www.godmode-trader.de/wissen/index.php/Chartlehrgang:Andrews_Pitchfork)

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

```csharp
AddChartAndrewsPitchfork(string name, bool autoScale, int start1BarsBack, double start1Y, int start2BarsBack, double start2Y, int start3BarsBack, double start3Y, Color color, DashStyle dashStyle, int width)
AddChartAndrewsPitchfork(string name, bool autoScale, DateTime start1Time, double start1Y, DateTime start2Time, double start2Y, DateTime start3Time, double start3Y, Color color, DashStyle dashStyle, int width)
```

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

A drawing object of the type IAndrewsPitchfork (interface)

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

|                |                                                                                         |
| -------------- | --------------------------------------------------------------------------------------- |
| name           | A clearly identifiable name for the drawing object                                      |
| autoScale      | Adjusts the scale of the y-axis so that drawing objects can be viewed in their entirety |
| start1BarsBack | Number of bars ago for start point 1 (x-axis)                                           |
| start1Time     | Date/time for start point 1 (x-axis)                                                    |
| start1Y        | y-value for start point 1                                                               |
| start2BarsBack | Number of bars ago for start point 2 (x-axis)                                           |
| start2Time     | Date/time for start point 2 (x-axis)                                                    |
| start2Y        | y-value for start point 2                                                               |
| start3BarsBack | Number of bars ago for start point 3 (x-axis)                                           |
| start3Time     | Date/time for start point 3 (x-axis)                                                    |
| start3Y        | y-value for start point 3                                                               |
| color          | Color of the object                                                                     |
| dashStyle      | LevelLine styles:                                                                       |
|                | DashStyle.Dash                                                                          |
|                | DashStyle.DashDot                                                                       |
|                | DashStyle.DashDotDot                                                                    |
|                | DashStyle.Dot                                                                           |
|                | DashStyle.Solid                                                                         |
|                |                                                                                         |
|                | You may have to integrate: using System.Drawing.Drawing2D;                              |
| width          | LevelLine strength in points                                                            |

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

```csharp
// Draw the Andrew’s Pitchfork (“MyAPF”)
AddChartAndrewsPitchfork("MyAPF-" + ProcessingBarIndex, true, 4, Low[4], 3, High[3], 1, Low[1], Color.Black, DashStyle.Solid, 2);
```

### AddChartArc() <a href="#addchartarc" id="addchartarc"></a>

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

AddChartArc() draws a circular arc.

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

```csharp
AddChartArc(string name, int barsBackStart, double startY, int barsBackEnd, double endY, Color color)
AddChartArc(string name, bool isAutoScale, int barsBackStart, double startY, int barsBackEnd, double endY, Color color, DashStyle dashStyle, int width)
AddChartArc(string name, bool isAutoScale, double startX, double  startY,double  endX,double  endY, double  middleX, double  middleY, Color color, DashStyle dashStyle, int width, showOnTop);
```

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

A drawing object of the type IArc (interface)

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

|                  |                                                                                         |
| ---------------- | --------------------------------------------------------------------------------------- |
| name             | A clearly identifiable name for the drawing object                                      |
| IsAutoScale      | Adjusts the scale of the y-axis so that drawing objects can be viewed in their entirety |
| startX, startY   | Beginning of the arch line                                                              |
| middleX, middleY | Top arc coordinate                                                                      |
| endX, endY       | end of the arch line                                                                    |
| barsBackEnd      | Number of bars ago for the end point                                                    |
| endTime          | Date/time for the end point                                                             |
| endY             | y-value for the end point                                                               |
| color            | Color of the drawing object                                                             |
| dashStyle        | LevelLine style:                                                                        |
|                  | DashStyle.Dash                                                                          |
|                  | DashStyle.DashDot                                                                       |
|                  | DashStyle.DashDotDot                                                                    |
|                  | DashStyle.Dot                                                                           |
|                  | DashStyle.Solid                                                                         |
|                  |                                                                                         |
|                  | You may have to integrate: using System.Drawing.Drawing2D;                              |
| width            | LevelLine strength in points                                                            |

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

```csharp
// AddChart a blue arc
AddChartArc("MyArc-" + ProcessingBarIndex, true, 10, 10, 0, 20, Color.Blue, DashStyle.Solid, 3);
//Add Arc
AddChartArc("test", true, first.Time, 1854, last.Time, 1854, mid.Time, 1938, Color.Black, DashStyle.Custom, 1, true);
```

### AddChartArrowDown() <a href="#addchartarrowdown" id="addchartarrowdown"></a>

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

AddChartArrowDown() draws an arrow pointing downwards:

![AddChartArrowDown()](https://agenatrader.github.io/AgenaScript-documentation/media/image21.png)

See [*AddChartArrowUp()*](#addchartarrowup), [*AddChartArrowDown()*](#addchartarrowdown), [*AddChartDiamond()*](#addchartdiamond),[ *AddChartDot()*](#addchartdot), [*AddChartSquare()*](#addchartsquare), [*AddChartTriangleUp()*](#addcharttriangleup), [*AddChartTriangleDown()*](#addcharttriangledown).

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

```csharp
AddChartArrowDown(string name, bool autoScale, int barsAgo, double y, Color color)
AddChartArrowDown(string name, bool autoScale, DateTime time, double y, Color color)
```

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

A drawing object of the type IArrowDown (interface)

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

|           |                                                                                         |
| --------- | --------------------------------------------------------------------------------------- |
| name      | A clearly identifiable name for the drawing object                                      |
| autoScale | Adjusts the scale of the y-axis so that drawing objects can be viewed in their entirety |
| barsAgo   | Sets the preceding bar on which the arrow should be drawn (0 = current bar)             |
| time      | Date/time of the bar on which the arrow should be drawn                                 |
| y         | y-value for the arrow                                                                   |
| color     | Color of the drawing object                                                             |

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

```csharp
// Draws a red arrow 3 ticks above the high for the current bar
AddChartArrowDown("MyArrow-" + ProcessingBarIndex, true, 0, High[0] + 3*TickSize, Color.Red);
// Draws a red arrow on a three-bar reversal pattern
if(High[2] > High[3] && High[1] > High[2] && Close[0] < Open[0])
AddChartArrowDown(ProcessingBarIndex.ToString(), true, 0, High[0] + 3*TickSize, Color.Red);
```

### AddChartArrowLine() <a href="#addchartarrowline" id="addchartarrowline"></a>

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

AddChartArrowLine() draws an arrow:

![AddChartArrowLine()](https://agenatrader.github.io/AgenaScript-documentation/media/image22.png)

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

```csharp
 AddChartArrowLine (string name,  int  barsBackStart,  double  startY,  int  barsBackEnd,  double  endY, Color color)
 AddChartArrowLine (string name,  bool  autoScale,  int  barsBackStart,  double  startY,  int  barsBackEnd,  double  endY, Color color, DashStyle dashStyle,  int  width)
 AddChartArrowLine (string name,  bool  autoScale, DateTime startTime,  double  startY, DateTime endTime,  double  endY, Color color, DashStyle dashStyle,  int  width)
```

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

A drawing object of the type IArrowLine (interface)

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

|               |                                                                                         |
| ------------- | --------------------------------------------------------------------------------------- |
| name          | A clearly identifiable name for the drawing object                                      |
| autoScale     | Adjusts the scale of the y-axis so that drawing objects can be viewed in their entirety |
| barsBackStart | Sets the preceding bar at which the arrow should start (0 = current bar)                |
| startTime     | Date/time of the bar at which the arrow should start                                    |
| startY        | y-value for the starting point of the arrow                                             |
| barsBackEnd   | Sets the preceding bar at which the arrow should end (0 = current bar)                  |
| endTime       | Date/time at which the arrow should end                                                 |
| endY          | y-value at which the arrow should end                                                   |
| color         | Color of the drawing object                                                             |
| dashStyle     | LevelLine style:                                                                        |
|               | DashStyle.Dash                                                                          |
|               | DashStyle.DashDot                                                                       |
|               | DashStyle.DashDotDot                                                                    |
|               | DashStyle.Dot                                                                           |
|               | DashStyle.Solid                                                                         |
|               |                                                                                         |
|               | You may have to integrate: using System.Drawing.Drawing2D;                              |
| width         | LevelLine strength in points                                                            |

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

```csharp
// Draws a black arrow
AddChartArrowLine("MyArrow-" + ProcessingBarIndex, false, 10, 10, 0, 5, Color.Black, DashStyle.Solid, 4);
```

### AddChartArrowUp() <a href="#addchartarrowup" id="addchartarrowup"></a>

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

AddChartArowUp() draws an arrow pointing upwards:

![AddChartArrowUp()](https://agenatrader.github.io/AgenaScript-documentation/media/image23.png)

See [*AddChartArrowUp()*](#addchartarrowup), [*AddChartArrowDown()*](#addchartarrowdown), [*AddChartDiamond()*](#addchartdiamond),[ *AddChartDot()*](#addchartdot), [*AddChartSquare()*](#addchartsquare), [*AddChartTriangleUp()*](#addcharttriangleup), [*AddChartTriangleDown()*](#addcharttriangledown).

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

```csharp
AddChartArrowUp(string name, bool autoScale, int barsAgo, double y, Color color)
AddChartArrowUp(string name, bool autoScale, DateTime time, double y, Color color)
```

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

A drawing object of the type IArrowUp (interface)

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

|           |                                                                                         |
| --------- | --------------------------------------------------------------------------------------- |
| name      | A clearly identifiable name for the drawing object                                      |
| autoScale | Adjusts the scale of the y-axis so that drawing objects can be viewed in their entirety |
| barsAgo   | Sets the preceding bar on which the arrow should be drawn (0 = current bar)             |
| time      | Date/time at which the arrow should be drawn                                            |
| y         | y-value for the arrow                                                                   |
| color     | Color of the drawing object                                                             |

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

```csharp
// Draws a green arrow for the current bar 3 ticks below the low
AddChartArrowUp("MyArrow-" + ProcessingBarIndex, true, 0, Low[0] - 3*TickSize, Color.Green);
```

### AddChartDiamond() <a href="#addchartdiamond" id="addchartdiamond"></a>

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

AddChartDiamond() draws a diamond:

![AddChartDiamond()](https://agenatrader.github.io/AgenaScript-documentation/media/image24.png)

See [*AddChartArrowUp()*](#addchartarrowup), [*AddChartArrowDown()*](#addchartarrowdown), [*AddChartDiamond()*](#addchartdiamond),[ *AddChartDot()*](#addchartdot), [*AddChartSquare()*](#addchartsquare), [*AddChartTriangleUp()*](#addcharttriangleup), [*AddChartTriangleDown()*](#addcharttriangledown).

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

```csharp
AddChartDiamond(string name, bool autoScale, int barsAgo, double y, Color color)
AddChartDiamond(string name, bool autoScale, DateTime time, double y, Color color)
```

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

A drawing object of the type IDiamond (interface)

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

|           |                                                                                         |
| --------- | --------------------------------------------------------------------------------------- |
| name      | A clearly identifiable name for the drawing object                                      |
| autoScale | Adjusts the scale of the y-axis so that drawing objects can be viewed in their entirety |
| barsAgo   | Defines the preceding bar on which the diamond should be drawn                          |
| time      | Date/time of the bar on which the diamond should be drawn                               |
| y         | y-value on which the diamond should be drawn                                            |
| color     | Color of the drawing object                                                             |

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

```csharp
// Draws a light blue diamond for the current bar 5 ticks below the low
AddChartDiamond("MyDiamond-" + ProcessingBarIndex, true, 0, Low[0] - 5*TickSize, Color.SteelBlue);
```

### AddChartDot() <a href="#addchartdot" id="addchartdot"></a>

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

AddChartDot() draws a dot:

![AddChartDot()](https://agenatrader.github.io/AgenaScript-documentation/media/image25.png)

See [*AddChartArrowUp()*](#addchartarrowup), [*AddChartArrowDown()*](#addchartarrowdown), [*AddChartDiamond()*](#addchartdiamond),[ *AddChartDot()*](#addchartdot), [*AddChartSquare()*](#addchartsquare), [*AddChartTriangleUp()*](#addcharttriangleup), [*AddChartTriangleDown()*](#addcharttriangledown).

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

```csharp
AddChartDot(string name, bool autoScale, int barsAgo, double y, Color color)
AddChartDot(string name, bool autoScale, DateTime time, double y, Color color)
```

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

A drawing object of the type IDot (interface)

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

|           |                                                                                         |
| --------- | --------------------------------------------------------------------------------------- |
| name      | A clearly identifiable name for the drawing object                                      |
| autoScale | Adjusts the scale of the y-axis so that drawing objects can be viewed in their entirety |
| barsAgo   | Defines the preceding bar on which the dot should be drawn (0 = current bar)            |
| time      | The date/time at which the dot should be drawn                                          |
| y         | y-value at which the dot should be drawn                                                |
| color     | Color of the drawing object                                                             |

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

```csharp
// Draws an orange dot for the current bar 5 ticks above the high
AddChartDot("MyDot-" + ProcessingBarIndex, true, 0, High[0] + 5*TickSize, Color.Orange);
```

### AddChartEllipse() <a href="#addchartellipse" id="addchartellipse"></a>

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

AddChartEllipse() draws an ellipse.

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

```csharp
AddChartEllipse(string name, int barsBackStart, double startY, int barsBackEnd, double endY, Color color)
AddChartEllipse(string name, bool autoScale, int barsBackStart, double startY, int barsBackEnd, double endY, Color color, Color areaColor, int areaOpacity)
AddChartEllipse(string name, bool autoScale, DateTime startTime, double startY, DateTime endTime, double endY, Color color, Color areaColor, int areaOpacity)
```

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

A drawing object of the type IEllipse (interface)

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

|               |                                                                                                               |
| ------------- | ------------------------------------------------------------------------------------------------------------- |
| name          | A clearly identifiable name for the drawing object                                                            |
| autoScale     | Adjusts the scale of the y-axis so that drawing objects can be viewed in their entirety                       |
| barsBackStart | Sets the preceding bar at which the ellipse should start                                                      |
| startTime     | Date/time at which the ellipse should start                                                                   |
| startY        | y-value for the start of the ellipse                                                                          |
| barsBackEnd   | Sets the preceding bar at which the ellipse should end (0 = current bar)                                      |
| endTime       | Date/time at which the ellipse should end                                                                     |
| endY          | y-value for the end of the ellipse                                                                            |
| color         | Border color of the drawing object                                                                            |
| areaColor     | Fill color of the drawing object                                                                              |
| areaOpacity   | Transparency of the fill color value between 0 and 255 (0 = completely transparent , 255 = completely opaque) |

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

```csharp
// Draws a yellow ellipse from the current bar to 5 bars ago
AddChartEllipse("MyEllipse-" + ProcessingBarIndex, true, 5, High[5], 0, Close[0], Color.Yellow, Color.Yellow, 1);
```

### AddChartExtendedLine() <a href="#addchartextendedline" id="addchartextendedline"></a>

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

AddChartExtendedLine() draws a line with an infinite end point.

See [*AddChartLine()*](#addchartline), [*AddChartHorizontalLine()*](#addcharthorizontalline),[ *AddChartVerticalLine()*](#addchartverticalline), [*AddChartRay()*](#addchartray).

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

```csharp
AddChartExtendedLine(string name, int barsBackStart, double startY, int barsBackEnd, double endY, Color color)
AddChartExtendedLine(string name, bool autoScale, int barsBackStart, double startY, int barsBackEnd, double endY, Color color, DashStyle dashStyle, int width)
AddChartExtendedLine(string name, bool autoScale, DateTime startTime, double startY, DateTime endTime, double endY, Color color, DashStyle dashStyle, int width)
```

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

A drawing object of the type IExtendedLine (interface)

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

|               |                                                                                                         |
| ------------- | ------------------------------------------------------------------------------------------------------- |
| name          | A clearly identifiable name for the drawing object                                                      |
| autoScale     | Adjusts the scale of the y-axis so that drawing objects can be viewed in their entirety                 |
| barsBackStart | Number of bars ago for the start point                                                                  |
| startTime     | Date/time for the start point                                                                           |
| startY        | y-value for the start point                                                                             |
| barsBackEnd   | Number of bars ago for the second point (a true end point does not exist; the line extends to infinity) |
| endTime       | Date/time for the end point                                                                             |
| endY          | y-value for the end point                                                                               |
| color         | Color of the drawing object                                                                             |
| dashStyle     | LevelLine styl :                                                                                        |
|               | DashStyle.Dash                                                                                          |
|               | DashStyle.DashDot                                                                                       |
|               | DashStyle.DashDotDot                                                                                    |
|               | DashStyle.Dot                                                                                           |
|               | DashStyle.Solid                                                                                         |
|               |                                                                                                         |
|               | You may have to integrate: using System.Drawing.Drawing2D;                                              |
| width         | LevelLine strength in points                                                                            |

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

```csharp
// Draws a line without an end point
AddChartExtendedLine("MyExt.LevelLine-" + ProcessingBarIndex, false, 10, Close[10], 0, Close[0], Color.Black, DashStyle.Solid, 1);
```

### AddChartFibonacciCircle() <a href="#addchartfibonaccicircle" id="addchartfibonaccicircle"></a>

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

AddChartFibonacciCircle() draws a Fibonacci circle.

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

```csharp
AddChartFibonacciCircle(string name, bool autoScale, int barsBackStart, double startY, int barsBackEnd, double endY)
AddChartFibonacciCircle(string name, bool autoScale, DateTime startTime, double startY, DateTime endTime, double endY)
```

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

A drawing object of the type IFibonacciCircle (interface)

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

|               |                                                                                         |
| ------------- | --------------------------------------------------------------------------------------- |
| name          | A clearly identifiable name for the drawing object                                      |
| autoScale     | Adjusts the scale of the y-axis so that drawing objects can be viewed in their entirety |
| barsBackStart | Defines the starting point in terms of bars ago                                         |
| startTime     | Date/time of the bar for the starting point                                             |
| startY        | y-value for the start of the Fibonacci circle                                           |
| barsBackEnd   | Defines the end point in terms of bars ago                                              |
| endTime       | Date/time for the end of the Fibonacci circle                                           |
| endY          | y-value for the end point of the Fibonacci circle                                       |

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

```csharp
//Draws a Fibonacci circle
AddChartFibonacciCircle("MyFibCircle-" + ProcessingBarIndex, true, 5, Low[5], 0, High[0]);
```

### AddChartFibonacciExtensions() <a href="#addchartfibonacciextensions" id="addchartfibonacciextensions"></a>

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

AddChartFibonacciExtensions() draws Fibonacci extensions.

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

```csharp
AddChartFibonacciExtensions(string name, bool autoScale, int start1BarsAgo, double start1Y, int start2BarsAgo, double start2Y, int start3BarsAgo, double start3Y)
AddChartFibonacciExtensions(string name, bool autoScale, DateTime start1Time, double start1Y, DateTime start2Time, double start2Y, DateTime start3Time, double start3Y)
```

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

A drawing object of the type IFibonacciExtensions (interface)

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

|               |                                                                                         |
| ------------- | --------------------------------------------------------------------------------------- |
| name          | A clearly identifiable name for the drawing object                                      |
| autoScale     | Adjusts the scale of the y-axis so that drawing objects can be viewed in their entirety |
| start1BarsAgo | Number of bars ago for start point 1                                                    |
| start1Time    | Date/time for start point 1                                                             |
| start1Y       | y-value for start point 1                                                               |
| start2BarsAgo | Number of bars ago for start point 2                                                    |
| start2Time    | Date/time for start point 2                                                             |
| start2Y       | y-value for the start point 2                                                           |
| start3BarsAgo | Number of bars ago for start point 3                                                    |
| start3Time    | Date/time for start point 3                                                             |
| start3Y       | y-value for start point 3                                                               |

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

```csharp
// Draws Fibonacci extensions
AddChartFibonacciExtensions("MyFibExt-" + ProcessingBarIndex, true, 4, Low[4], 3, High[3], 1, Low[1]);
```

### AddChartFibonacciProjections() <a href="#addchartfibonacciprojections" id="addchartfibonacciprojections"></a>

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

Draw Fibonacci Projections () sketches Fibonacci Projections.

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

```csharp
AddChartFibonacciProjections(string name, bool autoScale, DateTime start1Time, double start1Y,DateTime start2Time, double start2Y, DateTime start3Time, double start3Y)
```

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

A drawing object of the type IFibonacciProjections (Interface)

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

|            |                                                                                         |
| ---------- | --------------------------------------------------------------------------------------- |
| name       | A clearly identifiable name for the drawing object                                      |
| autoScale  | Adjusts the scale of the y-axis so that drawing objects can be viewed in their entirety |
| start1Time | Date/time for start point 1                                                             |
| start1Y    | y-value for start point 1                                                               |
| start2Time | Date/time for start point 2                                                             |
| start2Y    | y-value for the start point 2                                                           |
| start3Time | Date/time for start point 3                                                             |
| start3Y    | y-value for start point 3                                                               |

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

```csharp
// zeichnet FibonacciProjections
AddChartFibonacciProjections("MyFibPro-" + ProcessingBarIndex, true, Low[4], 3, High[3], 1, Low[1], 2);
```

### AddChartFibonacciRetracements() <a href="#addchartfibonacciretracements" id="addchartfibonacciretracements"></a>

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

AddChartFibonacciRetracements() draws Fibonacci retracements.

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

```csharp
AddChartFibonacciRetracements(string name, bool autoScale, int barsBackStart, double startY, int barsBackEnd, double endY)
AddChartFibonacciRetracements(string name, bool autoScale, DateTime startTime, double startY, DateTime endTime, double endY)
```

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

A drawing object of the type IFibonacciRetracements (interface)

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

|               |                                                                                         |
| ------------- | --------------------------------------------------------------------------------------- |
| name          | A clearly identifiable name for the drawing object                                      |
| autoScale     | Adjusts the scale of the y-axis so that drawing objects can be viewed in their entirety |
| barsBackStart | Defines how many bars ago the starting point of the Fibonacci retracement is located    |
| startTime     | Date/time of the bar at which the Fibonacci retracement should begin                    |
| startY        | y-value at which the Fibonacci retracement will begin                                   |
| barsBackEnd   | Defines how many bars ago the end point of the Fibonacci retracement is located         |
| endTime       | Date/time at which the Fibonacci retracement should end                                 |
| endY          | y-value at which the Fibonacci retracement should end                                   |

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

```csharp
// Draws Fibonnaci retracements
AddChartFibonacciRetracements("MyFibRet-" + ProcessingBarIndex, true, 10, Low[10], 0, High[0]);
```

### AddChartFibonacciTimeExtensions() <a href="#addchartfibonaccitimeextensions" id="addchartfibonaccitimeextensions"></a>

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

AddChartFibonacciTimeExtensions() draws Fibonacci time extensions.

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

```csharp
AddChartFibonacciTimeExtensions(string name, int barsBackStart, double startY, int barsBackEnd, double endY)
AddChartFibonacciTimeExtensions(string name, DateTime startTime, double startY, DateTime endTime, double endY)
```

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

A drawing object of the type IFibonacciTimeExtensions (interface)

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

|               |                                                       |
| ------------- | ----------------------------------------------------- |
| name          | A clearly identifiable name for the drawing object    |
| barsBackStart | Defines how many bars ago the extensions should start |
| startTime     | Date/time at which the extensions should start        |
| startY        | y-value at which the extensions should start          |
| barsBackEnd   | Defines how many bars ago the extensions should end   |
| endTime       | Date/time at which the extensions should end          |
| endY          | y-value at which the extensions should end            |

#### Example <a href="#example_13" id="example_13"></a>

```csharp
// Draws Fibonacci time extensions
AddChartFibonacciTimeExtensions("MyFibTimeExt-" + ProcessingBarIndex, 10, Low[10], 0, High[0]);
```

### AddChartGannFan() <a href="#addchartgannfan" id="addchartgannfan"></a>

#### Description <a href="#description_14" id="description_14"></a>

AddChartGannFan() draws a Gann fan.

#### Usage <a href="#usage_14" id="usage_14"></a>

```csharp
AddChartGannFan(string name, bool autoScale, int barsAgo, double y)
AddChartGannFan(string name, bool autoScale, DateTime time, double y)
```

#### Return Value <a href="#return-value_14" id="return-value_14"></a>

A drawing object of the type IGannFan (interface)

#### Parameter <a href="#parameter_14" id="parameter_14"></a>

|           |                                                                                         |
| --------- | --------------------------------------------------------------------------------------- |
| name      | A clearly identifiable name for the drawing object                                      |
| autoScale | Adjusts the scale of the y-axis so that drawing objects can be viewed in their entirety |
| barsAgo   | Sets the preceding bar on which the Gann fan should be drawn                            |
| time      | Date/time at which the Gann fan should start                                            |
| y         | y-value for the Gann fan                                                                |

#### Example <a href="#example_14" id="example_14"></a>

```csharp
// Shows a Gann fan at the low of the bar from 10 periods ago
AddChartGannFan("MyGannFan-" + ProcessingBarIndex, true, 10, Low[10]);
```

### AddChartHorizontalLine() <a href="#addcharthorizontalline" id="addcharthorizontalline"></a>

#### Description <a href="#description_15" id="description_15"></a>

AddChartHorizontalLine() draws a horizontal line in the chart.

See [*AddChartLine()*](#addchartline), [A*ddChartVerticalLine()*](#addchartverticalline),[ *AddChartVerticalLine()*](#addchartverticalline), [*AddChartRay()*](#addchartray).

#### Usage <a href="#usage_15" id="usage_15"></a>

```csharp
AddChartHorizontalLine(string name, double y, Color color)
AddChartHorizontalLine(string name, bool autoScale, double y, Color color, DashStyle dashStyle, int width)
```

#### Return Value <a href="#return-value_15" id="return-value_15"></a>

A drawing object of the type IHorizontalLine (interface)

#### Parameter <a href="#parameter_15" id="parameter_15"></a>

|           |                                                                                         |
| --------- | --------------------------------------------------------------------------------------- |
| name      | A clearly identifiable name for the drawing object                                      |
| autoScale | Adjusts the scale of the y-axis so that drawing objects can be viewed in their entirety |
| y         | Any double value of your choice                                                         |
| color     | LevelLine color                                                                         |
| dashStyle | LevelLine style:                                                                        |
|           | DashStyle.Dash                                                                          |
|           | DashStyle.DashDot                                                                       |
|           | DashStyle.DashDotDot                                                                    |
|           | DashStyle.Dot                                                                           |
|           | DashStyle.Solid                                                                         |
|           |                                                                                         |
|           | You may have to integrate: using System.Drawing.Drawing2D;                              |
| width     | LevelLine strength                                                                      |

#### Example <a href="#example_15" id="example_15"></a>

```csharp
// Draws a horizontal line at y=10
AddChartHorizontalLine("MyHorizontalLine-" + ProcessingBarIndex, 10, Color.Black);
```

### AddChartLine() <a href="#addchartline" id="addchartline"></a>

#### Description <a href="#description_16" id="description_16"></a>

AddChartLine() draws a (trend) line.

See [*AddChartLine()*](#addchartline), [A*ddChartVerticalLine()*](#addchartverticalline),[ *AddChartVerticalLine()*](#addchartverticalline), [*AddChartExtendedLine()*](#addchartextendedline), [*AddChartRay()*](#addchartray).

#### Usage <a href="#usage_16" id="usage_16"></a>

```csharp
AddChartLine(string name, int barsBackStart, double startY, int barsBackEnd, double endY, Color color)
AddChartLine(string name, bool autoScale, int barsBackStart, double startY, int barsBackEnd, double endY, Color color, DashStyle dashStyle, int width)
AddChartLine(string name, bool autoScale, DateTime startTime, double startY, DateTime endTime, double endY, Color color, DashStyle dashStyle, int width)
```

#### Return Value <a href="#return-value_16" id="return-value_16"></a>

A drawing object of the type ITrendLine (interface).

#### Parameter <a href="#parameter_16" id="parameter_16"></a>

|               |                                                                                         |
| ------------- | --------------------------------------------------------------------------------------- |
| name          | A clearly identifiable name for the drawing object                                      |
| autoScale     | Adjusts the scale of the y-axis so that drawing objects can be viewed in their entirety |
| barsBackStart | Number of bars ago for the starting point                                               |
| startTime     | Date/time for the starting point                                                        |
| startY        | y-value for the starting point                                                          |
| barsBackEnd   | Number of bars ago for the end point                                                    |
| endTime       | Date/time for the end point                                                             |
| endY          | y-value for the end point                                                               |
| color         | Color of the drawing object                                                             |
| dashStyle     | LevelLine style:                                                                        |
|               | DashStyle.Dash                                                                          |
|               | DashStyle.DashDot                                                                       |
|               | DashStyle.DashDotDot                                                                    |
|               | DashStyle.Dot                                                                           |
|               | DashStyle.Solid                                                                         |
|               |                                                                                         |
|               | You may have to integrate: using System.Drawing.Drawing2D;                              |
| width         | LevelLine strength in points                                                            |

#### Example <a href="#example_16" id="example_16"></a>

```csharp
// Draws a line
AddChartLine("MyLine-" + ProcessingBarIndex, false, 10, Close[10], 0, Close[0], Color.Black, DashStyle.Solid, 1);
```

### AddChartRay() <a href="#addchartray" id="addchartray"></a>

#### Description <a href="#description_17" id="description_17"></a>

AddChartRay() draws a (trend) line and extends it to infinity.

See [*AddChartLine()*](#addchartline), [*AddChartHorizontalLine()*](#addcharthorizontalline),[ *AddChartVerticalLine()*](#addchartverticalline), [*AddChartExtendedLine()*](#addchartextendedline), [*AddChartRay()*](#addchartray).

#### Usage <a href="#usage_17" id="usage_17"></a>

```csharp
AddChartRay(string name, int start1BarsAgo, double start1Y, int start2BarsAgo, double start2Y, Color color)
AddChartRay(string name, bool autoScale, int start1BarsAgo, double start1Y, int start2BarsAgo, double start2Y, Color color, DashStyle dashStyle, int width)
AddChartRay(string name, bool autoScale, DateTime start1Time, double start1Y, DateTime start2Time, double start2Y, Color color, DashStyle dashStyle, int width)
```

#### Return Value <a href="#return-value_17" id="return-value_17"></a>

A drawing object of the type IRay (interface)

#### Parameter <a href="#parameter_17" id="parameter_17"></a>

|               |                                                                                         |
| ------------- | --------------------------------------------------------------------------------------- |
| name          | A clearly identifiable name for the drawing object                                      |
| autoScale     | Adjusts the scale of the y-axis so that drawing objects can be viewed in their entirety |
| start1BarsAgo | Number of bars ago for start point 1                                                    |
| start1Time    | Date/time for anstartchor point 1                                                       |
| start1Y       | y-value for start point 1                                                               |
| start2BarsAgo | Number of bars ago for start point 2                                                    |
| start2Time    | Date/time for start point 2                                                             |
| start2Y       | y-value for start point 2                                                               |
| color         | Color of the drawing object                                                             |
| dashStyle     | LevelLine style                                                                         |
|               | DashStyle.Dash                                                                          |
|               | DashStyle.DashDot                                                                       |
|               | DashStyle.DashDotDot                                                                    |
|               | DashStyle.Dot                                                                           |
|               | DashStyle.Solid                                                                         |
|               |                                                                                         |
|               | You may have to integrate: using System.Drawing.Drawing2D;                              |
| width         | LevelLine strength                                                                      |

#### Example <a href="#example_17" id="example_17"></a>

```csharp
// Draws a line from the bar from 10 periods ago to the current bar (x-axis)
// --> line is extended to the right
// from y=3 to y=7
AddChartRay("MyRay-" + ProcessingBarIndex, 10, 3, 0, 7, Color.Green);
// Draws a line from the current bar to the bar from 10 periods ago
// --> line is extended to the left
// from y=3 to y=7
AddChartRay("MyRay-" + ProcessingBarIndex, 0, 3, 10, 7, Color.Green);
```

### AddChartRectangle() <a href="#addchartrectangle" id="addchartrectangle"></a>

#### Description <a href="#description_18" id="description_18"></a>

AddChartRectangle() draws a rectangle.

#### Usage <a href="#usage_18" id="usage_18"></a>

```csharp
AddChartRectangle(string name, int barsBackStart, double startY, int barsBackEnd, double endY, Color color)
AddChartRectangle(string name, bool autoScale, int barsBackStart, double startY, int barsBackEnd, double endY, Color color, Color areaColor, int areaOpacity)
AddChartRectangle(string name, bool autoScale, DateTime startTime, double startY, DateTime endTime, double endY, Color color, Color areaColor, int areaOpacity)
```

#### Return Value <a href="#return-value_18" id="return-value_18"></a>

A drawing object of the type IRectangle (interface)

#### Parameter <a href="#parameter_18" id="parameter_18"></a>

|               |                                                                                                               |
| ------------- | ------------------------------------------------------------------------------------------------------------- |
| name          | A clearly identifiable name for the drawing object                                                            |
| autoScale     | Adjusts the scale of the y-axis so that drawing objects can be viewed in their entirety                       |
| barsBackStart | Sets the preceding bar at which the one corner of the rectangle should be located (0 = current bar)           |
| startTime     | Date/time at which the start of the one rectangle corner should be located                                    |
| startY        | y-value at which the one corner of the rectangle should be located                                            |
| barsBackEnd   | Sets the preceding bar at which the second corner of the rectangle should be located (0 = current bar)        |
| endTime       | Date/time of the second rectangle corner                                                                      |
| endY          | y-value of the second rectangle corner                                                                        |
| color         | Color of the drawing object                                                                                   |
| areaColor     | Fill color of the drawing object                                                                              |
| areaOpacity   | Transparency of the fill color. Value between 0 and 255 (0 = completely transparent, 255 = completely opaque) |

#### Example <a href="#example_18" id="example_18"></a>

```csharp
// Draws a green rectangle from the low of 10 periods ago to the high of 5 periods ago
// with a fill color of pale green and a transparency of 2
AddChartRectangle("MyRect-" + ProcessingBarIndex, true, 10, Low[10], 5, High[5], Color.PaleGreen, Color.PaleGreen, 2);
```

### AddChartRegion() <a href="#addchartregion" id="addchartregion"></a>

#### Description <a href="#description_19" id="description_19"></a>

AddChartRegion() fills a specific area on a chart.

#### Usage <a href="#usage_19" id="usage_19"></a>

```csharp
AddChartRegion(string name, int barsBackStart, int barsBackEnd, IDataSeries series, double y, Color outlineColor, Color areaColor, int areaOpacity)
AddChartRegion(string name, int barsBackStart, int barsBackEnd, IDataSeries series1, IDataSeries series2, Color outlineColor, Color areaColor, int areaOpacity)
AddChartRegion(string name, DateTime startTime, DateTime endTime, IDataSeries series, double y, Color outlineColor, Color areaColor, int areaOpacity)
AddChartRegion(string name, DateTime startTime, DateTime endTime, IDataSeries series1, IDataSeries series2, Color outlineColor, Color areaColor, int areaOpacity)
```

#### Return Value <a href="#return-value_19" id="return-value_19"></a>

A drawing object of the type IRegion (interface)

#### Parameter <a href="#parameter_19" id="parameter_19"></a>

|                  |                                                                                                                                                            |
| ---------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- |
| name             | A clearly identifiable name for the drawing object                                                                                                         |
| barsBackStart    | Sets the preceding bar at which the drawing should begin (0 = current bar)                                                                                 |
| startTime        | Start time for the drawing                                                                                                                                 |
| barsBackEnd      | Sets the preceding bar at which the drawing should end (0 = current bar)                                                                                   |
| endTime          | End time for the drawing                                                                                                                                   |
| series1, series2 | Every data series, for example an indicator, close, high, low and so on. The respective value of the data series for the current bar is used as a y-value. |
| y                | Any double value                                                                                                                                           |
| outlineColor     | Color for the border                                                                                                                                       |
| areaColor        | Fill color for the area                                                                                                                                    |
| areaOpacity      | Transparency of the fill color. Value between 0 and 255 (0 = completely transparent, 255 = completely opaque)                                              |

#### Example <a href="#example_19" id="example_19"></a>

```csharp
// Fills the area between the upper and lower Bollinger Bands
AddChartRegion("MyRegion-" + ProcessingBarIndex, ProcessingBarIndex, 0, Bollinger(2, 14).Upper, Bollinger(2, 14).Lower, Color.Empty, Color.Lime, 100);
```

### AddChartRegressionChannel() <a href="#addchartregressionchannel" id="addchartregressionchannel"></a>

#### Description <a href="#description_20" id="description_20"></a>

AddChartRegressionChannel() draws a regression channel.

#### Usage <a href="#usage_20" id="usage_20"></a>

```csharp
AddChartRegressionChannel(string name, int barsBackStart, int barsBackEnd, Color color)
AddChartRegressionChannel(string name, bool autoScale, int barsBackStart, int barsBackEnd, Color upperColor, DashStyle upperDashStyle, int upperWidth, Color middleColor, DashStyle middleDashStyle, int middleWidth, Color lowerColor, DashStyle lowerDashStyle, int lowerWidth)
AddChartRegressionChannel(string name, bool autoScale, DateTime startTime, DateTime endTime, Color upperColor, DashStyle upperDashStyle, int upperWidth, Color middleColor, DashStyle middleDashStyle, int middleWidth, Color lowerColor, DashStyle lowerDashStyle, int lowerWidth)
```

#### Return Value <a href="#return-value_20" id="return-value_20"></a>

A drawing object of the type IRegressionChannel (interface)

#### Parameter <a href="#parameter_20" id="parameter_20"></a>

|                                                 |                                                                                         |
| ----------------------------------------------- | --------------------------------------------------------------------------------------- |
| name                                            | A clearly identifiable name for the drawing object                                      |
| autoScale                                       | Adjusts the scale of the y-axis so that drawing objects can be viewed in their entirety |
| barsBackStart                                   | Sets the preceding bar at which the regression channel should start (0 = current bar)   |
| startTime                                       | Start time for the regression channel                                                   |
| barsBackEnd                                     | Sets the preceding bar at which the regression channel should end (0 = current bar)     |
| endTime                                         | End time for the regression channel                                                     |
| color                                           | Color of the drawing object                                                             |
| upperDashStyle, middleDashStyle, lowerDashStyle | LevelLine style:                                                                        |
|                                                 | DashStyle.Dash                                                                          |
|                                                 | DashStyle.DashDot                                                                       |
|                                                 | DashStyle.DashDotDot                                                                    |
|                                                 | DashStyle.Dot                                                                           |
|                                                 | DashStyle.Solid                                                                         |
|                                                 |                                                                                         |
|                                                 | You may have to integrate: using System.Drawing.Drawing2D;                              |
| upperColor, middleColor, lowerColor             | LevelLine color                                                                         |
|                                                 |                                                                                         |
| upperWidth, middleWidth, lowerWidth             | LevelLine strength                                                                      |
|                                                 |                                                                                         |

#### Example <a href="#example_20" id="example_20"></a>

```csharp
// Draws a regression channel from the low of the bar from 10 days ago to the high of the bar from 5 days ago.
AddChartRegressionChannel("MyRegChannel-" + ProcessingBarIndex, 10, 0, Color.Black);
```

### AddChartSquare() <a href="#addchartsquare" id="addchartsquare"></a>

#### Description <a href="#description_21" id="description_21"></a>

AddChartSquare() draws a square:

![AddChartSquare()](https://agenatrader.github.io/AgenaScript-documentation/media/image26.png)

See [*AddChartArrowUp()*](#addchartarrowup), [*AddChartArrowDown()*](#addchartarrowdown), [*AddChartDiamond()*](#addchartdiamond),[ *AddChartDot()*](#addchartdot), [*AddChartSquare()*](#addchartsquare), [*AddChartTriangleUp()*](#addcharttriangleup), [*AddChartTriangleDown()*](#addcharttriangledown).

#### Usage <a href="#usage_21" id="usage_21"></a>

```csharp
DrawSqare(string name, bool autoScale, int barsAgo, double y, Color color)
DrawSqare(string name, bool autoScale, DateTime time, double y, Color color)
```

#### Return Value <a href="#return-value_21" id="return-value_21"></a>

A drawing object of the type ISquare (interface)

#### Parameter <a href="#parameter_21" id="parameter_21"></a>

|           |                                                                                         |
| --------- | --------------------------------------------------------------------------------------- |
| name      | A clearly identifiable name for the drawing object                                      |
| autoScale | Adjusts the scale of the y-axis so that drawing objects can be viewed in their entirety |
| barsAgo   | Sets the preceding bar at which the square should be drawn (0 = current bar)            |
| Time      | Date/time of the bar at which the square should be drawn                                |
| Y         | y-value for the square                                                                  |
| color     | Color of the drawing object                                                             |

#### Example <a href="#example_21" id="example_21"></a>

```csharp
// Draws a dark red square at the current bar 10 ticks above the high
AddChartSquare("MySquare-" + ProcessingBarIndex, true, 0, High[0] + 10*TickSize, Color.DarkRed);
```

### AddChartText() <a href="#addcharttext" id="addcharttext"></a>

#### Description <a href="#description_22" id="description_22"></a>

AddChartText() writes whatever text you want onto the chart using price and datetime coordinates.

See [*AddChartTextFixed()*.](#addcharttextfixed)

#### Usage <a href="#usage_22" id="usage_22"></a>

```csharp
AddChartText(string tag, string text, int barsAgo, double y, Color color);
AddChartText(string tag, string text, TextPosition textPosition, Color textColor, Font font, Color outlineColor, Color areaColor, int areaOpacity);
AddChartText(string tag, string text, int barsAgo, double y, Color textColor, Font font, StringAlignment alignment, Color outlineColor, Color areaColor, int areaOpacity);
AddChartText(string tag, bool autoScale, string text, int barsAgo, double y, int yPixelOffset, Color textColor, Font font, StringAlignment alignment, Color outlineColor, Color areaColor, int areaOpacity);
AddChartText(string tag, bool autoScale, string text, DateTime x, double y, int yPixelOffset, Color textColor, Font font, StringAlignment alignment, Color outlineColor, Color areaColor, int areaOpacity);
AddChartText(string tag, bool autoScale, string text, DateTime x, double y, int pixelOffset, Color textColor, Font font, StringAlignment alignment, HorizontalAlignment hAlign, VerticalAlignment vAlign, Color outlineColor, Color areaColor);
AddChartText(string tag, bool autoScale, string text, int barsAgo, double y, int yPixelOffset, Color textColor, Font font, StringAlignment alignment, HorizontalAlignment hAlign, VerticalAlignment vAlign, Color outlineColor, Color areaColor, int areaOpacity);
AddChartText(string tag, bool autoScale, string text, DateTime x, double y, int pixelOffset, Color textColor, Font font, StringAlignment alignment, HorizontalAlignment hAlign, VerticalAlignment vAlign, Color outlineColor, Color areaColor);   
```

**Important note:** When using signatures that contain horizontal alignment and vertical alignment, you need to add the following lines:

```csharp
using System.Windows.Forms;
using System.Windows.Forms.VisualStyles;
```

#### Return Value <a href="#return-value_22" id="return-value_22"></a>

A drawing object of the type IText (interface)

#### Parameter <a href="#parameter_22" id="parameter_22"></a>

|              |                                                                                                               |
| ------------ | ------------------------------------------------------------------------------------------------------------- |
| name         | A clearly identifiable name for the drawing object                                                            |
| autoScale    | Adjusts the scale of the y-axis so that drawing objects can be viewed in their entirety                       |
| Text         | Text to be displayed (may contain escape sequences)                                                           |
| barsAgo      | Sets how many bars ago the text should be displayed                                                           |
| Time         | Date/time of the bar at which the text should begin                                                           |
| Y            | y-value at which the text should be written                                                                   |
| yPixelOffset | Vertical offset of the text; positive numbers move it up, and negative numbers move it down                   |
| textColor    | Text color                                                                                                    |
| Font         | Font                                                                                                          |
| Alignment    | Possible values are: StringAlignment.Center, StringAlignment.Far, StringAlignment.Near                        |
| HAlign       | Possible values are: HorizontalAlign.Left, HorizontalAlign.Center, HorizontalAlign.Right                      |
| VAlign       | Possible values are: VerticalAlign.Top, VerticalAlign.Center, VerticalAlign.Bottom                            |
| outlineColor | Border color around the text (for no border, select Color.Empty)                                              |
| areaColor    | Fill color for the text box                                                                                   |
| areaOpacity  | Transparency of the fill color. Value between 0 and 255 (0 = completely transparent, 255 = completely opaque) |

#### Example <a href="#example_22" id="example_22"></a>

```csharp
// writes text at y=3.0
AddChartText("MyText-" + ProcessingBarIndex, "This is sample text.", 10, 3, Color.Black);
// writes red text in the font Arial 7
AddChartText("MyText-" + ProcessingBarIndex, false, "This is sample text.", Time[0], Close[0]+50*TickSize, 0,
Color.Red, new Font("Arial",7), StringAlignment.Center, Color.Blue, Color.DarkOliveGreen, 10);
```

This leads to the following result:

![AddChartText()](https://agenatrader.github.io/AgenaScript-documentation/media/image27.png)

```csharp
AddChartText("MyTag-" + ProcessingBarIndex,true,"Text",1,
// barsAgo
High[1], // y
10, // yPixelOffset
Color.Blue, // Text color
new Font("Arial", 10, FontStyle.Bold),
StringAlignment.Center,
HorizontalAlignment.Center,
VerticalAlignment.Bottom,
Color.Red, // Outline color
Color.Yellow, // Fill color
100); // Opacity
```

### AddChartTextFixed() <a href="#addcharttextfixed" id="addcharttextfixed"></a>

#### Description <a href="#description_23" id="description_23"></a>

AddChartTextFixed() writes text into one of 5 predetermined locations on the chart.

See [*AddChartText()*](#addcharttext).

#### Usage <a href="#usage_23" id="usage_23"></a>

```csharp
AddChartTextFixed(string tag, string text, TextPosition textPosition);
AddChartTextFixed(string tag, string text, TextPosition textPosition, Color textColor, Font font, Color outlineColor, Color areaColor);
AddChartTextFixed(string tag, string text, TextPosition textPosition, Color textColor, Font font, Color outlineColor, Color areaColor, int areaOpacity);
```

#### Return Value <a href="#return-value_23" id="return-value_23"></a>

A drawing object of the type ITextFixed (interface)

#### Parameter <a href="#parameter_23" id="parameter_23"></a>

|              |                                                                                                                     |
| ------------ | ------------------------------------------------------------------------------------------------------------------- |
| name         | A clearly identifiable name for the drawing object                                                                  |
| text         | The text to be displayed                                                                                            |
| TextPosition | TextPosition.BottomLeft, TextPosition.BottomRight, TextPosition.Center, TextPosition.TopLeft, TextPosition.TopRight |
| textColor    | Text color                                                                                                          |
| font         | Font                                                                                                                |
| outlineColor | Color for the border around the text. For no border color, use Color.Empty                                          |
| areaColor    | Fill color of the text box. For no fill color, use Color.Empty                                                      |
| areaOpacity  | Transparency of the fill color. Value between 0 and 255 (0 = completely transparent, 255 = completely opaque)       |

#### Example <a href="#example_23" id="example_23"></a>

```csharp
// Writes text into the middle of the chart
AddChartTextFixed("MyText", "This is sample text.", TextPosition.Center);
// Writes red text with a blue border into the middle of the chart
AddChartTextFixed("MyText", "This is sample text.", TextPosition.Center, Color.Red, new Font("Arial",35), Color.Blue, Color.Empty, 10);
```

### AddChartTrendChannel() <a href="#addcharttrendchannel" id="addcharttrendchannel"></a>

#### Description <a href="#description_24" id="description_24"></a>

AddChartTrendChannel() draws a trend channel.

#### Usage <a href="#usage_24" id="usage_24"></a>

```csharp
AddChartTrendChannel(string name, bool autoScale, int start1BarsAgo, double start1Y, int start2BarsAgo, double start2Y, int start3BarsAgo, double start3Y)
AddChartTrendChannel(string name, bool autoScale, DateTime start1Time, double start1Y, DateTime start2Time, double start2Y, DateTime start3Time, double start3Y)
```

#### Return Value <a href="#return-value_24" id="return-value_24"></a>

A drawing object of the type ITrendChannel (interface)

#### Parameter <a href="#parameter_24" id="parameter_24"></a>

|               |                                                                                         |
| ------------- | --------------------------------------------------------------------------------------- |
| name          | A clearly identifiable name for the drawing object                                      |
| autoScale     | Adjusts the scale of the y-axis so that drawing objects can be viewed in their entirety |
| start1BarsAgo | Number of bars ago for start point 1 (x-axis)                                           |
| start1Time    | Date/time for start point 1 (x-axis)                                                    |
| start1Y       | y-value for start point 1                                                               |
| start2BarsAgo | Number of bars ago for start point 2 (x-axis)                                           |
| start2Time    | Date/time for start point 2 (x-axis)                                                    |
| start2Y       | y-value for start point 2                                                               |
| start3BarsAgo | Number of bars ago for start point 3 (x-axis)                                           |
| start3Time    | Date/time for start point 3 (x-axis)                                                    |
| start3Y       | y-value for start point 3                                                               |

#### Example <a href="#example_24" id="example_24"></a>

```csharp
// Draws a trend channel
AddChartTrendChannel("MyTrendChannel-" + ProcessingBarIndex, true, 10, Low[10], 0, High[0], 10, High[10] + 5 * TickSize);
```

### AddChartTriangle() <a href="#addcharttriangle" id="addcharttriangle"></a>

#### Description <a href="#description_25" id="description_25"></a>

AddChartTriangle() draws a triangle.

#### Usage <a href="#usage_25" id="usage_25"></a>

```csharp
AddChartTriangle(string name, int start1BarsAgo, double start1Y, int start2BarsAgo, double start2Y, int start3BarsAgo, double start3Y, Color color)
AddChartTriangle(string name, bool autoScale, int start1BarsAgo, double start1Y, int start2BarsAgo, double start2Y, int start3BarsAgo, double start3Y, Color color, Color areaColor, int areaOpacity)
AddChartTriangle(string name, bool autoScale, DateTime start1Time, double start1Y, DateTime start2Time, double start2Y, DateTime start3Time, double start3Y, Color color, Color areaColor, int areaOpacity)
```

#### Return Value <a href="#return-value_25" id="return-value_25"></a>

A drawing object of the type ITriangle (interface)

#### Parameter <a href="#parameter_25" id="parameter_25"></a>

|               |                                                                                                               |
| ------------- | ------------------------------------------------------------------------------------------------------------- |
| name          | A clearly identifiable name for the drawing object                                                            |
| autoScale     | Adjusts the scale of the y-axis so that drawing objects can be viewed in their entirety                       |
| start1BarsAgo | Number of bars ago for start point 1 (x-axis)                                                                 |
| start1Time    | Date/time for start point 1 (x-axis)                                                                          |
| start1Y       | y-value for start point 1                                                                                     |
| start2BarsAgo | Number of bars ago for start point 2 (x-axis)                                                                 |
| start2Time    | Date/time for start point 2 (x-axis)                                                                          |
| start2Y       | y-value for start point 2                                                                                     |
| start3BarsAgo | Number of bars ago for start point 3 (x-axis)                                                                 |
| start3Time    | Date/time for start point 3 (x-axis)                                                                          |
| start3Y       | y-value for start point 3                                                                                     |
| color         | Color of the drawing object                                                                                   |
| areaColor     | Fill color of the drawing object                                                                              |
| areaOpacity   | Transparency of the fill color. Value between 0 and 255 (0 = completely transparent, 255 = completely opaque) |

#### Example <a href="#example_25" id="example_25"></a>

```csharp
// Draws a green triangle
AddChartTriangle("tag1-" + ProcessingBarIndex, 4, Low[4], 3, High[3], 1, Low[1], Color.Green);
```

### AddChartTriangleDown() <a href="#addcharttriangledown" id="addcharttriangledown"></a>

#### Description <a href="#description_26" id="description_26"></a>

AddChartTriangleDown() draws a small downwards-pointing triangle:

![AddChartTriangleDown()](https://agenatrader.github.io/AgenaScript-documentation/media/image29.png)

See [*AddChartArrowUp()*](#addchartarrowup), [*AddChartArrowDown()*](#addchartarrowdown), [*AddChartDiamond()*](#addchartdiamond),[ *AddChartDot()*](#addchartdot), [*AddChartSquare()*](#addchartsquare), [*AddChartTriangleUp()*](#addcharttriangleup), [*AddChartTriangleU*p()](#addcharttriangleup).

#### Usage <a href="#usage_26" id="usage_26"></a>

```csharp
AddChartTriangleDown(string name, bool autoScale, int barsAgo, double y, Color color)
AddChartTriangleDown(string name, bool autoScale, DateTime time, double y, Color color)
```

#### Return Value <a href="#return-value_26" id="return-value_26"></a>

A drawing object of the type ITriangleDown (interface)

#### Parameter <a href="#parameter_26" id="parameter_26"></a>

|           |                                                                                         |
| --------- | --------------------------------------------------------------------------------------- |
| name      | A clearly identifiable name for the drawing object                                      |
| autoScale | Adjusts the scale of the y-axis so that drawing objects can be viewed in their entirety |
| barsAgo   | Sets how many bars ago the triangle should be drawn                                     |
| time      | Date/time for the bar at which the triangle should be drawn                             |
| Y         | y-value at which the triangle should be drawn                                           |
| color     | Color of the drawing object                                                             |

#### Example <a href="#example_26" id="example_26"></a>

```csharp
// Draws a small red triangle at the current bar 10 ticks above the high
AddChartTriangleDown("MyTriangleDown-" + ProcessingBarIndex, true, 0, High[0] + 10*TickSize, Color.Red);
```

### AddChartTriangleUp() <a href="#addcharttriangleup" id="addcharttriangleup"></a>

#### Description <a href="#description_27" id="description_27"></a>

AddChartTriangleUp() draws a small upwards-pointing triangle:

![AddChartTriangleUp()](https://agenatrader.github.io/AgenaScript-documentation/media/image28.png)

See [*AddChartArrowUp()*](#addchartarrowup), [*AddChartArrowDown()*](#addchartarrowdown), [*AddChartDiamond()*](#addchartdiamond),[ *AddChartDot()*](#addchartdot), [*AddChartSquare()*](#addchartsquare), [*AddChartTriangleUp()*](#addcharttriangleup), [*AddChartTriangleDown()*](#addcharttriangledown).

#### Usage <a href="#usage_27" id="usage_27"></a>

```csharp
AddChartTriangleUp(string name, bool autoScale, int barsAgo, double y, Color color)
AddChartTriangleUp(string name, bool autoScale, DateTime time, double y, Color color)
```

#### Return Value <a href="#return-value_27" id="return-value_27"></a>

A drawing object of the type ITriangleUp (interface)

#### Parameter <a href="#parameter_27" id="parameter_27"></a>

|           |                                                                                         |
| --------- | --------------------------------------------------------------------------------------- |
| name      | A clearly identifiable name for the drawing object                                      |
| autoScale | Adjusts the scale of the y-axis so that drawing objects can be viewed in their entirety |
| barsAgo   | Sets how many bars ago the triangle should be drawn                                     |
| time      | Date/time for the bar at which the triangle should be drawn                             |
| y         | y-value at which the triangle should be drawn                                           |
| color     | Color of the drawing object                                                             |

#### Example <a href="#example_27" id="example_27"></a>

```csharp
// Draws a small light green triangle at the current bar 10 ticks below the low
AddChartTriangleUp("MyTriangleUp-" + ProcessingBarIndex, true, 0, Low[0] - 10*TickSize, Color.LightGreen);
```

### AddChartVerticalLine() <a href="#addchartverticalline" id="addchartverticalline"></a>

#### Description <a href="#description_28" id="description_28"></a>

AddChartVerticalLine() draws a vertical line in the chart.

See [*AddChartLine()*](#addchartline), [*AddChartHorizontalLine()*](#addcharthorizontalline), [*AddChartExtendedLine()*](#addchartextendedline),[ *AddChartRay()*](#addchartray).

#### Usage <a href="#usage_28" id="usage_28"></a>

```csharp
AddChartVerticalLine(string name, int barsAgo, Color color)
AddChartVerticalLine(string name, int barsAgo, Color color, DashStyle dashStyle, int width)
AddChartVerticalLine(string name, DateTime time, Color color, DashStyle dashStyle, int width)
```

#### Return Value <a href="#return-value_28" id="return-value_28"></a>

A drawing object of the type IVerticalLine (interface)

#### Parameter <a href="#parameter_28" id="parameter_28"></a>

|           |                                                                            |
| --------- | -------------------------------------------------------------------------- |
| name      | A clearly identifiable name for the drawing object                         |
| barsAgo   | Sets how many bars ago the vertical line should be drawn (0 = current bar) |
| time      | Date/time of the bar at which the vertical line should be drawn            |
| color     | LevelLine color                                                            |
| dashStyle | LevelLine style                                                            |
|           | DashStyle.Dash                                                             |
|           | DashStyle.DashDot                                                          |
|           | DashStyle.DashDotDot                                                       |
|           | DashStyle.Dot                                                              |
|           | DashStyle.Solid                                                            |
| width     | LevelLine strength                                                         |

#### Example <a href="#example_28" id="example_28"></a>

```csharp
// Draws a vertical line at the bar from 10 periods ago
AddChartVerticalLine("MyVerticalLine-" + ProcessingBarIndex, 10, Color.Black);
```


# TradersYard Social Trading

### **GetSharingSourceForTY(Action\<IEnumerable\<ISocialChannel>, Exception> callback)**

**Description**

This method is used to get the user TraderYard groups list where post can be shared. Can be used in OnInit() and OnCalculate()

**Usage**

```csharp
GetSharingSourceForTY(Action<IEnumerable<ISocialChannel>, Exception> callback);
```

**Parameter**

callback - method which will be called when will get a list of the user group in ISocialChannel and if some error will\
arise Exception will contain an explanation.

**Return Value**\
none

**Example**

```csharp
protected override void OnInit()
{
  GetSharingSourceForTY(GetChenalDes);
}

private void GetChenalDes(IEnumerable<ISocialChannel> channels, Exception exception)
{  
  if (exception == null)
  {
    foreach (var channel in channels)
      if (channel.DisplayName.Equals("My Account"))
        Log(string.Format("You can share post to {0}", channel.DisplayName),InfoLogLevel.Info);
  }
  else
  {
    Log(string.Format("You cant get TY channels list because: {0}", exception.Message), InfoLogLevel.Alert);
  }  
}
```

&#x20;

### **GetPost()**

**Description**

This method is used to get post from the current chart. Which will contain a chart image and message with instrument and timeframe.

**Usage**

```csharp
Chart.GetPost();
```

**Parameter**

none

**Return Value**\
SocialNetworkPost - post from the current chart which will contain chart image and message with instrument and timeframe.

**Example**

```csharp
protected override void OnCalculate()
{
  var post = Chart?.GetPost();
}
```

&#x20;

### **GetChartPostWithAnalytics**

**Description**

This method is used to get post from the current chart with drawings. Which will contain a chart image(with displayed drawings) and a message with instrument and timeframe. This method also can throw “TradersYardException“ exceptions when chart doesn't have a drawing.

**Usage**

```csharp
Chart.GetChartPostWithAnalytics();
```

**Parameter**

none

**Return Value**\
SocialNetworkPost - post from the current chart which will contain chart image with drawings and message with instrument and timeframe.

**Example**

```csharp
protected override void OnCalculate()
{
  var post = Chart?.GetChartPostWithAnalytics();
}
```

&#x20;

### **GetChartPostWithOrdersSetup**

**Description**

This method is used to get post from the current chart with orders. Which will contain a chart image(include orders) and message with instrument and timeframe. This method also can throw “KeyNotFoundException“ exceptions when the chart doesn't have an open order.

**Usage**

```csharp
Chart.GetChartPostWithOrdersSetup();
```

**Parameter**

none

**Return Value**\
SocialNetworkPost - post from the current chart which will contain chart image with orders and message with instrument and timeframe.

**Example**

```csharp
protected override void OnCalculate()
{
  var post = Chart?.GetChartPostWithOrdersSetup();
}
```

&#x20;

### **GetChartPostWithAtPlusPlusSetupTool**

**Description**

This method is used to get post from the current chart with drawings. Which will contain a chart image(with displayed orders), a message with instrument and timeframe, and AT Analysis as attached file. This method also can throw “KeyNotFoundException“ exceptions when the chart doesn't have an open order or “TradingAtPlusPlusSetupSharedContent“ when ATpp not running currently.

**Usage**

```csharp
Chart.GetChartPostWithAtPlusPlusSetupTool();
```

**Parameter**

none

**Return Value**\
SocialNetworkPost - post from the current chart which will contain chart image with orders and message with instrument and timeframe.

**Example**

```csharp
protected override void OnCalculate()
{
  var post = Chart?.GetChartPostWithAtPlusPlusSetupTool();
}
```

&#x20;

### **SharePostToTY(SocialNetworkPost post, ISocialChannel source)**

**Description**

This method uses for sharing posts to TradersYard. For this method, there is a restriction that it can be performed no more than once every 0.5s. Otherwise, the OverflowException will be throw.

**Usage**

```csharp
SharePostToTY(post, source);
```

**Parameter**

post - a post to be published in TradersYard. One of the fields ImageFunc, Message, Document mast is set it is also possible to set all fields.

source - a group where post will be created. Can be empty if the field Channels of the post are set.

**Return Value**\
none

**Example**

```csharp
private bool _messageNotSend = true;
private ISocialChannel chanelToShare;

protected override void OnInit()
{
  GetShearingSourceForTY(GetChenalDes);
}

protected override void OnCalculate()
{
  if (_messageNotSend && chanelToShare != null)
  {
    var post = Chart.GetChartPostWithAnalytics();
    SharePostToTY(post, chanelToShare);
    _messageNotSend = false;
  }
}

private void GetChenalDes(IEnumerable<ISocialChannel> channels, Exception exception)
{
  if (exception == null)
  {
    foreach (var channel in channels)
      if (channel.DisplayName.Equals("My Account"))
        chanelToShare = channel;
  }
  else
  {
    Log(string.Format("You cant get TY channels list because: {0}", exception.Message), InfoLogLevel.Alert);
  }
}
```


# Hints & Advice

## Hints & Advice <a href="#hints-advice" id="hints-advice"></a>

**Note:** Code changes made in self-scripted indicators are automatically applied to conditions in which this indicators are used if the changes were made in the "body" of e.g. "OnCalculate/OnBarUpdate. Changes of parameters, outputs series, etc. require a manual edit of the conditions.

### Bar Numbering Within the Chart <a href="#bar-numbering-within-the-chart" id="bar-numbering-within-the-chart"></a>

The following example demonstrates the usage of the plot method and the properties of the [*Chart*](/keywords#chart) object.

![Bar Numbering Within the Chart](https://agenatrader.github.io/AgenaScript-documentation/media/image30.png)

**Note:** For demonstration purposes, each time Paint is called up within the "Bar Numbering" section, "New" and "Dispose" will also be called up multiple times. From a performance point of view, this solution can be better implemented by using constant variable declarations and calling up "Dispose" within the OnDispose statement.

```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
{
[Description("PlotSample")]
public class PlotSample : UserIndicator
{
Pen pen = new Pen(Color.Blue);
StringFormat sf = new StringFormat();
SolidBrush brush = new SolidBrush(Color.Black);
Font font = new Font("Arial", 10, FontStyle.Bold);
protected override void OnInit()
{
IsOverlay = true;
}
protected override void OnDispose()
{
if (pen!=null) pen.Dispose();
if (sf!=null) sf.Dispose();
if (brush!=null) brush.Dispose();
if (font!=null) font.Dispose();
}
protected override void OnCalculate()
{}
public override void OnPaint(Graphics g, Rectangle r, double min, double max)
{
if (Bars == null || Chart == null) return;
// Properties of Chart
string s;
s = "bounds: "+r.X.ToString()+" "+r.Y.ToString()+" "+r.Height.ToString()+" "+r.Width.ToString();
g.DrawString(s, font, brush, 10, 50, sf);
s = "min: "+Instrument.Round2TickSize(min).ToString()+" max: "+Instrument.Round2TickSize(max).ToString();
g.DrawString(s, font, brush, 10, 70, sf);
s = "BarSpace: "+Chart.BarSpace.ToString()+" BarWidth: "+Chart.BarWidth.ToString();
g.DrawString(s, font, brush, 10, 90, sf);
s = "Bars.Count: "+Bars.Count.ToString();
g.DrawString(s, font, brush, 10, 110, sf);
s = "BarsPainted: "+Chart.BarsPainted.ToString() + " FirstBarPainted: "+Chart.FirstBarPainted.ToString() + " LastBarPainted: "+Chart.LastBarPainted.ToString();
g.DrawString(s, font, brush, 10, 130, sf);
s = "BarsVisible: "+Chart.BarsVisible.ToString() + " FirstBarVisible: "+Chart.FirstBarVisible.ToString() + " LastBarVisible: "+Chart.LastBarVisible.ToString();
g.DrawString(s, font, brush, 10, 150, sf);
// Bar numbering
StringFormat _sf = new StringFormat();
SolidBrush _brush = new SolidBrush(Color.Blue);
Font _font = new Font("Arial", 8);
SizeF _stringSize = new SizeF();
_sf.Alignment = StringAlignment.Center;
for (int i=Chart.FirstBarVisible; i<=Chart.LastBarVisible; i++)
{
string text = i.ToString();
_stringSize = g.MeasureString(text, _font);
int x = Chart.GetXByBarIdx(Bars, i);
int y = Chart.GetYByValue(this, High[Abs2Ago(i)] + 3*TickSize) - (int) _stringSize.Height;
g.DrawString(text, _font, _brush, x, y, _sf);
}
_sf.Dispose();
_brush.Dispose();
_font.Dispose();
}
private int Abs2Ago(int idx)
{
return Math.Max(0,Bars.Count-idx-1-(CalculateOnClosedBar?1:0));
}
}
}
```

### Custom Chart Background Image <a href="#custom-chart-background-image" id="custom-chart-background-image"></a>

The plot method allows you to add a background image to the chart. The following example uses an image with the JPG format located in the main directory on the hard drive (C:).

```csharp
using System;
using System.Drawing;
using AgenaTrader.Custom;
using AgenaTrader.Plugins;
namespace AgenaTrader.UserCode
{
public class BackgroundPicture : UserIndicator
{
Image img;
protected override void OnStart()
{
try { img = Image.FromFile("C:\\\\MyCar.jpg"); } catch {}
}
public override void OnPaint(Graphics g, Rectangle r, double min, double max)
{
if (Chart == null || img == null) return;
g.DrawImage(img,r);
}
}
}
```

![Custom Chart Background Image](https://agenatrader.github.io/AgenaScript-documentation/media/image31.png)

### File Selection in the Properties <a href="#file-selection-in-the-properties" id="file-selection-in-the-properties"></a>

To enable file selection within the properties dialog of an indicator, you will need a type converter. The following example displays how a selection of WAV files can be programmed for an alert:

```csharp
using System;
using System.IO;
using System.Collections;
using System.ComponentModel;
using AgenaTrader.Custom;
using AgenaTrader.Plugins;
namespace AgenaTrader.UserCode
{
[Description("File Picker Example.")]
public class FilePicker : UserIndicator
{
private string _soundFile = "Alert4.wav";
private static string _dir = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"\\AgenaTrader\\Sounds\\";
internal class MyConverter : TypeConverter
{
public override bool GetStandardValuesSupported(ITypeDescriptorContext context)
{
return true;
}
public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context)
{
if (context == null) return null;
ArrayList list = new ArrayList();
DirectoryInfo dir = new DirectoryInfo(_dir);
FileInfo[] files = dir.GetFiles("*.wav");
foreach (FileInfo file in files) list.Add(file.Name);
return new TypeConverter.StandardValuesCollection(list);
}
}
protected override void OnStart()
{
PlaySound(_soundFile);
}
[Description("Choose file to play.")]
[Category ("Sound")]
[TypeConverter(typeof(MyConverter))]
public string SoundFile
{
get { return _soundFile; }
set { _soundFile = value; }
}
}
}
```

### Formatting of Numbers <a href="#formatting-of-numbers" id="formatting-of-numbers"></a>

#### Formatting of Numbers <a href="#formatting-of-numbers_1" id="formatting-of-numbers_1"></a>

**General information on formatting in C#**

```csharp
double d = 123.4567890;
Print("Without formatting : " + d.ToString()); // 123.456789
Print("As a currency : " + d.ToString("C")); // 123.46 €
Print("Exponential : " + d.ToString("E")); // 1.234568E+002
Print("As a fixed point : " + d.ToString("F2")); // 123.46
Print("General : " + d.ToString("G")); // 123.456789
Print("As a percentage : " + d.ToString("P0")); // 12.346%
Print("To 2 decimal places : " + d.ToString("N2")); // 123.45
Print("To 3 decimal places : " + d.ToString("N3")); // 123.457
Print("To 4 decimal places : " + d.ToString("N4")); // 123.4568
```

#### Useful Functions <a href="#useful-functions" id="useful-functions"></a>

Returns the currency symbol for the current instrument:

```csharp
public string getWaehrungssymbol() {
string s = "";
switch (Instrument.Currency) {
case Currencies.USD : s = "$"; break;
case Currencies.EUR : s = "€"; break;
case Currencies.CHF : s = "CHF"; break;
case Currencies.GBP : s = ((char)163).ToString(); break;
case Currencies.JPY : s = ((char)165).ToString(); break;
}
return s;
}
```

Converts a number into a currency with a thousands separator and 2 decimal places. The block separation per 1000 units can be set in "Culture".

```csharp
public string getWaehrungOhneSymbol(double d) {
// Separate 1000s and two decimal points
return d.ToString("\#,\#\#0.00");
}
```

Converts a number into a currency with a thousands separator and 2 decimal places and a currency symbol:

```csharp
public string getWaehrungMitSymbol(double d) {
// Dollar is prefixed, everything else is added afterwards
string s=getWaehrungOhneSymbol(d);
string w=getWaehrungssymbol();
if (w=="$") s=w+" "+s; else s+=" "+w;
return s;
}
```

Converts a number into a currency with a thousands separator and 2 decimal places as well as a currency symbol, and fills up to a fixed length with empty spaces. The function is great for outputting values into a table.

```csharp
public string getWaehrungMitSymbol(double d, int Laenge) {
// Leading spaces until a fixed length has been reached
string s=getWaehrungMitSymbol(d);
for (int i=s.Length; i<Laenge; i++) s=" "+s;
return s;
}
```

Converts a number into a percentage. Nothing is calculated, only formatted. Leading plus sign, a decimal place and a percent sign.

```csharp
public string getPercent(double d) {
d=Math.Round(d, 1);
string s=(d>0)?"+":""; // Leading plus sign
return s+d.ToString("0.0")+"%";
}
```

Formats the market price depending on the number of decimal places to which the currency is notated. This includes a thousands separator and fixed length, meaning that zeros are filled on the right hand side. Because Culture Info is being used, you must integrate the NameSpace **System.Globalization**.

```csharp
public string format(double d)
{
int tickLength = 0;
// ticksize.ToString() is for example 6J = "1E-06" and length is then 5
// and not 8 as it should be with "0.000001")
if (TickSize < 1) tickLength = TickSize.ToString("0.\#\#\#\#\#\#\#\#\#\#\#").Length - 2;
string f = "{0:n"+tickLength.ToString()+"}";
return string.Format(CultureInfo.CurrentCulture, f, d);
}
```

#### Example <a href="#example" id="example"></a>

```csharp
double profit = 1234.567890;
Print("getCurrencyWithoutSymbol ": + getWaehrungOhneSymbol(Gewinn)); // 1234.57
Print("getCurrencyWithSymbol :" + getWaehrungMitSymbol(Gewinn)); // $ 1,234.57
Print("getCurrencyWithSymbol :" + getWaehrungMitSymbol(Gewinn)); // $ 1,234.57
double percentage profit = 12.3456789;
Print("getPercent :" + getPercent(ProzGewinn)); // +12.3%
double price = 123.4567;
Print("getPrice :" + getKurs(Kurs)); // 123.46
```

### Index Conversion <a href="#index-conversion" id="index-conversion"></a>

There are two types of indexing in AgenaTrader.

1. The bars are numbered from youngest to oldest. This type is used in the OnCalculate() method. The last bar has an index of 0, while the oldest bar has the index Bars.Count-1.
2. The bars are numbered from oldest to youngest. This type is most commonly used in the OnPaint() method in "for" loops. The oldest Bbar receives an index of 0, while the youngest bar has the index Bars.Count-1. The following function can be used to recalculate the index types:

```csharp
private int Convert(int idx)
{
return Math.Max(0,Bars.Count-idx-1-(CalculateOnClosedBar?1:0));
}
```

### Overwriting Indicator Names <a href="#overwriting-indicator-names" id="overwriting-indicator-names"></a>

The name of an indicator (or a strategy) is displayed within the properties dialog and at the top edge of the chart. Use the ToString() method and DisplayName property to overwrite it.

```csharp
public override string ToString()
{
return "My Name";
}
```

```csharp
public override string DisplayName
     {
         get
         {
            return "My Name";
         }
     }
```

**Important tip:** Always use both override methods in your scripts to assure that your special name is used on all AgenaTrader forms.

### Rectangle with Rounded Corners <a href="#rectangle-with-rounded-corners" id="rectangle-with-rounded-corners"></a>

By using the graphics methods, you can create interesting forms and place them onto the chart. One example of this is the RoundedRectangle class, which is a rectangle with rounded corners.

![Rectangle with Rounded Corners](https://agenatrader.github.io/AgenaScript-documentation/media/image32.png)

```csharp
Example Code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Linq;
using System.Xml;
using System.Xml.Serialization;
using System.Drawing.Drawing2D;
using AgenaTrader.API;
using AgenaTrader.Custom;
using AgenaTrader.Plugins;
namespace AgenaTrader.UserCode
{
[Description("Demo of RoundedRectangles")]
public class DemoRoundedRectangle : UserIndicator
{
protected override void OnInit()
{
IsOverlay = true;
}
protected override void OnCalculate() {}
public override void OnPaint(Graphics g, Rectangle r, double min, double max)
{
GraphicsPath path;
// draws a rectangle with rounded corners
path = RoundedRectangle.Create(30, 50, 100, 100,8);
g.DrawPath(Pens.Black, path);
// draws a filled rectangle with a radius of 20
// only round the upper left and lower right corner
path = RoundedRectangle.Create(160, 50, 100, 100, 20,
RoundedRectangle.RectangleCorners.TopLeft|RoundedRectangle.RectangleCorners.BottomRight);
g.FillPath(Brushes.Orange, path);
}
}
public abstract class RoundedRectangle
{
public enum RectangleCorners
{
None = 0, TopLeft = 1, TopRight = 2, BottomLeft = 4, BottomRight = 8,
All = TopLeft | TopRight | BottomLeft | BottomRight
}
public static GraphicsPath Create(int x, int y, int width, int height, int radius, RectangleCorners corners)
{
Rectangle r = new Rectangle(x,y,width, height);
Rectangle tlc = new Rectangle(r.Left, r.Top,Math.Min(2 * radius, r.Width),Math.Min(2 * radius, r.Height));
Rectangle trc = tlc;
trc.X = r.Right - 2 * radius;
Rectangle blc = tlc;
blc.Y = r.Bottom - 2 * radius;
Rectangle brc = blc;
brc.X = r.Right - 2 * radius;
Point[] n = new Point[]
{
new Point(tlc.Left, tlc.Bottom), tlc.Location,
new Point(tlc.Right, tlc.Top), trc.Location,
new Point(trc.Right, trc.Top),
new Point(trc.Right, trc.Bottom),
new Point(brc.Right, brc.Top),
new Point(brc.Right, brc.Bottom),
new Point(brc.Left, brc.Bottom),
new Point(blc.Right, blc.Bottom),
new Point(blc.Left, blc.Bottom), blc.Location
};
GraphicsPath p = new GraphicsPath();
p.StartFigure();
//Top left corner
if ((RectangleCorners.TopLeft & corners) == RectangleCorners.TopLeft)
p.AddArc(tlc, 180, 90);
else
p.AddLines(new Point[] { n[0], n[1], n[2] });
//Top edge
p.AddLine(n[2], n[3]);
//Top right corner
if ((RectangleCorners.TopRight & corners) == RectangleCorners.TopRight)
p.AddArc(trc, 270, 90);
else
p.AddLines(new Point[] { n[3], n[4], n[5] });
//Right edge
p.AddLine(n[5], n[6]);
//Bottom right corner
if ((RectangleCorners.BottomRight & corners) == RectangleCorners.BottomRight)
p.AddArc(brc, 0, 90);
else
p.AddLines(new Point[] { n[6], n[7], n[8] });
//Bottom edge
p.AddLine(n[8], n[9]);
//Bottom left corner
if ((RectangleCorners.BottomLeft & corners) == RectangleCorners.BottomLeft)
p.AddArc(blc, 90, 90);
else
p.AddLines(new Point[] { n[9], n[10], n[11] });
//Left edge
p.AddLine(n[11], n[0]);
p.CloseFigure();
return p;
}
public static GraphicsPath Create(Rectangle rect, int radius, RectangleCorners c)
{ return Create(rect.X, rect.Y, rect.Width, rect.Height, Math.Max(1,radius), c); }
public static GraphicsPath Create(int x, int y, int width, int height, int radius)
{ return Create(x, y, width, height, Math.Max(1,radius), RectangleCorners.All); }
public static GraphicsPath Create(Rectangle rect, int radius)
{ return Create(rect.X, rect.Y, rect.Width, rect.Height, Math.Max(1,radius)); }
public static GraphicsPath Create(int x, int y, int width, int height)
{ return Create(x, y, width, height, 8); }
public static GraphicsPath Create(Rectangle rect)
{ return Create(rect.X, rect.Y, rect.Width, rect.Height); }
}
}

```


