CreateStopLimitOrder Function

The CreateStopLimitOrder() Function allows you to set stops and limits on open positions (in case the position was opened without predefined stop and limit). It has 4 parameters:

1.Trade: TTrade – the open position (object) on which the order is placed.
2.Rate: Double – the stop or limit rate.
3.OrderType: TOrderType — the order type. Values: otStop, otLimit.
4.OperationTag: String — the custom order tag.

Example: Let us create a strategy that will open a buy position when the strategy is started, without a predefined stop and limit. Then it will set a stop 20 points below the market rate, and a limit 30 points above the market rate, once the Ask rate of the instrument rises above the predefined level, indicated in the settings.

 

We will use the tick history for this strategy. The procedure OnNewRate will check the conditions every time a feed update is received. We will also use the procedure OnTradeChange in order to identify the position that was opened when the strategy started. After the Stop and Limit orders are created, the strategy will stop (terminate).

 

The script will be as follows:

 

const

StrategyName='My Strategy';

 

var

History: TTickHistory;

Account: TAccount;

Amount, Point: Double;

Stop, Limit, TraderRange: Integer;

MyTrade: TTrade;

Rate: Double;

 

procedure OnCreate;

begin

AddTickHistorySetting(@History, 'Tick History', 'EURUSD', 100);

History.OnNewRateEvent := @OnNewRate;

AddAccountSetting(@Account, 'Account', '');

AddFloatSetting(@Amount, 'Amount(Lots)', 5);

AddFloatSetting(@Rate, 'Rate to set Stop/Limit', 1.7);

AddIntegerSetting(@Stop, 'Stop in pips', 20);

AddIntegerSetting(@Limit, 'Limit in pips', 60);

AddIntegerSetting(@TraderRange, 'Trader Range', 3);

end;

 

procedure OnStart;

begin

CreateOrder(History.Instrument, Account, Amount, bsBuy, NullRate, NullRate, TraderRange, 'MyPosition');

end;

 

 // this procedure is used to identify the order when it is inserted

procedure OnTradeChange(const Action: TDataModificationType; const Trade: TTrade);

begin

if (Action = dmtInsert) and (Trade.Tag='MyPosition') then MyTrade:=Trade;

end;

 

procedure OnNewRate;

begin

Point := History.Instrument.PointSize;

if History.Last.Rate>Rate then

 begin

  CreateStopLimitOrder(MyTrade, History.Instrument.Sell-Stop*Point, otStop, 'Stop');

  CreateStopLimitOrder(MyTrade, History.Instrument.Sell+Limit*Point, otLimit, 'Limit');

   Terminate;

 end;

end;