Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Ошибка в trailing логике ProtectiveProcessor #436

Closed
falkolab opened this issue Apr 30, 2024 · 0 comments
Closed

Ошибка в trailing логике ProtectiveProcessor #436

falkolab opened this issue Apr 30, 2024 · 0 comments

Comments

@falkolab
Copy link

Исходим из того, что защищаем лонговую позицию со стоплосом в 1% и трейлинговым режимом без таймаута, используем рыночные заявки
StopValue = new Unit(1, UnitTypes.Percent)

То есть при входе в позицию мы должны установить стоп на уровень -1% от точки входа и далее при увеличении цены передвигать стоплос на уровень -1% от новой цены на рынке. При ходе цены вниз мы должны выставить заявку при достижении последнего обновленного уровня стоплос.

Если так, рассмотрим пример из репозитория SmpleHistoryTesting и последний код из master ветки
На первом трейде вызывается метод

public override (bool isTake, Sides side, decimal price, decimal volume, OrderCondition condition)? Update(decimal price, decimal value)

И инициализируем ProtectiveProcessor

var protectiveSide = _posValue > 0 ? Sides.Buy : Sides.Sell;
_take = TakeValue.IsSet() ? new(protectiveSide, _posPrice, protectiveSide == Sides.Buy, IsTakeTrailing, TakeValue, UseMarketOrders, new(), TakeTimeout, this) : null;
_stop = StopValue.IsSet() ? new(protectiveSide, _posPrice, protectiveSide == Sides.Sell, IsStopTrailing, StopValue, UseMarketOrders, new(), StopTimeout, this) : null;

_stop = StopValue.IsSet() ? new(protectiveSide, _posPrice, protectiveSide == Sides.Sell, IsStopTrailing, StopValue, UseMarketOrders, new(), StopTimeout, this) : null;
То есть конструктор будет вызван с параметрами:

Sides protectiveSide = Buy
      Decimal protectivePrice = пусть 180
      bool isUpTrend = False
      bool isTrailing = True
      Unit protectiveLevel = new Unit(1, UnitTypes.Percent)
      bool useMarketOrders = true
      Unit priceOffset = new Unit(),
      TimeSpan timeout = default

Далее по коду примера вызываем _posController?.TryActivate(candle.ClosePrice, CurrentTime) на каждом ProcessCandle из стратегнии.

Еще раз подчеркну, у нас _isUpTrend = False
Далее, первый раз попадая сюда

var activationPrice = getActivationPrice();
if (isActivation(activationPrice))
{
// Protective level reached, trailing activated
_prevBestPrice = currPriceDec;
}
}

Мы считаем activationPrice
var activationPrice = _protectiveLevel.Type == UnitTypes.Limit
? _protectiveLevel.Value
: (_isUpTrend ? _protectivePrice + _protectiveLevel.Value : _protectivePrice - _protectiveLevel.Value);

Как _protectivePrice - _protectiveLevel.Value тоесть 180-1%=178.2 что выглядит правильно
Но назначаем
if (isActivation(activationPrice))
{
// Protective level reached, trailing activated
_prevBestPrice = currPriceDec;

Только если текущая цена ниже этого уровня,
bool isActivation(decimal activationPrice)
=> (_isUpTrend && currPriceDec >= activationPrice) || (!_isUpTrend && currPriceDec <= activationPrice);

Хотя должны уже закрывать позицию, но код делает иначе,
мы сдвигаем _prevBestPrice еще ниже
if (_prevBestPrice > currPriceDec)
_prevBestPrice = currPriceDec;
else
return getClosePosPrice();

И только после того, как цена дернется выше _prevBestPrice (хотя делать должны наоборот, двигать лучшую цену вверх, да еще и учитывать -1%) ми закрываем позицию.
При стоп трейлинге getActivationPrice используется один раз вначале и далее не учитывается
var activationPrice = getActivationPrice();

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants