SMART - Error X occurred at disk power-on lifetime

I was setting up a Debian server with all SSDs and I kept getting a strange error that caused mdadm to not be able to flush data which made the entire system lock up.

I decided to check the SMART log and I saw a strange error. All of the SMART attributes are good with no reallocated sectors. I’m using all Intel SSDs and I’ve never had a problem with them until this one.

The error does not appear to be the drive itself as I tested another Intel 730 SSD and even moved a known good drive to the port and it still ocurred. It’s actually a problem with the cable. Most likely it was just loose and not making perfect contact with the SATA port on the motherboard. I moved the cables around and I have yet to see it happen again.

One strange thing is the other 730 drive I tested already had a bunch of these errors. I do not recall having issues with it so maybe it was from unplugging it while it was on?

As you can see I also ran an extended SMART test and it passed just fine.

TL;DR Check the SATA cable and reseat it.

SMART (Intel 730 240 GB)

SMART (Intel 730 480 GB)

Docker - MSSQL 2017

Microsoft has released MSSQL for Linux and they even released a docker container for it. This makes things pretty straight forward to get running.

There are some issues with ZFS datasets because ZFS does not support O_DIRECT. There’s a hack to get it working but it did not for me. It works fine with ext4 though.

  1. Download the container.

    • docker pull
  2. Configure the systemd server. Change your SA password and the persistent database path (mine is /mnt/db).

    • /etc/systemd/system/mssql.service
    • 1
      ExecStartPre=/usr/bin/docker pull
      ExecStart=/usr/bin/docker run --rm -e ACCEPT_EULA=Y -e SA_PASSWORD=PASSWORD -e MSSQL_PID=Express -p 1433:1433 --name mssql -v /mnt/db:/var/opt/mssql
      ExecStop=/usr/bin/docker stop mssql
  3. Use a Windows PC to access the database using SQL Server Management Studio.

Trading Update - 5

Update 6 - Live
Update 4 - Bull Flag 1 Results
Update 3 - Bull Flag 1 Trades

This algorithm is slightly modified compared to the update 3 post. Since the beta version of the TWS API contains better filters, I’m now using those instead of basic volume/market cap filters. I’ll try to upload them to YouTube, but if it’s anything like last time it’s just boring trades that get stopped out.

Three trades today. Two wins and one break even trade. There may have been trades prior to these but this is when I got the scans and algo setup correctly.

$CLVS 5m/1m candles

Forgot to add this Greek shipping stock to the ignore list.

$PXS 5m/1m candles

Break even. Spreads were really bad on this one. Almost hit the target before getting stopped out.

$HUYA 5m/1m candles

No trades. Yesterday was crazy and now Friday is pretty boring. I had some issues with my TWS layout around 11:30 so it was not watching for about 30 minutes.

Basically nothing moving today. Market is pretty dead. Could be the upcoming election or the tarrifs.

It tried to take $GALT but it wouldn’t have gotten filled at 5.78, so I moved the order up. Tiny move to 5.89 then it started to dump. I’m not counting this one because the spreads would have made it cancel the order.

$GALT 5m/1m candles

No trades. Hopefully something happens tomorrow after the election results are in.

There were a few things moving finally but nothing crazy. $SEND made a huge move on earnings but I looked at the daily and didn’t see big volume while it was flagging. I backtested it and it won but no trades because the market cap is 1.6B (scan limit is 750M). No trades.

I was messing with the scans for a few hours so it made a bad trade on $SGMS which is not a low market cap. I then got the scans dialed in better and it traded $LCI for a win. I should probably start the test over with the new filters. I think IB removed the “shares outstanding” scan because it’s not there anymore in the parameters. I wish they had a float filter because that would narrow it down significantly.

This one actually hit the non-weak market target, but I moved it down not expecting it to run that much.

$LCI 5m/1m candles

No trades. Very boring day. It wasn’t even watching any stocks until 10:00 AM because everything sold off.

Weak again. I really needed to dip buy $AMD at $19.00 so I logged into my live account and put some orders out. Algo was watching like 8 stocks by 10:30 so I doubt there was anything happening today.

It’s just getting boring now so I’m running it on my live account but as read-only so it logs the trades but won’t be able to place them. I need to be able to make trades if I see something good instead of just paper trading it. I sold my small $AMD position today since it got a $1 run and I didn’t want to bag hold if it dumped. I have an order to rebuy at $19 again.

No trades.

Tried to take a trade on $SWCH but no fill. Order was canceled.

Finally a trade and it somewhat worked. Unfortunately, it was $NBEV so it usually stuffs. Small move up to $4.50 then it dumped and got out break even. I’m adding a whole/half dollar top check because things like that happen often. Any human watching it could determine there was going to be resistance there or by looking at the level 2. I saw a higher number of sellers, then a bunch of sellers came in a penny below once it tapped it.

$NBEV 5m/1m candles

No trades.

No trades.

No trades. A few small caps were strong today unlike the previous few days.

I took a look at $ABIL since it had a perfect 5m flag and the algo didn’t take it. The high of that flag went up more than 1% so it didn’t trade it. Percentages tend to mess with the strategy on lower priced stocks. I added an ATR check just like I did on the “big move” candle. That may increase the number of trades but lately there hasn’t been much going on.

I’ll probably start the test over once I’m satisfied with it. I’d like to get it to a point where I can trust it to make good decisions if I need to step away for a couple minutes.

Starting backtest on $ABIL...
Retrieving intraday candles/ticks...
Retrieving daily candles...
Backtesting 11/21/2018...
[11/21/2018 10:05:00] Entry 52 @ $4.37, target $4.81, stop $4.18 [ Bull Flag ]
Trailing stop: 4.18, 4.40
[11/21/2018 10:10:00] Exit @ $4.82 [ $0.45 ]
Drawdown: $0.41 / -8.76%
Max profit: $0.36 / 7.67%
P/L: $23.40
Gross P/L: $23.40 / $0.00
Commissions: $-2.00
Net P/L: $21.40
Win/Loss: 1 / 0 (100.00% / ∞)
Trades: 1 (1 long, 0 short)
Avg $ win/loss: $23.40 / $0.00
Best/Worst: $23.40 [ Bull Flag ] / $0.00 [ ]

Thanksgiving holiday.

Good setup and I was asleep for this one. It would have been cool to see what happened if it traded something after hours since it was a half day.

I just noticed there was a perfect 5m setup earlier but it did not close high enough so it didn’t meet the requirements. I backtested a few stocks after changing it and didn’t really change much so hopefully going forward it has more trades. I don’t know if that’ll be good or bad.

$OSTK 5m/1m candles

Insane move on $ANY today with lots of other stocks getting halted. I scalped it earlier then the algo took it a little later and I was not expecting it to work. Stop loss ended up being perfect.

$ANY 5m/1m candles

No trades. Pretty boring.

Market bounced really strong today. This is the first flag I’ve seen it take near market close. I have it set to exit the position when it’s after 15:50.

$PYX 5m/1m candles

Traded $ALQA for a loss. It should not have traded this one because it dipped too low off the high. I already have code to check for that but it’s percentage based which ends up not working for all price ranges. I changed this to an ATR check as well.

If those two bottom candles before the entry held a little higher like $3.45 or $3.50 instead of $3.30 it would have been a more valid setup with a higher likelihood of working. Instead, it held lower, so the first candle to make a new high works better as a short unless it has insane volume to carry it.

$ALQA 5m/1m candles

I scalped the crap out of $ADIL earlier so that’s why there’s a lot of trades. This setup is not exactly ideal but it did get a bounce into $5.00 before dumping.

$ADIL 5m/1m candles

These trades seem a little weird to me. On both of them it got filled really low instead of near the high. Could just be the spreads and when it polls the candle data.

$AGE 5m/1m candles

Last trade was on $NTEC. I can’t retrieve the chart in IB, but it was a $1 gain since it chopped around after the flag. Got out because of an exit indicator.

First large cap trade. It shouldn’t have even traded it but due to a scan “bug” it ended up watching it. Setup was perfect so it did work but the entry was too high.

Update: It got in too high because of that ATR check I previously added (dumping too far off the highs). It wasn’t the check itself but because it was checking the wrong index in the ATR array. In fact, it was doing that for every single indicator like EMAs. Luckily, the indicator values would not change too much from each candle so each previous trade would work the same way. Glad I found that bug.

$TWTR 5m/1m candles

Realtime chart data in IB was broken today. After receiving the initial chart data it would no longer update the candles correctly. The bid/ask would not match up with the candle. They did send out a bulletin saying to use directed charts which does work but I can’t find a way to auto select “ARCA”. Anyway, I don’t think this would affect the algorithm since it requests the chart snapshot and not tick updates.

No trades. Market had a nice crash midday.

Stock market is closed.

No trades. Since the market was really wild today I decided to backtest $TQQQ and it ended up taking a perfect flag and it got the full move out of it. I’m adding that to the list to see how it does each day. Could be interesting.

Perfect timing. I added $SQQQ as well and it ended up trading it shortly after $TQQQ had a bear flag. First trade that it was able to ride the 9 EMA up.

(this video managed to get more views than usual due to people learning about inverse ETFs when the market was dumping)

$SQQQ 5m/1m candles

About an hour later it traded $MNTA. It ran enough to put the stop near the whole number, but that unfortunately caused it to get stopped out. I don’t really want to change the stops so I think I need better price targets or the ability to detect exponential moves.

$MNTA 5m/1m candles

Lastly, $DOMO near the close. Out for basically break even. The algo automatically sells when it’s after 15:50.

I did record this one, but I’m not going to upload it because the stock did nothing then it exits at 15:50.

$DOMO 5m/1m candles

Lots of volatility in the overall market with not many stocks up. This setup is not exactly ideal since it had that huge wick and it does not have much volume. Algo sold earlier than the stop because it topped at the half dollar. I think that was right move because it tapped the stop then bounced to the entry afterwards.

$XPER 5m/1m candles

Later it took $INNT but did not get filled so I manually put the orders in. I backtested it had an entry of 2.99 with an exit at 3.02 which is basically what my manual trades reflect.

$INNT 5m/1m candles

Two trades back to back. $SPY was kind of all over the place in the first few minutes so I expected $TWTR to just roll over with it.

$TWTR 5m/1m candles

I thought there was a daily flag setup on this one but I guess not. Basically caught the exact top. Amazing.

$ASNA 5m/1m candles

This setup ended up being perfect but the timing was off. On the 1m there is a perfect ascending triangle that exploded when it finally broke out. You could say that it’s still too extended based on the distance from the 9 EMA, but how many good trades would it remove from the list?

$SFIX 5m/1m candles

This is the 3rd or 4th time it has traded $NBEV and it rarely ever works. I’m adding it to the ignore list.

$NBEV 5m/1m candles

Not an ideal setup. It’s traded a few of these previously because I decided to change the high check from close - open to high - open to see what it would trade. I’m not sure if that change works better or if I should just check to make sure it’s not buying over the high.

$HUYA 5m/1m candles

Not an easy day. Most traders I follow on Twitter are struggling today or red. I decided to sleep.

My algo was watching only 32 stocks today. Usually by end of day it’s at least 50 on a bad day or 80+ on a day where the market is up/moving.

It traded $HUYA again but three times today. First one had a little move then a loss. Second one got the full move for a win. Third another loss. Still positive on this name believe it or not. For this stock it seems like moving stops up really causes a problem. After each entry it ends up being choppy without breaking out quickly.

The last trade it took on this one (top right) is another “not ideal” setup. The stock is not what I’d consider “up” at that point to take a flag trade. The previous two were even though only one really worked.

If you go back to $DOMO, that one is technically OK (I mean look at the candle tops, too perfect) but it was just too close to the close for it to make a move.

$HUYA 5m/1m candles

Next was $SQQQ for a loss. Got a little move then it crashed. I don’t have enough data to know how accurate it is on the overall market so this could just be one of the times it did not work.

$SQQQ 5m/1m candles

The past few days have been pretty boring. Another $HUYA trade and another one for the overall market.

This one shouldn’t have actually been traded because it didn’t get a fill then it tried to re-enter a few minutes later on the next candle. The setup was decent but it just dumped then decided to try buying again.

$HUYA 5m/1m candles

Setup seems OK but the market has been too choppy lately.

$TQQQ 5m/1m candles


I’m thinking about going live on Monday depending on how the market looks. This algo is to the point where it’s able to identify bull flags very well and most of the time when it gets stopped out it could have had a profit. I’ll be managing the trade how I see fit because sometimes it’s just too obvious that it’s about to dump ($SFIX / $HUYA recently).

I was too tired to get up so I didn’t go live. No trades today anyway. I’ll try again tomorrow.

I finally let it trade live. Nothing really going on today though. Could be the holidays or the market being slow / choppy. $MTLS had a perfect 5m flag setup but the volume was too low.

I shut it down early at 12:00 PM since most of the trades occur before that time. If it hasn’t made a trade by then it probably won’t later on. Not worth waiting around all day for it. Besides, it’s only watching 23 stocks which means there’s nothing moving. As I said previously, on good days it’s watching 50 stocks by 10:30 / 11:00.

Let’s see what happens tomorrow.

I wasn’t up today. Fed announcement at 2:00 PM so I wasn’t planning to let it trade. No paper trades before 12:00 so it didn’t matter anyway.

At 1:05 PM it tried to take $WGO but no fill. Slow grind up. It would have exited for a $10 gain due to the maximum hold time being 35 minutes. Not bad.

A little later $MRIN which was a good setup but it was a bit extended to keep going. I think the ideal times are 9:50 to 12:00 then 3:00 until end of day.

I don’t really trust flags to work in this market so I’m hesitent to go live again. If I do then I’ll have to transmit the orders manually to be on the safe side.

This one sort of worked but it dumped first. Probably could have made it all back going long on the candle that broke above VWAP.

$INPX 5m/1m candles

Dumped immediately on the entry. Choppy flag though.

$OSTK 5m/1m candles

I started working on a similar bull flag algo that looks for perfect pennants and bull flags. Both flags have the highs being lower on each candle but with a pennant the lows uptrend. They are slightly different but I think that might work a little better in terms of improving accuracy. If the setup looks perfect more people are able to recognize it and see what’s likely to happen next.

Next week is shorter plus a half day on Monday. Last few weeks have been slow so hopefully next year there will be some better opportunities for flags.

One trade on $PTI today but it couldn’t even get to the target so it had a $1 gain. Not a bad setup besides that giant wick. Just not enough movement. I may experiment with using the 9 EMA as the stop instead so it always trails it up. A lot of the time it gets stopped out due to moving it up to break even and it dumps then runs. It’s a difficult balancing act.

$PTI 5m/1m candles

Half day today. One trade on $MRIN which worked OK but had a double top then dumped. There was actually a deadlock so it didn’t exit until the stop was moved up and it dumped into it. This flag is part of my new pennant algo. It would have still been taken by the original algo.

Market is closed on Christmas then normal trading hours the rest of the week.

$MRIN 5m/1m candles


Insane bounce today. Only one algo trade from the previous bull flag algo. I really don’t think this old algo is going to ever work because it’s not precise enough. Sometimes it gets some huge gains but most of the time it get stopped out.

$CRC 5m/1m candles

Nice move out of $WATT today. Two flags but it only took one of them because the first one broke the high of the flag top and it does not chase. I’ve added code to buy on the dip if it comes back down below the previous candle high.

I actually had it running live but not transmitting orders. I should have just taken the first one on my own when it dipped. If I used the same risk level it would have been perfect.

[12/27/2018 09:50:00] Entry 40 @ $6.45, target $6.98, stop $6.20 [ Bull Flag ]
Trailing stop: 6.20, 6.48, 6.51
[12/27/2018 10:15:00] Exit @ $6.89 [ $0.44 ] (exit indicator)
Drawdown: $0.08 / -1.25%
Max profit: $0.60 / 9.40%
P/L: $17.60
[12/27/2018 10:40:00] Entry 34 @ $7.17, target $7.76, stop $6.88 [ Bull Flag ]
Trailing stop: 6.88, 7.20
[12/27/2018 10:50:00] Exit @ $7.19 [ $0.02 ]
Drawdown: $0.28 / -3.86%
Max profit: $0.25 / 3.45%
P/L: $0.68

$WATT 5m/1m candles

Holidays plus a Friday so it’s watching only 5 stocks by 10:00. I let it trade live until 11:00 but it was only watching 13 stocks by then. Just a really boring day.

I’ve started adding crypto trading support and so far the same bull flag algo appears to work on the hourly chart for Litecoin. I need to optimize it a bit and figure out how to get 1m candles past a few months so I can properly backtest it.

Last day of the year and it’s a half day! Market is closed on the 1st. I’m letting the algo trade the pennant’s live and normal bull flags will be submitted but not transmitted. This gives me the ability to choose which trades it takes.

I’ll be writing another trading year review today like I did for 2017.

No trades today. I’m almost done with the algo order flow for GDAX.


I’ve already been going live but now I’m moving those trades over to a new post. Hopefully we see some nice moves in the first few months of 2019!


I am not a registered financial adviser/broker/anything. Use this information for entertainment/informational purposes only. Any tickers mentioned are not recommendations to buy/sell/or sell short. They are used as examples only.

Please remember that past performance may not be indicative of future results.

Trading Update - 4

Update 5 - Bull Flag 2 Trades
Update 3 - Bull Flag 1 Trades

As I said at the end of the previous update, the market got extremely weak the moment I started logging the trades. The patterns were all pretty good but it just could not get enough out of each one to hit the targets. There were still some solid winners but they were rare. I know this pattern is valid since I’ve seen it get massive wins on multiple occasions. Sometimes it feels like I’m predicting the future, but due to market conditions or the scans I’m using they do not work consistently at the moment.

P/L: $84.42
Wins: 7 46.67%
Losses: 8 53.33%
Break Even: 5 25.00%
Wins + BE: 12 60.00%
Trades: 20


The stats appear pretty bad in my eyes. There are more losers than winners but that doesn’t tell the whole story since the P/L is profitable. If you factor in the fact that 25% of the trades were break even it’s not as bad. Break even means the stock moved up enough (15c) for the algorithm to move the stop to the entry price.

After seeing so many break even trades I added a “weak market” flag that I can toggle. This lowers the price targets and increases the minimum volume required. With this flag set: $NDLS, $QNST, $PYX, $SPAR, $DRYS are all removed. $ACRS becomes a tiny win, $VTVT first flag is a win, second is a loss but the profit is higher, and I can’t test IGC since it has been delisted - most likely the first one would have won and second a win since that’s what happened when it traded it.

This bumps the win rate up to about 65% but there is no way to actually know if that is accurate because the scans are now different. I will need to test the modifications and log them.

I am going to make a few changes to the algo in my next iteration of tests:

  1. Never trade Greece shipping stocks. They are literally always shorts due to all the bag holders from 2016 onward.
  2. Increase minimum scan volume to 500K. This would prevent the $PYX trade and $SPAR. Possibly others.
  3. Add scan filters now that the TWS API has support for it. Trades, volume USD, and shares outstanding (instead of just market cap).
  4. Apply my volume tweak to trade stocks where the pull back volume is a little more than the large move candle.
  5. Enable my “weak market” tweaks which take profit sooner and move the stop so there’s at least 1c of profit after commissions.

Today alone it traded $CLVS (win), $PXS (win), and $HUYA (break even) with the modifications. Not bad so far. I’ll start logging these in a new post.


I am not a registered financial adviser/broker/anything. Use this information for entertainment/informational purposes only. Any tickers mentioned are not recommendations to buy/sell/or sell short. They are used as examples only.

Please remember that past performance may not be indicative of future results.

TWS API - New Scan Filters

In the beta release of the TWS API there are now custom scan filters that you can apply. This functionality mirrors what is available in TWS so now it can all be done through the API. This should make filtering out junk way easier.

To get this you need to apply for the private GitHub repository by signing a form. Eventually this should make its way into the “latest” API version.

Some really important ones:


TWS API Sample Application

Benchmarking KVM/ZFS on Ubuntu 18.04 (raidz2)


  • Xeon E3-1230 V3 @ 3.3GHz (turbo off)
  • 32 GB DDR3 1600 MHz
  • Supermicro X10SLM-F
  • 4 x 1TB Seagate Constellation ES.3 (raidz2)
  • 128 GB Samsung USB 3.1 flash drive (host)
  • vm.swappiness=0 / vm.vfs_cache_pressure=50
  • ksm, hugepages, zwap
  • CFQ scheduler
  • Ubuntu 18.04.1 x64

I redid some of the tests with an mdadm RAID 10 array of 240 GB SSDs and the results were nearly identical. It’s possible the virtio drivers or Windows version I used was causing strange storage performance.

I re-ran none/threads under a Debian 9 host / Server 2008 R2 and the sequential reads/writes are great. 1455 MB/s / 548 MB/s sequentials. Everything else looks good too. Very strange.

I don’t intend to use ZFS for VMs at the moment due to lack of encryption support and some annoyances like Ubuntu not booting half the time because ZFS datasets won’t mount correctly.


  • 4 cores / 4 threads
  • 8 GB RAM
  • 120 GB zvol / qcow2, lz4, relatime
  • virtio
  • No page file, optimize for programs, DEP off
  • Windows Server 2016

I’ll be using CrystalDiskMark (CDM) for benchmarking under Windows.


none / threads

Memory usage spiked up to 30.9 GB and crashed the host while doing the write test.

writeback / threads

Remote desktop died but the test continued. Memory usage kept hitting 17 GB from 12.8 GB.

writethrough / threads

I can immediately tell that this is faster than writeback. The VM started quicker and loaded the server config tool faster. However, the write speeds are absolutely awful. Memory usage was a consistent 12.8 GB during the entire test.

This seems close to what an individual drive is capable of except the sequential writes should be a lot higher. Strange.

directsync / threads

Appears to be really fast just like writethrough. I remember testing this option before with mdadm RAID 10 under a Linux VM and it was extremely slow. With ZFS it appears to be different. Consistent 12.8 GB memory usage as well.

Overall it looks like the performance is slightly worse than writethrough.

unsafe / threads

This is supposedly similar to writeback. However, the OS and programs loaded faster than writeback. Memory usage peaked around 14 GB which is lower than writeback.

none / native

This is the option I use on a production server. I had severe performance issues while doing lots of random I/O in a Linux VM with “threads”.

Memory usage peaked at 30 GB. It slowly came down as it was flushed to disk. Sequential write speeds are that of a single SATA 3 hard drive. Even though it is higher than ‘writethrough’ from above, the test took longer to complete.

So far this option appears to be the best

directsync / native

Took forever to boot. Not worth testing.

qcow2 on dataset

zfs set compression=lz4 local/vms
zfs set xattr=sa local/vms
zfs set recordsize=8K local/vms
qemu-img create -f qcow2 -o preallocation=full server2016.qcow2 120G

none / threads

Not supported.

writethrough / threads

Similar performance to the zvol.

writeback / threads

Reads are half compared to the zvol with writeback. Writes are a little better than a standard hard drive. Memory usage dropped when the write test started. ZFS freeing the cache?

unsafe / threads

Reads are slower than writeback but sequential writes are slightly improved. Windows appears to be snappier using unsafe no matter if it’s a zvol or qcow2 image.


Not supported.


The tests above were conducted using the default cfq scheduler. I will only be testing zvols for this part.


This is usually the best scheduler for SSDs and not spinning disks.

none / native

Ran out of memory. native with no cache does not appear to be safe with limited memory.

writethrough / threads

Sequential reads are a lot higher because the requests are not being re-ordered. Writes do suffer.


unsafe / threads



writethrough / threads

Marginally better than noop. In theory this scheduler should be better suited towards VMs than CFQ when lots of requests are being made.


unsafe / threads

No real difference between noop and deadline for this.



I’m not sure if I got it working correctly. After I enabled the kernel option all of the other schedulers were removed and the VMs were very slow. I’ve used it on Arch before and never noticed anything weird.


unsafe is clearly the fastest and best option if you want speed without caring about data integrity. writeback is fast but it uses more memory.

qcow2 is slower than using a zvol but has some benefits like thin provisioning and being able to specify an exact file name. With zvols they sometimes change on reboot.

writethrough is surprisingly snappy in Windows despite the write tests showing poor performance.

native offers good performance according to CDM however memory usage will peak and slow the performance. This option causes Windows and programs to load slower. Simple benchmarks are not telling the whole story. It may cause the host to crash which means I would not recommend using it.

No matter what option you use, read performance is good with zfs + KVM. It’s always the writes that are the problem.

Trader Workstation - Automatic Start (Paper Trading)

TWS automatically logs out after about 11:45 PM. They recently added an automatic restart feature to the beta release but I have yet to get it working.

Since I am just paper trading to test algorithms I found an AutoHotKey script that will start/reopen TWS and login when the process disappears. I decided to write my own using Powershell so it works on all Windows systems without needing to install something.

$sig = @"
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
public static extern IntPtr FindWindow(String sClassName, String sAppName);
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
public static extern int SetForegroundWindow(int hWnd);
public static extern int SendMessage(int hWnd, int hMsg, int wParam, int lParam);
$fw = Add-Type -Namespace Win32 -Name Funcs -MemberDefinition $sig -PassThru
function Get-TWS {
return Get-Process -Name "tws" -ErrorAction SilentlyContinue
function Start-TWS {
$proc = "C:\Jts\tws.exe"
$app = Get-TWS
if(($app) -eq $null) {
$app = Start-Process -PassThru $proc "username= password="
return $app
if ((Get-TWS) -eq $null) {
$app = Start-TWS
Start-Sleep -s 60
$next = Get-TWS
if ($next.ID -ne $app.ID) {
Stop-Process -Id $next.ID
Start-Sleep -s 30
$hwnd = $fw::FindWindow("SunAwtDialog", "Warning")
if ($hwnd -ne 0) {
$WM_KEYDOWN = 0x0100
$fw::SendMessage($hwnd, $WM_KEYDOWN, $VK_RETURN, 0)

Use task scheduler to start this script when you want it to open. I then start my custom algorithm process about 10 minutes later.

Program/script: powershell.exe
Add arguments: -ExecutionPolicy Bypass <.ps1 script path>

Make sure the trading mode is set to paper inside C:\Jts\jts.ini.


Trading Update - 3

I believe I finally have something usable that trades 5m bull flag setups with high accuracy. I have been letting it paper trade for weeks now and just recently got it to what I’d consider “tradable”. It took months of learning how to code a strategy that would have the proper entries, exits, and stops. Not to mention the numerous bugs that caused it to exit trades too soon or not trade certain flags at all.

I am no longer making modifications to the algo, so from this point forward I plan to log a minimum of 20 paper trades to find out its accuracy and how profitable it is with small positions. If I am satisfied with the results I will then trade my live Interactive Brokers account in the coming weeks. Each trade seems to work in one of two ways: it makes an unbelievable gain that I never thought would work, or it gets stopped out quickly for a small loss.

I will be logging all of the trades it makes below, good or bad. I also plan to record the trades and upload them to YouTube like I have been.

P/L: $84.42
Wins: 7 46.67%
Losses: 8 53.33%
Break Even: 5 40.00%
Wins + BE: 12 60.00%
Trades: 20

Break even trades mean the stock went up at least 15c over the entry and it moved the stop to break even.

These two trades below were made Friday at almost the exact same time and both worked perfectly with it almost catching the exact top both times. Before this day it made a couple mistakes (stopped out due to a bug / trading a setup with terrible volume) but also had some nice gains. The winners were always bigger than the losers despite these issues.

Unfortunately, I was not recording when it made these trades so I can’t show them in real time.

$ATXI 5m/1m candles
$FNKO 5m/1m candles

Week 1 - 10/15/2018
Not a whole lot going on today besides $YGYI having some nice 1m flag setups. It traded $NBEV twice. One loss in the morning and one small gain around noon. Not a great start to the week but the risk/reward is always good. Let’s see what happens tomorrow!

$NBEV 5m/1m candles

$NDLS was very choppy and slow. It got out break even when it spiked into $12.99 and came back down to the entry. No gain or loss on this one. I’m not planning to upload a video of it because the entire flag just went sideways forever until finally breaking over $13.00 after a strong dip.

I manually traded two different flags on $FFHL which was fun. There’s really not a lot going on this week so far. That just means it’ll take longer to get the 20 trades. It’s good because these are worst case scenario trades. Earnings season is coming up so there should be some good opportunities.

New TWS theme in the beta release! I dig it but they need to fix some of the chart bugs and add premarket/after hours shading.

$NDLS 5m/1m candles

Update: I actually see a perfect bull flag on $ALT but it was not traded because the volume on the next candle was higher. I added a separate algo that changes that check. It will now trade them both separately so it will not change the results of this “forward test”. I’ll start logging those tomorrow in a separate spreadsheet.

Yet another boring day. It traded $QNST but was not getting filled so I moved the order up slightly. The stock ended up moving quite a lot but could not get over $14.95 so it sold for break even. If this was real money I would have sold into the first push to that level or dumped it when it made the lower high. This trade and yesterday’s trade could have been winners if I decided to get out before the stop was hit. Not bad I guess.

No video for this one again. It’s just too slow.

$QNST 5m/1m candles

A little later it took a decent flag setup on $HEAR. This stock always has big moves which is nice. Got a little push into $22 then it dumped hard. Algo exited for a $2 gain, but that was with only 25 shares. Not bad. Could have easily been a win if I were managing it.

$HEAR 5m/1m candles

Another slow stock. I’ve seen this exact setup work last week. Unfortunately, this one did not. I think if it managed to get over $3 it would have ran, but I guess there’s just not enough volume. Decent exit since it gave it lots of time and got out on a spike.

$OMED 5m/1m candles

I actually saw a lot of halts late day so small caps might be heating up again. Eventually there will be one where it makes a crazy gain. It has before and it will again. Just grinding for now.

It traded $PYX early in the morning. I’m starting to wonder if this is even going to work now because all the traders are now watching Chinese stocks and ignoring everything else. It’s also not as volatile as it was last week. The setup is perfect but that doesn’t matter. I’ll probably increase the volume requirements in the scan after I get 20 wins/losses. Flags seems to be crappy this entire week so I may need even more than 20 to determine an accurate win/loss ratio. Last week was amazing.

$PYX 5m/1m candles

A few minutes later $ACRS. Decent setup but got stopped out for break even. A little squeeze up to $11.84 which I could have sold into so technically a win if I managed it.

$ACRS 5m/1m candles

This whole week has been rather boring.

It traded $VTVT and got a nice move over $4.00 pretty quickly. However, it was yet another break even trade. I think because small caps are kind of weak (besides the China sector) it’s only able to get 15-20c out of it and dumps quicker so there’s never an exit indicator. Basically what I’d have to do is change the profit target to like +30c / 3% instead of what I have now. That would make all of these break even trades winners. I’ll have to either change it when the markets slow or manage it myself.

It traded it again on the next flag but barely got a move out of it this time. I probably would have sold it right away for a $1 gain or something.

$VTVT 5m/1m candles

Winning percentage is actually decent (72%) if the targets are lower which means there’s usually a move right after it enters. It’s just getting stopped out when it comes back down because the moves they make are generally too weak. I wrote extra code that can be manually toggled for when the market is slow and it’ll have lower targets + move the stop above break even so it will more likely have some gain. I will not have that enabled until I get 20 trades.

Let’s see what happens next week.

Week 2 - 10/22/2018
No trades. I wasn’t here so I don’t really know how the day looked, but it seems like the shipping stocks were hot today.

I was not here again. However, it managed to nail $PTI for a big win like I said it would eventually. Always feels nice to get a big win out of a trade while you’re sleeping.

$PTI 5m/1m candles

Decent setup on this one but ultimately failed. Plenty of time to get out for a small win if I managed it.

$CASI 5m/1m candles

Small pop that I could have sold into. Still seems like small caps are a bit weak. Break even trade.

Traded it again a few candles later just like $VTVT last week. It chopped around for a long time until the algo moved the stop. Got out for a small win which wiped out the previous loss (which would have been a win if I managed it). I’m not quite sure how this didn’t get stopped out despite hitting the stop loss exactly. Maybe it needs to tick below and since previous candles technically went below it so maybe those trades came in late and it never triggered, or maybe at IB it needs a full “tick” below so it needs to hit 1c lower (stop at 3.01, must touch <= 3.00).

$IGC 5m/1m candles

Only 4 more trades and I’ll have 20.

No trades. I wasn’t able to start it until 10:30 so it’s possible it may have taken a trade earlier but we’ll never know.

No trades. At this rate it’s going to take another week.

I really didn’t expect this trade considering the entire market was being really whippy. Hit the target perfectly but for some reason the algo kept moving the stop to break even. I think it’s a rounding bug but that doesn’t matter. 3 more!

$YECO 5m/1m candles

Week 3 - 10/29/2018
No trades.

$VCYT was part of another bull flag algo I modified to trade flags that have a little more volume on the pull back. Spreads were awful so no fill. It did get a decent 20c move so it could have been a win. This will not be counted since it’s a slightly different pattern.

$VCYT 5m/1m candles (no trade)

Couple minutes later it bought $DRYS which is part of the garbage shipping stocks that rarely make moves nowadays. I will probably make it ignore these simply because they never go anywhere but down. I’ll still count this one. I just hate this market right now.

$DRYS 5m/1m candles

Last day of October. I’m hoping next month picks up because this one has been awful.

My separate volume algo tried to buy $DBD but no fill due to crappy spreads. Really nice setup and it would have hit the target too.

No other trades. My volume algo seems to be doing OK if it could get filled.

DBD 5m/1m candles (no trade)

It would trade another shipping stock wouldn’t it. This time $GLBS which is just as bad as $DRYS from earlier. They are permanent shorts for me. Got a decent move from the entry of $10.17 to $10.50. No idea if there was enough time to even exit for a profit. Spreads were horrible.

Later it actually managed to hit the target. Impossible to trade.

$GLBS 5m/1m candles

About 10 minutes later, $SPAR. IB changed the stop orders slightly so it did not get out exactly where it wanted to. There’s a new flag you have to set called OpenClose and it needs to be set to C. It would have been a loss no matter what so that doesn’t matter.

$SPAR 5m/1m candles

20 Trades Later

I finally have 20 trades and the data does not look good for this strategy. The week I wrote this post about testing bull flags the entire market started dropping and got really weak. There were several days where it made no trades at all. The market does appear to be getting a little stronger. I can tell from the number of trades and stocks gapping up in premarket today.


I am not a registered financial adviser/broker/anything. Use this information for entertainment/informational purposes only. Any tickers mentioned are not recommendations to buy/sell/or sell short. They are used as examples only.

Please remember that past performance may not be indicative of future results.

Clean Windows Caches

I wrote a simple PowerShell script that will delete all files/folders inside the temporary file paths. It will also clear the shader cache for AMD GPUs. I set this up to run on every reboot.

$folders = @("C:\Windows\Temp\*", "C:\Windows\Prefetch\*", "C:\Documents and Settings\*\Local Settings\temp\*", "C:\Users\*\AppData\Local\Temp\*", "C:\Users\*\Appdata\Local\Microsoft\Windows\Temporary Internet Files\*", "C:\Users\*\AppData\Local\AMD\DxCache\*", "C:\Users\*\AppData\Local\AMD\GLCache\*")
Remove-Item $folders -force -recurse -ErrorAction SilentlyContinue