Finally… How to Get The Size Of Your Account Inside Of A NinjaTrader Strategy

Posted by TraderWerks | Indicators,ninjatrader coding,Strategy,Trading Systems | Tuesday 24 January 2012 1:25 am

FINALLY

I have been using this for a while, since the early NinjaTrader 7 betas, which seems like forever ago  and it has been very useful. Mainly used in risk management, which is usually overlooked by many.

Knowing the account size is very , very helpful for writing code for risk management. Risk management is so important in strategies that most of MY strategies have most of the code in risk management, not entries or exits. Developers really need to spend more time getting the risk management part of the code perfect.

THE OLD WAY

When I USED to do custom programming ( I have no time ) , what I would do would be to keep the starting value of the account and then use the running profit to calculate what the current value of the account was during the trading session.

Painful and convuluted, but it worked. It did have a couple of problems. Well, big problems. The first was that you have to input the starting account value at the start of the session. The second is when you are trading more than one automated system in your account. You are keeping the running total for THAT strategy only and you have no idea of what the other strategies are  doing.

FIXED FRACTIONAL PRICING EXAMPLE

As an example, say you only want to risk 2% of your trade on an a trade. That is fixed fractional risk management which is very popular. You have a $20,000 account,  are trading two strategies and you want to trade one contract per $5,000.

The old way, Say strategy #1 had lost $10,000. Strategy #1 will know about the loss and start trading 2 contracts instead of the previous 4 contracts. Strategy #2 should start to trade 2 contracts BUT it doesn’t know about the loss so it will continue to trade 4 contracts. This was typical using NinjaTrader 6.5, which frankly sucked.

TRADE SIZE

I think the biggest thing is that is helps position sizing and here are some code snippets to help get you started. Tons of people recommend you only risk a certain percentage of capital on each trade and the following code shows you how to do that.. You can use this to set trade size or the amount you risk by setting the stop loss.

Say you want to enter a trade one contract for every $5,000 in cash you have.

position_size = (int) GetAccountValue(AccountItem.CashValue)) / 5000 ;

Or you could calculate the max risk by calculating 2% of your cash.

max_risk = GetAccountValue(AccountItem.CashValue)) * 0.02 ;

Now, please note that futures and equities work differently in the amounts reported.
GET ACCOUNT VALUE

The function that does all the work is the GetAccountValue call. There are a couple of things to notice about this call. The first is that it will return 0 for historical data and that it returns the information on the account that the strategy is running on at the time. The other is that there are more items in Cbi.AccountItem then just the cash value, so you should explore those.

public double GetAccountValue(Cbi.AccountItem accountItem)

PUTTING IT ALL TOGETHER

So let us make a simple example. We will trade 10 contracts when backtesting, one contract per $5,000 running real time or replay.

protected override void OnBarUpdate()
{
    if (Historical)
    {
        contracts_to_trade = 10 ; // trade 10 historically
    }
    else
    {
        if (GetAccountValue(AccountItem.CashValue) > 5000)
        {
            contracts_to_trade = (int) GetAccountValue(AccountItem.CashValue)) / 5000 ;
        }
    }
}


GetAccountValue() doesn’t require very much computing power so you can call it fairly often.

NOTE

The ability  or inability for these functions to work depend on the information provided by the broker to NinjaTrader. So you should test using your brokers connection.

If you have any questions, just leave a comment.


Photo Courtesy John Althouse Cohen


PIMPING MY NEWSLETTER

I don’t post often, but I do have a mailing list you can subscribe to in the meantime. I usually write about Ninjatrader programming, but other trading topics as well. Subscribe to TraderWerks Blog by Email

 


Good to see you! If you are new here, you can subscribe to the RSS feed for updates


Writing Passive Relative Orders in NinjaTrader Strategies ( PASSV REL )

Posted by TraderWerks | Indicators | Tuesday 10 January 2012 9:45 pm

INTERACTIVE BROKERS PASS REL ORDERS

I was chatting with a friend that was trying to write passive relative orders in Ninja Trader that he had used in Interactive Brokers TWS.

Since you know I have no love for interactive brokers, I thought I would give him a hand.Besides, I have not written a coding post for the blog in a while.

 

If you want to find out how I feel about Interactive Brokers, just use the search bar over there.

Regardless, Interactive Brokers ( From now on, I will just type IB instead of Interactive Brokers because it is getting way to tiring to write the whole thing ) has a pretty good selection of orders, one of them being a Passive relative order (PASSV REL )

WHAT IS A PASSIVE RELATIVE ORDER ?

Lets start by looking at the IB website.

Passive Relative orders provide a means for traders to seek a less aggressive price than the National Best Bid and Offer (NBBO) while keeping the order pegged to the best bid (for a buy) or ask (for a sell). The  order price is automatically adjusted as the markets move to keep the order less aggressive

 

What is is in reality is an attempt to get a better price. Putting in an order away from the market hoping the market will come back and get you into the trade at a better price.

Stocks, futures and options ( and other things , but you get the idea) move up and down all the time. A passive relative order is an order that sits relative to the bid / ask and waits for the price to come back and get filled.

The difference between this and a limit order is that limit price will move relative to the bid/ask price. So here is an example of this type of order.

 

I won’t go into detail here, but there is a really good explanation on the IB website.

THE CODE

This PSEUDO code below is for Ninjatrader strategies. I think the closest you have in the ATM strategies is the ATM strategy. The code is a little advanced so you will have to bear with me on this one. If you are just a beginner at Ninja script, I would leave  this type of programming alone.

I went with PSEUDO code because if you are advanced enough write this, you probably would not have a problem writing the C# code yourself. I was going to release code, but I thought that would be to confusing. If there is enough interest, I will release it. So leave a comment and if enough people want it I will release the NinjaTrader code.

 

The first thing you will need is the order object and the bid / ask prices.

double offset_price ;
double max_price ;
bool entry_direction ;
double current_limit_price ;

...

We need to keep the entry direction since passive relative orders act with the direction.

The next part is in OnOrderUpdate(), remember to check for the IOrder.Token.

OnOrderUpdate()
{
  // wait until order comes back confirmed,and store the value.
if ( order completed ) current_limit_price = order price 

}
OnMarketData {

    ...
    double mid_point = ( GetCurrentBid() + GetCurrentAsk() ) / 2 ;
  // if the price is at max price do not move
  if ( current_limit_price gt max_price ) return
   // now if price is to far away, move the limit order
   if ( difference (mid_price , current_limit_price ) > offset_price )
      cancel order
     enter_new_order(mid_price , current_limit_price)
    ...
}

Most , well all , of the heavy lifting will be done in the OnMarketData and OnOrderUpdate. You cannot do this using on bar update.
 
I have just touched on the subject, if you would like me to write more , leave a comment so I know other people are interested.
 

A LITTLE WARNING


Programming this stuff is considered advanced programming and is for experienced programmers. Don’t blame me if something goes wrong.

Using this type of order can and will generate a lot of cancel order messages as the limit order is moved.

For futures there are message limits that can lead to a fine and in options there are usually cancel fees from the exchange. Of course your broker may add something on also, so you mileage will vary.

And finally, using a lot of cancel and replace orders , you may run into ‘in-flight’ order problems. Which are usually not nice.


Photo by szeke



PIMPING MY NEWSLETTER

I don’t post often, but I do have a mailing list you can subscribe to in the meantime. I usually write about Ninjatrader programming, but other trading topics as well. Subscribe to TraderWerks Blog by Email


Good to see you! If you are new here, you can subscribe to the RSS feed for updates