- ago
Hello,

I'm working through a strategy that pivots into a variety of select stocks based on RSI signals. I'm curious if there's a way to allocate a % of equity within a strategy that is then right-sized with my brokerage account balance?

1. I came across this post (https://www.wealth-lab.com/Discussion/Access-broker-account-info-programatically-7914) that talks about sourcing broker account balance information, but I was more curious if there's a simpler way ot assign a % of equity in code when placing a trade, and if the "use Broker Account value for Equity-based PosSizers" preference could then adjust for overall account balance?

My actual example is that I want one of my regimes to split 1/3 into 3 different ETFs.

And to preemptively ask some follow-up questions - 2. can I leverage Strategy Monitor for your proposed solution? 3. Should I "group" (?) the trades for easier entry/exit closing?

I'm also struggling a bit with getting the strategy manager to load data for this strategy. 4. I'm not really sure what to select for the symbol (or should I create my own data set from my broker, somehow, with each of the symbols the strategy uses?)


Thanks!
0
444
Solved
10 Replies

Reply

Bookmark

Sort
Cone8
 ( 22.26% )
- ago
#1
1. No code required. Just select Preferences > Trading > Portfolio Sync > Use Broker Account Value... Use the % of Equity sizing required. Live Signals will then use the buying power of the account specified in the tool (Strategy Monitor, Streaming Chart window, etc.)

2. The Preference works for any tool that generates signals.

3. Group what exactly? What's the example?

4. If you're trading 3 ETFs, create a DataSet of those 3 symbols, and use it in just one Strategy Monitor item.
0
- ago
#2
Thanks Cone!

My strategy uses 4 different regimes based on RSI/SMA values:
1. Buy equity 1, 100%, or
2. Buy equity 2, 100%, or
3. Buy equity 3, 4, and 5 at 33% each.

What’s the syntax to use to place trades those #3 trades, each with a % of equity (ex. 33%)?

And by grouping I meant - I think there’s a way to assign a group using a value/tag in the PlaceTrade()? If I’m understanding that correctly, it might be useful to use to group my #3 trades for easier exit handling?

Thanks again!
0
Cone8
 ( 22.26% )
- ago
#3
If the case is that only one of 1, 2, or 3 can happen at a time, then the Spread Equity Equally sizer should do the trick.
You need the PowerPack Extension for that sizer to show up.

Also, if using Market orders to enter, make sure to configure Margin to 1.05 or more to prevent missed (NSF) trades due to gaps.

0
- ago
#4
Oh, that's a great option - I'll check it out!

Can I still restrict the total equity of the entire strategy when I use it in the strategy manager, with this setting?

Say I wanted this strategy to use 50% of account equity (and set that value when placing the strategy in the strategy manager), would that still appropriately "equalize" the 1/3rd trades in regime 3 (effectively making them 1/6th)?

Curious if there's code to do this as well, in case I have more complex scenarios or add extra regimes that aren't equally split? Is there a way to use % of equity in-code to place trades (outside of dividing up my equity balance and manually calculating units for trading)?
0
Cone8
 ( 22.26% )
- ago
#5
In those complex scenarios, you'll have to either 1) create your own Pos Sizer and pass data to it using the Transaction.Tag, or, 2) calculate and assign the Transaction.Quantity right in your script.

For 2, you'd use the Backtester's CurrentEquity property and multiply it by the % required, and assign to the Transaction's Quantity. On the signal bar, you'll need to get substitute your account buying power in place of CurrentEquity. You can get the live account value easily as shown - but only when:
a. the Live Position Trading Preference is enabled,
b. Running the script in the Strategy Monitor or Streaming Chart.

CODE:
            double eq = CurrentEquity;                          // get the selected live account equity on the last bar for live trade sizing             if (idx == bars.Count - 1)                if (ExecutionMode == StrategyExecutionMode.StrategyMonitor || ExecutionMode == StrategyExecutionMode.StreamingChart)                   eq = Backtester.LiveAccount.AccountValue;             Transaction t = PlaceTrade(bars, TransactionType.Buy, OrderType.Market, 0, 0);                t.Quantity = Math.Floor(eq * 0.33 / bars.Close[idx]); // 33% sizing
0
Best Answer
- ago
#6
Amazing - I was thinking I'd have to do something like that (and could probably make my own handler to pass the bars reference for each different symbol, to calculate and return each symbol's equity). I'm pretty rough/new to C#, but I'll give that a go.

I was noticing, though, that most of my strategies are having issues with NSF positions. It seemed to relate to the sequencing of buying/selling transactions between each of the regimes. I thought that because I was using Market transaction types, the sells would execute before the buys and there wouldn't be issues, but that doesn't appear to be the case.

A couple of new, related questions:
1. When switching between my regimes (where I have to fully close positions so that I can allocate 100% of my equity to another regime), do I need to place the close/sell and buy on different bars? That is, do I need to wait for the close to complete before placing the buy, in order to avoid NSF? I switched to trying to use...
CODE:
if (OpenPositionsAllSymbols.Count == 0)

...before placing orders, to avoid NSF, which naturally delays all of my buys by at least a bar (day), but ... I think there must be a way to place a market sell and market buy on the same day/bar, where the sell goes first and then the buy can be filled?

2. Given that some of my stocks are highly volatile, I'm noticing further NSF transactions that appear to be caused by close-to-open price gaps. When I have my "Basis Price" set at "Market Close this Bar" I notice missing transactions (extracted the backtest results into Excel and compared with Retain NSF checked/unchecked). When I switched my "Basis Price" to "Market Open next Bar" I started to see transactions populating earlier and no more NSF positions (still using the OpenPositionsAllSymbols.Count == 0 code, though). My question here is, what's the right/best approach to avoid NSF? It feels like relying on/living with NSF Positions is not actually adhering to a strategy. In combination with question 1 above, I'm trying to understand the optimal sequencing for a daily strategy that's using 100% equity and switches 100% positions each day, at market pricing. Is using "Market Open next Bar" inverting some of my logic or peaking into the future? Or is it basically the right setting always, for a daily strategy trading at market pricing (I could see a daily strategy using limit orders wanting to use close pricing, instead)?
0
Cone8
 ( 22.26% )
- ago
#7
QUOTE:
sells would execute before the buys and there wouldn't be issues, but that doesn't appear to be the case.
But it is the case. What's your evidence to the contrary?

QUOTE:
do I need to place the close/sell and buy on different bars?
No.

QUOTE:
do I need to wait for the close to complete before placing the buy
You don't have a choice. Nothing is processed until the close of a [new] bar.
Exception: At-Close Signaling in the Strategy Monitor

Re: "Market Open Next Bar"
Correct. See the Help (F1) for details.
Just know that few brokers support the notional (cash) value order - Alpaca does. For live trading these would be converted to shares using the known last price (previous close) for those that do not support it.

You can also avoid NSF simply by increasing the margin value sufficiently high. In the few cases that margin is required, you'll use a bit of margin, that's all. Although for a gap like the one ORCL had 2 days ago (2025-10-25), that would required something like 35% margin.
1
- ago
#8
Thanks, Cone for continuing to be patient with me here.

My only evidence for sells not executing before buys was a review of my trade history between backtests with "Retain NSF Positions" and backtests without "Retain NSF Positions". It seemed like regime swapping was causing NSF issues that I was just guessing were related to sells/buys occurring on the same day. Is there a way to actually output the NSF trades so that I could analyze them a bit closer?

I guess from your response, it's more likely that there just isn't enough funds to cover the size of the position (... maybe because the selling symbol gapped down and/or the buying symbol gapped up, creating a spread).

I will be live trading this with a registered, non-margin account, so I can't set a margin amount. But I guess I could set a % of equity lower than 100% and that would create some padding? I tried dropping down 5% and that allowed a few more of the trades to flow through (in combination with using the "Market Open next Bar" Basis Price).

I'm using Interactive Brokers - I know they allow dollar-based sizing with their platform - not sure about their API?
0
Cone8
 ( 22.26% )
- ago
#9
QUOTE:
Is there a way to actually output the NSF trades so that I could analyze them a bit closer?
Sure. In `public override void BacktestComplete()`, add a routine that loops through GetPositionsAllSymbols(true), and log each Position whose NSF property is true.

QUOTE:
... maybe because the selling symbol gapped down and/or the buying symbol gapped up, creating a spread).
Great point. You're on the right track.

In practice, you'd generally place all orders before the open. That won't work for a cash account when you need the proceeds from exits to create sufficient funds for the new purchases. In that case, entry orders must be delayed until the account has cleared the sales. There's no out-of-the-box solution for that kind of Auto-trading with a cash account.

QUOTE:
IB ... not sure about their API?
I'm sure - it's not available.
0
- ago
#10
QUOTE:
...add a routine that loops through GetPositionsAllSymbols(true), and log each Position whose NSF property is true.

Great recommendation! That worked - I looped through and output price * quantity to get value, and then compared the value to my exit trades on the same dates, and they were dramatically different! One of the symbols is highly volatile, so that's what is causing the issues. I also found Backtester.NSFPositions when looking through the Coding QuickReference ... though it seemed to be empty (couldn't loop through it/count of values was 0).

QUOTE:
There's no out-of-the-box solution for that kind of Auto-trading with a cash account.
Yeah, understandable .... but unfortunate. It's too bad that the strategy monitor couldn't handle recalculating "price" for market orders (given ... they're market orders). I guess... I could switch my strategy down to a different timeframe and trade more frequently? Would just have to handle timeframes manually to make sure my indicator/regime logic is based on daily bars? That sounds daunting given how new I am to all of this, but I'd imagine with a strategy like this, I'd get better results (placing orders at open/before close).

QUOTE:
I'm sure - it's not available.

Good to know, but unfortunate!

Again - thanks a ton Cone! I'm learning a lot and can appreciate the efforts you go to in responding to everyone across the discussion threads.
1

Reply

Bookmark

Sort