113 lines
2.5 KiB
C#
113 lines
2.5 KiB
C#
using Backend.MarketDataRequest;
|
|
using IBApi;
|
|
|
|
namespace Backend.ServiceHander
|
|
{
|
|
public sealed class MarketDataService
|
|
{
|
|
private readonly IBGatewayControl Gateway;
|
|
private int NextRequestId = 1;
|
|
private readonly object Lock = new();
|
|
|
|
public MarketDataService()
|
|
{
|
|
Gateway = new IBGatewayControl();
|
|
try
|
|
{
|
|
Gateway.Start("127.0.0.1", 4002, 1);
|
|
}
|
|
catch
|
|
{
|
|
Console.WriteLine("Invalid connection to IB Gateway. Please ensure gateway is running and connected.");
|
|
Environment.Exit(1);
|
|
}
|
|
}
|
|
|
|
private int GetNextRequestId()
|
|
{
|
|
lock (Lock)
|
|
{
|
|
return NextRequestId++;
|
|
}
|
|
}
|
|
|
|
public LiveEquitySnapshot GetLiveQuote(string Symbol) //
|
|
{
|
|
var Request = new LiveEquityRequest
|
|
{
|
|
RequestId = GetNextRequestId(),
|
|
Symbol = Symbol,
|
|
SecType = "STK",
|
|
Exchange = "SMART",
|
|
PrimaryExchange = "NASDAQ",
|
|
Currency = "USD",
|
|
RegulatorySnapshot = false
|
|
};
|
|
|
|
return Gateway.RequestLiveEquityBlocking(Request, TimeSpan.FromSeconds(10));
|
|
}
|
|
|
|
public List<object> GetHistorical(string symbol, string endDateTime, string duration, HistoricalBarSize barSize, HistoricalWhatToShow whatToShow = HistoricalWhatToShow.Trades, bool useRth = true)
|
|
{
|
|
var Request = new HistoricalEquityRequest
|
|
{
|
|
RequestId = GetNextRequestId(),
|
|
Symbol = symbol,
|
|
EndDateTime = endDateTime,
|
|
Duration = duration,
|
|
BarSize = barSize,
|
|
WhatToShow = whatToShow,
|
|
UseRth = useRth,
|
|
KeepUpToDate = false,
|
|
FormatDate = 1
|
|
};
|
|
|
|
var Bars = Gateway.RequestHistoricalBlocking(Request, TimeSpan.FromSeconds(20));
|
|
|
|
return Bars.Select(b => new
|
|
{
|
|
time = b.Time,
|
|
open = b.Open,
|
|
high = b.High,
|
|
low = b.Low,
|
|
close = b.Close,
|
|
volume = b.Volume
|
|
}).Cast<object>().ToList();
|
|
}
|
|
|
|
public List<object> GetHistoricalLine(string symbol, string endDateTime, string duration, HistoricalBarSize barSize, HistoricalWhatToShow whatToShow = HistoricalWhatToShow.Trades, bool useRth = true)
|
|
{
|
|
var Request = new HistoricalEquityRequest
|
|
{
|
|
RequestId = GetNextRequestId(),
|
|
Symbol = symbol,
|
|
EndDateTime = endDateTime,
|
|
Duration = duration,
|
|
BarSize = barSize,
|
|
WhatToShow = whatToShow,
|
|
UseRth = useRth,
|
|
KeepUpToDate = false,
|
|
FormatDate = 1
|
|
};
|
|
|
|
var Bars = Gateway.RequestHistoricalBlocking(Request, TimeSpan.FromSeconds(20));
|
|
|
|
return Bars.Select(b => new
|
|
{
|
|
timestamp = b.Time,
|
|
price = b.Close,
|
|
volume = b.Volume
|
|
}).Cast<object>().ToList();
|
|
}
|
|
|
|
public void Dispose()
|
|
{
|
|
Gateway.Dispose();
|
|
}
|
|
|
|
public void Disconnect()
|
|
{
|
|
Gateway.Disconnect();
|
|
}
|
|
}
|
|
} |