Navigation:  ActFX > User Indicators >

6. Automatic Trading Systems

Previous pageReturn to chapter overviewNext page

6.1. Introduction

 

Mechanical Trading Systems are scripts that open and close positions, enter stop/limit or entry orders on the basis of algorithms.

Structurally trading system script differs from the script that calculates and draws indicators:

1)To write a script for the indicator Recalculate() procedure is being used that makes calculations for each candlestick on the basis of the historical data.  It shouldn’t be done in case of trading systems, so Recalculate() procedure can be left empty and undertake all calculations in Add procedure.
2)To make system be compelled and work you should proclaim graphical variable (TLineGraph, TVolumeGraph, TPointGraph) and create this object of the graphical class in the Init procedure even if you use it in the body of the script. Without it you can’t compile your script. At that it is recommended to make Layout embedded.

 

Layout = Embedded;

 

As for the rest there is no significant difference.

 

6.2 Trade Functions

 

Four special functions are being used to undertake trade process:

 

CreateOrder(
  const AccountID: String;
  const Amount: Double;
  const BuySell: TBuySell;
  const StopRate: Double;
  const LimitRate: Double;
  const TraderRange: Integer;
  const OperationTag: String);

Create order for new position. Parameters:

1.AccountID – Account number.
2.Amount – Lot Amount.
3.BuySell – Buy or Sell.
4.StopRate – Price rate for preset Stop Order, NullRate – if no order needed.
5.LimitRate – Price for preset Limit Order, NullRate – if no order needed.
6.TraderRange – Trader Range.
7.OperationTag – Order Tag.

CreateEntryOrder(
  const AccountID: String;
  const Amount: Double;
  const BuySell: TBuySell;
  const Rate: Double;
  const OrderType: TOrderType;
  const OperationTag: String);

Create Entry Order. Parameters:

1.AccountID – Account number.
2.Amount – Lot Amount.
3.BuySell – Buy or Sell.
4.Rate – Price.
5.OrderType – Order Type: otEStop – Entry Stop; otELimit – Entry Limit.
6.OperationTag – Order Tag.

CreateStopLimitOrder(
  const TradeID: String;
  const OperationTag: String;
  const Rate: Double;
  const OrderType: TOrderType);

Create Stop or Limit Order. Parameters:

1.TradeID – Trade number, if no order tag preset.
2.OperationTag – Order Tag, if no number of trade is preset.
3.Rate – Price.
4.OrderType – Order type: otStop – Stop; otLimit – Limit.

CloseTrade(
  const TradeID: String;
  const OperationTag: String;
  const Amount: Double;
  const WithHedge: Boolean;
  const TraderRange: Integer);

Close Position. Parameters:

1.TradeID – Trade number, if no order tag preset.
2.OperationTag – Order Tag, if no number of trade is preset.
3.Amount – Lot Amount.
4.WithHedge – Close position with hedge positions.
5.TraderRange – Trader Range.

 

Details for each function:

 

6.2.1 CreateOrder Function

 

CreateOrder() function is created for opening position at the current market price.  It has 7 parameters:

 

1.AccountID – Account number.
2.Amount – Lot Amount.
3.BuySell – Buy or Sell.
4.StopRate – Price rate for preset Stop Order, NullRate – if no order needed.
5.LimitRate – Price for preset Limit Order, NullRate – if no order needed.
6.TraderRange – Trader Range.
7.OperationTag – Order Tag.

 

Tag order is used to make position search process easier. Order tag is a unique name of your open position, for this reason they shouldn’t be repeated. It means that existence of 2 positions with the same name (OpetarionTag) can lead to the incorrect work of the system. To avoid such mistakes one can keep external counter that will assign unique numbers for the open positions to make your script identify them.

 

Example: Let’s write a small trading system that will open your Buy position in case High and Low difference of the last candle accedes 50 points. At the same time it has to make Stop order  20 points lower than Low of that candle and Limit 20 points higher that High of this candle.

 

Script that realize such trading system by the following way:

 

Const

IndicatorName = 'My Trading System';                       // Name of trade system

Layout = Embedded;                                                     // Don’t create separate window because

                                                                                             there is no need for it

var

 Graph:TLineGraph;                                                       // Announce a liner chart,

                                                                                           // to make trading system compiled.

 PointSize, NowPrice, Volatility:Double;

 tag, Stop, Limit:integer;

 Account, OperationTag: string;

 

procedure CreateSettings;                                           // Create Settings

begin

AddSetting('point_size', 'Point Size', '0.0001');               // Set point size

AddSetting('account', 'Account number', '3312');     // Set account number

AddSetting('stop', 'Stop Distance in pips', '20');         // Set Stop distance in pips

AddSetting('limit', 'Limit Distance in pips', '20');           // Set Limit distance in pips

end;

 

procedure ApplySettings;                                           // Apply Settings

begin

Account := GetSetting('account');                         // Apply account settings

Stop := StrToInt(GetSetting('stop'));                         // Apply Stop settings in pips

Limit := StrToInt(GetSetting('limit'));                         // Apply Limit settings in pips

PointSize := StrToFloat(GetSetting('point_size'));   // Apply point size settings

end;

 

procedure Init;

begin

Graph := TLineGraph.Create();                               //Create linear graph to make trade system                                                                            

                                                                                   // compiled.

end;

 

procedure Recalculate;                                         // In the recalculate procedure you assign 1 to

                                                                                   //  the Tag. Later this variable will serve to

                                                                                       // generate unique numbers, because once

                                                                                       // new candles appear it’ll increase by one.                                                                                      

begin

tag:=1;

end; // Recalculate

 

procedure Add(const ValueIndex: Integer);           // Procedure that on the appearance of the

                                                                                        // new candle will check the preset

                                                                                        // conditions. If they are realized it will open

                                                                                        // position.

begin

tag:=tag+1;                                                                   // Increase identifier by one

if ValueIndex > SourceGraph.Count()-2 then

  begin

  OperationTag:=IntToStr(Tag);                               // Variable OperationTag assign identifier

                                                                                      // value converted  into String variable

  NowPrice:=SourceGraph.YValue(ValueIndex); // variable NowPrice we assign value

  Volatility:=(SourceGraph.HighValue(ValueIndex-1)- SourceGraph.LowValue(ValueIndex-1))/PointSize;

                                                                                      // Set candle size in points

if Volatility>50 then CreateOrder(Account, 10, bsBuy, NowPrice-Stop*PointSize,

                                                               NowPrice+Limit*PointSize, 3, OperationTag);

                                                                                    // If candle size is higher than 50 points

                                                                                     // open Buy position

  end;

end;

 

clip0679

 

 

6.2.2 CreateEntryOrder Function

 

CreateOrder() Function is created for  creation of pending orders. It has 6 parameters:

 

1.AccountID – Account number.
2.Amount – Lot Amount.
3.BuySell – Buy or Sell.
4.Rate – Price.
5.OrderType -  Order Type: otEStop – Entry Stop; otELimit – Entry Limit.
6.OperationTag – Order Tag.

 

Example:  create a small trade system that will create 2 pending orders. First – order to buy   30 points higher than current price. Second – order to sell 50 points higher than current price. Script has to generate orders if close price of the candle is higher than close price of the previous one.

 

Const

IndicatorName = 'My Trading System';                       // Name trading system

Layout = Embedded;                                                     // Don’t create separate window because there is no use in it

var

 Graph:TLineGraph;                                                       // Announce some linear chart,

                                                                                           // to have trading system compiled.

 PointSize, NowPrice, PreviousPrice:Double;

 tag, BuyDistance, SellDistance:integer;                

 Account, OperationTag: string;

 

procedure CreateSettings;                                           // Create setting

begin

AddSetting('point_size', 'Point Size', '0.0001');                   //Create point size settings

AddSetting('account', 'Account number', '3312');         // Create account size settings

AddSetting('buy_distance', 'Buy Distance in pips', '30'); // Create buy distance settings

AddSetting('sell_distance', 'Sell Distance in pips', '50');   // Create sell distance settings

end;

 

procedure ApplySettings;                                             // Apply Settings

begin

Account := GetSetting('account');                             // Apply account setting number

BuyDistance := StrToInt(GetSetting('buy_distance')); // Apply buy distance setting

SellDistance := StrToInt(GetSetting('sell_distance')); // Apply sell distance setting

PointSize := StrToFloat(GetSetting('point_size'));       // Apply point size

end;

 

procedure Init;

begin

Graph := TLineGraph.Create();                                   // Create linear chart to have trading system

                                                                                        // compelled.

end;

 

procedure Recalculate;                                               // In the recalculation processes variable

                                                                                       // tag is assigned one. Later this variable will

                                                                                       // serve to assign positions unique numbers.

                                                                                       // With each new candle it will increase by 1.

begin

tag:=1;

end; // Recalculate

 

procedure Add(const ValueIndex: Integer);            // Procedure that on the appearance of the

                                                                                        // new candle will check the preset

                                                                                        // conditions. If they are realized it will open

                                                                                        // position.

 

begin

if ValueIndex > SourceGraph.Count()-2 then

  begin

  NowPrice:=SourceGraph.CloseValue(ValueIndex-1);  // Variable NowPrice assign                                                                                                    

                                                                                                                   // last candle close value

  PreviousPrice:= SourceGraph.CloseValue(ValueIndex-2); // Variable PreviousPrice                                                                                                      

                                                                                                          // assign next to last candle close value

  if NowPrice> PreviousPrice then

    begin

    tag:=tag+1;                                                     // Increase identifier by one

    OperationTag:=IntToStr(Tag);                     // Variable OperationTag assign

                                                                                           // identifier value converted  into String

                                                                                           // variable

 

    CreateEntryOrder(Account, 10, bsBuy,  NowPrice+BuyDistance*PointSize, otEStop, OperationTag);                               // Create pending order Buy Entry Stop

    tag:=tag+1;                                               // increase identifier by one

    OperationTag:=IntToStr(Tag);                 // Variable OperationTag assign

                                                                                      // identifier value converted  into String

                                                                                      // variable

 

    CreateEntryOrder(Account, 5, bsSell,  NowPrice+SellDistance*PointSize, otELimit, OperationTag);                             // Create pending order Sell Entry Limit

   end;

  end;

end;

 

For this example, CreateEntryOrder() Function has the following view:

 

clip0680

 

6.2.3 CreateStopLimitOrder Function

 

CreateStopLimitOrder() Function created for generating stops and limits on open positions (in case if position was opened without preset Stop and Limit). It has 4 parameters:

 

1.TradeID – Trade number, if no tag order is preset.
2.OperationTag – Order tag, if  no trade number preset.
3.Rate – Price.
4.OrderType – Order Type: otStop – Stop; otLimit – Limit.

 

Example 1:  let’s write a trading system that will generate Stop 20 point higher and Limit 30 points lower than the current sell position that has a tag ‘a123’. If the close price of the last candle accedes some concrete price (for example if close price is higher than 1.3680). To make things easier let’s concentrate only on Add procedure. In this case Add will have the following view:

 

procedure Add(const ValueIndex: Integer);          

begin

if ValueIndex > SourceGraph.Count()-1 then

  begin

  NowPrice:=SourceGraph.CloseValue(ValueIndex-1); // Variable NowPrice assign

                                                                                                                // current market price value

  if NowPrice>1.368 then

     begin    

     CreateStopLimitOrder('',’a123’, NowPrice+20*PointSize, otStop); // Create Stop Order

     CreateStopLimitOrder('',’a123’, NowPrice-30*PointSize, otLimit); // Create Limit Order

     end;

  end;

end;

 

Example 2: let’s write the same trading system, like in the first example, but search for positions by the trade number. For example trade number 352155. In this case Add procedure will have the following view:

 

procedure Add(const ValueIndex: Integer);          

begin

if ValueIndex > SourceGraph.Count()-1 then

  begin

  NowPrice:=SourceGraph.CloseValue(ValueIndex-1); // Variable NowPrice assign

                                                                                                         // current market price value

  if NowPrice>1.368 then

     begin    

     CreateStopLimitOrder('352155',’’, NowPrice+20*PointSize, otStop); // Create Stop Order

     CreateStopLimitOrder('352155',’’, NowPrice-30*PointSize, otLimit); // Create Limit Order

     end;

  end;

end;

We should bare in mind that order tag and trade number we put in the single quotes.

 

clip0681

 

6.2.4 CloseTrade Function

 

CloseTrade() function is created for closing positions. Position can be closed by trade number or order tag. It has 5 parameters:

 

1.TradeID – Trade number, if order tag is not preset.
2.OperationTag – Order tag, if trade number isn’t preset.
3.Amount – Lot Amount.
4.WithHedge – Close position with hedge positions.
5.TraderRange - Trader Range.

 

Example 1: Let’s write a trading system that will close position with ‘a123’ tag for 5 lots, if close price of the last candle goes below some concrete price (for example, if close candle price is lower than 1.8620). To make things easier let’s concentrate only on Add procedure. In this case Add procedure will have the following view:

 

procedure Add(const ValueIndex: Integer);          

begin

if ValueIndex > SourceGraph.Count()-1 then

  begin

  NowPrice:=SourceGraph.CloseValue(ValueIndex-1); // Variable NowPrice assign

                                                                                                                // current market price value

  if NowPrice<1.862 then CloseTrade('',’a123’,5,False,3); // Close position without hedge

  end;

end;

Example 2: let’s write a trading system that will close position with number 54921 for 10 lots, if close candle price goes below some concrete price (for example, if close candle price goes lower than 1.8620). The position will be closed with hedge. In this case Add will have the following view:

 

procedure Add(const ValueIndex: Integer);          

begin

if ValueIndex > SourceGraph.Count()-1 then

  begin

  NowPrice:=SourceGraph.CloseValue(ValueIndex-1);   // Variable NowPrice is

                                                                                                                  // assigned current price value

  if NowPrice<1.862 then CloseTrade('54921',’’,5,True,3);// Close position with hedge

  end;

end;

clip0682