Общие вопросы по разработке > закрытие позиции

Общие вопросы по разработке в Альфа-Директ 4. Обсуждение разработки пользовательских индикаторов, стратегий.
magnaut
Сообщения: 10
Зарегистрирован: 14 авг 2016, 10:10
Благодарил (а): 2 раза

Re: закрытие позиции

Непрочитанное сообщение magnaut » 14 авг 2016, 12:52

И К НЕМУ ЕЩЁ ДВА ИНДИКАТОРА ДОПОЛНЕНИЯ

magnaut
Сообщения: 10
Зарегистрирован: 14 авг 2016, 10:10
Благодарил (а): 2 раза

Re: закрытие позиции

Непрочитанное сообщение magnaut » 14 авг 2016, 12:56

Код: Выделить всё

// Gaussian IIR Filter with 1 to 4 Poles
// implementation: DrKoch
function GaussianSeries( Series: Integer; Period: Float; Poles: Integer): integer;
begin
  var Bar: integer;
  var sName: string;
  var a, b, w: float;
  var x: float; // Input value
  var y, y1, y2, y3, y4: float; // Output series
  var a_1, a_12, a_13, a_14: float;
  var a2, a3, a4: float;

  sName := 'Gaussian(' + GetDescription( Series )
   + ',' + FloatToStr( Period )
   + ',' + IntToStr( Poles )
   + ')';
  Result := FindNamedSeries( sName );
  if Result >= 0 then
    Exit;
  Result := CreateNamedSeries( sName );

  if (poles < 1) or (poles > 4) then begin
       raise exception.Create('GaussianSeries: bad number of poles (expect 1..4)');
  end;

  w := 2 * Pi / Period; // omega
  w := 180 * w / Pi;    // in degrees
 
  b := (1 - cos(w)) / (power(1.414, 2.0/poles) - 1.0);

  a := -b + sqrt(b*b + 2*b);
  a_1 := 1.0 - a;
  a_12 := a_1 * a_1;
  a_13 := a_1 * a_1 * a_1;
  a_14 := a_12 * a_12;
  a2 := a * a;
  a3 := a * a * a;
  a4 := a2 * a2;
 
  y1 := GetSeriesValue(0, Series);
  y2 := y1;
  y3 := y2;
  y4 := y3;

  for Bar := 0 to BarCount() - 1 do
  begin
    { Calculate your indicator value here }
    x :=  GetSeriesValue( Bar, Series);
    case poles of
      1: begin
        y := a * x + a_1 * y1;
      end;
      2: begin
        y := a2 * x + 2 * a_1 * y1 - a_12 * y2;
      end;
      3: begin
        y := a3 * x + 3 * a_1 * y1 - 3 * a_12 * y2
            + a_13 * y3;
      end;
      4: begin
        y := a4 * x + 4 * a_1 * y1 - 6 * a_12 * y2
            + 4 * a_13 * y3 - a_14 * y4;
      end;
    end;

    SetSeriesValue( Bar, Result, y );
    y4 := y3; // delayed by four bars
    y3 := y2; // delayed by three bars
    y2 := y1; // delayed by two bars
    y1 := y;  // delayed by one bar
  end;
end;


// Gaussian IIR Filter with N Poles
function Gaussian( Bar: integer; Series: Integer; Period: Float;
                   Poles: Integer ): float;
begin
  Result := GetSeriesValue( Bar, GaussianSeries( Series, Period, Poles ) );
end;

magnaut
Сообщения: 10
Зарегистрирован: 14 авг 2016, 10:10
Благодарил (а): 2 раза

Re: закрытие позиции

Непрочитанное сообщение magnaut » 14 авг 2016, 13:03

Код: Выделить всё

// PeekChecker
// Check if Script peeks into future
type PeekCheck = class
private
  active: boolean;
  warn_level: integer;
  poslink: integer;
  timestamp: float;
  access_proc: string;
  access_info: string;
  access_bar: integer;
  autostops_first_time, autostops_last_time: float;
  procedure Trade(Bar: integer; time: float; proc: string; info: string);
protected
public
  qprint: boolean;
  constructor Create;
  procedure Access(Bar: integer; time: float; proc: string; info: string);
  procedure Enter(Bar: integer; time: float; proc: string; info: string);
  procedure Exitp(Bar: integer; time: float; proc: string; info: string);
  procedure Start(level, poslink: integer);
  procedure auto_time(atime: float);

end;

constructor PeekCheck.Create;
begin
  active := false;
  warn_level := 0;
  timestamp := 0.0;
  autostops_last_time := 0.0;
  autostops_first_time := 1.0;
  qprint := false;
end;

procedure PeekCheck.auto_time(atime: float);
begin
  // ApplyAutoStops does two things:
  // first it trades at a certine time (autostops_first_time
  // (this is the earliest of all auto trades)
  // second it accesses data at a certain time
  // (this is the latest of all auto trades)
  if atime > autostops_last_time then autostops_last_time := atime;
  if atime < autostops_first_time then autostops_first_time := atime;
end;

procedure PeekCheck.Access(Bar: integer; time: float; proc: string; info: string);
begin
  if not active then exit;
  var ts: float;
  ts := Bar + time;
  if ts > timestamp then begin
    timestamp := ts;
    access_proc := proc;
    access_bar := Bar;
    access_info := info;
    if qprint then Print(FloatToStr(timestamp) + ': Access from ' + proc + info);
  end;
end;

procedure PeekCheck.Enter(Bar: integer; time: float; proc: string; info: string);
begin
    Trade(Bar, time, proc, info);
    if(poslink > 0) then Access(Bar, time, proc, info);
end;

procedure PeekCheck.exitp(Bar: integer; time: float; proc: string; info: string);
begin
    Trade(Bar, time, proc, info);
    // a trade accesses info also
    Access(Bar, time, proc, info);
end;

procedure PeekCheck.Trade(Bar: integer; time: float; proc: string; info: string);
begin
  if not active then exit;
  var ts: float;
 
  ts := Bar + time;
  if warn_level > 1 then ts := Bar; // no trade on same bar as access
  if qprint then Print(FloatToStr(ts) + ': Trade from ' + proc + info);
  if ts < timestamp then begin
    // generate error message
    var msg: string;
    msg := 'Impossible trade!' + #10
         + 'Script peeks into future.' + #10
         + '  (in proc ' + proc + ' at Bar '
    + IntToStr(Bar);
    if info <> '' then begin
        msg := msg + ', info: ' + info;
    end;
    msg := msg + ', timestamp = ' + FloatToStr(ts) + ')' + #10
        + 'Trade uses data later than this trade. Data was accessed:' + #10
        + '  (by ' + access_proc
    + ' at Bar ' + IntToStr(access_bar);
    if access_info <> '' then begin
        msg := msg + ', info: ' + access_info;
    end;
    msg := msg + ', timestamp: ' + FloatToStr(timestamp);
    msg := msg + ')';
    AddCommentary( msg ); // for www.wealth-lab.com scripts
    ShowMessage( msg );   // for WLD Scripts
    active := false;      // stop after first error
  end;
end;

// start checking
// level:
//   0 - no checks
//   1 - check causality, allow pessimistic sequences
//   2 - check causality strictly
// poslink:
//   0 - no checks
//   1 - warn about Buys in afternoon before sells in the morning
procedure PeekCheck.Start(level: integer; poslink: integer);
begin
  warn_level := level;
  active := (level > 0);  // active if level > 0
  self.poslink := poslink;
end;


var PeekChecker: PeekCheck;
PeekChecker := PeekCheck.Create();

// Control
procedure StartPeekCheck(level, poslink: integer);
begin
  PeekChecker.Start(level, poslink);
end;

// Drop-in replacements
// access prices
function PriceAverageR( Bar: integer ): float;
begin
    PeekChecker.Access(Bar, 0.9, 'PriceAverage', '');
    Result := PriceAverage( Bar );
end;

function PriceAverageCR( Bar: integer ): float;
begin
    PeekChecker.Access(Bar, 0.9, 'PriceAverageC', '');
    Result := PriceAverageC( Bar );
end;

function PriceCloseR( Bar: integer ): float;
begin
    PeekChecker.Access(Bar, 0.9, 'PriceClose', '');
    Result := PriceClose( Bar );
end;

function PriceHighR( Bar: integer ): float;
begin
    PeekChecker.Access(Bar, 0.8, 'PriceHigh', '');
    Result := PriceHigh( Bar );
end;

function PriceLowR( Bar: integer ): float;
begin
    PeekChecker.Access(Bar, 0.8, 'PriceLow', '');
    Result := PriceLow( Bar );
end;

function PriceOpenR( Bar: integer ): float;
begin
    PeekChecker.Access(Bar, 0.1, 'PriceOpen', '');
    Result:= PriceOpen( Bar );
end;

function VolumeR( Bar: integer ): float;
begin
    PeekChecker.Access(Bar, 0.9, 'Volume', '');
    Result := Volume( Bar )
end;

// access indicators
function GetSeriesValueR( Bar: integer; Series: integer ): float;
begin
    PeekChecker.Access(Bar, 0.9, 'GetSeriesValue', '');
    Result := GetSeriesValue( Bar, Series);
end;

// Auto Stops
procedure InstallBreakEvenStopR( Trigger: float );
begin
    PeekChecker.auto_time(0.5);
    InstallBreakEvenStop( Trigger);
end;

procedure InstallProfitTargetR( Target: float );
begin
    PeekChecker.auto_time(0.7);
    InstallProfitTarget( Target);
end;

procedure InstallReverseBreakEvenStopR( LossLevel: float );
begin
    PeekChecker.auto_time(0.5);
    InstallReverseBreakEvenStop( LossLevel);
end;

procedure InstallStopLossR( StopLevel: float );
begin
    PeekChecker.auto_time(0.3);
    InstallStopLoss( StopLevel );
end;

procedure InstallTimeBasedExitR( Bars: integer );
begin
    PeekChecker.auto_time(0.0);
    InstallTimeBasedExit( Bars );
end;

procedure InstallTrailingStopR( Trigger: float; StopLevel: float );
begin
    PeekChecker.auto_time(0.3);
    InstallTrailingStop( Trigger, StopLevel);
end;
 
procedure ApplyAutoStopsR( Bar: integer );
begin
  if ActivePositionCount > 0 then begin
    var do_check: boolean;
    var p: integer;
    var num_p: integer;
    num_p := 0;
    for P := LastPosition downto 0 do begin
      if PositionActive(P) then begin
        num_p := num_p + 1;
        if PeekChecker.qprint then begin
         Print('ApplyAutoStops(Bar=' + IntToStr(Bar)
           + ' Pos= ' + IntToStr(P)
           + ' EntryBar= ' + IntToStr(PositionEntryBar(P)));
          Print('  autostops_first_time: ' +
            FloatToStr(PeekChecker.autostops_first_time));
          Print('  autostops_last_time: ' +
            FloatToStr(PeekChecker.autostops_last_time));
         end;
         // ApplyAutoStops never works at Bar of entry
         if PositionEntryBar(P) < Bar then begin
          do_check := true;
          // PeekChecker.exitp(Bar, PeekChecker.autostops_first_time, 'ApplyAutoStops', 'Trade');
          // PeekChecker.Access(Bar, PeekChecker.autostops_last_time, 'ApplyAutoStops', 'Access');
        end;
        if num_p >= ActivePositionCount then break; // avoid quadratic performance
      end;
    end;
    if do_check then begin // we have active positions for autostop
      PeekChecker.exitp(Bar, PeekChecker.autostops_first_time, 'ApplyAutoStops', 'Trade');
      PeekChecker.Access(Bar, PeekChecker.autostops_last_time, 'ApplyAutoStops', 'Access');
    end;
  end;
  ApplyAutoStops( Bar );
end;

// Trading
procedure BuyAtCloseR( Bar: integer; SignalName: string );
begin
    PeekChecker.Enter(Bar, 0.9, 'BuyAtClose', SignalName);
    BuyAtClose(Bar, SignalName);
end;

function BuyAtLimitR( Bar: integer; StopPrice: float; SignalName: string ): boolean;
begin
    PeekChecker.Enter(Bar, 0.1, 'BuyAtLimit', SignalName);
    Result := BuyAtLimit( Bar, StopPrice, SignalName );
end;

procedure BuyAtMarketR( Bar: integer; SignalName: string );
begin
    PeekChecker.Enter(Bar, 0.0, 'BuyAtMarket', SignalName);
    BuyAtMarket( Bar, 'Market' );
end;

function BuyAtStopR( Bar: integer; StopPrice: float; SignalName: string ): boolean;
begin
    PeekChecker.Enter(Bar, 0.2, 'BuyAtStop', SignalName);
    Result := BuyAtStop( Bar, StopPrice, SignalName);
end;

procedure CoverAtCloseR( Bar: integer; Position: integer; SignalName: string );
begin
    PeekChecker.exitp(Bar, 0.9, 'CoverAtClose', SignalName);
    CoverAtClose( Bar, Position, SignalName );
end;

function CoverAtLimitR( Bar: integer; LimitPrice: float; Position: integer;
     SignalName: string ): boolean;
begin
     PeekChecker.exitp(Bar, 0.7, 'CoverAtLimit', SignalName);
     Result := CoverAtLimit( Bar, LimitPrice, Position, SignalName);
end;

procedure CoverAtMarketR( Bar: integer; Position: integer;
     SignalName: string );
begin
     PeekChecker.exitp(Bar, 0.0, 'CoverAtMarket', SignalName);
     CoverAtMarket( Bar, Position, SignalName );
end;

function CoverAtStopR( Bar: integer; LimitPrice: float; Position: integer;
     SignalName: string ): boolean;
begin
    PeekChecker.exitp(Bar, 0.3, 'CoverAtStop', SignalName);
    Result := CoverAtStop( Bar, LimitPrice, Position, SignalName );
end;

function CoverAtTrailingStopR( Bar: integer; LimitPrice: float; Position: integer;
     SignalName: string ): boolean;
begin
    PeekChecker.exitp(Bar, 0.3, 'CoverAtTrailingStop', SignalName);
    Result := CoverAtTrailingStop( Bar, LimitPrice, Position, SignalName );
end;

procedure SellAtCloseR( Bar: integer; Position: integer;
     SignalName: string );
begin
    PeekChecker.exitp(Bar, 0.9, 'SellAtClose', SignalName);
    SellAtClose( Bar, Position, SignalName);
end;

function SellAtLimitR( Bar: integer; LimitPrice: float; Position: integer;
      SignalName: string ): boolean;
begin
    PeekChecker.exitp(Bar, 0.7, 'SellAtLimit', SignalName);
    Result := SellAtLimit( Bar, LimitPrice, Position, SignalName);
end;

procedure SellAtMarketR( Bar: integer; Position: integer;
     SignalName: string );
begin
    PeekChecker.exitp(Bar, 0.0, 'SellAtMarket', SignalName);
    SellAtMarket( Bar, Position, SignalName);
end;

function SellAtStopR( Bar: integer; LimitPrice: float; Position: integer;
      SignalName: string ): boolean;
begin
    PeekChecker.exitp(Bar, 0.3, 'SellAtStop', SignalName);
    Result := SellAtStop( Bar, LimitPrice, Position, SignalName);
end;

function SellAtTrailingStopR( Bar: integer; LimitPrice: float; Position: integer;
      SignalName: string ): boolean;
begin
    PeekChecker.exitp(Bar, 0.3, 'SellAtTrailingStop', SignalName);
    Result := SellAtTrailingStop( Bar, LimitPrice, Position, SignalName);
end;

procedure ShortAtCloseR( Bar: integer; SignalName: string );
begin
    PeekChecker.Enter(Bar, 0.9, 'ShortAtClose', SignalName);
    ShortAtClose( Bar, SignalName );
end;

function ShortAtLimitR( Bar: integer; StopPrice: float; SignalName: string ): boolean;
begin
    PeekChecker.Enter(Bar, 0.1, 'ShortAtLimit', SignalName);
    ShortAtLimit( Bar, StopPrice, SignalName );
end;

procedure ShortAtMarketR( Bar: integer; SignalName: string );
begin
    PeekChecker.Enter(Bar, 0.0, 'ShortAtMarket', SignalName);
    ShortAtMarket( Bar, SignalName);
end;

function ShortAtStopR( Bar: integer; StopPrice: float; SignalName: string ): boolean;
begin
    PeekChecker.Enter(Bar, 0.2, 'ShortAtStop', SignalName);
    Result := ShortAtStop( Bar, StopPrice, SignalName);
end;


Вернуться в «Общие вопросы по разработке»

Кто сейчас на конференции

Сейчас этот форум просматривают: нет зарегистрированных пользователей и 8 гостей