Skip to main content

MesoLive development update #1

· 6 min read
MesoLive Banner

Introduction

It’s been a while since we started working on MesoLive - the Live version of MesoSim. It’s a good time to give an update on what has been achieved so far.

Before we dive into the specifics here are the requirements driving the development:

  • MesoLive must become an excellent position, strategy, and account monitor
  • It must support the deployment and management of trading strategies developed in MesoSim
  • It has to be accurate, secure, and affordable

Based on the above requirements MesoLive is not a replica or clone of any other software. It’s a new way of addressing the real pain points of options trading today. 


Position / Strategy / Account Monitoring

State of the art

The majority of time spent in trading is dedicated to monitoring open positions and waiting for Profit Target or Stop Loss to be hit. While brokerages offer the tools (TWS by IBKR, ThinkOrSwim, or TastyTrade’s app) which display live positions and certain risk metrics, they lack the following functionalities:

  • Organizing Legs into Positions
  • Assigning Positions to Strategies
  • Tracking Position and Strategy PnL and Greeks over time

The most frequently used analytical tool for Options Trade by retail users - OptionNet Explorer (ONE) - bridges some of the gaps, but it still falls short on the following points:

  • Moving legs around is cumbersome:
    One needs to specify trade details (such as entry price and commission) manually.

  • Low-resolution PnL chart on a strategy level:
    Just the realized PnL is shown, but intra-trade drawdowns and quantitative metrics are missing.

  • Limited information on Greeks:

    • Historical charts of greeks over time are absent.
    • Greeks are shown only at T+0 and not projected to the future.

Therefore, people (including us) often track their trades not just in ONE, but in a tracker Excel or Google Sheets. This approach works but takes a lot of time to administer.

MesoLive’s approach

With MesoLive we are addressing the above pain points by

  1. Automatically Tracking Positions, Executions, and Account information, eliminating the need for manual entry of fills
  2. Combining legs on the fly to make up a positions
  3. Assigned positions to Strategies
  4. Collecting Position, Strategy, and Account level PnLs and Greeks frequently (every minute)
MesoLive Accounts Overview
MesoLive Strategies Overview
MesoLive Position Monitor Grid
MesoLive Position Monitor

To fully address the “Limited information on Greeks” part we utilize 3D charts to display the changes in Greeks and PnL throughout the trades lifecycle. These graphs are useful to better understand the trade characteristics of position.

MesoLive 3D Risk Graph - Theta
MesoLive 3D Risk Graph - WVega
MesoLive 3D Risk Graph - Gamma
MesoLive 3D Risk Graph - Delta

For open positions we show the PnL for both At Bid/Ask and at the Mark/Mid price level.

info

The monitoring capability of MesoLive is still a Work in Progress, but we believe it is already providing value compared to the currently existing solutions. 


Execution

Some might think that once a trade plan is made the hardest part is over. While this is true, our experience shows that a lot of risk is present during execution. Sometimes it is hard to precisely follow the trade plan, due to:

  • Time constraints: you might not always be available to enter / exit or adjust
  • Mistakes: wrong contract selection can happen even with the best
  • Negligence: hopium is a hard drug

These points will be addressed by MesoLive by taking MesoSim’s Job Definition and turning a backtest into a live trading job. We still believe that a full hands-off mode is risky with options trading, therefore it is not our goal to develop a fully automated system here. We might revisit this decision later.

The workflow we propose for executions (Entry / Adjustment / Exit) is as follows:

  • Initiated from MesoLive
  • Legs are automatically selected, and order is prepared
  • Order is reviewed and submitted by the user

This part of MesoLive is not ready yet, but it is the next big work item in our roadmap.

We’ll take an iterative approach: Exits, Entries then finally Adjustments will be implemented.


Accuracy, Security, and Costs

While the three items in the heading seem distinctly related, they are actually defining our software architecture. Here is why:

  • Realtime data is expensive, especially for professionals and businesses.
    Delayed data is unfeasible for trading, unless you do “buy and hold with monthly rebalances” type of strategy.

    While it would be easy and pleasant to develop a solution using data feeds from Exchanges or Data Vendors, it would make the price of the offering unfeasible for retail.

  • Security is of very high priority when it comes to handling money.
    Storing access keys to brokerage accounts comes with risks we wish not to take.
    Additionally, the user must be in full control at all times managing their account.

Both of the points above are addressed with our model:

We’ve created an Agent application that is run by the user providing a bridge between their brokerage account, live data stream, and our system. The Agent is certified by trusted software vendors, such as Microsoft and Apple. The Agent uses secure communication channels with tamper-proof keys to bring in account and realtime data to our systems. It is resilient to network failures and uses minimal system resources. The user is in full control of running this application.


Availability and price

MesoLive has been undergoing private beta for some time now with IBKR accounts.

We’re onboarding customers have shown interest in small groups on a weekly basis.

info

Currently, IBKR TWS is the only supported platform; additional brokerages may be supported later.

We consider the Position Monitor part to be 80% ready and expect to start the execution-related tasks immediately. As MesoSim provides a rich set of tools, reaching feature parity between Sim and Live is likely to be some quarters ahead.Since the offering is fairly resource intensive it will not be free.

We are continuously improving its performance so that it can operate in a cost-effective manner. Therefore, it would be too early to put a price tag on the offering.

As MesoLive in its full form will take MesoSim Jobs to Live, it makes sense to consider it as a paid add-on to MesoSim. We might or might not release the monitoring part as a separate solution later. Execution without access to MesoSim plan is a definite no from our standpoint.

Advanced MesoSim Patterns pt. 1

· 7 min read
cauliflower

The Lua Script engine in MesoSim empowers our users to dynamically set simulator parameters. Due to the exceptional flexibility we are proud to call our Job Definition a Domain Specific Language (DSL) for Options Trading

In this post we will showcase some of the more complex setups that can be used to create more dynamic strategies.


Calculations using VarDefines

The VarDefines section has been present since the early days of MesoSim and has become one of the cornerstones of strategy analysis. You can define and update variables on Entry, Adjustment, Exit, and at any point in time using the UpdateVarsAdjustment. 

Daily PnL

If you would like to track the daily profit and loss for your positions you can do so by setting up and updating two variables:

  1. pnl_until_yesterday: tracking the PnL until yesterday
  2. daily_pnl: capturing today's profit.

Later, these variables can be analyzed using the DataVoyager ('Analyze' tab).

Use Entry.VarDefines to set the initial state of the variables:

  "Entry": {
...
"VarDefines": {
"pnl_until_yesterday": "0",
"daily_pnl": "0"
},
...
}

Then set UpdateVarsAdjustment to calculate the daily PnL:

"Adjustment": {
...,
"ConditionalAdjustments": {
"true -- execute always": {
"UpdateVarsAdjustment": {
"VarDefines": {
"daily_pnl": "pos_pnl - pnl_until_yesterday",
"pnl_until_yesterday": "pos_pnl"
}
}
}
},
"MaxAdjustmentCount": null
}

Example run: https://portal.deltaray.io/backtests/5ca7ee68-93bc-42b6-94c7-fdc0f3dcb92d

Trailing Stop

We already dedicated a full blog post to Trailing Stop, which helped a sideways strategy to become profitable. Here is a quick refresher:

  • We keep track of the highest profit achieved by a position (high watermark) using UpdateVarsAdjustment.
  • We exit whenever the current position's profit becomes less than x% of the high watermark.

Example run: https://portal.deltaray.io/backtests/b9aff006-60fb-49dc-9a71-9737dd380395

For all the details please check out the Improving Volatility Risk Premium with Trailing Stops blog post.

Maximum Favorable and Adverse Excursion

[Contributed by Rafael M - Thank you!]

MFE and MAE are often used to study the trade's potential.These metrics capture the maximum amount of loss and profit experienced by a trade during it's lifecycle.

Calculating these metrics requires us to keep two variables (MAE and MFE) updated throughout the position. Similar to the High Watermark in a Trailing Stop, the variables should be updated conditionally: whenever a new high or low is reached.

Rafael has chosen to do the conditional variable setting using Lua Ternary operator (more on this later):

    "ConditionalAdjustments": {
"true -- execute always": {
"UpdateVarsAdjustment": {
"VarDefines": {
"MFE": "(pos_pnl - MFE > 0) and pos_pnl or MFE",
"MAE": "(pos_pnl - MAE < 0) and pos_pnl or MAE"
}
}
}
},

Example run: https://portal.deltaray.io/backtests/cdf03e3e-cd80-4705-b609-4047f0ad54ac

Higher order greeks with Black Scholes

[ Motivated by Carlos P - Thank you! ]

MesoSim provides the five common Greeks (delta, gamma, theta, vega, rho) as well as  Weighted Vega out of the box. What if you would like to use other higher-order Greeks, such as Vomma, Speed, or Charm?

These metrics can be calculated easily using the VarDefines section in Entry, Adjustment, and Exit. Let's take Vomma as an example:

  "Entry": {
...
"VarDefines": {
"S": "underlying_price",
"K": "leg_short_put_strike",
"r": "0.045",
"v": "leg_short_put_iv",
"t": "leg_short_put_dte/365",
"q": "0",
"d1": "((log(S / K) + (r - q + 0.5*v*v)*t)) / (v*sqrt(t))",
"d2": "d1 - v * sqrt(t)",
"vomma": "(leg_short_put_vega * d1*d2) / v"
},
...
}

In this example, we're leveraging that VarDefines are evaluated in order of appearance. With sequential evaluation, we can refer to previously set variables in our calculations.

Example run: https://portal.deltaray.io/backtests/864241b3-33e6-41f6-8010-e3c358a1d9e8


Marking legs for later entry

Some strategies, like the Black Swan Hedge by Ron Bertino, rely on the market state at initiation to construct the full trade structure at a later time. To support this setup we introduced the concept of 'marker leg', which captures the initial state for a subsequently added leg.

Marker legs can be created by specifying Qty=0 at entry:

"Legs": [
...
{
"Name": "long_put_marker",
"Qty": "0",
"ExpirationName": "exp1",
"StrikeSelector": {
"Delta": "15"
}
}
]

Later, the variables associated with the marker leg can be used to enter the real leg when the conditions become favorable. For example:

Enter short_put and mark long_put at a specific delta. Enter when the marker long_put price becomes less than the credit received for short_put leg.

    "ConditionalAdjustments": {
"open_trades_cnt == 2 and leg_long_put_marker_price < short_put_entry_price": {
"AddLegsAdjustment": {
"Legs": [
{
"Name": "long_put",
"Qty": "1",
"ExpirationName": "exp1",
"StrikeSelector": {
"Statement": "leg_long_put_marker_strike"
},
"OptionType": "Put"
}
]
}
}
}
important

You need to set the LegSelectionConstraint (in SimSettings) to None for this approach to work.

Example run: https://portal.deltaray.io/backtests/af590e6d-792f-44d4-8394-49f817b506ab

note

That the Black Swan Hedge is a proprietary trade and therefore it is not shared here. The above run just shows the required building blocks to build the BSH.


If - Then - Else in Statements

Probably the most frequently asked question by our seasoned users:"Can I specify a variable conditionally?"

The answer is yes, using Lua's ternary operator.

Consider the following example:

We would like to target $100 as a Profit target in the first 10 days of the trade, then after the 11th day in trade, we reduce our Profit Target to $50.

In Lua the if-then-else type of constructs can be expressed using the ternary semantics:

(condition) and (statement-for-true-condition) or (statement-for-false-condition) 

Expressing the above example in Exit.Conditions:

  "Exit": {
...
"Conditions": [
"(days_in_trade <= 10) and (pos_pnl >= 100) or (pos_pnl >= 50)"
]
}

Example run: https://portal.deltaray.io/backtests/82a87cba-96b2-48e1-aed9-a7058e43cc5a

Ternary operator is probably the most versatile construct. It allows you for example to select deltas based on other variables (indicators, internal or external data), enter or exit conditionally.


Randomizing trading schedule

With version v2.10 we converted all the fields in the job definition to Lua Statements. Doing so you are now allowed to change the Schedule programmatically and create schedules dynamically. 

As part of strategy robustness test it might be useful to know how your strategy performs if you enter / exit / adjust different times of the day. This can easily be achieved by setting the respective Schedule to random:

    "Schedule": {
"AfterMarketOpenMinutes": null,
"BeforeMarketCloseMinutes": "random(30, 210)",
"Every": "day"
},

The statement random(30, 210) instructs the Script Engine to draw a random number from the range of 30 to 210. We use 210 minutes here to support early closes of the exchange.

With this approach, you just need to run your strategy a couple of times and see how its performance changes with the randomized schedules. This approach is also useful if you would encounter any Missing Data related problems in your runs.

Example run: https://portal.deltaray.io/backtests/3875f455-0639-4463-8b8c-9077acc03624


Processing Event Log for custom analysis

Our users with a paid subscription are capable of extracting Event Logs and OptionNet Explorer exports from runs. The Event Log is particularly interesting if you would like to roll your own analytics as it captures the simulation state in every processing step. 

[ Contributed by Brent P - Thank you! ]

To study how Event Log processing can be done we recommend taking a look at Brent's mesosim-stuff repository. It contains post-processers for events and NAVs:

  • NAV Combiner to see performance profile of multiple runs combined
  • Hedging power studies for various long puts
  • PnL by entry to see if vega/theta/delta/rho drives the final PnL
  • Delta Hedging using SPX prices (needs modification)

Final words

We hope the above patterns will help your studies related to Options Backtesting in MesoSim.

Introducing Q-API

· 2 min read

At Deltaray we are committed to providing retail traders and institutions tools that help them make informed trading decisions. As part of this initiative, we are releasing a Free API today, which provides access to some of the building blocks of MesoSim and MesoLive.


Q stands for Quantitative

In trading, the ultimate goal is to increase your capital while minimizing the risk to an acceptable level. Measuring risk is a complicated process. Even the simplest risk metric - Max Drawdown - requires you to keep track of the highs and lows in a rolling manner. When evaluating strategy performance, it is advised to study the Risk-Adjusted Return (e.g., Sharpe or Sortino), which takes both returns and drawdowns into account.

QuantStats

In MesoSim and MesoLive we are using Ran Aroussi's excellent QuantStats library to calculate quantitative metrics and create portfolio analytics tearsheets. 

Tear Sheet Example Page 1
Tear Sheet Example Page 3
Tear Sheet Example Page 2

With Q-API we are releasing the tearsheet generation and risk metrics calculation free for personal use. These functionalities are available using the following endpoints:

/quantstats/v1/tearsheet-from-json
/quantstats/v1/tearsheet-from-csv
/quantstats/v1/metrics-from-json
/quantstats/v1/metrics-from-csv

Both endpoints require the user to provide the Strategy Performance and a Benchmark Price (such as ^SPX) as time-series. 

Market Calendar

It's important to know when we can engage in a particular activity we're interested in. This holds true for trading as well; it's essential to be aware of the market's opening and closing times, including early closures.

Q-API enables the users to access this information using the /market-calendar/v1/trading-hours endpoint. Our trading calendar's historical data dates back to 1998. 

On the roadmap

We plan to expand Q-API's functionality, including (but not limited to):

  • Position sizing via Kelly Criterion (Formula)
  • Options Pricers
  • Additional market data

Note on MesoSim API

MesoSim API is currently available to institutional clients only.Therefore, Q-API does not include access to MesoSim's API.


Start using it Today

Head to Q-API and begin using it today.You can leverage the Swagger-UI to explore and try the API.

The Weekend Effect

· 5 min read

In our next post in the series of options trading strategies on the public domain, we are presenting the Weekend Effect.

This trade (and others) has been discussed in detail in Euan Sinclair’s Positional Option Trading (Wiley, 2020) book. We highly recommend reading Euan’s books as he provides practical guidance on Options Trading in great detail. 

Euan Sinclair Positional Option Trading - Front Cover
Euan Sinclair Positional Option Trading - Back Cover

Overview

The Weekend Effect in options refers to the tendency of options prices to decrease more over the weekend than in their respective weekday period.

Traders aware of the weekend effect can potentially profit by selling short-term options on Friday and buying them back on Monday at a lower price.

However, this strategy also comes with risks, such as unexpected market events that could cause a significant change in option prices over the weekend. Therefore, it is strongly suggested (mandatory) to pair this trade with a hedge. We will cover hedging strategies in a later article.

The validity of this hypothesis can be evaluated using MesoSim through a series of straightforward tests, which we are undertaking in the subsequent section of this article.


Trade Rules

The original trading rule is defined in Euan Sinclair’s book:

"On a Friday, sell the options that expire the next Monday."

Based on this guidance, our backtest trading rules are as follows:

  • Find next Monday's or Tuesday's expiration
  • Enter trades using the chosen expiration on Friday, 15 minutes before close
  • Exit trades on Monday or Tuesday, 15 minutes after the open
note

The Tuesday expiration selection and Exit rules are present so that we can cover long weekends. In case of normal weekends, the Monday expiration and exit should be used. 

For demonstrational purposes, we will be using short puts and strangles to showcase this trade. It should be noted though, that the strategy should work with more complex structures, such as butterflies and iron condors.


Short Put version

Job Definition

We set the strategy to enter a position on a Friday and exit on Monday by using the following conditions in the Job Definition.

In the Expirations section, we specify that expirations will be selected between three and four DTEs, targeting 3. This enables trades entered on Friday and kept until Monday or Tuesday (in case of a long weekend).

"Expirations": [
{
"Name": "exp",
"DTE": "3",
"Min": “3”,
"Max": “4”,
"Roots": null
}
]

The Entry schedule is set to enter the trade each Friday 15 minutes before market close, and the Exit set to exit the trade the next trading day, 15 minutes after the market opens.

"Entry": {
"Schedule": {
"BeforeMarketCloseMinutes": "15",
"Every": "fri"
},
...
},
"Exit": {
"Schedule": {
"AfterMarketOpenMinutes": "15",
"Every": "day"
},
"MaxDaysInTrade": "1",
...
},

The Strike Selection is done based on Delta, we simply pick a 10 delta put to avoid selling tail risk.

"Legs": [
{
"Name": "short_put",
"Qty": "-1",
"ExpirationName": "exp",
"StrikeSelector": {
"Min": "5",
"Max": "15",
"Delta": "10"
},
"OptionType": "Put"
}
]

Backtest results: 2016 - 2022

Short Put - Friday to Monday

Weekend Effect Short Put Backtest 2016-2022
warning

While we reduced the time spent in the market the returns are outperforming a simple S&P buy-and-hold strategy with a great margin: CAGR is doubled while the Max Drawdown stayed the same.

The full run with all the statistics is available at the following link: https://portal.deltaray.io/backtests/755c4562-b166-490b-9295-74c36d56dc21

Short Put -  Weekday version

To validate the existence of weekend premium, we modify the backtest’s entry and exit schedule to run to cover the opposite timeframe: Mondays to Fridays (4 DTE short put). 

The strategy multiple times has drawdowns above 50%, including (but not limited to) the Covid crash period. 

Weekdays Short Put Backtest 2016-2022

Backtest URL: https://portal.deltaray.io/backtests/7f95f66e-f1be-4e8a-a524-d30f92229e71

Short strangle

While the Short Put setup meets the Weekend Effect's instructions (sell options on Friday) and shows the effect in its purest form, it is possible to improve the strategy by selling more options: 

If we sell Calls as well as Puts we end up having a Short Strangle structure. The collected premium is increased, therefore we expect larger returns. Since there is more risk on the downside, selling Calls likely won't increase our risk exposure.

Weekend Effect Short Strangle Backtest 2016-2022

Backtest URL: https://portal.deltaray.io/backtests/e1b98b9c-cbb2-43f0-8abb-78ad1384e71f

info
  • CAGR: 21.14% (Improved)
  • Max Drawdown: -30.07% (Improved)
  • Sharpe: 1.02 (slightly decreased due to higher volatility)

Backtest results: 2023

Finally, we run the Short Put and Short Strangle trades for the Weekend Effect in the most recent period: 2023. The results speak for themselves:

Weekend Effect Short Strangle Backtest 2023
Weekend Effect Short Put Backtest 2023

Conclusion and further work

Our analysis confirms the significance of the Weekend Effect when the strategy is backtested on S&P Index Options (SPX). Not surprisingly, the Strategy suffers its largest drawdowns during crash situations, such as COVID. Therefore, this (and any other option selling strategy) should be traded when adequate hedging is in place.

We would like to thank Euan Sinclair for spreading his knowledge via his excellent books and courses! 

The Short Strangle version of the Weekend Effect is available in MesoSim as a built-in template, named: [WeekendEffect]

Improving Volatility Risk Premium with Trailing Stops

· 4 min read

Overview

Writing options is a common and straightforward method for generating income from derivatives, often referred to as Volatility Risk Premium (VRP) harvesting.

Selling put options is akin to operating an insurance business:

the option seller is rewarded with the premium (option price) in exchange for taking the risk of assignment if the market moves below the strike price at expiration.

This simple strategy can be highly profitable in bull markets, but it can result in significant losses during bear markets and sudden down moves.

SPX Short Put Bull Market Simulation
SPX Short Put Bear Market Simulation

Simulating Option Writing on SPX

MesoSim was created to study options trading strategies. It offers numerous built-in templates demonstrating key features as well as ready-to-use strategies. 

For simulating Option Writing, we will utilize the [SPX-ShortPut] built-in template.

The above screenshots capture the overview of two runs for different time periods:


Trailing Stops

In general

Trailing Stops are well known to equity, futures and options traders alike. The idea is simple: As the profit increases we store the highest profit achieved (high watermark) and create a stop order relative to the high watermark. This way, our stop loss will not be fixed, but it will continuously move higher as the strategy gains.

Programatically it can be described as:

  1. At entry:
    Set pnl_high_watermark to 0.

  2. When current_pnl > pnl_high_watermark:
    Set pnl_high_watermark to current_pnl.

  3. When current_pnl < pnl_high_watermark * x%:
    Exit the position.

Implementing in MesoSim

To explore how a trailing stop could enhance a trading strategy - such as option writing-  in different market conditions, we will implement it in MesoSim. The above logic can be translated into a Job Definition as follows:

  1. At entry initialize pnl_high_watermark variable to 0:
"Entry": {
...
"VarDefines": {
"pnl_high_watermark": "0"
}
},
  1. Increase pnl_high_watermark when we reach a new high of pnl:
"Adjustment": {
...
"ConditionalAdjustments": {
"pos_pnl > pnl_high_watermark -- record new high watermark": {
"UpdateVarsAdjustment": {
"VarDefines": {
"pnl_high_watermark": "pos_pnl"
}
}
}
}
},
  1. Exit when the current pnl falls below the 75% of the high watermark:
"Exit": {
...
"Conditions": [
"pos_pnl < (pnl_high_watermark * 0.75) -- Exit if pnl drops 25pct from high water mark"
]
},

Trailing Stop with SPX Short Put results

Incorporating the trailing stop snippets into the Short Put template and re-running the tests produces the following results:

SPX Trailing Stop Bull Market Simulation
SPX Trailing Stop Bear Market Simulation

The above runs can be accessed in the following URLs:


Summarizing the results

When comparing the original Short Put runs with the Trailing Stop version, we can conclude that the trailing stop signifficantly improved the strategy performance in Bear market. In contrast, the results in bull market became more modest, although it remains fairly good (with a sharpe ratio around 2).

SPX Trailing Stop vs Short Put Comparison

Conclusion

Trailing stop is a dynamic approach to increase strategy performance. It has proven to be beneficial for the simple SPX Put Writing strategy by locking in gains without sacrificing much upside potential. 

Someone interested in this approach should try different relative ranges from the high watermark to see how it affects her strategy performance.