I'm working on position sizing rule in a strategy. The rule is simple, I want to risk 2% of my capital on every trade.
So, following the guideline on this forum
/*
Using an example of USD/JPY
1st Step: 100,000*114.28 = 11,428,000
100,000*114.23 = 11,423,000
5,000 difference between bid and ask
2nd Step: Determine Midpoint between bid and ask
114.28+114.23 = 228.51/2 = 114.255
3rd Step: Divide the Difference in Japanese yen by the midpoint of the bid/offer
5000/114.255 = 43.76
4th Step: Divide the total US dollar difference by the number of pips to attain the average pip value at the current value.
43.76/5 = $8.75
Using these steps you can figure the pip value and then determine how many units to trade based on a percentage of your account.
*/
This involves getting Bid, Ask prices, spread, and midpoint.
But in my case, I want to develop position sizing rule separately for backtesting and live trading in the same strategy.
Here is my code
private double histBid = 0;
private double histAsk = 0;
private double curBid = 0;
private double curAsk = 0;
private double spread = 0;
private double midPoint = 0;
protected override void OnStateChange()
if (State == State.Historical)
{
spread = Math.Abs(100000 * (histBid - histAsk));
midPoint = Math.Abs (histBid - histAsk)/2;
}
else if (State == State.Realtime)
{
spread = Math.Abs(100000 * (curBid - curAsk));
midPoint = Math.Abs(curBid - curAsk)/2;
}
protected override void OnBarUpdate()
// Get historical Bid, Ask for backtesting
histBid = Bars.GetBid(CurrentBar);
histAsk = Bars.GetAsk(CurrentBar);
// Get realtime Bid, Ask for live trading
curBid = GetCurrentBid();
curAsk = GetCurrentAsk();
Thank you

Comment