I don't like threads that have an open end with no solution. In the meantime I managed to solve my own post. So here it goes.
This is with autotrader only, and with use of ELcollections/ADE dll (see forum how to install this). With this code you can sync the brokerposition with the strategy position (when you turn autotrader on) and be able to store the trailingstop value (if triggered ofcourse) when trading and read this value for example the next morning or during the day when the autotrader went off due to circumstances.
When you put on the autotrader back on. It syncs your position and reads the last known trailingstop value. For best use, you have to incorporate this code in your own strategy and pay attention to the order of code. Also included is spikecontrol. In case of spikes your targets are not triggered.
Code: Select all
// DESCRIPTION:
// Code to sync the broker position with the strategy position in Multicharts when using AUTOTRADER.
// In this code I use a fixed profit and stoploss and a trailing stop loss.
// The trailing stoploss is stored in a csv file that will be used to read the trailing value
// the next day (overnight) when the autotrader is put on again.
[IntrabarOrderGeneration = True]
[LegacyColorValue = TRUE];
DEFINEDLLFUNC: "kernel32.dll", int, "GetTickCount";
inputs:
// TIME INPUTS
Begin_time_Trade (900), // start time for engaging trades
End_time_Trade (2300), // end time for trading
Begin_time_Targets (800), // start time for enabling profit/stoploss targets
End_time_Targets(2300), // end time for disabling profit/stoploss targets. Usefull for end of market when price are crazy
Begin_time_Sync (700), // start time for enabling syncing
End_time_Sync (2300), // end time for syncing
// SYNCING INPUTS
TimeOutMS(1500), // time interval between detection of difference between marketposition and an correction order (1000ms =1 sec)
LatencyMS(1500), // time interval between correction order and reinstating monitoring (1000ms = 1 sec)
// PROFIT TARGETS AND STOPLOSS INPUTS
StockAmt (1000), // amount of stocks
ProfittargetAmt (500), // profittarget
RiskRewardAmt (2), // riskreward
TrailingTrigger (150), // amount which the trailing value is triggered
TrailingAmt (500), // trailingamount
Price (Close), // close of the bar
//SPIKE CONTROL
SpikeAmt(0.25); // with AUTOTRADER on, cancels profit/stoploss targets during spikes
variables:
ResultStoploss (0),
Stoploss_Fixed (0),
Stoploss_Fixed_Long (0),
Stoploss_Fixed_Short (0),
Profit_Fixed (0),
Profit_Fixed_Long(0),
Profit_Fixed_Short(0),
Position_profit_loss(0),
Trailing_value(0),
Trailing_value_Long(0),
Trailing_value_short(0),
Intrabarpersist TrailingStop_Trigger (False),
Begin_time_trigger(0),
End_time_trigger(0),
Brokerposition(0),//Actual brokerposition
Sync_trigger(False),
Intrabarpersist _get_tick_count(0),
Intrabarpersist mp_diff(false),
Intrabarpersist mp_diff_time_start(0),
Intrabarpersist mp_corrected(false),
Intrabarpersist mp_corrected_time_start(0),
Intrabarpersist place_correction_marketorder(false),
Intrabarpersist _exit_price(0),
spike_trigger(false),
spike_value(0),
Mp(0),// Actual Multicharts position
// STOPLOSS AND PROFIT TARGET VALUES
Filename_trailing_long("C:\Documents\" +
"trailing_value_long_" + getsymbolname + "_" + ".csv"),
Filename_trailing_short("C:\Documents\" +
"trailing_value_short_" + getsymbolname + "_" + ".csv"),
Filename_trailing_trigger("C:\Documents\" +
"trailing_value_trigger_" + getsymbolname + "_" + ".csv"),
Trailing_value_long_list(ListN.New),
Trailing_value_short_list(ListN.New),
Trailing_value_trigger_list(ListN.New),
TrailingStop_ADE (0),
Trailing_value_long_ADE (0),
Trailing_value_short_ADE (0),
CloseLong (False),
CloseShort (False);
// BEGIN SYNCING ----------------------------------------------------------------------------------
If (time > Begin_time_Sync) and (time < end_time_sync) then begin;
// Sync open brokerposition with Multicharts when realtime data and Autotrader is on
// This part is the !From Broker To Strategy MP Synchronizer! signal that is in Multicharts
// Begin syncing
If (GetAppInfo(aiRealTimeCalc)= 1)and (GetappInfo(aiStrategyAuto)=1) then begin;
Mp = marketposition * currentContracts; //multicharts position
BrokerPosition = MarketPosition_At_Broker; //broker position
// Multicharts position and brokerposition are different
If mp <> brokerposition then begin
_get_tick_count = GetTickCount ;
// Status difference in positions
If not mp_diff and not mp_corrected then begin
mp_diff = true;
mp_diff_time_start = _get_tick_count;
end;
// Start detection difference in positions
If mp_diff and not mp_corrected then begin
_exit_price = close;
if _get_tick_count - mp_diff_time_start > TimeOutMS then begin
place_correction_marketorder = true ;
mp_corrected = true ;
mp_corrected_time_start = _get_tick_count ;
end;
end;
// Restart monitoring the marketpositions
if mp_corrected then begin
if (_get_tick_count - mp_corrected_time_start) > LatencyMS then begin
mp_corrected_time_start = _get_tick_count ;
mp_diff = false;
mp_corrected = false;
end;
end;
// Place correction order
if place_correction_marketorder then begin
place_correction_marketorder = false ;
if 0 <> Brokerposition then _exit_price = AvgEntryPrice_at_Broker;
ChangeMarketPosition(brokerposition - mp, _exit_price, "Sync Order");
end;
end
else begin
mp_corrected = false;
mp_diff = false;
end;
end;
End;
// END SYNCING ---------------------------------------------------------------------------
// START TRAILING VALUE ------------------------------------------------------------------
// SENDER PART:
// this part is sending the trailing value to the csv file and also to the ELcollections data map
If (time > Begin_time_Sync) and (time < end_time_sync) then begin;
If (GetappInfo(aiStrategyAuto)=1) and marketposition = 1 and TrailingStop_trigger = true and trailing_value_long > 0 then begin
If (barstatus(1) = 2)then begin;
Value8 = ListN.PushBack(trailing_value_long_list, trailing_value_long);
Value9 = ListN.Setback(trailing_value_long_list, trailing_value_long);
If Trailing_value_long <> trailing_value_long[2] then
FileAppend(Filename_trailing_long, Text(numtostr(trailing_value_long,3),newline));
end;
end;
If (GetappInfo(aiStrategyAuto)=1) and marketposition = -1 and TrailingStop_trigger = true and trailing_value_short > 0 then begin
If (barstatus(1) = 2)then begin;
Value8 = ListN.Pushback(trailing_value_short_list, trailing_value_short);
Value9 = ListN.Setback(trailing_value_short_list, trailing_value_short);
If Trailing_value_short <> trailing_value_short[2] then
FileAppend(Filename_trailing_short, Text(numtostr(trailing_value_short,3),newline));
end;
end;
If (Getappinfo(aiStrategyAuto)=1) and TrailingStop_Trigger = true then begin
TrailingStop_ADE = 1;
end
else begin
TrailingStop_ADE = 0;
end;
If (GetappInfo(aiStrategyAuto)=1) and marketposition <> 0 and TrailingStop_ADE = 1 and trailing_value_short > 0 then begin
If (barstatus(1) = 2)then begin;
Value10 = ListN.Pushback(trailing_value_trigger_list, trailingStop_ADE);
Value11 = ListN.Setback(trailing_value_trigger_list, trailingStop_ADE);
If TrailingStop_ADE <> trailingStop_ADE[2] then
FileAppend(Filename_trailing_trigger, Text(trailingStop_ADE,newline));
end;
end;
// RECEIVER PART TRAILINGVALUE ----------------------------------------------------
// This part is reading the data map during the day and the csv file.
If ELC.PathExists(Filename_trailing_trigger) then begin
value12 = ListN.readfile(trailing_value_trigger_list, Filename_trailing_trigger);
TrailingStop_ADE = ListN.Back(trailing_value_trigger_list);
If TrailingStop_ADE = 1 then begin
TrailingStop_Trigger = true;
If ELC.PathExists(Filename_trailing_long) = true then begin
Value13 = ListN.readfile(trailing_value_long_list,filename_trailing_long);
Trailing_value_long_ADE = ListN.Back(maxlist(trailing_value_long_list));
end;
If ELC.PathExists(Filename_trailing_short) = true then begin
Value14 = ListN.readfile(trailing_value_short_list,filename_trailing_short);
Trailing_value_short_ADE = ListN.Back(minlist(trailing_value_short_list));
end;
end;
end;
// Delete csv files after the autotrader has closed the position
If marketposition <> 0 and (GetappInfo(aiStrategyAuto)=1) and Trailing_value_long > 0 and Trailing_value_short > 0 then begin
Closelong = False;
Closeshort = false;
end;
If (GetappInfo(aiStrategyAuto)=1) and marketposition = 0 and Trailing_value_long > 0 and Trailing_value_short > 0 then begin
Closelong = true;
CloseShort = true;
end;
if CloseLong = True then begin
FileDelete(Filename_trailing_trigger);
FileDelete(Filename_trailing_long);
value13 = ListN.Clear(trailing_value_trigger_list);
Value14 = ListN.Clear(trailing_value_long_list);
CloseLong = False;
end;
If CloseShort = True then begin
FileDelete(Filename_trailing_trigger);
FileDelete(Filename_trailing_short);
Value15 = ListN.Clear(trailing_value_short_list);
CloseShort = False;
end;
End;
// END TRAILING VALUE ---------------------------------------------------
// Spike control, only with AUTOTRADER on
// With the setting in the inputs you can prevent spikes from triggering profit or stoploss targets
If (GetappInfo(aiStrategyAuto)=1) and date = currentdate then begin
spike_value = absvalue(close - close[1]); {Voorkomt dat spikes signalen creeren}
spike_trigger = spike_value >= spikeAmt;
end
else begin
spike_trigger = false;
end;
// ENTRY VALUES
// Determine Profit and stoploss
Profit_Fixed = ProfittargetAmt/StockAmt;
Stoploss_Fixed = (profittargetAmt/RiskRewardAmt)/StockAmt;
ResultStoploss = Profit_Fixed / stoploss_fixed;
// Entry
// You can put your own conditions here
Condition1 = price > price[1];
Condition2 = price < price[1];
// Entry Condities
If (barstatus(1) = 2)then begin;
If time > Begin_time_trigger and time < End_time_trigger then begin
If resultstoploss >= 2 and Condition1 = true then // only take positions with minimal riskreward of 2
if MarketPosition = 0 then begin
Buy ("Long") next bar market;
end;
If resultstoploss >= 2 and Condition2 = true then // only take positions with minimal riskreward of 2
if MarketPosition = 0 then begin
Sellshort ("Short") next bar market;
end;
end;
End;
// Exit Condities ---------------------------------------------------------------------------------------
// Stoploss and profit target calculated per stock
If time > Begin_time_targets and time < End_time_Targets then begin
If marketposition = 0 then TrailingStop_Trigger = false;
If Position_profit_loss >= Trailingtrigger and (trailingtrigger <>0) then trailingstop_trigger = true;
if marketposition <> 0 then begin
Trailing_value = ((Position_profit_loss - TrailingAmt)/stockamt);
Profit_Fixed_Long = AvgEntryprice + Profit_Fixed;
Profit_Fixed_Short = AvgEntryprice - Profit_Fixed;
Stoploss_Fixed_Long = AvgEntryprice - Stoploss_Fixed;
Stoploss_Fixed_Short = AvgEntryprice + Stoploss_Fixed;
Trailing_value_Long = AvgEntryprice + trailing_value;
Trailing_value_Short = AvgEntryprice - trailing_value;
end;
// Profit target fixed
// Long exit:
if ProfitTargetAmt > 0 then begin;
If marketposition = 1 and not spike_trigger then
Sell ("CloseProfitLong") next bar Profit_Fixed_Long limit;
end;
// Short exit
if ProfitTargetAmt > 0 then begin;
If marketposition = -1 and not spike_trigger then
BuytoCover ("CloseProfitShort") next bar Profit_Fixed_Short limit;
end;
// Stoploss fixed -----------------------------------------------------------------
// Long exit:
if (TrailingStop_Trigger=false) then begin;
if marketposition = 1 and not spike_trigger then
Sell ("StopLossLong") next bar Stoploss_Fixed_Long stop;
end;
// Short exit:
if (TrailingStop_Trigger=false) then begin;
if marketposition = -1 and not spike_trigger then
Buytocover ("StopLossshort") next bar Stoploss_Fixed_Short stop;
end;
// Trailingstop with activation on specified input -------------------------------
// Long exit:
if (Trailingstop_Trigger=true) and TrailingAmt > 0 then begin;
if marketposition = 1 and trailing_value_long <> 0 and not spike_trigger then
if (GetappInfo(aiStrategyAuto)=1)and trailing_value_long_ADE <> 0 and trailing_value_long_ADE > Trailing_value_long then begin
trailing_value_long = maxlist(Trailing_value_long_ADE,
iff(Trailing_value_long_ADE[1]=0,Trailing_value_long_ADE,trailing_value_long_ADE[1]));
end
Else begin
Trailing_value_long = maxlist(trailing_value_long,
iff(trailing_value_long[1]=0, trailing_value_long, trailing_value_long[1]));
end;
Sell ("TrailingStopLong") next bar Trailing_value_long stop;
end;
// Short exit:
If (Trailingstop_Trigger=true) and TrailingAmt > 0 then begin;
if marketposition = -1 and trailing_value_short <> 0 and not spike_trigger then
If (GetappInfo(aiStrategyAuto)=1) and trailing_value_short_ADE <> 0 and Trailing_value_short_ADE < Trailing_value_Short then begin
trailing_value_short = minlist(Trailing_value_short_ADE,
iff(Trailing_value_short_ADE[1]=0,Trailing_value_short_ADE,trailing_value_short_ADE[1]));
end
Else begin
Trailing_value_short = minlist(trailing_value_short,
iff(trailing_value_short[1]=0, trailing_value_short, trailing_value_short[1]));
end;
BuytoCover ("TrailingStopShort") next bar Trailing_value_short stop;
end;
End;