I started with the 'Bar formation' sample and made some small adjustments - I'm using the 'Quantity' field here to refer to number of ticks to process before completing bar (set at 5000 in my settings). First problem is I can't tell if its working and the 2nd problem is my strategy which works fine on a regular 5000 tick bar suddenly rarely starts taking trades.
Is this the right way to code what I'm trying to do?
Code: Select all
#region Properties
private int _ticks_per_bar = DefaultSettings.Quantity;
private int _current_tick_count = 0;
private Int64 _last_tick_time = 0;
private OHLC m_OHLC = new OHLC();
#endregion
public void Init(IBaseOptions baseOptions, IParams customParams)
{
object obj = null;
customParams.GetValue((int)EFields.QuantityField, out obj);
if (obj != null)
{
_ticks_per_bar = (int)obj;
}
Trace.TraceInformation(string.Format("Init {0}: Quantity={1}", ToString(), _ticks_per_bar));
}
public void OnData(ICustomBar Bar, Int64 time_in_ticks, Int32 tickId, double open, double high, double low, double close, long volumeAdded, long upVolumeAdded, long downVolumeAdded, ECustomBarTrendType trend, bool isBarClose)
{
if ( _last_tick_time == 0 ) _last_tick_time = time_in_ticks;
_current_tick_count++;
bool tickThreshold = _current_tick_count >= _ticks_per_bar;
bool timeThreshold = IsCrossingBoundary(_last_tick_time, time_in_ticks);
if(tickThreshold || timeThreshold)
{
Bar.CloseBar();
_current_tick_count = 0;
m_OHLC.Clear();
}
m_OHLC.Update(open, high, low, close, volumeAdded, upVolumeAdded, downVolumeAdded, time_in_ticks, tickId);
Bar.UpdateBar(m_OHLC.Time_in_ticks, m_OHLC.TickId, m_OHLC.Open, m_OHLC.High, m_OHLC.Low, m_OHLC.Close, m_OHLC.BarVolume, m_OHLC.BarUpVolume, m_OHLC.BarDownVolume, m_OHLC.Trend, true, true);
_last_tick_time = time_in_ticks;
}
public void Reset()
{
_current_tick_count = 0;
_last_tick_time = 0;
m_OHLC.Clear();
}
#endregion
public static bool IsCrossingBoundary(Int64 lastTickTime, Int64 currentTickTime)
{
// Convert ticks to DateTime
DateTime lastTime = new DateTime(lastTickTime);
DateTime currentTime = new DateTime(currentTickTime);
// Calculate the next boundary time from current time
DateTime nextBoundary = GetNextBoundary(currentTime);
// Check if crossing the boundary
return currentTime >= nextBoundary && lastTime < nextBoundary;
}
private static DateTime GetNextBoundary(DateTime time)
{
// Define the boundary hours
int[] boundaryHours = new int[] { 4, 8, 12, 16, 20, 24 };
// Find the next boundary hour
foreach (int hour in boundaryHours)
{
DateTime boundaryTime = DateTime.Today.AddHours(hour);
if (time < boundaryTime)
{
return boundaryTime;
}
}
// If no boundary is found for today, return the first boundary of the next day
return DateTime.Today.AddDays(1).AddHours(boundaryHours[0]);
}