Strategy Programming

Account

Description

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

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()

Description

The property "BarsCountFromTradeClose" outputs the number of bars that have occurred since the last exit from the market.

Usage

For multi-bar strategies

Parameter

strategyName

The Strategy name (string) that has been used to clearly label the exit within the exit method.

multibarSeriesIndex

For *MultiBars strategies. Index of the data series for which the exit order has been executed. See ProcessingBarSeriesIndex.

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

BarsCountFromTradeOpen()

Description

The property "BarsCountFromTradeOpen" returns the number of bars that have occurred since the last entry into the market.

Usage

For multi-bar strategies

Parameter

strategyName

The strategy name (string) that has been used to clearly label the entry within an entry method.

multibarSeriesIndex

For *MultiBars strategies. Index of the data series for which the exit order has been executed. See ProcessingBarSeriesIndex.

entriesAgo

Number of entries in the past. A zero indicates the number of bars that have formed after the last entry.

Example

CancelAllOrders()

Description

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().

Usage

Parameter

None

Example

Order.CancelOrder()

Description

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().

Usage

Parameter

An order object of the type "IOrder"

Example

CreateIfDoneGroup()

Description

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

Parameter

An order object of type IOrder as a list

Example

CreateOCOGroup()

Description

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

Parameter

An order object of type IOrder as a list

Example

CreateOROGroup()

Description

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

Parameter

An order object of type IOrder as a list

Example

DataSeriesConfigurable

DefaultOrderQuantity

Description

Change order changes an order.

Default quantity defines the amount to be used in a strategy. Default quantity is set within the OnInit() method.

Usage

Parameter

An int value containing the amount (stocks, contracts etc.)

Example

ExcludeTradeHistoryInBacktest

CloseLongTrade ()

Description

CloseLongTrade creates a sell order for closing a long position (sell).

See: SubmitOrder(), CloseShortTrade()

Usage

See StrategyOrderParameters

Parameter

See StrategyOrderParameters

Return Value

An order object of the type "IOrder"

Example

ExitOnClose

ExitOnCloseSeconds

CloseShortTrade()

Description

CloseShortTradecreates a buy-to-cover order for closing a short position (buy).

See: SubmitOrder(), CloseLongTrade()

Usage

See StrategyOrderParameters

Parameter

See StrategyOrderParameters

Return Value

An order object of the type "IOrder"

Example

Account.GetValue()

Description

Get account value outputs information regarding the account for which the current strategy is being carried out.

See GetProfitLoss().

Usage

Parameter

Possible values for account item are:

AccountItem.BuyingPower

AccountItem.CashValue

AccountItem.RealizedProfitLoss

Return Value

A double value for the account item for historical bars, a zero (0) is returned

Example

GetEntries()

Description

This DataSeries is used in conditions and indicates multiple entry prices for entry orders

Usage

Overload in scripted condition for short and long signal indication

Parameter

None

Return Value

int

Example

GetProfitLoss()

Description

Get profit loss outputs the currently unrealized profit or loss for a running position.

See Account.GetValue().

Usage

Parameter

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

3 – P/L in ticks

Return Value

A double value for the unrealized profit or loss

Example

GetProfitLossAmount()

Description

GetProfitLossAmount () provides the current unrealized gain or loss of a current position as the currency amount.

See Account.GetValue().

Usage

Parameter

Double

Return Value

A double value for the unrealized profit or loss

Example

GetProfitLossRisk()

Description

GetProfitLossRisk () returns the current unrealized gain or loss of a current position in R-multiples.

See Account.GetValue().

Usage

Parameter

None

Return Value

A double value for the R-Multiple

Example

GetScriptedCondition()

Description

This method allows user to communicate between scripts.

IsAutoConfirmOrder

Description

IsAutoConfirmOrder determines whether orders are activated automatically. IsAutoConfirmOrder is specified in the 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

Bool value

Example

Order

Description

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

Description

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 collection object containing all trades generated by a strategy.

  • Performance.LongTrades A Trade collection object containing all long trades generated by a strategy.

  • Performance.ShortTrades A Trade collection object containing all short trades generated by a strategy.

  • Performance.WinningTrades A Trade collection object containing all profitable trades generated by a strategy.

  • Performance.LosingTrades A Trade collection object containing all loss trades generated by a strategy.

Example

Position

Description

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().

  • 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

PositionType

See Position.PositionType.

TraceOrders

Description

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() 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

TraceOrders

Parameter

none

Return Value

true Tracing is currently switched on false Tracing is switched off

Example

Quantity

See Position.Quantity, Position.PositionType.

ReplaceOrder()

Description

Change order, as the name suggests, changes an order.

Usage

Parameter

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

SetUpProfitTarget()

Description

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(), SetUpTrailStop().

Usage

Parameter

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

SetUpStopLoss()

Description

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(), SetUpTrailStop().

Usage

Parameter

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

SetUpTrailStop()

Description

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() 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(), SetUpTrailStop().

Usage

Parameter

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

StrategyOrderParameters

Description

This class aggregates all properties needed to submit the order.

See SubmitOrder(), CloseLongTrade(), CloseShortTrade().

Usage

Parameter

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 or until it reaches its expiry (see 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()

Description

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(), OnOrderExecution().

Usage

See StrategyOrderParameters

Parameter

See StrategyOrderParameters

Return Value

an order object of the type "IOrder"

Example

TimeInForce

Description

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() method.

Permitted values are: TimeInForce.day TimeInForce.loc TimeInForce.gtc (GTC = good till canceled) TimeInForce.gtd

Default: TimeInForce.GTC

Usage

TimeInForce

Example

Trade

Description

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

Unmanaged

Backtesting and Optimization

Performance Characteristics

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.

The individual factors are:

AvgEtd The average drawdown at the end of a trade <TradeCollection>.TradesPerformance.<TradesPerformanceValues>.AvgEtd

AvgMae Average maximum adverse excursion <TradeCollection>.TradesPerformance.<TradesPerformanceValues>.AvgMae

AvgMfe Average maximum favorable excursion <TradeCollection>.TradesPerformance.<TradesPerformanceValues>.AvgMfe

AvgProfit Average profit for all trades <TradeCollection>.TradesPerformance.<TradesPerformanceValues>.AvgProfit

CumProfit The cumulative winnings over all trades <TradeCollection>.TradesPerformance.<TradesPerformanceValues>.CumProfit

DrawDown The drawdown for all trades <TradeCollection>.TradesPerformance.<TradesPerformanceValues>.DrawDow

LargestLoser The largest losing trade <TradeCollection>.TradesPerformance.<TradesPerformanceValues>.LargestLoser

LargestWinner The largest winning trade <TradeCollection>.TradesPerformance.<TradesPerformanceValues>.LargestWinner

ProfitPerMonth The total performance (wins/losses) for the month (also in percent) <TradeCollection>.TradesPerformance.<TradesPerformanceValues>.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

Next Previous


Built with MkDocs using a theme provided by Read the Docs.

Last updated