本文整理汇总了C#中TradeBars.ContainsKey方法的典型用法代码示例。如果您正苦于以下问题:C# TradeBars.ContainsKey方法的具体用法?C# TradeBars.ContainsKey怎么用?C# TradeBars.ContainsKey使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类TradeBars
的用法示例。
在下文中一共展示了TradeBars.ContainsKey方法的6个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: OnData
/// <summary>
/// On receiving new tradebar data it will be passed into this function. The general pattern is:
/// "public void OnData( CustomType name ) {...s"
/// </summary>
/// <param name="data">TradeBars data type synchronized and pushed into this function. The tradebars are grouped in a dictionary.</param>
public void OnData(TradeBars data)
{
//int x = 0;
//int y = 10;
//int z = y / x;
//if (!Portfolio.Invested)
//{
// SetHoldings("SPY", 1);
//}
if (!Portfolio.HoldStock && data.ContainsKey("SPY"))
{
Order("SPY", (int)Math.Floor(Portfolio.Cash / data["SPY"].Close));
Debug("Debug Purchased MSFT: " + Portfolio.Cash);
}
if (Time.TimeOfDay.TotalSeconds % 10 == 0)
{
int i = Transactions.GetIncrementOrderId();
var order = new Order("BTC", 10, OrderType.Market, Time, data["BTC"].Price, "Tag: Test");
order.Status = OrderStatus.Filled;
Transactions.Orders.AddOrUpdate<int, Order>(i, order);
}
}
示例2: OnData
/// <summary>
/// Raises the data event.
/// </summary>
/// <param name="data">Data.</param>
public void OnData(TradeBars data)
{
if (!Portfolio.HoldStock && data.ContainsKey("AAPL"))
{
int quantity = (int)Math.Floor(Portfolio.Cash / data["AAPL"].Close);
Order("AAPL", quantity);
Debug("Purchased SPY on " + Time.ToShortDateString());
Notify.Email("[email protected]", "Test", "Test Body", "test attachment");
}
}
示例3: OnData
/// <summary>
/// OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.
/// </summary>
/// <param name="data">Slice object keyed by symbol containing the stock data</param>
public void OnData(TradeBars data)
{
TradeBar currentBar = data [Symbol];
if (!data.ContainsKey (Symbol))
return;
_tradeBars.Add (currentBar);
if (!_tradeBars.IsReady)
return;
if (!ema.IsReady)
return;
_emaValues.Add (ema.Current.Value);
if (_emaValues.Count > 10)
_emaValues.RemoveAt (0);
var slope = 0m;
if (_emaValues.Count > 2) {
var xVals = new double[_emaValues.Count];
var yVals = new double[_emaValues.Count];
// load input data for regression
for (int i = 0; i < _emaValues.Count; i++) {
xVals [i] = i;
// we want the log of our y values
yVals [i] = (double)_emaValues [i];
}
//http://numerics.mathdotnet.com/Regression.html
// solves y=a + b*x via linear regression
var fit = Fit.Line (xVals, yVals);
var intercept = fit.Item1;
slope = (decimal)fit.Item2;
}
var diff = currentBar.Close / ema.Current.Value - 1.0m;
if (diff > 0.01m && slope > 0m) {
if (!Portfolio[Symbol].Invested) {
SetHoldings (Symbol, 1);
Debug ("Purchased Stock");
}
} else {
Liquidate (Symbol);
}
}
示例4: OnData
/// <summary>
/// OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.
/// </summary>
/// <param name="data">TradeBars IDictionary object with your stock data</param>
public void OnData(TradeBars data)
{
if (!macd.IsReady) return;
if (!data.ContainsKey("IBM")) return;
if (lastAction.Date == Time.Date) return;
lastAction = Time;
var holding = Portfolio["SPY"];
if (holding.Quantity <= 0 && macd > macd.Signal && data["IBM"].Price > ema)
{
SetHoldings("IBM", 0.25m);
}
else if (holding.Quantity >= 0 && macd < macd.Signal && data["IBM"].Price < ema)
{
SetHoldings("IBM", -0.25m);
}
}
示例5: Run
/********************************************************
* CLASS METHODS
*********************************************************/
/// <summary>
/// Launch the algorithm manager to run this strategy
/// </summary>
/// <param name="job">Algorithm job</param>
/// <param name="algorithm">Algorithm instance</param>
/// <param name="feed">Datafeed object</param>
/// <param name="transactions">Transaction manager object</param>
/// <param name="results">Result handler object</param>
/// <param name="setup">Setup handler object</param>
/// <param name="realtime">Realtime processing object</param>
/// <remarks>Modify with caution</remarks>
public static void Run(AlgorithmNodePacket job, IAlgorithm algorithm, IDataFeed feed, ITransactionHandler transactions, IResultHandler results, ISetupHandler setup, IRealTimeHandler realtime)
{
//Initialize:
var backwardsCompatibilityMode = false;
var tradebarsType = typeof (TradeBars);
var ticksType = typeof(Ticks);
var startingPerformance = setup.StartingCapital;
var backtestMode = (job.Type == PacketType.BacktestNode);
var methodInvokers = new Dictionary<Type, MethodInvoker>();
//Initialize Properties:
_frontier = setup.StartingDate;
_runtimeError = null;
_algorithmId = job.AlgorithmId;
_algorithmState = AlgorithmStatus.Running;
_previousTime = setup.StartingDate.Date;
//Create the method accessors to push generic types into algorithm: Find all OnData events:
//Algorithm 1.0 Data Accessors.
//If the users defined these methods, add them in manually. This allows keeping backwards compatibility to algorithm 1.0.
var oldTradeBarsMethodInfo = (algorithm.GetType()).GetMethod("OnTradeBar", new[] { typeof(Dictionary<string, TradeBar>) });
var oldTicksMethodInfo = (algorithm.GetType()).GetMethod("OnTick", new[] { typeof(Dictionary<string, List<Tick>>) });
//Algorithm 2.0 Data Generics Accessors.
//New hidden access to tradebars with custom type.
var newTradeBarsMethodInfo = (algorithm.GetType()).GetMethod("OnData", new[] { tradebarsType });
var newTicksMethodInfo = (algorithm.GetType()).GetMethod("OnData", new[] { ticksType });
if (newTradeBarsMethodInfo == null && newTicksMethodInfo == null)
{
backwardsCompatibilityMode = true;
if (oldTradeBarsMethodInfo != null) methodInvokers.Add(tradebarsType, oldTradeBarsMethodInfo.DelegateForCallMethod());
if (oldTradeBarsMethodInfo != null) methodInvokers.Add(ticksType, oldTicksMethodInfo.DelegateForCallMethod());
}
else
{
backwardsCompatibilityMode = false;
if (newTradeBarsMethodInfo != null) methodInvokers.Add(tradebarsType, newTradeBarsMethodInfo.DelegateForCallMethod());
if (newTicksMethodInfo != null) methodInvokers.Add(ticksType, newTicksMethodInfo.DelegateForCallMethod());
}
//Go through the subscription types and create invokers to trigger the event handlers for each custom type:
foreach (var config in feed.Subscriptions)
{
//If type is a tradebar, combine tradebars and ticks into unified array:
if (config.Type.Name != "TradeBar" && config.Type.Name != "Tick")
{
//Get the matching method for this event handler - e.g. public void OnData(Quandl data) { .. }
var genericMethod = (algorithm.GetType()).GetMethod("OnData", new[] { config.Type });
//Is we already have this Type-handler then don't add it to invokers again.
if (methodInvokers.ContainsKey(config.Type)) continue;
//If we couldnt find the event handler, let the user know we can't fire that event.
if (genericMethod == null)
{
_runtimeError = new Exception("Data event handler not found, please create a function matching this template: public void OnData(" + config.Type.Name + " data) { }");
_algorithmState = AlgorithmStatus.RuntimeError;
return;
}
methodInvokers.Add(config.Type, genericMethod.DelegateForCallMethod());
}
}
//Loop over the queues: get a data collection, then pass them all into relevent methods in the algorithm.
Log.Debug("AlgorithmManager.Run(): Algorithm initialized, launching time loop.");
foreach (var newData in DataStream.GetData(feed, setup.StartingDate))
{
//Check this backtest is still running:
if (_algorithmState != AlgorithmStatus.Running) break;
//Go over each time stamp we've collected, pass it into the algorithm in order:
foreach (var time in newData.Keys)
{
//Set the time frontier:
_frontier = time;
//Execute with TimeLimit Monitor:
if (Isolator.IsCancellationRequested) return;
//Refresh the realtime event monitor:
realtime.SetTime(time);
//Fire EOD if the time packet we just processed is greater
if (backtestMode && _previousTime.Date != time.Date)
//.........这里部分代码省略.........
示例6: OnData
public void OnData(TradeBars data)
{
OrderSignal actualOrder = OrderSignal.doNothing;
int i = 0; // just for logging
foreach (string symbol in Symbols)
{
if (!data.ContainsKey(symbol) || !Strategy[symbol].IsReady) continue;
bool breakCondition = (Time.Date == new DateTime(2015, 08, 07) || Time.Date == new DateTime(2015, 08, 10))
&& isNormalOperativeTime
&& symbol == "MSFT";
if (isNormalOperativeTime)
{
actualOrder = Strategy[symbol].ActualSignal;
}
else if (noOvernight && isMarketAboutToClose)
{
actualOrder = CloseAllPositions(symbol);
}
ExecuteStrategy(symbol, actualOrder);
#region Logging stuff - Filling the data StockLogging
//Time,Close,Decycle,InvFisher,LightSmoothPrice,Momersion,PSAR,Position
string newLine = string.Format("{0},{1},{2},{3},{4}",
Time.ToString("u"),
data[symbol].Close,
Strategy[symbol].SmoothedSeries.Current.Value,
PSARDict[symbol].Current.Value,
Portfolio[symbol].Invested ? Portfolio[symbol].IsLong ? 1 : -1 : 0
);
stockLogging[i].AppendLine(newLine);
i++;
#endregion Logging stuff - Filling the data StockLogging
}
barCounter++; // just for logging
}