pyhta4og
|
Date: 11/9/2012
|
|
|
|
vk37 Я бы инициализацию стратегии перенес сюда. А то ошибка происходит, про состояние объекта что-то. Code
_trader.StateChanged += (oldState, newState) =>
{
if (_trader.State == EmulationStates.Stopped)
{
this.GuiAsync(() =>
{
StartBtn.IsEnabled = true;
if (_trader.IsFinished)
{
TestingProcess.Value = TestingProcess.Maximum;
MessageBox.Show(this, "Закончено за " + (DateTime.Now - _startEmulationTime));
}
else
MessageBox.Show(this, "Отменено");
});
}
else if (_trader.State == EmulationStates.Started)
{
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// создаем торговую стратегию, скользящие средние на 80 5-минуток и 10 5-минуток
_strategy = new SmaStrategy(series, new SimpleMovingAverage { Length = 80 }, new SimpleMovingAverage { Length = 10 })
{
Volume = 1,
Portfolio = portfolio,
Security = security,
Trader = _trader
};
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// запускаем стратегию когда эмулятор запустился
_strategy.Start();
}
};
тогда у вас стратегия не факт что запустится с начала данных - эмулятор уедет вперед
|
|
Thanks:
|
|
|
|
|
vk37
|
Date: 11/10/2012
|
|
|
|
Ошибка, в общем, возникает при инициализации старетгии. Вне зависимости в каком месте ее инициализировать. Возникает не при каждом запуске. Одна и та же сборка иногда нормально сработает, а иногда с ошибкой. Может кто сталкивался? Code
System.AggregateException: One or more errors occurred. ---> System.InvalidOperationException: Operation is not valid due to the current state of the object.
at StockSharp.Algo.BaseTrader.ProcessEvents(Action handler)
at AlgoTrading.HistoryTesting.Optimizer.<>c__DisplayClassb.<Optimize>b__5(ParamsDto period) in c:\ActiveProjects\AlgoTrading3\trunk\SourceCode\HistoryTesting\Optimizer.cs:line 83
at System.Threading.Tasks.Parallel.<>c__DisplayClassf`1.<ForWorker>b__c()
at System.Threading.Tasks.Task.InnerInvokeWithArg(Task childTask)
at System.Threading.Tasks.Task.<>c__DisplayClass10.<ExecuteSelfReplicating>b__f(Object param0)
--- End of inner exception stack trace ---
at System.Threading.Tasks.Task.Wait(Int32 millisecondsTimeout, CancellationToken cancellationToken)
at System.Threading.Tasks.Task.Wait()
at System.Threading.Tasks.Parallel.ForWorker[TLocal](Int32 fromInclusive, Int32 toExclusive, ParallelOptions parallelOptions, Action`1 body, Action`2 bodyWithState, Func`4 bodyWithLocal, Func`1 localInit, Action`1 localFinally)
at System.Threading.Tasks.Parallel.ForEachWorker[TSource,TLocal](IEnumerable`1 source, ParallelOptions parallelOptions, Action`1 body, Action`2 bodyWithState, Action`3 bodyWithStateAndIndex, Func`4 bodyWithStateAndLocal, Func`5 bodyWithEverything, Func`1 localInit, Action`1 localFinally)
at System.Threading.Tasks.Parallel.ForEach[TSource](IEnumerable`1 source, ParallelOptions parallelOptions, Action`1 body)
at AlgoTrading.HistoryTesting.Optimizer.Optimize() in c:\ActiveProjects\AlgoTrading3\trunk\SourceCode\HistoryTesting\Optimizer.cs:line 129
at AlgoTrading.HistoryTesting.Program.Main() in c:\ActiveProjects\AlgoTrading3\trunk\SourceCode\HistoryTesting\Program.cs:line 29
---> (Inner Exception #0) System.InvalidOperationException: Operation is not valid due to the current state of the object.
at StockSharp.Algo.BaseTrader.ProcessEvents(Action handler)
at AlgoTrading.HistoryTesting.Optimizer.<>c__DisplayClassb.<Optimize>b__5(ParamsDto period) in c:\ActiveProjects\AlgoTrading3\trunk\SourceCode\HistoryTesting\Optimizer.cs:line 83
at System.Threading.Tasks.Parallel.<>c__DisplayClassf`1.<ForWorker>b__c()
at System.Threading.Tasks.Task.InnerInvokeWithArg(Task childTask)
at System.Threading.Tasks.Task.<>c__DisplayClass10.<ExecuteSelfReplicating>b__f(Object param0)<---
---> (Inner Exception #1) System.InvalidOperationException: Operation is not valid due to the current state of the object.
at StockSharp.Algo.BaseTrader.ProcessEvents(Action handler)
at AlgoTrading.HistoryTesting.Optimizer.<>c__DisplayClassb.<Optimize>b__5(ParamsDto period) in c:\ActiveProjects\AlgoTrading3\trunk\SourceCode\HistoryTesting\Optimizer.cs:line 83
at System.Threading.Tasks.Parallel.<>c__DisplayClassf`1.<ForWorker>b__c()
at System.Threading.Tasks.Task.InnerInvokeWithArg(Task childTask)
at System.Threading.Tasks.Task.<>c__DisplayClass10.<ExecuteSelfReplicating>b__f(Object param0)<---
---> (Inner Exception #2) System.InvalidOperationException: Operation is not valid due to the current state of the object.
at StockSharp.Algo.BaseTrader.ProcessEvents(Action handler)
at AlgoTrading.HistoryTesting.Optimizer.<>c__DisplayClassb.<Optimize>b__5(ParamsDto period) in c:\ActiveProjects\AlgoTrading3\trunk\SourceCode\HistoryTesting\Optimizer.cs:line 83
at System.Threading.Tasks.Parallel.<>c__DisplayClassf`1.<ForWorker>b__c()
at System.Threading.Tasks.Task.InnerInvokeWithArg(Task childTask)
at System.Threading.Tasks.Task.<>c__DisplayClass10.<ExecuteSelfReplicating>b__f(Object param0)<---
---> (Inner Exception #3) System.InvalidOperationException: Operation is not valid due to the current state of the object.
at StockSharp.Algo.BaseTrader.ProcessEvents(Action handler)
at AlgoTrading.HistoryTesting.Optimizer.<>c__DisplayClassb.<Optimize>b__5(ParamsDto period) in c:\ActiveProjects\AlgoTrading3\trunk\SourceCode\HistoryTesting\Optimizer.cs:line 83
at System.Threading.Tasks.Parallel.<>c__DisplayClassf`1.<ForWorker>b__c()
at System.Threading.Tasks.Task.InnerInvokeWithArg(Task childTask)
at System.Threading.Tasks.Task.<>c__DisplayClass10.<ExecuteSelfReplicating>b__f(Object param0)<---
---> (Inner Exception #4) System.InvalidOperationException: Operation is not valid due to the current state of the object.
at StockSharp.Algo.BaseTrader.ProcessEvents(Action handler)
at AlgoTrading.HistoryTesting.Optimizer.<>c__DisplayClassb.<Optimize>b__5(ParamsDto period) in c:\ActiveProjects\AlgoTrading3\trunk\SourceCode\HistoryTesting\Optimizer.cs:line 83
at System.Threading.Tasks.Parallel.<>c__DisplayClassf`1.<ForWorker>b__c()
at System.Threading.Tasks.Task.InnerInvokeWithArg(Task childTask)
at System.Threading.Tasks.Task.<>c__DisplayClass10.<ExecuteSelfReplicating>b__f(Object param0)<---
---> (Inner Exception #5) System.InvalidOperationException: Operation is not valid due to the current state of the object.
at StockSharp.Algo.BaseTrader.ProcessEvents(Action handler)
at AlgoTrading.HistoryTesting.Optimizer.<>c__DisplayClassb.<Optimize>b__5(ParamsDto period) in c:\ActiveProjects\AlgoTrading3\trunk\SourceCode\HistoryTesting\Optimizer.cs:line 83
at System.Threading.Tasks.Parallel.<>c__DisplayClassf`1.<ForWorker>b__c()
at System.Threading.Tasks.Task.InnerInvokeWithArg(Task childTask)
at System.Threading.Tasks.Task.<>c__DisplayClass10.<ExecuteSelfReplicating>b__f(Object param0)<---
---> (Inner Exception #6) System.InvalidOperationException: Operation is not valid due to the current state of the object.
at StockSharp.Algo.BaseTrader.ProcessEvents(Action handler)
at AlgoTrading.HistoryTesting.Optimizer.<>c__DisplayClassb.<Optimize>b__5(ParamsDto period) in c:\ActiveProjects\AlgoTrading3\trunk\SourceCode\HistoryTesting\Optimizer.cs:line 83
at System.Threading.Tasks.Parallel.<>c__DisplayClassf`1.<ForWorker>b__c()
at System.Threading.Tasks.Task.InnerInvokeWithArg(Task childTask)
at System.Threading.Tasks.Task.<>c__DisplayClass10.<ExecuteSelfReplicating>b__f(Object param0)<---
---> (Inner Exception #7) System.InvalidOperationException: Operation is not valid due to the current state of the object.
at StockSharp.Algo.BaseTrader.ProcessEvents(Action handler)
at AlgoTrading.HistoryTesting.Optimizer.<>c__DisplayClassb.<Optimize>b__5(ParamsDto period) in c:\ActiveProjects\AlgoTrading3\trunk\SourceCode\HistoryTesting\Optimizer.cs:line 83
at System.Threading.Tasks.Parallel.<>c__DisplayClassf`1.<ForWorker>b__c()
at System.Threading.Tasks.Task.InnerInvokeWithArg(Task childTask)
at System.Threading.Tasks.Task.<>c__DisplayClass10.<ExecuteSelfReplicating>b__f(Object param0)<---
|
|
Thanks:
|
|
|
|
|
pyhta4og
|
Date: 11/12/2012
судя по колстаку у вас Parallel.For или что-то в этом духе. Там точно нет ситуации что EmulationTrader дергается из двух разных потоков? Он вполне может быть не потокобезопасным.
если вам надо сделать оптимизацию гораздо быстрее будет сделать кучу экземпляров стратегии с разными параметрами и всю кучу прогнать в одном эмуляйшн-трейдере.
|
|
Thanks:
|
|
|
|
|
vk37
|
Date: 11/12/2012
|
|
|
|
В упрощенном виде код оптимизации такой: Code
public class Optimizer
{
private IStorageRegistry _storageRegistry;
private LocalMarketDataDrive _defaultDrive;
public void Optimize()
{
var startTime = new DateTime(2012, 9, 10);
var stopTime = new DateTime(2012, 11, 8);
_storageRegistry = new StorageRegistry();
_defaultDrive = (LocalMarketDataDrive)_storageRegistry.DefaultDrive;
_defaultDrive.Path = @"D:\DBs\HydraData\Smart";
var security = Securities.Instance.RtsF;
var periods = MyStrategy.GetParamCombinations();
Parallel.ForEach(periods, new ParallelOptions { MaxDegreeOfParallelism = 8 }, period =>
{
using (var waitHandle = new AutoResetEvent(false))
{
var rts = security.Clone();
var portfolio = new Portfolio { Name = "test account", BeginValue = 100000m };
var trader = new EmulationTrader(
new[] { rts },
new[] { portfolio },
_storageRegistry)
{
UseMarketDepth = true,
StorageRegistry = _storageRegistry,
};
trader.MarketEmulator.Settings.Latency = TimeSpan.FromSeconds(1);
trader.RegisterMarketDepth(rts);
trader.Connect();
trader.StartExport();
var strategy = new MyStrategy(period)
{
Volume = 1,
Security = rts,
Portfolio = portfolio,
Trader = trader,
CommissionManager = rts.GetComissionManager(),
};
trader.StateChanged += (oldState, newState) =>
{
if (trader.State == EmulationStates.Started)
strategy.Start();
else if (trader.State == EmulationStates.Stopped)
{
new ExcelStrategyReport(strategy, path).Generate();
waitHandle.Set();
}
};
trader.Start(startTime, stopTime);
waitHandle.WaitOne();
}
});
}
}
Вроде EmulationTrader на правильном месте. Не знаю как правильно )
|
|
Thanks:
|
|
|
|
|
Mikhail Sukhov
|
Date: 11/12/2012
Quote:System.InvalidOperationException: Operation is not valid due to the current state of the object. at StockSharp.Algo.BaseTrader.ProcessEvents(Action handler) at AlgoTrading.HistoryTesting.Optimizer.<>c__DisplayClassb.<Optimize>b__5(ParamsDto period) in c:\ActiveProjects\AlgoTrading3\trunk\SourceCode\HistoryTesting\Optimizer.cs:line 83 По стек трейсу видно, что напрямую вызывается BaseTrader.ProcessEvents. Зачем?
|
|
Thanks:
|
|
|
|
|
vk37
|
Date: 11/13/2012
|
|
|
|
Mikhail Sukhov Quote:System.InvalidOperationException: Operation is not valid due to the current state of the object. at StockSharp.Algo.BaseTrader.ProcessEvents(Action handler) at AlgoTrading.HistoryTesting.Optimizer.<>c__DisplayClassb.<Optimize>b__5(ParamsDto period) in c:\ActiveProjects\AlgoTrading3\trunk\SourceCode\HistoryTesting\Optimizer.cs:line 83 По стек трейсу видно, что напрямую вызывается BaseTrader.ProcessEvents. Зачем? Даже не знаю что это такое. Строка 83 - инициализация стратегии. Упрощенный код моей стратегии: Code
public sealed class MyStrategy : AbstractStrategy
{
private bool _canProcess = true;
private readonly object _locker = new object();
public CsvLogManager CsvLogManager { get; set; }
protected override void OnStarted()
{
Security
.WhenMarketDepthChanged()
.Do(ProcessDepth)
.Sync(_locker)
.Apply(this);
this.WhenNewMyTrades()
.Do(myTrades =>
{
foreach (var myTrade in myTrades)
{
CsvLogManager.WriteLine(new MyTradeLogItem()
{
Now = DateTime.Now,
CurrentTime = CurrentTime,
TradeId = myTrade.Trade.Id,
TransactionId = myTrade.Order.TransactionId,
Time = myTrade.Trade.Time,
TradePrice = myTrade.Trade.Price,
OrderPrice = myTrade.Order.Price,
TradeVolume = myTrade.Trade.Volume,
Direction = myTrade.Order.Direction,
OrderId = myTrade.Order.Id,
Slippage = myTrade.GetSlippage(true),
SlippageQuoting = SlippageManager.GetSlippage(myTrade),
Comment = comment,
});
CsvLogManager.WriteLine(new MyTradeWmsLogItem()
{
Time = myTrade.Trade.Time,
SecurityCode = Security.Id == Securities.Instance.RtsF.Id ? "RTS" : Security.Code,
Direction = myTrade.Order.Direction,
Price = myTrade.Trade.Price,
Volume = myTrade.Trade.Volume,
Comission = myTrade.Trade.Volume * 2,
});
}
})
.Apply(this);
base.OnStarted();
}
protected override void OnStopped()
{
base.OnStopped();
CsvLogManager.Dispose();
}
private void ProcessDepth(MarketDepth depth)
{
if (!Security.Exchange.IsTradeTime(depth.LastChangeTime))
return;
if (CsvLogManager.MarketDepthLogEnabled)
CsvLogManager.WriteLine(new MarketDepthLogItem()
{
Now = DateTime.Now,
CurrentTime = CurrentTime,
MarketDepthTime = depth.LastChangeTime,
Ratio = ratio,
CanProcess = Convert.ToInt32(_canProcess),
CurrentPrice = price,
BestAsk = depth.BestAsk == null ? 0 : depth.BestAsk.Price,
BestBid = depth.BestBid == null ? 0 : depth.BestBid.Price,
PnL = PnL,
PortfolioBeginValue = Portfolio.BeginValue,
PortfolioCurrentValue = Portfolio.CurrentValue,
PortfolioVariationMargin = Portfolio.VariationMargin,
PortfolioComission = Portfolio.Commission,
PortfolioGetPrice = Portfolio.GetPrice(),
});
if (!_canProcess)
return;
var closePosition = ShouldClose();
var openPosition = ShouldOpen();;
if (closePosition || openPosition)
{
_canProcess = false;
var volume = 0m;
if (closePosition)
volume += Math.Abs(Position);
if (openPosition)
volume += Volume;
var strategy = new MyQuotingStrategy(orderDirection,
new Unit(price, UnitTypes.Absolute, Security),
new Unit(1, UnitTypes.Step, Security),
comment) { Volume = volume };
strategy
.WhenStopped()
.Do(() =>
{
_canProcess = true;
})
.Once()
.Sync(_locker)
.Apply(this);
ChildStrategies.Add(strategy);
}
}
}
Может неявно как-то вызывается. Могу выслать код стратегии котирования. Для ревью )
|
|
Thanks:
|
|
|
|
|
Mikhail Sukhov
|
Date: 11/13/2012
vk37 Может неявно как-то вызывается. Могу выслать код стратегии котирования. Для ревью )
Если только Михаил заинтересуется[biggrin] Мне и своего кода для ревьирования хватает, спасибо. Надо поднтянуть матчасть связанную с отладкой ошибок. Дебаггер, рефлектор.
|
|
Thanks:
|
|
|
|
|
vk37
|
Date: 11/13/2012
Mikhail Sukhov Дебаггер, рефлектор. деобфускатор? )
|
|
Thanks:
|
|
|
|
|
Mikhail Sukhov
|
Date: 11/13/2012
vk37 Mikhail Sukhov Дебаггер, рефлектор. деобфускатор? ) Да я про ваш код имел ввиду. Хотя конечно я бы начал с основ - что такое исключение и что такое стектрейс. Но я так понял вы не из тех, кто любит на всякие разности отвлекаться.[rolleyes]
|
|
Thanks:
|
|
|
|
|
komaranton
|
Date: 9/8/2019
Получилось разобраться?
|
|
Thanks:
|
|
|
|