Trend-following Thinkscript

Updated Sat Aug 27 5:00AM

## Identify Last
def lastBar = BarNumber();
def current = HighestAll(If(IsNaN(close), 0, lastBar));
## Chop Thinkorswim’s MovAvgAdaptive
input mode = {default KAMA, AMA};
def direction;
def volatility;
def ER;
switch (mode) {
case KAMA:
direction = AbsValue(close – close[10]);
volatility = Sum(AbsValue(close – close[1]), 10);
ER = if volatility != 0 then direction / volatility else 0;
case AMA:
direction = Double.NaN;
volatility = Double.NaN;
ER = AbsValue((close – Lowest(low, 10)) –
(Highest(high, 10) – close)) / (Highest(high,
10) – Lowest(low, 10));}
def SlowSF = 0.2222;
def ScaledSF = ER * (0.4 – SlowSF) + SlowSF;
def AMA = CompoundValue(1, AMA[1] + Sqr(ScaledSF) * (close – AMA[1]),
plot MAA = AMA;
MAA.assignvaluecolor(if OHLC4 > AMA then createcolor(38,115,251)
else createcolor(234,33,0));
### Calculate Tangent
def m = Tan(OHLC4 * Double.Pi / 10) – Tan(OHLC4[5] * Double.Pi / 10);
# 7-bar slope line
def lrs = 6 * (WMA(OHLC4,7) – Average(OHLC4,7))/(6);
input fr = No;
def mlr;
if (fr) then {
mlr = InertiaAll(OHLC4);} else {
mlr = InertiaAll(OHLC4,7);}
def dist = HighestAll(AbsValue(mlr – OHLC4));
plot mlrPlot = mlr;
mlrPlot.assignvaluecolor(if m < 0 then else createcolor(25,115,250));
# 20-bar slope line;
def lrs2 = 6 * (WMA(OHLC4, 20) – Average(OHLC4, 20))/(19);
input fr2 = No;
def mlr2;
if (fr2) then {
mlr2 = InertiaAll(OHLC4);} else {
mlr2 = InertiaAll(OHLC4, 20);}
plot mlr2Plot = mlr2;

addlabel(current == lastBar and close > AMA,” Long “,createcolor(38,115,251));
addlabel(current == lastBar and close < AMA,” Short “,createcolor(206,49,56));
assignpricecolor(if close > AMA then createcolor(38,115,251) else createcolor(206,49,56));

07.24.22 | NYU VLab’s Measure of Expected Capital Shortfalls in a Crisis

A Comparative Analysis of Sector Health in the S&P 500

For Friday, every sector had decreases in their liquidity.  All but three showed increases in illiquidity more than 2%.

The NYU V-Lab publishes summary information about the fitted liquidity models for equity sectors. Liquidity is defined as the degree to which an asset can be bought or sold in a market without affecting the asset’s price.

In a crisis, undercapitalized sectors, funded largely with fragile short-term debt, experience capital shortfalls and failures.

Over time, expected market illiquidity has been shown to positively affect ex ante stock excess return, suggesting that expected stock excess return partly represents an illiquidity premium. In addition, stock returns are negatively related over time to contemporaneous unexpected illiquidity. The Amihud illiquidity measure is the average across stocks of the daily ratio of absolute stock return to dollar volume. Illiquidity affects more strongly small firm stocks, thus explaining time series variations in their premiums over time.

07.24.22 | An Algorithm to Tag Significant Changes in Dark Pools’ Trading Volume

Pictured above is output from an algorithm, based on FINRA short sale volume. What follows are images of the trading signals generated by the algorithm, along with an explanation of what the algorithm says about market timing performance by discretionary traders.


  • Dark pool trading has redefined the balance of power in the financial market ecosystem. Institutional investors are endowed with short-lived information and demonstrate proprietary flow.  Trading off exchange can, to a small extent, limit the amount of information that is revealed about intentions of dark subscribers. Moreover, the notion that dark pools are primarily used to shield large orders from information leakage is erroneous.
  • The market share of trading conducted in dark pools has stabilized around 45%.
  • Information about dark volume is informative to equity markets. Dark trading has a spillover effect on liquidity in equity markets.  At the same time, excessive volatility on lit exchanges is linked with a significant loss of market share by dark pools to lit exchanges … known as a “flight to transparency.”
  • “High speed traders” who subscribe to dark pools are known to front-run trades of larger investors, such as mutual and pension funds, by detecting buy and sell orders of the large investors in lit venues and trade accordingly in behalf of their clients.
  • Market share loss has been shown to be driven by the cross-migration of informed and uninformed traders between lit and dark venues.  In research carried out by Ibikunle et al, the author writes, “Informed traders migrate from lit venues to dark venues when lit venues’ volatility becomes excessive, while uninformed traders, wary of the presence of informed traders in dark pools, shift their trading to lit exchanges rather than delay trading in a volatile market environment.”
  • Algorithms teach and conclusions about institutional sentiment can be drawn by examining a model’s output.

What Can Algorithmic Trading Signals Teach Us About Price Discovery?

  • Exceptional volume and expectancy, together, reflect positive and negative expectations by institutional traders. The dark pool index (short volume/total volume) has a high miss rate and does not, by itself, provide reliable entry nor exit signals.  Statistically significant changes in dV/dt perform far better … but the algorithm contributing to these signals is complex and computationally expensive.
  • While single signals often appear well timed, patterns … that is, serial signals reflecting accumulation and distribution show greater persistence.  Take, for example, the signals in UVXY suggesting accumulation between May 26 and June 7..
  • Signals are often seen appearing and reappearing on subsequent days  around certain price levels.  Take, for example, the signals for SQQQ around the 12500 level in NDX.
  • Trades are frequently triggered by wide range intraday auctions … which coincide with surprises … news shocks and corporate earnings revisions.
  • Confluence across sectors:  Signals in leveraged ETPs often appear in multiple assets, simultaneously, on the same day.  Those signals show a tendency toward high predictive value and persistence.
  • During market declines, short signals appear far more frequently than long signals.

Final Notes

  • The model’s trade signals are insufficient, by themselves, to execute trades with confidence.  There is no well-behaved optimal order execution strategy that can be derived from dark volume alone.  Predictive accuracy is increased, however, when combined with index options positioning reflecting changes in sentiment.  In the case of the S&P 500, this is exemplified by considering SPX options dollar net put delta values … in context.  Thus, a system to qualify signals is crucial and understanding the auction market process is essential.
  • Lastly, one size does not fit all.  What appears high and fast with respect to accumulation for one fund … varies across ETPs.


  1. Angel, J., Harris, L.E., & Spatt, C. (2015). Equity Trading in the 21st Century: An Update. Quarterly Journal of Finance, 05, 1-39.
  2. Balakrishnan, K., Taori, P. (2017). Information Asymmetry and Trading in Dark Pools: Evidence From Earnings Announcement and Analyst Recommendation Revisions. Regulation of Financial Institutions eJournal.
  3. Brugler, J.A. (2015). Into the Light: Dark Pool Trading and Intraday Market Quality on the Primary Exchange. Microeconomics: General Equilibrium & Disequilibrium Models of Financial Markets eJournal.
  4. Brummer, C.J. (2015). Disruptive Technology and Securities Regulation. Diffusion of Innovation eJournal.
  5. Gatheral, J., & Schied, A. (2013). Dynamical Models of Market Impact and Algorithms for Order Execution. ERN: Econometric Modeling in Financial Economics (Topic).
  6. Ibikunle, G., & Rzayev, K. (2020). Volatility, Dark Trading and Market Quality: Evidence from the 2020 COVID-19 Pandemic-Driven Market Volatility.
  7. Johnson, K.N. (2017). Regulating Innovation: High Frequency Trading in Dark Pools. Capital Markets: Market Microstructure eJournal.
  8. Kumar, P. (2011). Optimal Execution Size in Algorithmic Trading.
  9. Ngo, C.N., Massacci, F., Kerschbaum, F., & Williams, J. (2021). Practical Witness-Key-Agreement for Blockchain-Based Dark Pools Financial Trading. Financial Cryptography.
  10. Petrescu, M., & Wedow, M. (2017). Dark Pools in European Equity Markets: Emergence, Competition and Implications. ERN: Econometric Studies of Private Equity.
  11. Yan, W. (2020). Essays on dark trading: An experimental asset market approach.
  12. Zaza, K. (2013). A Fiduciary Standard as a Tool for Dark Pool Subscribers.

07.17.22 | Dark Pools Expert System v2.0

Download image


Here is the layout for 16 commodities, each displaying accumulation/distribution flows for the past 3 weeks.

Dark pools transaction volumes account for about 45% of total shares traded.  Frankly, interpreting dark pools short sales data is as much art as science.  For at times, institutions time the market impeccably.  Most of the time, however, institutions buy on the way down and sell into strength, on the way up.  Notwithstanding, this information is invaluable when constructing portfolios that employ tactical asset allocation models.

Accumulating at the writing…

  • Electricity and natural gas:  XEL provides both and has a 10.34% ROE.
  • Grains:  Expect price increases as droughts occur in the face of increasing demand (CORN, WEAT)
  • Lithium:  Demand for EV batteries steadily increasing
  • Copper:  Demand swamping supply and current price extremely undervalued

You get the idea.