本文整理匯總了C#中QuantConnect.Packets.LiveNodePacket類的典型用法代碼示例。如果您正苦於以下問題:C# LiveNodePacket類的具體用法?C# LiveNodePacket怎麽用?C# LiveNodePacket使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
LiveNodePacket類屬於QuantConnect.Packets命名空間,在下文中一共展示了LiveNodePacket類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的C#代碼示例。
示例1: DoesNotSetRunTimeErrorWhenReconnectMessageComesThrough
public void DoesNotSetRunTimeErrorWhenReconnectMessageComesThrough()
{
var algorithm = new AlgorithmStub(equities: new List<string> { "SPY" });
var referenceTime = DateTime.UtcNow;
algorithm.SetDateTime(referenceTime);
var localReferencTime = referenceTime.ConvertFromUtc(TimeZones.NewYork);
algorithm.Securities["SPY"].Exchange.SetMarketHours(localReferencTime.AddSeconds(1).TimeOfDay, TimeSpan.FromDays(1), localReferencTime.DayOfWeek);
var job = new LiveNodePacket();
var results = new TestResultHandler();//packet => Console.WriteLine(FieldsToString(packet)));
var api = new Api.Api();
var handler = new DefaultBrokerageMessageHandler(algorithm, job, results, api, TimeSpan.FromMinutes(15), TimeSpan.FromSeconds(.25));
Assert.IsNull(algorithm.RunTimeError);
handler.Handle(BrokerageMessageEvent.Disconnected("Disconnection!"));
Thread.Sleep(100);
handler.Handle(BrokerageMessageEvent.Reconnected("Reconnected!"));
Thread.Sleep(500);
Assert.IsNull(algorithm.RunTimeError);
results.Exit();
}
示例2: CreateBrokerage
/// <summary>
/// Creates a new IBrokerage instance and set ups the environment for the brokerage
/// </summary>
/// <param name="job">The job packet to create the brokerage for</param>
/// <param name="algorithm">The algorithm instance</param>
/// <returns>A new brokerage instance</returns>
public override IBrokerage CreateBrokerage(LiveNodePacket job, IAlgorithm algorithm)
{
var errors = new List<string>();
// read values from the brokerage datas
var useTws = Config.GetBool("ib-use-tws");
var port = Config.GetInt("ib-port", 4001);
var host = Config.Get("ib-host", "127.0.0.1");
var twsDirectory = Config.Get("ib-tws-dir", "C:\\Jts");
var ibControllerDirectory = Config.Get("ib-controller-dir", "C:\\IBController");
var account = Read<string>(job.BrokerageData, "ib-account", errors);
var userID = Read<string>(job.BrokerageData, "ib-user-name", errors);
var password = Read<string>(job.BrokerageData, "ib-password", errors);
var agentDescription = Read<AgentDescription>(job.BrokerageData, "ib-agent-description", errors);
if (errors.Count != 0)
{
// if we had errors then we can't create the instance
throw new Exception(string.Join(Environment.NewLine, errors));
}
// launch the IB gateway
InteractiveBrokersGatewayRunner.Start(ibControllerDirectory, twsDirectory, userID, password, useTws);
var ib = new InteractiveBrokersBrokerage(algorithm.Transactions, algorithm.Portfolio, account, host, port, agentDescription);
Composer.Instance.AddPart<IDataQueueHandler>(ib);
return ib;
}
示例3: Unsubscribe
/// <summary>
/// Removes the specified symbols to the subscription
/// </summary>
/// <param name="job">Job we're processing.</param>
/// <param name="symbols">The symbols to be removed keyed by SecurityType</param>
public void Unsubscribe(LiveNodePacket job, IEnumerable<Symbol> symbols)
{
foreach (var symbol in symbols)
{
lock (_lock) _subscriptions.Remove(symbol);
}
}
示例4: TestLiveTradingDataFeed
/// <summary>
/// Creates a test live trading data feed with the specified fast forward factor
/// </summary>
/// <param name="algorithm">The algorithm under analysis</param>
/// <param name="job">The job for the algorithm</param>
public TestLiveTradingDataFeed(IAlgorithm algorithm, LiveNodePacket job)
: base(algorithm, job)
{
_start = DateTime.Now;
_current = DateTime.Now;
_tickResolution = TimeSpan.FromSeconds(1);
}
示例5: Subscribe
/// <summary>
/// Adds the specified symbols to the subscription
/// </summary>
/// <param name="job">Job we're subscribing for:</param>
/// <param name="symbols">The symbols to be added keyed by SecurityType</param>
public void Subscribe(LiveNodePacket job, IEnumerable<Symbol> symbols)
{
var symbolsToSubscribe = (from symbol in symbols
where !_subscribedSymbols.Contains(symbol) && CanSubscribe(symbol)
select symbol).ToList();
if (symbolsToSubscribe.Count == 0)
return;
Log.Trace("FxcmBrokerage.Subscribe(): {0}", string.Join(",", symbolsToSubscribe));
var request = new MarketDataRequest();
foreach (var symbol in symbolsToSubscribe)
{
TradingSecurity fxcmSecurity;
if (_fxcmInstruments.TryGetValue(_symbolMapper.GetBrokerageSymbol(symbol), out fxcmSecurity))
{
request.addRelatedSymbol(fxcmSecurity);
}
}
request.setSubscriptionRequestType(SubscriptionRequestTypeFactory.SUBSCRIBE);
request.setMDEntryTypeSet(MarketDataRequest.MDENTRYTYPESET_ALL);
lock (_locker)
{
_gateway.sendMessage(request);
}
foreach (var symbol in symbolsToSubscribe)
{
_subscribedSymbols.Add(symbol);
}
}
示例6: Subscribe
/// <summary>
/// Adds the specified symbols to the subscription: new IQLevel1WatchItem("IBM", true)
/// </summary>
/// <param name="job">Job we're subscribing for:</param>
/// <param name="symbols">The symbols to be added keyed by SecurityType</param>
public void Subscribe(LiveNodePacket job, IEnumerable<Symbol> symbols)
{
try
{
foreach (var symbol in symbols)
{
if (CanSubscribe(symbol))
{
lock (_sync)
{
Log.Trace("IQFeed.Subscribe(): Subscribe Request: " + symbol.ToString());
var type = symbol.ID.SecurityType;
if (_symbols.Add(symbol))
{
var ticker = symbol.Value;
if (type == SecurityType.Forex) ticker += ".FXCM";
_level1Port.Subscribe(ticker);
Log.Trace("IQFeed.Subscribe(): Subscribe Processed: " + symbol.ToString());
}
}
}
}
}
catch (Exception err)
{
Log.Error("IQFeed.Subscribe(): " + err.Message);
}
}
示例7: Subscribe
/// <summary>
/// Adds the specified symbols to the subscription
/// </summary>
/// <param name="job">Job we're subscribing for:</param>
/// <param name="symbols">The symbols to be added keyed by SecurityType</param>
public void Subscribe(LiveNodePacket job, IDictionary<SecurityType, List<Symbol>> symbols)
{
var symbolsToSubscribe = (from secType in symbols
from symbol in secType.Value
where !_subscribedSymbols.Contains(symbol)
select symbol).ToList();
if (symbolsToSubscribe.Count == 0)
return;
Log.Trace("FxcmBrokerage.Subscribe(): {0}", string.Join(",", symbolsToSubscribe));
var request = new MarketDataRequest();
foreach (var symbol in symbolsToSubscribe)
{
request.addRelatedSymbol(_fxcmInstruments[ConvertSymbolToFxcmSymbol(symbol)]);
}
request.setSubscriptionRequestType(SubscriptionRequestTypeFactory.SUBSCRIBE);
request.setMDEntryTypeSet(MarketDataRequest.MDENTRYTYPESET_ALL);
lock (_locker)
{
_gateway.sendMessage(request);
}
foreach (var symbol in symbolsToSubscribe)
{
_subscribedSymbols.Add(symbol);
}
}
示例8: Subscribe
/// <summary>
/// Adds the specified symbols to the subscription
/// </summary>
/// <param name="job">Job we're subscribing for:</param>
/// <param name="symbols">The symbols to be added keyed by SecurityType</param>
public void Subscribe(LiveNodePacket job, IDictionary<SecurityType, List<Symbol>> symbols)
{
foreach (var kvp in symbols)
{
foreach (var symbol in kvp.Value)
{
lock (_lock) _subscriptions.Add(symbol);
}
}
}
示例9: CreateBrokerage
/// <summary>
/// Creates a new IBrokerage instance
/// </summary>
/// <param name="job">The job packet to create the brokerage for</param>
/// <param name="algorithm">The algorithm instance</param>
/// <returns>A new brokerage instance</returns>
public IBrokerage CreateBrokerage(LiveNodePacket job, IAlgorithm algorithm)
{
//Try and use the live job packet cash if exists, otherwise resort to the user algo cash:
if (job.BrokerageData.ContainsKey("project-paper-equity"))
{
var consistentCash = Convert.ToDecimal(job.BrokerageData["project-paper-equity"]);
algorithm.SetCash(consistentCash);
}
return new PaperBrokerage(algorithm);
}
示例10: InitializesInstanceFromComposer
public void InitializesInstanceFromComposer()
{
var composer = Composer.Instance;
using (var factory = composer.Single<IBrokerageFactory>(instance => instance.BrokerageType == typeof (InteractiveBrokersBrokerage)))
{
Assert.IsNotNull(factory);
var job = new LiveNodePacket {BrokerageData = factory.BrokerageData};
var brokerage = factory.CreateBrokerage(job, AlgorithmDependency);
Assert.IsNotNull(brokerage);
Assert.IsInstanceOf<InteractiveBrokersBrokerage>(brokerage);
brokerage.Connect();
Assert.IsTrue(brokerage.IsConnected);
}
}
示例11: EmitsData
public void EmitsData()
{
var algorithm = new AlgorithmStub(forex: new List<string> {"EURUSD"});
// job is used to send into DataQueueHandler
var job = new LiveNodePacket();
// result handler is used due to dependency in SubscriptionDataReader
var resultHandler = new BacktestingResultHandler();
var dataFileProvider = new DefaultDataFileProvider();
var lastTime = DateTime.MinValue;
var timeProvider = new RealTimeProvider();
var dataQueueHandler = new FuncDataQueueHandler(fdqh =>
{
var time = timeProvider.GetUtcNow().ConvertFromUtc(TimeZones.EasternStandard);
if (time == lastTime) return Enumerable.Empty<BaseData>();
lastTime = time;
return Enumerable.Range(0, 9).Select(x => new Tick(time.AddMilliseconds(x*100), Symbols.EURUSD, 1.3m, 1.2m, 1.3m));
});
var feed = new TestableLiveTradingDataFeed(dataQueueHandler, timeProvider);
var mapFileProvider = new LocalDiskMapFileProvider();
feed.Initialize(algorithm, job, resultHandler, mapFileProvider, new LocalDiskFactorFileProvider(mapFileProvider), dataFileProvider);
var feedThreadStarted = new ManualResetEvent(false);
Task.Factory.StartNew(() =>
{
feedThreadStarted.Set();
feed.Run();
});
// wait for feed.Run to actually begin
feedThreadStarted.WaitOne();
var emittedData = false;
ConsumeBridge(feed, TimeSpan.FromSeconds(10), true, ts =>
{
if (ts.Slice.Count != 0)
{
emittedData = true;
Console.WriteLine("HasData: " + ts.Slice.Bars[Symbols.EURUSD].EndTime);
Console.WriteLine();
}
});
Assert.IsTrue(emittedData);
}
示例12: NextJob
/// <summary>
/// Desktop/Local Get Next Task - Get task from the Algorithm folder of VS Solution.
/// </summary>
/// <returns></returns>
public AlgorithmNodePacket NextJob(out string location)
{
location = AlgorithmLocation;
Log.Trace("JobQueue.NextJob(): Selected " + location);
//If this isn't a backtesting mode/request, attempt a live job.
if (_liveMode)
{
var liveJob = new LiveNodePacket
{
Type = PacketType.LiveNode,
Algorithm = File.ReadAllBytes(AlgorithmLocation),
Brokerage = Config.Get("live-mode-brokerage", PaperBrokerageTypeName),
Channel = Config.Get("job-channel"),
UserId = Config.GetInt("job-user-id"),
Version = Constants.Version,
DeployId = Config.Get("algorithm-type-name"),
RamAllocation = int.MaxValue
};
try
{
// import the brokerage data for the configured brokerage
var brokerageFactory = Composer.Instance.Single<IBrokerageFactory>(factory => factory.BrokerageType.MatchesTypeName(liveJob.Brokerage));
liveJob.BrokerageData = brokerageFactory.BrokerageData;
}
catch (Exception err)
{
Log.Error(string.Format("JobQueue.NextJob(): Error resoliving BrokerageData for live job for brokerage {0}. {1}", liveJob.Brokerage, err.Message));
}
return liveJob;
}
//Default run a backtesting job.
var backtestJob = new BacktestNodePacket(0, 0, "", new byte[] {}, 10000, "local")
{
Type = PacketType.BacktestNode,
Algorithm = File.ReadAllBytes(AlgorithmLocation),
Version = Constants.Version,
BacktestId = Config.Get("algorithm-type-name"),
RamAllocation = int.MaxValue,
Language = (Language)Enum.Parse(typeof(Language), Config.Get("algorithm-language"))
};
return backtestJob;
}
示例13: Unsubscribe
/// <summary>
/// Removes the specified symbols from the subscription
/// </summary>
/// <param name="job">Job we're processing.</param>
/// <param name="symbols">The symbols to be removed keyed by SecurityType</param>
public void Unsubscribe(LiveNodePacket job, IEnumerable<Symbol> symbols)
{
var symbolsToUnsubscribe = (from symbol in symbols
where _subscribedSymbols.Contains(symbol)
select symbol).ToList();
if (symbolsToUnsubscribe.Count == 0)
return;
Log.Trace("OandaBrokerage.Unsubscribe(): {0}", string.Join(",", symbolsToUnsubscribe.Select(x => x.Value)));
// Oanda does not allow more than a few rate streaming sessions,
// so we only use a single session for all currently subscribed symbols
var symbolsToSubscribe = _subscribedSymbols.ToList().Where(x => !symbolsToUnsubscribe.Contains(x)).ToList();
SubscribeSymbols(symbolsToSubscribe);
_subscribedSymbols = symbolsToSubscribe.ToHashSet();
}
示例14: DoesNotSetAlgorithmRunTimeErrorOnDisconnectIfAllSecuritiesClosed
public void DoesNotSetAlgorithmRunTimeErrorOnDisconnectIfAllSecuritiesClosed()
{
var referenceTime = DateTime.UtcNow;
var algorithm = new AlgorithmStub(equities: new List<string> { "SPY" });
algorithm.SetDateTime(referenceTime);
algorithm.Securities["SPY"].Exchange.SetMarketHours(TimeSpan.Zero, TimeSpan.Zero, referenceTime.ConvertFromUtc(TimeZones.NewYork).DayOfWeek);
var job = new LiveNodePacket();
var results = new TestResultHandler();//packet => Console.WriteLine(FieldsToString(packet)));
var api = new Api.Api();
var handler = new DefaultBrokerageMessageHandler(algorithm, job, results, api, TimeSpan.FromMinutes(15));
Assert.IsNull(algorithm.RunTimeError);
handler.Handle(BrokerageMessageEvent.Disconnected("Disconnection!"));
Assert.IsNull(algorithm.RunTimeError);
results.Exit();
}
示例15: SetsAlgorithmRunTimeErrorOnDisconnectIfNonCustomSecurityIsOpen
public void SetsAlgorithmRunTimeErrorOnDisconnectIfNonCustomSecurityIsOpen()
{
var algorithm = new AlgorithmStub(equities: new List<string> { "SPY" });
algorithm.Securities[Symbols.SPY].Exchange = new SecurityExchange(SecurityExchangeHours.AlwaysOpen(TimeZones.NewYork));
var job = new LiveNodePacket();
var results = new TestResultHandler();//packet => Console.WriteLine(FieldsToString(packet)));
var api = new Api.Api();
var handler = new DefaultBrokerageMessageHandler(algorithm, job, results, api, TimeSpan.Zero, TimeSpan.Zero);
Assert.IsNull(algorithm.RunTimeError);
handler.Handle(BrokerageMessageEvent.Disconnected("Disconnection!"));
Thread.Sleep(100);
Assert.IsNotNull(algorithm.RunTimeError);
results.Exit();
}