💬 Join the Matrix chat, we can get money together.
Beat the capitalists at their own game with ThetaGang 📈

ThetaGang is an IBKR trading bot that started as a basic implementation of "The Wheel" strategy and has grown into a broader, configurable portfolio automation tool. ThetaGang still supports a modified version of The Wheel, and now also includes features like direct share rebalancing, cash management, VIX call hedging, regime-aware rebalancing, and exchange-hours gating.
⚠️ WARNING: Options trading involves substantial risk and is not suitable for all investors. Selling options can result in significant losses, potentially exceeding your initial investment. Selling naked puts has theoretically unlimited downside risk if the underlying asset goes to zero. This is not a "free money" strategy—you are being compensated for taking on real financial risk.
Before using ThetaGang: - Understand that you can lose money, especially in trending or volatile markets - Ensure you have sufficient capital to handle worst-case scenarios - Be prepared to own the underlying securities at potentially unfavorable prices - Consider paper trading first to understand the mechanics and risks - Consult with a financial advisor if you're unsure about the risks
The strategy, as implemented here, is intended to be used to augment a typical index-fund based portfolio with specific asset allocations. The default configuration includes a diversified portfolio with SPY (40%), QQQ (30%), TLT (20%), and smaller positions in individual stocks. This strategy reduces risk, but may also limit gains from big market swings. By reducing risk, one can increase leverage.
ThetaGang is quite configurable, and you can adjust the parameters to suit your
preferences and needs, but the default configuration is designed to be a good
starting point. ThetaGang makes some assumptions about how to run this strategy,
but you can tweak it to your liking by modifying the
thetagang.toml
file.
The main difference between ThetaGang and simply buying and holding index funds is that this script will attempt to harvest volatility by selling options, rather than buying shares directly. This works because implied volatility is typically higher than realized volatility on average. Instead of buying shares, you write puts. This has pros and cons, which are outside the scope of this README.
ThetaGang can also be used in combination with other strategies such as PMCCs,
Zebra, stock replacement, and so forth. For these strategies, however, ThetaGang
will not manage long positions for you. You will need to manage these positions
yourself. ThetaGang will, however, continue to execute the short legs of these
strategies as long as you have the buying power available and set the
appropriate configuration (in particular, by setting
write_when.calculate_net_contracts = true).
If you want to run materially different strategies, it is strongly recommended to use separate IBKR accounts (for example, separate linked sub-accounts) and fund each one independently.
Mixing multiple strategy styles in one account can produce confusing or harmful interactions because ThetaGang decisions are account-level. Buying power usage, position targeting, rebalancing logic, option rolls, cash management, and hedge logic all see the same combined portfolio and can interfere with each other in ways that are hard to reason about.
In practice, one strategy per account is usually the cleanest setup: - Cleaner risk boundaries and capital budgets - Cleaner performance attribution - Fewer unexpected cross-strategy side effects - Easier debugging when behavior is not what you expected
Over time, additional features were added to support different portfolio workflows and risk controls. You can enable or disable them independently via config:
ThetaGang will try to acquire your desired allocation of each stock or ETF according to the weights you specify in the config. To acquire the positions, the script will write puts when conditions are met (config parameters, adequate buying power, acceptable contracts are available, enough shares needed, etc).
ThetaGang will continue to roll any open option positions indefinitely, with the only exception being ITM puts (although this is configurable). Once puts are in the money, they will be ignored until they expire and are exercised (after which you will own the underlying). When rolling puts, the strike of the new contracts are capped at the old strike plus the premium received (to prevent your account from blowing due to over-ratcheting up the buying power usage).
If puts are exercised due to being ITM at expiration, you will own the stock,
and ThetaGang switches from writing puts to writing calls at a strike at least
as high as the average cost of the stock held. To avoid missing out on upward
moves, you can limit the number of calls that are written with
write_when.calls.cap_factor, such as setting this to 0.5 to limit the number
of calls to 50% of the shares held.
Please note: this strategy is based on the assumption that implied volatility is, on average, always higher than realized volatility. In cases where this is not true, this strategy will cause you to lose money.
In the case of deep ITM calls, the bot will prefer to roll the calls to next strike or expiration rather than allowing the underlying to get called away. If you don't have adequate buying power available in your account, it's possible that the options may get exercised instead of rolling forward and the process starts back at the beginning. Please keep in mind this may have tax implications, but that is outside the scope of this README.
In normal usage, you would run the script as a cronjob on a daily, weekly, or monthly basis according to your preferences. Running more frequently than daily is not recommended, but the choice is yours. Some features (like regime-aware rebalancing) assume a daily cadence.

ThetaGang can optionally hedge your account by purchasing VIX calls for the next
month based on specified parameters. The strategy is based on the Cboe VIX Tail
Hedge Index, which you can
read about on the internet. You can enable this feature in thetagang.toml
with:
[vix_call_hedge]
enabled = true
Default values are provided, based on the VXTH index, but you may configure them to your taste. Key parameters include:
[vix_call_hedge]
enabled = true
allocation = 0.01 # 1% of buying power
close_hedges_when_vix_exceeds = 50 # Auto-close at high VIX
ignore_dte = 5 # Don't hedge if expiry within 5 days
See thetagang.toml
for all available options.
Buying VIX calls is not free, and it will create some drag on your portfolio, but in times of extreme volatility–such as the COVID-related 2020 market panic–VIX calls can provide outsized returns.
At the time of writing, interest rates have reached yields that make bonds look attractive. To squeeze a little more juice, thetagang can do some simple cash management by purchasing a fund when you have extra cash. Although you do earn a yield on your cash balance, it's not the juiciest yield you can get, so a little optimization might help you earn 1 or 2 extra pennies to take the edge off your rent payments.
You can enable cash management with:
[cash_management]
enabled = true
fund = "SGOV" # Default short-term treasury ETF
buy_threshold = 0.01 # Buy when cash > 1% of buying power
sell_threshold = 0.005 # Sell when cash < 0.5%
[cash_management.orders]
algo.strategy = "Vwap" # Use VWAP for cash fund orders
This feature uses VWAP (Volume Weighted Average Price) orders by default to
minimize market impact when moving in and out of cash positions. Refer to
thetagang.toml for all the options.
ThetaGang includes several advanced features that provide fine-grained control over your trading strategy:
For symbols where options premiums are insufficient or unavailable, you can enable direct stock purchases for portfolio rebalancing:
[symbols.AAPL]
buy_only_rebalancing = true
buy_only_min_threshold_shares = 10 # Minimum shares to buy
buy_only_min_threshold_amount = 1000 # Minimum dollar amount to buy
This feature is useful for maintaining target allocations in stocks with limited options liquidity or when you want to dollar-cost average into positions.
Regime-aware rebalancing lets you gate share rebalances on a simple regime
filter before acting. It builds a proxy series from the configured symbols’
daily closes, then checks for “choppy/mean-reverting” conditions using
choppiness and efficiency thresholds. If the regime passes, and allocations
drift beyond the soft relative band around target weights (or cash flow moves
all positions in the same direction), it queues share trades to move back
toward targets. A hard relative band acts as a safety rail and triggers even
when the regime filter fails, optionally rebalancing only partway back to
target. A cooldown prevents frequent soft-band rebalances and is based on
recent executions tagged with tg:regime-rebalance. When using this feature,
run the script once per day.
[regime_rebalance]
enabled = true
symbols = ["QQQ", "BTAL"]
lookback_days = 40
soft_band = 0.25 # +/-25% relative drift from target weight
hard_band = 0.50 # +/-50% relative drift from target weight
hard_band_rebalance_fraction = 1.0 # 1.0 = full to target, 0.5 = halfway
cooldown_days = 5
choppiness_min = 3.0
efficiency_max = 0.30
order_history_lookback_days = 30
shares_only = true # disable option writes/rolls while rebalancing
Control when ThetaGang operates relative to market hours:
[exchange_hours]
exchange = "XNYS" # NYSE by default
action_when_closed = "wait" # Options: "wait", "exit", "continue"
delay_after_open = 1800 # Wait 30 minutes after market open
delay_before_close = 1800 # Stop 30 minutes before market close
max_wait_until_open = 3600 # Max wait time if market is closed
Set boundaries for option strikes to prevent writing options at unfavorable prices:
[symbols.SPY.puts]
strike_limit = 400 # Don't write puts above $400
[symbols.SPY.calls]
strike_limit = 450 # Don't write calls below $450
Use standard deviation-based thresholds instead of fixed percentages:
[constants]
write_threshold_sigma = 1.0 # Write when 1 standard deviation from current price
[symbols.QQQ.puts]
write_threshold_sigma = 1.5 # More conservative for this symbol
When specified, sigma thresholds override regular write_threshold values.
Prevent rolling calls to lower strikes:
[roll_when.calls]
maintain_high_water_mark = true
Automatically close positions when suitable roll contracts aren't available:
[roll_when]
close_if_unable_to_roll = true
Automatically adjust limit orders after initial delay:
[symbols.SPY]
adjust_price_after_delay = true # Adjusts to midpoint after delay
Customize order execution algorithms:
[orders.algo]
strategy = "Adaptive"
params.priority = "Patient" # Options: "Urgent", "Normal", "Patient"
Enable for spread strategies (PMCCs, calendars):
[write_when]
calculate_net_contracts = true
Write calls only on shares exceeding target allocation:
[write_when.calls]
excess_only = true
Temporarily disable trading for specific symbols:
[symbols.TSLA]
no_trading = true # Monitor only, no trades
Fine-tune IBKR API behavior:
[ib_async]
api_response_wait_time = 60 # Seconds to wait for API responses
logfile = "ib_async.log" # Enable API logging for debugging
Set absolute caps on new contracts:
[target]
maximum_new_contracts = 10 # Absolute limit per run
maximum_new_contracts_percent = 0.5 # Or limit by percentage
This project is, in its current state, considered to be complete. I'm open to contributions, but I am unlikely to accept PRs or feature requests that involve significant changes to the underlying algorithm.
If you find something that you think is a bug, or some other issue, please [create a new issue](https://github.com/brndnmtthws/thetagang/issu
$ claude mcp add thetagang \
-- python -m otcore.mcp_server <graph>