0% found this document useful (0 votes)
9 views

Option Lab - Option Language Guide

Uploaded by

alexgrios
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

Option Lab - Option Language Guide

Uploaded by

alexgrios
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 55

OptionLAB

Option Language Guide


www.OptionLAB.ch
You can learn How to Use OptionLAB in these 6 free videos (activate “Subtitles” clicking “CC” icon on the right
side of the Youtube Bar and choose Auto Translate in your own language).

Coding and Backtest Strategies with OptionLAB

Position Management on Options Strategies


(from stop loss to Future Hedging)

How to Negotiate Options right in Easy Language


(and backtest whatever Strategy based on underlying chart)

Equities Options Strategies Around EPS Release

Multi Symbol Backtest, Transaction Costs and more advanced


backtesting setups

How to Backtest Dynamic Hedging, Gamma Scalping, Future


Hedging, in OptionLAB

If you want to go in depth on Option Language Advanced Coding,


you can buy a collection of 7 Webinars dedicated to how to code
whatever Options Strategy in OptionLAB (write us an email for more info

3
www.OptionLAB.ch
Table of Contents
1. Introduction ................................................................................................ 6
2. The Option Language Editor ......................................................................... 7
3. Strategy Code ............................................................................................... 8
An example ................................................................................................ 8
Variables declaration ................................................................................. 8
Implementation of Entry condition ........................................................... 8
Identification of the contracts to be traded .............................................. 9
Orders execution ....................................................................................... 9
4. Variables ................................................................................................... 10
Data types ................................................................................................ 10
Variable declaration ................................................................................ 10
5. Language Elements ..................................................................................... 11
Mathematical operators .......................................................................... 11
Bool operators ......................................................................................... 11
Bool expressions ...................................................................................... 12
If - Then statements................................................................................. 12
Begin – End statements: .......................................................................... 13
While cycles: ............................................................................................ 13
Reserved words ....................................................................................... 14
6. Option Data and Chain Management .......................................................... 16
How Option data is structured, database dimensionality ....................... 16
Option Chain access shortcuts ................................................................ 17
GetMaturity ............................................................................................. 17
GetStrike .................................................................................................. 18
How to retrieve information from the Option Chain .............................. 18
7. Trading Functionalities .............................................................................. 20
Buy and Sell ............................................................................................. 20
Exit ........................................................................................................... 20
SetStop..................................................................................................... 21
8. Position Info .............................................................................................. 23
Position .................................................................................................... 23
GetProfit .................................................................................................. 24
9. Trades Management and Information ........................................................ 25
How the backtesting engine handles trades ........................................... 25
How to access trades information ........................................................... 25
GetTradesCount....................................................................................... 25
GetTradeTicket ........................................................................................ 26
GetTradeInfo ........................................................................................... 27
10.Our first Backtest ...................................................................................... 28
System Launcher...................................................................................... 28
Multi Symbol Backtests ................................................................. 29
Performance Report – Charts .................................................................. 31
Performance Report – Metrics ................................................................ 33
Performance Report – Trade List............................................................. 33
Performance Report – Payoff Graph ....................................................... 34
Perfromance Report – Tools .................................................................... 35
11.Ticketing, Grouping and Labelling .............................................................. 38
What are tickets ...................................................................................... 38
How to use tickets ................................................................................... 38
What is grouping ..................................................................................... 38
How grouping works................................................................................ 39
How to use grouping ............................................................................... 39
What is labelling ...................................................................................... 40
How labelling works ................................................................................ 41
How to use labelling ................................................................................ 42
12.Fundamental and News Data ..................................................................... 43
EPS Report Data ....................................................................................... 43
13.TradeStation Integration Functionalities .................................................... 47
Equity Line Import ................................................................................... 47
Naked Shorts Hedging ............................................................................. 47
Dynamic Delta Hedging ........................................................................... 48
Easy Language integration functions ....................................................... 50
Integration Directory ............................................................................... 52
Code Example .......................................................................................... 53
TS Signal Replication ................................................................................ 55

5
www.OptionLAB.ch
1. Introduction
Option Language is a Turing complete, imperative paradigm, proprietary
programming language that allows the user to implement and automatically test
trading strategies based on options.
It provides a simple but complete interface to access the high dimensional data
structure of options prices.
In the Option Language framework, along with its integration with Trade Station,
the user can code and test virtually any systematic, rule-based trading strategy on
Options, Futures, or a hybrid combination of the two.
Option Language, in its semantic, resembles visual basic, while in data-typing it’s
closer to c. In developing the language, we followed the imperative that someone
familiar with Easy Language should be able to quickly adjust with ease to the new
option compatibility features, while coding in a friendly and familiar environment.
The following code prints in the strategy log, for each day of the test, the string
“Hello World!”.

6
www.OptionLAB.ch
2. The Option Language Editor
To open the Option Language Editor from the main Option Explorer interface, go to
Option Language -> Option Language Editor as shown in the picture.

The editor is divided into three sections:

1. Code box (red square)


2. Strategies tree (green square)
3. Error log (blue square)

7
www.OptionLAB.ch
3. Strategy Code
An example
To describe how to write a simple trading strategy for options with Option
Language let’s start with a simple example.
As said before, to be implemented, a system must be rule-based. For our example
these will be the rules of our trading strategy:

Sell Short a strangle on Euro FX Futures using contracts with closest weekly expiry
date, with both legs at Delta = 0.2, and let the trade survive until maturity. Then
open the next trade using the same rules.

The following code is the easiest way to write such a strategy:

Every trading system must contain four essential sections:


1. Variables declaration
2. Implementation of entry conditions
3. Identification of the contracts to be traded (Strike Price, Maturity)
4. Orders execution

Variables declaration
In line 1 and 2 all the variables that are used through the code are declared. To see
in detail how variables work in Option Language go to section 4.

Implementation of Entry condition


There are only two condition that must be met to generate a trade: first we want
our strategy to be currently flat. In fact, if we are already at market with an older
trade the system must wait until it expires before opening the next. This condition
is coded in line 4.
The second condition makes sure that trades only last for one week. In line 8 the
strategy controls the difference in days between current date and the maturity date
8
www.OptionLAB.ch
of the options to be traded. If this difference is equal or less than seven days the
condition is met.

Identification of the contracts to be traded


If all entry conditions are met, before buying or selling any options we want to know
which options to trade.
This means that we need to know, to be able to call the trading functions, the strike
prices and maturities of all options traded.
This information is retrieved from the historical option chain of the day the
conditions are met. Option Language provides many functionalities to access the
option chain and to handle the data contained in it, the GetMaturity and GetStrike
functions are an example.
In line 6 GetMaturity is used to find the date of the first available expiry with at
least 5 days of remaining time. In line 10 and 11, instead, GetStrike is used to
retrieve the strike prices whose options (expiring on MyMaturity) have delta closest
to 0.2.
Now that we know that entry conditions are met and which contracts to trade, it is
time to call the trading functions.

Orders execution
Our trading system is based on selling short a strangle, thus we must use the Sell
function to sell the two delta 20 options.
In line 13 and 14 the two options are sold.

This was just a quick example of how a trading system on option is built in Option
Language, we’ll now look in a deeper way into how the language works.

9
www.OptionLAB.ch
4. Variables
Data types
Option Language currently supports 5 different data Types:
1. Int: it is used to hold integer numbers.
2. Double: it is used to hold floating point numbers.
3. String: it is used to hold arrays of characters.
4. Bool: it can only assume value True or False.
5. OLDate: it is used to hold date values. It’s an integer number representing the
number of days passed since January 1st, 1900.

Variable declaration
Variables are declared with the following syntax:

Type VariableName;

With the equal sign “=” it is possible to assign a starting value to the variable; this
assignment is only operated once at declaration stage.
It’s possible to declare multiple variables of the same type within a single
instruction by using the comma sign “,” between one declaration and another.
When declaring multiple variables at the same time it’s as well possible to assign all
or some of them. This is a series of examples of valid declaration instructions:

A variable must always be declared before being used. Reference to an undeclared


variable will result in a compiling error.

10
www.OptionLAB.ch
5. Language Elements
Mathematical operators
Basic mathematics is allowed in Option Language. Math operators include:
1. Plus sign “+”: calculates the sum of two numbers, or joins two strings together.
An integer can be summed to a OLDate, and the result would be the date plus
a number of days equal to the integer summed.

2. Minus sign “-”: subtracts two numbers. An integer can be subtracted to an


OLDate to return the date minus a number of days equal to the integer
subtracted. Two dates can be subtracted, and the result would be the number
of days between the first date and the second. If the first date is smaller than
the second, the resultant number of days will be negative.

3. Multiply sign “*”: can only be used to multiply numbers.


4. Divide sign “/”: can only be used to divide two double numbers.
5. Module sign “%”: can only be used to calculate the remainder of the division of
a number by another.

Bool operators
Two variables can be compared using standard Boolean operators. They are:
1. Equal sign “=”: returns True if the two compared expressions reduce to the
same value. Note: OLDate type is an integer value representing the number of
days passed since January 1st, 1900. Thus, for example the following expression
would return True:

2. Inequality sign “<>”: returns True if the two compared expressions reduce to
two different values.
11
www.OptionLAB.ch
3. Greater than “>”: returns True if the expression on the left side reduces to a
greater value than the expression on the right side. It’s only available for
numbers and OLDates.
4. Greater than or equal to “>=”: returns True if the expression on the left side
reduces to a value greater than or equal to the expression on the right side. It’s
only available for numbers and OLDates.
5. Smaller than “<”: returns True if the expression on the left side reduces to a
smaller value than the expression on the right side. It’s only available for
numbers and OLDates.
6. Smaller than or equal to “<=”: returns True if the expression on the left side
reduces to a value smaller than or equal to the expression on the right side. It’s
only available for numbers and OLDates.

This are all examples of valid use of bool operators:

Bool expressions
A bool expression is an expression that, if reduced to a single term, is either equal
to True or False.
Such an expression can be of any degree of complexity, involving an undefined
number of nested parenthesis, nested function calls and bool operators.
Variables, constants and functions can all be used to compose such a statement.
Multiple conditions can be joint with and or or gates following standard logic:

Bool 1 Bool 2 “and” gate “or” gate


True True True True
True False False True
False True False True
False False False False

Mathematical operators are allowed, and must be used to compose an expression


to be compared to another expression.

If - Then statements
The if statement allows the user to check whether a condition is true or false and
execute code blocks accordingly.
An if statement must be followed by a bool expression of any kind. After the
condition a then statement anticipate the start of the instruction to be execute in
case the bool expression reduces to value True.
12
www.OptionLAB.ch
In case the bool expression reduces to value False instead, the program will skip
the instruction following the then keyword.
This is an example of how to use an if – then statement:

Begin – End statements:


The begin – end statement is used to include a code block and to tell the program
to treat it as if it was a single instruction.
If used after an if – then statement, in case the condition is True, the whole code
block will be executed, otherwise the whole code block will be ignored as in the
following example:

While cycles:
The while cycle makes the program repeat an action as long as the condition
following the while statement is True.
After the condition, a begin – end statement containing the code to be executed
multiple times must follow. Inside the begin – end statement something must
change in order to eventually make become False the condition of the while cycle.
Failing to do so would result in an infinite loop and in the resulting malfunctioning
of the program.
When coding in Easy Language to need a while cycle is quite rare. When dealing
with options, though, due to the high dimensional nature of options databases, it
is often required.
13
www.OptionLAB.ch
When needing to look for certain information inside the option chains, sometimes,
the only option is to cycle through the chain itself until needed information is found.
Most common operations are embedded in single functions so that the user does
not have to loop in the chain. An example is the GetStrike function, that allows the
user to find the strike price it needs based on some criteria, for example the Delta,
as shown in the example of the first chapter.
But if the strike price had to be chosen based on Vega, or Theta, or Open Interest
(just to mention a couple examples), the user would have to implement a while
cycle looping through the chain until needed conditions are met.
In the example a while loop is implemented, printing the first 100 even numbers.

Reserved words
Not all words are available to be used as variable names. The language uses many
constants values all of which have got its own name.
All function names can’t be used as variable names either.
As a mean of checking what can be used and what can’t simply try typing the word
in the editor and see if it remains black. Constants are coloured in light blue,
keywords in blue and functions in purple.
Numbers as well can’t be used as variable names, they are coloured in fuchsia.

Special cases of reserved words are Close, C, Bar and Date.

C and Close are synonym, and can be used to access the closing price of the
underlying futures of an option. Since all options expiring the same day have the
same underlying futures only 2 parameters are needed: the number of bars back,
and of which maturity we need the underlying price (0 = 1st, 1 = 2nd…).
Bar returns the bar number of BarsBack bars ago.
Date returns the date of BarsBack bars ago.
Parameters are not always required: often we will need the underlying settlement
price of today, for the first available maturity date. In this case no inputs are
14
www.OptionLAB.ch
needed. The same can be said for Bars and Date: if we need the bar number or date
of the current bar, there’s no need to pass any input.
Here are some examples:

15
www.OptionLAB.ch
6. Option Data and Chain Management
How Option data is structured, database dimensionality
Futures and Stock data, for each time stamp, usally present 5 datapoints: open,
high, low, close and volume. When having to deal with options, instead, things are
far from being that simple.

For each available date of the


backtest.

For each time stamp multiple maturities are available, and for each maturity
multiple strikes. Even after blocking maturity and strike price, you can still access
put or call data. Now, for both put and call, for each strike price available for each
maturity date, the database shows the daily settlement price, 5 greeks and implied
volatility.
Navigating such a database is a very difficult task, doing it efficiently is even harder.
We had to choose how to divide the process of accessing information to make it as
simple as possible for the user.
We chose to make the maturity date the first layer, the strike price the second, and
put/call the third. This means the for every available day there will be an 𝑁 number
of chains with different maturity dates, for each 𝑖 𝑡ℎ chain there will be an 𝑀𝑖
number of strike prices, and for each strike price there will be either the put and
call quotes.

For each available date of


the backtest.

Navigability of a database is highly influenced by its dimensionality, which in this


case is high enough to represent an increase in complexity.
Therefore, in the next two sections we will address how to access information, an
issue that in stock and futures would be solved be simply calling O, H, L, C keywords.

16
www.OptionLAB.ch
Option Chain access shortcuts
To send an historical option trade, the Option Explorer, must first know which
contract have to be traded. Thus, the strategy must feed buy and sell functions with
all needed contract information: maturity date, strike price, and put/call right.
It’s true that an option database is a big one, but nonetheless it is possible to
identify some classical or at least more commonly used way of approaching
contract selection. For example, we most of the time use simply the first available
maturity date, and choose the strike price simply base on moneyness or on the
delta we need to trade. For this kind of basic operation we have included built in
functions that will not require the user to go through the entire chain to make
decisions.
These are in some ways a kind of shortcut for chain navigation, and mainly refer to
maturity date and strike prices.
Let’s see how they work.

GetMaturity

Gathering the maturity date we need is very easy.


All we have to do is calling the GetMaturity function in one of its 2 modes:
1. ByPos (By Position)
2. MinDays (First maturity with a Minimum number of remaining Days)

The first, which is the default mode, allows us to gather the maturity date based on
its position: if, for example, we simply need the first maturity available it will be
enough to call this function in mode ByPos asking for the 0-th maturity, hence the
first.
If instead we want the first available maturity with at least N remaining days, we’ll
have to call the function in mode MinDays, passing the value N.
If today is a maturity date, it won’t be included and will be treated as not available
as any other older maturity date.
Here are some examples of allowed syntax:

17
www.OptionLAB.ch
GetStrike

To find the strike price we need the GetStrike function must be called. Since the
strike price is taken from the chain, we first need to have computed the maturity
date of the contract we want to extract.
Then, by telling to the GetStrike function if we are interested in Put or Call we can
easily get the strike we need based on one of the three shortcuts available:
1. ByPos (By Position)
2. Nearest (Strike nearest to a price)
3. Moneyness (Strike with moneyness closest to a certain value)
4. Delta (Strike whose contract has a delta closest to a certain value)

The first simply return, for a certain maturity date and put/call right the n-th
available strike, where the most Out of the Money is 0, the 2nd most OTM is 1 and
so on and so forth.
The second mode, Nearest, returns the available strike price that is the closest to a
certain value.
Moneyness mode gets the strike prices based on a certain amount of moneyness,
positive moneyness being ITM and negative moneyness OTM.
Last mode, Delta, is maybe the most used. Because of how delta is calculated it
takes into account volatility and this property is what makes choosing the strike
price upon delta so versatile.
Here are some examples of allowed syntax:

How to retrieve information from the Option Chain


The Option Chain can be entirely navigated programmatically at backtest time. A
set of functions have been implemented in order to make this task easy and
accessible.
There are three functions available and which one to use depends on the type of
information we need to retrieve.

18
www.OptionLAB.ch
For example if we need to retrieve a value that we now is represented by an integer
value, such as Open Interest, we will need to call the “int” function.
All three functions’ name start with GetChainInfo followed by the type of then
needed info. Thus, since there is no “string” information to be retrieved in the
option chain, the three functions will be: GetChainInfoInt, GetChaininfoDouble,
and GetChainInfoDate.
This is the syntax (in this example the “date” version is used):

The first three inputs are used to identify the contract we need to get information
about. The last input is the number of bars we want to reference back in time (0 is
default).
The input that really matter is the 4th, which is used to tell the function what
information to gather from the chain.
This field can assume many values depending by which of the three functions we
are using. In the following table are shown the possible fields for each function:

19
www.OptionLAB.ch
7. Trading Functionalities
Buy and Sell

Buy and Sell are the functions used to send historical trades.
These functions allow the user to buy and sell options contract, and to combine
these trades into single multi-legs trades.
Of course, the first information needed by these functions is which contract to
trade, and the first three inputs serve this purpose.
Maturity and Strike price can be calculated in advance and stored in a variable (as
in the case of the example of chapter 3. Strategy Code), or GetMaturity and
GetStrike can be called directly as parameters (we only wanted to highlight this fact
because it can come handy sometimes, but really any parameter of any function
can be represented by any expression as long as the type returned match with the
type needed for the parameter).
The Right parameter is of type constant and only Put or Call can be used.
Size represents the number of contracts to be traded, Group the ID of the group to
which we want this trade to belong. The Label string, instead, assign a name to this
entry.
The two functions return an integer number. This integer number is the Ticket of
the trade just opened. It must only be recorded if it will be needed in the future,
otherwise, as in most cases, it can be discarded and saved into a Bin variable.

(To see what tickets, groups and labels are and how they work refer to chapter 11.
Ticketing, Grouping and Labelling).

Exit

Option Explorer makes no distinction between closing a Sell or a Buy trade. Both
types of trade are closed out using the Exit function.

20
www.OptionLAB.ch
The behaviour of this function can vary dramatically based on what parameters are
given.
It’s really important to understand how it works or it will be difficult to code a
strategy that behaves as intended.

The first parameter Basket is perhaps the most important, it tells the program with
which logic select the trades to close. If the logic is Group or Label, then e value
passed as Val parameter defines which group number or label string to exit.
The Basket parameter can be set to Ticket, Label, Group, and All.
ExitName is used to give a name to the current exit that can be later used to
distinguish different exit logics in the Performance Report.

The Exit function doesn’t return any value.

Important: it is not always necessary to use this function to close trades. Option
trades are always intended to be closed at maturity. Exit at maturity is managed
automatically by the backtesting engine, and, if maturity is the intended exit logic,
no further action has to be taken after the trades are opened.
The example of chapter 3. Strategy Code shows how no exit logic is implemented if
natural expiration is how we want trades to be closed.

(To see what tickets, groups and labels are and how they work refer to chapter 11.
Ticketing, Grouping and Labelling).

SetStop

Stop Losses and Profit Targets are sent using the SetStop function.
The first parameter defines if we intend to implement a TP or a SL. It is a constant
value and can assume values TP, TakeProfit, SL and StopLoss. The first twos are
equivalent to each other, and the second twos as well.
As with Exit function the Basket parameter allows the user to set the stop only for
a subset of currently open trades.

21
www.OptionLAB.ch
Important: when assigning a stop loss to more than one trade by using as basket
All, Group, and Label, we are not assigning multiple stop losses to multiple trades
at the same time, we are actually setting a stop loss based on the sum of the open
profits of the trades. So, if we set a Group stop loss of -400$ to group 6, when the
SUM of the open profits of all open trades of group 6 reaches -400$ all trades are
closed. Note that the profits of different trades might offset each other, so that if a
trade is in a loss of -1000$ but another trade is in profit o +800$, resulting in a group
profit of -200$, the stop loss of our example would not close any trade.

If the Basket selected is not All, a value must be passed as parameter Val that
defines to which trade ticket, group or label the stop will be assigned based upon
the chosen logic.
The Amount parameter must be a negative dollar expressed loss for stop losses and
a positive dollar expressed profit for profit targets.
The use of the reserved word BigPointValue can help when wanting to set a stop
based on points.

22
www.OptionLAB.ch
8. Position Info
To monitor the position status is an important matter when creating trading
systems. In Option Language there are two main functions that allow the user to
easily and quickly monitor the position status, plus a long array of functions to
monitor open and close trades.
Position

The Position function is used to know if we are currently in the market.


It can be used in two different modes:

1. Simple: if no mode is specified “Simple” mode is assumed. It can only return


“Flat”, “Long”, “Short” and “Mixed” based on the position currently held.
In futures trading it makes no sense to be at the same time Long and Short, but
when trading options, since we are trading different contracts it is very often
the case. An iron condor consists of 2 long and 2 short option trades, thus the
resulting position would be “Mixed”.

2. Detailed: this mode distinguishes between many cases. Returned values are:
a. Flat
b. LongCall
c. LongPut
d. LongMixed (for example a long strangle: both LongPut and LongCall)
e. ShortCall
f. ShortPut
g. ShortMixed (for example a short strangle: both ShortPut and ShortCall)
h. Call (for example a Bear Vertical Spread: both LongCall and ShortCall)
i. Put (for example a Bull Vertical Spread: both LongPut and ShortPut)
j. Mixed (When none of previous values is exclusively true)

This are possible usages of the Position function:

23
www.OptionLAB.ch
GetProfit

Other than knowing which position we are currently holding, a quick info very often
needed is how our position is performing.
To gather this information the GetProfit function provides a very quick and easy to
use interface. It allows us to ask for the profit status of any basket of trades.
If, as in the example of chapter 3. Strategy Code, we are trading a strangle, we
would most likely be more interested in knowing the current profit of the whole
structure then of the single trades. This function allows us to do this and many other
things.
The first parameter, OpenClose, is used to choose whether to get the open or
closed profit. Possible values are Open and Closed.
The second input, Basket, lets the user decide for which basket to request the open
or closed profit.
Depending on the situation the user may need to know the open or closed profit of
a single trade (Basket = Ticket), of all trades with the same entry label (Basket =
Label), of all trades of a group (Basket = Group), or of all open or closed trades
(Basket = All).
In the following figure a few examples of how to call this function are shown:

24
www.OptionLAB.ch
9. Trades Management and Information
How the backtesting engine handles trades
Historical trades are opened and managed according to the following logic. When
a trade is opened it is inserted in the Open Trades List. As soon as it is closed it is
removed from the Open Trades List and moved into the Closed Trades List.
If no active exit is performed the maturity of open trades is automatically executed
by the engine at expiry date.
An ID called Ticket is assigned to all trades. The ticket is used to access information
about the trade or to implement operations such as setting a Stop Loss or exiting
the trade.
The Ticket of a trade, after closing, stays the same so it can be used to access
information about closed trades too.
In the Open Trades List trades are sorted chronologically upon opening date, while
in the Closed Trades List trades are sorted chronologically upon closing date.
Trades can be grouped into baskets called Groups, and labelled with an Entry Name.
For more information go to 11. Ticketing, Grouping and Labelling.

How to access trades information


To access trades information the user must know the ticket of the needed trade.
For example, if we want to track the delta of the option of a trade, all we have to
do is, after opening, holding the ticket of that trade in a variable. We can then use
that variable to interrogate the trade for delta.
If the ticket is not known in advance the user can cycle through all trades of the
Open and Closed lists and ask for tickets at each iteration of the cycle.
For example if we want to know the total profit of positive closed trades we will
have to cycle through the Closed Trades List and, for each trades, sum their profit
together when positive.

GetTradesCount
The function GetTradesCount tells us how many trades are stored in a Trades List.

The first input is used to ask for the Open Trades List or the Closed Trades List. The
Second is used to tell the function if we want to know the total number of trades,
or the number of trades that belong to a certain group or entry name.
If group or labelling is used as basket, the third input provides the engine with the
group number or entry name.
If Open or Closed is not specified, then Open is used as default.
Is no basket is specified, then All is used as default.
If Group or Label is used as basket, then a group number or entry name must be
specified. When using basket All no other value must be used.

25
www.OptionLAB.ch
These are all examples of valid uses of this function:

After calling the GetTradesCount function the variable N will hold the number of
trades in the selected basket of the selected Open/Closed list.
This value can be used to stop a while cycle.

GetTradeTicket
At each iteration the incremental variable of the cycle can be used to ask for the
Ticket using the By Position mode of the function GetTradeTicket.

This function works very similarly to the GetTradesCount function.


The difference is in the second input: a selection method can be chosen. For now
only the By Position method is available.
The fist input (Open/Closed), the third (Basket) and the fourth (Val) work in the
same way as in the case of the GetTradesCount function.
These are all valid implementations:

The first trade of the list, which is the last in chronological order, is the one in
position 0, as shown in the figure above.
Once the Ticket is known it can be used to gather information or execute operations
on the relative trade.
In the following section we will see how to ask for trade information.

26
www.OptionLAB.ch
GetTradeInfo
There are 4 different functions that can be used to access trade information. Which
one to use depends by the type of information needed.
The 4 functions are the following:

The first input is used to pass to the function the ticket of the trade we need, the
second is used to tell the function which information we need.
The available fields depend on the type needed (Int, Double, OLDate, String)
according to the following table:

When asking for chain information, such as Volume, Delta, etc, the value of the
current bar when calling the function is returned.
If the Close Price of an Open Trade is asked, the current price is returned.
Let’s see now an example of how to use these function. In the previous paragraph
we used the following example: calculate the sum of the profits of all open trades
currently positive.
Here is how this task is accomplished:

27
www.OptionLAB.ch
10. Our first Backtest
System Launcher
The System Launcher is a device used to launch backtests of previously coded
trading systems. In the System Launcher the user can choose the inputs of the
backtests.
To open the System Launcher go to the main interface of the Option Explorer and
click on Option Language -> System Launcher.

Here, with different sections highlighted, is how it appears:

Let’s address all the sections one by one.

Red: here is located the Strategy Tree. It is structured the same way as the Strategy
Tree in the editor but it can’t be modified. By clicking on any strategy, the user
selects which one to test.
After clicking a strategy the name of the selected system will be reported at the
Selected System field in the blue section.

28
www.OptionLAB.ch
Blue: the main settings of the backtest can be found here. Here the user can set the
cadence of the options he wants to test the system on, the symbol, and
starting/ending dates of the backtest.
The option “Load maturities expiring in less than months: N” allows the user to
cap the amount of data loaded in memory. Certain series can be very memory
consuming. In most cases not all available chains are needed, if for example we only
need to trade the first available maturity, no more than a couple months of
maturities would be needed at each date.
This can dramatically reduce the amount of memory locked and the time needed
to load a data series.
The option “Allow Multiple Entries with Same Name” allows the user to choose
whether to let the backtest engine open a trade if another trade with the same
name is currently open.
Usually it’s better to leave this option flagged, but in some cases (as when
integrating Trade Station with Option Explorer) it may acquire critical relevance.

Orange: Only available for Options on Equities. In this section the user can indicate
how the backtest engine executes trade. He can specify to execute trades at closing
time or 15 minutes before (bid/ask spreads tend to increase at closing time). The
user can also selecte between 4 different logics of price selection for trade
execution. With “Best” and “Worst” the engine will use Bid and Ask price
accordingly with the side of the trade, with “Mid” the mid price will be selected,
with “Last/Settlement” the engine will use the last traded price for 15:45 execution
and the Settlement price for closing time executions.

Green: Here are found all the inputs needed to manage the trade signals coming
from Trade Station. The communication file can be chosen, and the user can tell
the program if to import the underlying equity or to ignore it.

Purple: usually both these inputs are left flagged. To learn how the Option Explorer
handles the issue of data holes refer to the User’s Guide at chapter 8. Price
Modelling and Database Adjusting.

Black: here the user can indicate the value of input variables.

Click Launch to start the test.

Multi Symbol Backtests


The Group button allows the user to perform multi symbol backtests to optimize
time consumption.
After clicking “Group” a menu asks the user to select the basket of instrument.
After launching the clicking “Launch” all needed data will be loaded at once and
then the multi symbol simulation starts. This is an example of the windows the
output of the test.

29
www.OptionLAB.ch
All symbols are listed along with some metrics. Selecting the respective raw will
result in the related equity line being selected in the lower chart and drawn in the
upper chart.

30
www.OptionLAB.ch
Performance Report – Charts
After the test is completed the Performance Report will be calculated and
automatically opened.

This is what will appear:


After opening the Performance Report will display two graphs: the Close To Close
equity line, and the Close To Close Draw Down.
Both the equity line and draw down can be shown in two different modes:
1. Close To Close (CtC): data points are close trades sorted in chronological order.
2. Detailed: data points are days, so intra trade price movement information is
not lost. This results in a noisier line that carries more information.

To switch between CtC and Daily click on Option -> Chart Type and select the
preferred type.

The upper chart will always show the equity line, while the lower can show four
different information:

31
www.OptionLAB.ch
1. Trades: the amount of variation of equity between one equity point and the
next. In case the equity is set to CtC this chart shows the actual profit of every
trade, in case the equity is set on Detailed this chart shows daily variations.

2. Draw Down: how much profit is given back after any new equity high. Can be
shown in both CtC and Detailed mode.

3. Open Premiums: The starting premium of every trade along with a moving
average that shows tendencies in market prices. When selling an option, the
premium has a positive effect on cash, and is thus represented positive and
green. When buying options, it has a negative effect on cash, so it’s negative
and red.

4. Close Premiums: the ending premium of every trade, along with a moving
average of premiums of the trades that didn’t expire Out of the Money
(premium: 0). Here as well colour and sign are assigned based on effect on cash.

32
www.OptionLAB.ch
To change what information to show in the lower chart click Option -> Lower Chart.

Performance Report – Metrics

Performance metrics allow the user to get an idea of how the system behave.
In this page are included the main metrics of the strategy regarding profits, draw
down, and trades sample analysis.
Ratios such as the Profit Factor or the NetProfit/MaxDD helps the user to
understand the risk reward profile of the system.

Performance Report – Trade List


All trades operated by the strategy are recorded In the Trade List. They are sorted
chronologically starting from the oldest.
All relevant information can be found here: starting and ending date of the trade,
the contract traded (maturity, strike, right), the type of operation (buy, sell).
Profits are listed at the right-hand side of the matrix.
The first column shows the Tickets of all trades.
In the “Group” column, if grouping was used in the strategy, the user can see how
trades were grouped together.

33
www.OptionLAB.ch
In columns “Entry” and “Exit” are shown the entry and exit labels assigned by the
strategy to each trade (if used).

Performance Report – Payoff Graph


By double clicking on any trade the relative payoff graph appears. The payoff is
calculated at maturity upon all trades of the group of the trade clicked. If no group
or a single trade was assigned a single blue line would be drawn. If the group
consisted of multiple trades then a green thin line would be drawn for each Call
trade and a red one for reach Put trade.
A light blue thick line shows the overall payoff of the group.

Over the payoff graph can be found a few dots that show information about the
position of the underlying futures and profit of the trade.
The purple diamond shows the position of the underlying when the trade was open.
It stays on the 0$ profit line because at the start of the trade floating profit is always
0.
The red/green diamond shows where the underlying was when trade was closed (X
axis) and how much profit was made (Y axis).

34
www.OptionLAB.ch
The red/green dot shows where the underlying was when the options of the trade
expired. This dot always lays on the payoff line since it is calculated at maturity. If
the trade was closed at maturity the red/green diamond and red/green dot overlap.

This is the payoff graph of a short strangle group made of two trades. See the green
line of the short call, and the red line of the short put. The trade was closed at
maturity thus the green dot and the green diamond overlap.

Perfromance Report – Tools


By clicking Tools three options are shown.
Let’s see them one by one.

1. Import Equity Line from TS: sometimes a strategy may require options to be
traded along the underlying. In the example above, the Short Strangle, carries
an infinite risk. We may decide that we want our naked shorts to be covered
with the underlying futures. This would mean to place a stop orders where the
strike prices are in order to offset the option loss in case one of the two legs of
the strangle expires In The Money.
Such a strategy cannot be implemented in Option Explorer because there isn’t
enough granularity in the underlying data, but it can be tested in Trade Station.
This is just an example, but there are many reasons why sometimes trading
both instruments is what we may want to do.
To see how a hybrid portfolio would have behaved in the past, a strategy on
the underlying must first be tested in Trade Station and its equity exported.
To create the code pattern that exports the equity line from Trade Station click
on Code Generator -> TS Equity Exporter.

35
www.OptionLAB.ch
After choosing the name of the file where the equity line will be exported (it
can be changed later) an Easy Language code will appear. That code, pasted in
any Trade Station strategy will export the equity line of the system in the
default folder of OE, within the file specified before.
After the equity has been exported, to combine it with the option system click
on Tools -> Import Equity Line from TS. The default folder will open, and, unless
it has been changed in Easy Language, the file of the equity just exported will
be shown.
Select the needed equity and click open.
The Performance Report will load it and will change accordingly. The black line
will now represent the portfolio, the blue line the option side of the system,
and the red line the underlying side.
The Performance metrics will be adjusted as well with three new columns, one
for each equity line: options, futures, and portfolio.

2. Export Report to CSV: if further inspections of results is needed the report can
be exportet into a csv file. All information found in the Performance Report will
be found in the csv file as well.

3. Code Generator -> TS Equity Exporter: this feature has been discussed at point
1.

4. Code Generator -> EL Code for Futures Hedging: this tool automatically creates
a hedging strategy for all naked sold options. To closely see how this feature
works, please refer to the User’s Guide at chapter 11. TS Code Generator for
Naked Shorts Hedging.

5. Code Generator -> EL Code for Delta Hedging: this tool automatically creates a
delta hedging strategy for your option position. To closely see how this feature
36
www.OptionLAB.ch
works, please go to 13 TradeStation Integration Functionalities - Dynamic Delta
Hedging.

37
www.OptionLAB.ch
11. Ticketing, Grouping and Labelling
What are tickets
Tickets are used by the backtest engine to identify uniquely every historical trade.
They are the tool used every time an action must be operated on a single trade.
when a stop loss or take profit has to be set or when information about a trade is
needed, the ticket is used in order to tell the engine which one is the trade that is
needed.

How to use tickets


The ticket is returned by the Buy and Sell functions. After those functions are called
the ticket can be saved in a variable for later use. Here we see a couple example of
how the ticket can be saved and used.

What is grouping
Groups are used to treat baskets of trades as a single entity. It’s extremely useful
to get a better idea of performance and strategy metrics when handling every trade
alone makes no sense. Let’s take the example of the strategy proposed in chapter
3. Strategy Code. It was a continuous weekly sale of short of strangles. When
analysing the Performance Report, we are not interested in knowing, for example,
how many option where sold, but how many strangles. We are not interested in
knowing how many options closed at a profit, but how many strangle. This fact is
true for pretty much every metric. The CtC equity line, as well, makes a lot more
sense with all data points representing the close of a strangle, not of a single option.
Groups are essentials, not only for performance interpretation, but as well for
strategy implementation.

38
www.OptionLAB.ch
If we want to set a stop loss on our short strangle we want it to be calculated upon
the sum of the profits of the two legs. It makes no sense that the stop loss gets
triggered when a single leg hits the loss target while the other’s profit is still
compensating the loss.

How grouping works


Trades are assigned to groups at the opening stage. Every trade with the same
group number will belong to the same group.
The group is assigned though the 5th input of the Buy/Sell functions as shown in the
screenshot:

In this case we are assigning the trade to group 5.


Such a script is not advisable because all trades would be assigned to the same
group resulting in a huge loss of information.
Something more dynamic must be implemented.
For example, we could increase the group number every time a structure is opened.
In this case all structures would be identified by a different group number.
In the example shown in chapter 3. Strategy Code such a protocol was not
implemented, and every trade was treated as a single entity. If we wanted to
include grouping to handle whole structures as single trades the code would look
like this.
The red squares highlight code blocks necessary to accomplish a sensible grouping:

How to use grouping


It is not required to use grouping. In fact a strategy can be coded with or without
grouping and the final result would stay the same.
We must choose whether to implement or not to implement grouping based on the
information we want the platform to give us.
Here follows an example of two equity lines: they are both obtained by the strategy
just shown in the previous paragraph.

39
www.OptionLAB.ch
The curve on the left, obtained without grouping trades, is composed by half the
number of data points and is smoothers.
The overall performance is the same, but the line on the left gives a better idea of
how our account would behave.
The difference is even more dramatic when looking at metrics:

Almost every metric shows a different value. For example, the %Profitable tells us
the 84.5% of options are closed at a profit, but only 75% of the strangles. This is an
important difference because it tells us how the loss accumulated on a leg expiring
In the Money is rarely offset by the premium gained on the other leg.
None of the two is “more correct” than the other, the simply carry different
information and both offer valuable information. It’s important that the user
understands the differences and how to use these two variants of the same
method.

What is labelling
Through labelling the user can assign names to different entries. This is used when
we need an extra layer of grouping for position management.

40
www.OptionLAB.ch
Let’s take as an example the implementation of an iron condor. While an iron
condor must obviously be treated a single trade, we may be interested in closing
the upper side independently by the lower one, and vice versa, if certain conditions
are met.
For example, we may want to implement two separated stop losses, but we may
still want to have a performance report calculated in a way that the whole iron
condor is considered a single trade. To accomplish this the user must assign the 4
trades of the iron condor to the same group, but give to the upper side a different
label than that of the lower side.

How labelling works


Entry labels, as group numbers, are assigned at opening stage. The input is the 6th,
just after the group.

As we can see in the image we are assigning a label “UpSide” to this trade.
Let’s see how the strategy discussed in the previous paragraph, rearranged to sell
iron condors instead of strangles, would look like.
All trades are assigned to the same group, but the Call are assigned to the “UpSide”
label while the Put to the “Down” side.

This code will produce a performance report in which all iron condors appear as a
single trade, but the labelling technique allowed us to give separated stop losses to
the two sides of the iron condor. This is achieved with the SetStop function as
shown in line 31 and 32.
The strike prices of the bought options are calculated at line 16 and 19.

41
www.OptionLAB.ch
How to use labelling
As said before, labelling must be used not as a mean of considering multiple trades
as one, but as a mean of managing multiple trades as they were a single one. In the
above example we set an individual stop loss for the two labels. Much more can be
done through labelling, every function that interact with open or closed trades
information can be used in “Label” mode.
In the performance report, in the Trade List, the label will be shown in the column
with header “Entry”, on the right of the “Group” column.

In this screenshot we see the trades belonging to groups 20, 23, 26 and 30 all
divided into two sub-groups “UpSide” and “DownSide” as indicated in the script.

42
www.OptionLAB.ch
12. Fundamental and News Data
Through Option Language the user can code strategies that take advantage of some
fundamental data. Available data include: EPS Report data for stocks, the dates of the Federal
Open Market Committee (FOMC) meetings, and the dates of Non Farm Payrolls data release.

EPS Report Data


EPS data is offered for all available stock symbols.
In order to get an idea of what kind of data can be accessed go to the Contract
Details of a stock symbol and click on EPS Stats:

The following window will open:

All the information shown in this table is accessible through Option Language. As
can be seen in the table the data is divided into 5 sections:
1) Date
2) Underlying Price
3) Underlying Price Variations
4) Implied Volatility Reaction
5) EPS value

43
www.OptionLAB.ch
Let’s see how this data is compiled and to access all this information using Option
Language.

1. Date:
Contrary to what may be expected this is not the date of the release of the
Earning Report. This is, instead, the date in which the price reacts to the EPS
release. Some EPS are released before the opening of markets, in which case
the date of the release and the date of market reaction coincide. Some EPS are
released after markets close. This means that the actual reaction of price will
be the following day.

To get the date of the next EPS Report use the function GetNextEPSDate:

The function returns an OLDate type representing the date of the next EPS
release for the symbol being backtested. The price reaction will occur when
GetNextEPSDate equas the date of the current bar.

To go on with other EPS information we first need to introduce the function


GetEPSInfo. The first input of the GetEPSInfo function, a positive integer, is used to
express how many EPS reports ago you want the information to be retrieved from.
0 means last EPS reports (or current if today is an EPS release day), 1 means second
last, and so on. The second input is a constant representing the needed information.

2. Underlying Price:
We stored underlying price data for all EPS report events. Available data
include: Last Close (market close price of the day before price reaction to EPS)
and Open, Low, High, Close of the day of reaction.
To access underlying price information, use the function GetEPSInfo in the
following way:

3. Underlying Price Variations


To properly analyse price reaction, we have included a measure that makes
price variation comparable over time. First we provide average percentage
variations, that are independent from price magnitude, then we provide the
average proportion between the movement in price, and the volatility of the
previous 22 trading days (standard deviation of price). This calculation is

44
www.OptionLAB.ch
executed on every EPS report date between some price pairs of the 5 provided.
These pairs are:

- Last Close -> Open


- Last Close -> Close
- Open -> Close

When calling GetEPSInfo the user can ask for the average reaction that the price
showed in earlier EPS reports, this is how the user retrieve this information.
First the average of percentage movement:

It is possible to make a distinction between average downward movement


(negatives) and average upward movement (positives) simply by adding “P” for
positives and “N” for negatives in front of the constant name, as follows:

To request the second type of available data, the ratio between price reaction
and the standard deviation of price of the 22 previous trading day, the user
simply adds “SD” at the end of the constant name, as follows:

4. Implied Volatility Reaction


Another interesting measure is the reaction of the implied volatility to EPS
reports, usually reported as Volatility Crash.
45
www.OptionLAB.ch
The user can access the magnitude of the average decrease in implied volatility
for near expiration and far expiration contracts. This is how this data is
retrieved:

AvgVolaCrash1 refers to the average decrease in implied volatility for near


expiration contracts. For weekly data the first weekly expiration with at least 2
remaining trading days is considered. For monthly data the first monthly is
chosen instead.
AvgVolaCrash2 refers to the average decrease in implied volatility for far
expiration contracts. For weekly data the first monthly expiration with at least
30 remaining days is chosen, for monthly data the second monthly expiration,
with at least 22 available days is chosen instead.
The average decrease in implied volatility is expressed in basis point, so that a
decrease from 30% to 15%, would result in a measure of 15.0.

5. EPS Value
It is possible to retrieve the value of the current and last EPS data. This
information is retrieved as follows:

46
www.OptionLAB.ch
13. TradeStation Integration Functionalities
In Option Language there is no functionality to trade the underlying instrument
directly.
We decided not to do so because other platforms, such as TradeStation, offer a
complete set of features for this task.
We chose to introduce some integration functionalities that would allow the user
to implement hybrid strategies using Trade Station.
The integration with Trade Station is structured in three ways. Let’s see them one
by one.

Equity Line Import


This feature was discussed in detail at 10. Our first Backtest - Perfromance Report
– Tools.
It allows the user to import an equity line generated by a trading system in Trade
Station. It Is used to combine two trading systems: one on Options and one on the
underlying or another instrument.

Naked Shorts Hedging


A strategy may implement the sale of naked options. This carries an undefined risk
that can be capped by trading the underlying.
If we sell a naked out of the money option, the system will generate a profit if the
option expires out of the money. If the option at maturity is in the money, the buyer
will exercise it and a loss will be realized. The size of the loss depends by the
moneyness at maturity and by the premium that we cashed in when opening the
position.
A possibility, to cap the risk, is to cover the option when the underlying reaches e
certain proximity to the strike price. To do this we would have to tell Trade Station
47
www.OptionLAB.ch
to buy (for calls) or sell (for puts) the underlying for each naked trade using buy and
sell stop orders.
Due to the amount of trades can be generated by an option strategy this is
impractical, so we introduced a code generator that automatically creates the cover
system for us.
After having launched the system, we will have to import its equity line as discussed
in the previous paragraph to see how it would have behaved when used along the
option strategy.
We discussed this functionality in detail in the User’s Guide at chapter 11. TS Code
Generator for Naked Shorts Hedging.

Dynamic Delta Hedging


The user can backtest different Delta Hedged portfolios. A Delta Hedged portfolio
is a portfolio in which market risk is partially or fully hedged using the underlying
asset. To test such a portfolio click on Tools -> Code Generator -> EL Code for Delta
Hedging. This window will show up:

First the user must indicate how often he wants the hedge to be rebalanced. Every
rebalance will carry some costs. Then the hedging logic must be specified, there are
two different logics available:
1) Keep On Target: the delta of the portfolio is keep within boundaries. As soon
as the delta of the Option + Underlying position exits those boundaries it is
brought back to the target delta by adjusting the underlying position. The
boundaries do not have to be symmetrical with respect to the target delta.
2) Hedge After Trigger: this logic works by following the delta of the option only
position. When the value of delta crosses above a certain trigger threshold the
delta hedging functionality is activated. In case the option only position delta
crosses below another threshold, the delta hedge is released. This activation
and deactivation levels are indicated at “Option Position Delta for Hedge
Activation” and “Option Position Delta for Hedge Deactivation”. When delta
48
www.OptionLAB.ch
hedging is active the delta of the overall portfolio (option + underlying) is kept
at the target level, and the underlying position is adjusted every time the
portfolio delta shifts by a certain amount. These inputs are “Target Portfolio
Delta” and “Tolerance Portfolio Delta Step”.

It’s unlikely that an integer number of contracts traded on the underlying will bring
the delta exactly at the target. The User can then specify how he wants the engine
to approximate the contract of the hedging rebalance:
- More Delta: the approximation that brings delta further from 0 is selected
- Less Delta: the approximation that brings delta closer to 0 is selected
- Nearest: the approximation that carries the lowest error is selected

The user must then specify the option multiplier, it will typically be 100 for options
on equities, and 1 for options on futures.

By clicking on “Create Hedge” a new window is shown:

On the left-hand side is shown the Easy Language code of the delta hedging
strategy, on the right-hand side is the data of the instrument on which the delta
hedging strategy must be traded. Once the strategy has been backtested, the equity
line can be imported in the Performance Repot.

The data of the instrument on with to launch the hedging strategy is compiled in
such a way that makes it possible to launch e visualize the evolution of the
underlying position. It is built starting from the raw underlying price data in our
option database, base on settlement prices. The open is always equal to the
previous close. No High or Low information or actual open data is included. We
recommend to only use this data to backtest the hedging strategy, that is
guaranteed to be 100% compatibile.
This is an example of what the backtest will look like:

49
www.OptionLAB.ch
It’s evident how the open of each bar is synthetically build from the close of the last
bar, and how there is no high-low information.
The position is constantly adjusted to match the required delta hedging position.

Easy Language integration functions


Along with the Option Explorer is delivered an .ELD file that can be imported into
Trade Station. Within the ELD are carried functions that are used to bridge Option
Language with Easy Language.
Using these functions, it is possible to trade options using traditional systems.
To see how this functionality works let’s make an example.

This is the traditional strategy we want to implement using options:

Buy when the RSI indicator calculated on 2 periods crosses below 20 and close the
position when it goes back to 40.

Sell short when the RSI indicator calculated on 2 periods crosses above 80 and close
the position when it goes back to 60.

The first part represents an upside bet, the second a downside bet.

50
www.OptionLAB.ch
Here is how this strategy is coded in Easy Language:

The only way to assume an upside exposure, using the underlying futures, is to buy
it. The only way to assume a downside exposure, using the underlying futures, is to
sell short it.
With options there are tens of ways through which the two bets can be
implemented.
We can sell or buy options, call or put, choose between hundreds of different
maturity dates and strike prices and make any combination of multiple contracts.
To explain how to implement this strategy using the functions provided with the
Option Explorer we will assume an upside position selling a Delta 40 put and a
downside position buying an AtM put.
We will close the upside trade according to the described logic, but will let run the
downside trade until maturity.

In order to sell or to buy options one of the following functions have to be used:

1. BuyCall
2. BuyPut
3. SellCall
4. SellPut

The syntax is the same for all 4 functions and is as follow:

Th Strile Price and Maturity can’t be known at TradeStation side, it will be the
Option Explorer, based on the provided parameters to find the needed strike and
maturity.

51
www.OptionLAB.ch
In order to give to the OE the right information it is necessary to call the function
GetStrike and GetMaturity. They pretty much work similarly to how they work in
Option language.

For the GetStrike function available methods are:


1. Nearest
2. Moneyness
3. Delta

Available methods for GetMaturity are:


1. ByPos
2. MinDays

The usage of these methods is analogous to the OE equivalent functions.


The Group and EntryName can be nullified using values -1 and empty string (“”). In
this way no group or entry name is assigned to the trade.
To discuss the input Directory a little explanation of how the integration works is
needed.

Integration Directory
Trade station can’t directly navigate the option database or perform a backtest on
option.
All information about option trades generated by Trade Station (that we call TS
Signals) will have to be written in a .txt file so that the OE can later check what
trades to perform.
Thus, a file have to be created and the path of this file passed to Trade Station.
To do so go to the option explorer main window and click on Info -> Get Useful
Directories -> TS Signal

52
www.OptionLAB.ch
After choosing a name for the file it will be created and the path shown. This path
will have to be copied and pasted in the Trade Station strategy.
The management of the integration file is the very first step to be performed when
implementing an option strategy with Trade Station.
The first 2 lines of all option strategy implemented in Easy Language will have to
look like this:

The actual path copied in the previous step will have to be pasted here.
The Bin variable is only used to store the garbage value forcefully returned by the
integration functions (in Easy Language void functions can’t be implemented).
The ResetFile function have to be called before doing anything else, this function
prepares the file for the test and updates information.

Now that the integration file has been successfully managed it’s time to implement
the core section of the strategy.

Code Example
This was the strategy of our example:

Sell a Put Delta 0.40 option with at least 14 days to maturity when the RSI indicator
calculated on 2 periods crosses below 20 and close the position when it goes back
to 40.

Buy a Put At the Money option with at least 14 days to maturity when the RSI
indicator calculated on 2 periods crosses above 80 and let the trade run until
maturity.

53
www.OptionLAB.ch
This is how the strategy of our example looks like when coded in Trade Station.

As can be seen no exit logic is implemented for the Up Side, in this way the trade
will automatically be closed at maturity.
An exit logic is coded for the Down Side trade at line 12.
The exit function works by closing baskets of trades. Since we didn’t use groups, we
had to use the Entry Name to tell the function which trade to close.
We have passed the value “Down Side”, so only the trade with label “Down Side”
would be closed when this function is called.
“Exit Down Side” is the optional name given to the exit.

This are all possible uses of the Exit function:

After the strategy is launched and calculated, the .txt file is filled with signals, this

is an example of how it should look like when opened:


This file allows the OE to test the strategy that was implemented in Trade Station.
To run this strategy a signal replication system has to be implemented.

54
www.OptionLAB.ch
TS Signal Replication
This is probably the easiest strategy to implement.
On every bar the strategy has to look in the file and execute the Signals available
for that date.
The function TSInputExecute does exactly this.

This is it.

Once the strategy is coded and compiled it has to be launched. To do so go to the


System Launcher and select the strategy just created.
We called it TS Signal Executor.

In the red square are highlighted the input necessary to run a strategy generated
by Trade Station.
Click on Select TS Input File to select the file on which the Signals were written by
Trade Station.

Important: Since the actual test is performed afterward Trade Station can’t know
the current position. This means that every time conditions are met a Signal will be
generate, even if an option resulting by the same entry would still be open.
The Option Explorer is able to ignore signals when the resulting trade would have
the same Entry Name of a currently open trade.
To enable this feature uncheck “Allow Multiple Entries with Same Name” as
squared in blue.

Click Launch and wait for the Performance Report to be generated.

55
www.OptionLAB.ch

You might also like