How don't display creation a file by fopen() / fputs() function?

I'm using Automatic Analysis - Scan for creation file with code like below.
I'm working on live dates and scan runs every 1 sec.
When Buy or Sell is happened on every 1 seconds the file is replaced.

I'd like to find a solution how to create the file only once (when buy or sell will appear).

Function Alarmif has some flags:
(4 - don't display repeated alerts having the same type,
8 - don't display repeated alerts having the same date/time))
and I'd like to achieve the same with my function.

if(LastValue(Buy OR Sell)>0)
{	
dispatch = "aaa";
fh = fopen( "e:\\Meta_Trader\\MQL4\\Files\\"+"nazwa"+".csv", "w"); 
if(fh) 
{ 
  // fputs( "Ticker,Date,Time,Open,High,Low,Close,Volume \n", fh ); 
	
	ile = feof( fh );
  	fputs(dispatch, fh);	 
   fclose( fh ); 
} 
}

Any idea please?
Thanks

You need a persistent flag. Read https://www.amibroker.com/guide/afl/staticvarset.html

1 Like

If you want to keep adding to your file instead of replacing it every time, you should use the mode "a" (append) rather than "w" (write).
https://www.amibroker.com/guide/afl/fopen.html

thanks for your answer but I have to create the file only once. I will be trying to fight with Staticvareset acc. to awilson (above) answer. ...if success I'll add a solution to this subject.

I think you mean ONCE per trade. yes?

are you try to send Order to mt4? If yes then this part of the code is fine

WHY ?
mt4 DELETEs automaticly that (nazwa.csv) file AFTER reading the file

if(LastValue(Buy))   // if buy is ==1 then do something
{
...
 // when mode is "w" (writing)  mean that you OVERWRITE that file, if previous exist or not
fh = fopen( "e:\\Meta_Trader\\MQL4\\Files\\"+"nazwa"+".csv", "w"); 
...
}

So i am guessing, that
i think your problem is somewere else in your code, sounds like you send BUY orders every second. Also AA settings are in bigger time frame. if is that then yes you need staticvar as @awilson recommends to you

look also in this link below
http://www.amibroker.com/kb/2015/10/06/how-to-run-certain-piece-of-code-only-once/

1 Like

yes, you have right. I'm trying to connect AB to MT4 .
AB is overwriting file every second (...when Buy or Sell appear on a new candle) and MT4 would like to "take" files every tick . Sometimes it is not possible (AB saving and MT4 reading in the same time).
Thank you for the link. At the first sight looking like good way for solution. I will try and give the asnwer here.

Hello @KertLOpper

At this moment, I will love to see the solution of,

  • how to create/write a file (with_the_exact_same_name) one by one using AA scan mode.

For example If the scan gives you a BUY at the same time in 3-5 different Symbols what you can do?

The only one solution that I can think at this moment is to read if the file exist or not in the specific folder. Using GetFormulaPath().

And then you have to place in your code a kind of

  • Delays between executions.

As we said MT4 delete the Order_file commandfile.txt * after 10 sec.
According to thread how-to-place-orders-to-mt4

( * ) your file has name "nazwa.csv"

Hello PanoS,

It is not directly related with this thread, to read thread how-to-place-orders-to-mt4 can be helpful.

I get a solution for the entry signal at the same time in 3-5 different symbols. When i write to order command to .txt i also assign magic number for every order like tthat;

Magic1=StrToNum("5"+fullName());
Magic2=StrToNum("15"+fullName());

"5" and "15" for time frame and i enter every symbol fullname like 1,2,3,4,5...
then i read openorder.txt with afl, if there is no number at magic number which buy or sell entry signal existing,
then afl write same order command again until existing entry signal magic number find in openorder.txt

1 Like

@batu1453 Nice to see you active again :smiley:

Yes that is nice trick, to solve the multyplay Orders at the same time with the "magic number".
If i have time tommorow i will try it, for fun.

please see some solution below, for many systems looks ok but still have some restrictions:

  • f.ex. if buy there is not possible to create the file with sell on next bar. It is necessary to have min. 1 bar without sell between (buy and sell).
  • order from AB to MT4 take ~ 1 sec (too long if scalp. ?)
if(LastValue(Buy OR Sell)>0 AND StaticVarGetText(Name())!= Name())  // AND STATIC VARIABLE ==0    StaticVarCount==0; 
															    // ZMIENIĆ NA -> AND POZWOL:
																 //JEŻELI NIE MA UTWORZONEJ STATIC VARIABLE KTORA NAZWA == Name()
{	
	// -> CREATE STATIC VARAIBLE - O NAZWIE JAKI TAKIEJ JAKI SYMBOL
   StaticVarSetText(Name(),Name());
   printf( "1) Total static variables = %g\n\n", StaticVarCount() );

open_or_close_pos = IIf(Buy,0,1); //0 to Buy, 1 to sell
//order_side = IIf(Buy,1,2); // 2 to sell
symbol = Name();
Lot = 0.1;
//Ask - wewnątrz mql4
Slippage = 3;
// TP i SL wewnątrz mql4
Magic_nr = IIf(Open_or_close_pos==0,Minute(),Ref(Minute(),-(BarsSince(Buy))));
//MAgic_nr = 55;

dispatch = NumToStr(open_or_close_pos,1.0) + ";"  + symbol + "; "  + NumToStr(Lot,1.1) + "; "+

NumToStr(Slippage,1.0) + "; " + NumToStr(Magic_nr);
fh = fopen( "e:\\Meta_Trader\\MQL4\\Files\\"+"nazwa"+".csv", "w"); 

 if(fh) 
 { 
  fputs(dispatch, fh);	 
  fclose( fh );  
 } 
}

// IF THERE IS NO BUY OR SELL SIGNAL -> JEZELI JEST UTWORZONA ZMIENNA O NAZWIE JAK SYMBOL USUŃ JĄ
if(LastValue(Buy)<1 AND LastValue(Sell)<1)
{
StaticVarRemove(Name());
printf( "2) Total static variables = %g\n\n", StaticVarCount() );
}

printf( "3) Total static variables = %g\n\n", StaticVarCount() );
printf(Name());


Hello Kert,

I'm not expert about afl code but maybe your problem about to use only "buy" array in your code

open_or_close_pos = IIf(Buy,0,1); //0 to Buy, 1 to sell

you can insert sell array to formula but this time when the buy signal come with sell signal exist, buy signal is not working.

i use for this case one time code with staticvar in if else function, it is not best solution, it makes more complicated if you add SL and TP conditions.

for scalping i guess you should work directly on MT4.

Hi,

I'm not expert about afl code but maybe your problem about to use only "buy" array in your code

no open_or_close_pos = IIf(Buy,0,1); is only for mql (MetaTrade). It is posible to replace by IIf(Buy,333,444); and make adequate modification in mql.

..it makes more complicated if you add SL and TP conditions.

I don't thinks so, because induction for TP and SL should be before the block with statvar
->before this: if(LastValue(Buy...

I've some idea how to solve the problem: f.ex. if buy there is not possible to create the file with sell on next bar. It is necessary to have min. 1 bar without sell between (buy and sell). I'll add solution in near future.

Hello @KertLOpper
I really lost it now.
You are speaking about seconds, and then bars without signals. Hmmm.
Can you tell us little bit about the logic for the system? And how you are going to connect AB to Mt4. Maybe we can help.
I thought you are planning to send a string to a file, and then mt4 is going to read this file every x_seconds.
@batu1453 said also there is the magic number that we can use to handle some special cases.

I'm sorry if confusion.

My problem is quite well resolved (thanks to this forum and your help).
Below full code.

  • The code is created for sending orders from AB to MetaTrade4.
  • The code is written only for a long position - buy is possible to add short pos. by oneself
  • MetaTrader needs a separate code.
  • The code is working with live dates.
  • Connection between AB and MT is possible because AB creates a .csv and MT can read it.
  • for live trade it is necessary to use - Auto.Analysis - Backtest/Scan - AutoRun (fx.every 3sec)
  • MT is "taking" .csv according to their separate code (fx. on each 3 sec, or on every tick,....)

The code is working but has some restrictions:

  • is no working when Buy and on next candle is Sell - AB won't create .csv with Sell in this case. The code need minimum one empty candle (without Buy or Sell signal)
    between Buy and Sell signals.
  • if at the same time (at the same AutoRun Scan section) AB show signal for two symbols ->the code will send .csv only for one.
    I'll resolve the both inconveniences in future.

_SECTION_BEGIN("Title");
//SetChartOptions(0,chartShowArrows|chartShowDates);
_N(Title = StrFormat("{{NAME}} - {{INTERVAL}} {{DATE}} Open %g, Hi %g, Lo %g, Close %g (%.1f%%) {{VALUES}}", O, H, L, C, SelectedValue( ROC( C, 1 ) ) ));
//Plot( C, "Close", ParamColor("Color", colorBlack ), styleNoTitle | ParamStyle("Style") | GetPriceStyle() ); 
_SECTION_END();

_rsi = RSI(7);
war_1= Cross (_rsi,70);
war_1_sell = Cross(40,_rsi);

Buy =war_1; 
Sell = war_1_sell; 
Buy=ExRem(Buy,Sell);
Sell=ExRem(Sell,Buy);
Short=Cover=0;

/////////////////////////////////////////////////////

if(LastValue(Buy OR Sell)>0 AND StaticVarCount()==0)  // AND STATIC VARIABLE ==0    StaticVarCount==0;
{	

open_or_close_pos = IIf(Buy,111,222); 
symbol = Name();
Lot = 0.1;
//Ask - wewnątrz mql4
Slippage = 3;
// TP i SL wewnątrz mql4
Magic_nr = IIf(Open_or_close_pos==0,Minute(),Ref(Minute(),-(BarsSince(Buy))));
dispatch = NumToStr(open_or_close_pos,1.0) + ";"  + symbol + "; "  + NumToStr(Lot,1.1) + "; "+

NumToStr(Slippage,1.0) + "; " + NumToStr(Magic_nr);
fh = fopen( "e:\\Meta_Trader\\MQL4\\Files\\"+"nazwa"+".csv", "w"); 
  
 if(fh) 
 { 
   fputs(dispatch, fh);	 
   fclose( fh ); 
   StaticVarSet("Dif", 1 );
   printf( "Total static variables = %g\n\n", StaticVarCount() );
 } 
}

if(LastValue(Buy OR Sell)<1)
 {
StaticVarRemove("Dif" );
printf( "Total static variables = %g\n\n", StaticVarCount() );
 }


	

Hello
Thanks you tell us what was about.

You don’t have to thank me as I didn’t help at all. But is it really polite by you to say things like that. Thank you too.

I saw the above code and I going to write here my own style so don’t get me wrong.

  • I will NOT use this type of assign with Underscore _RSI = RSI(7);

  • I will NOT use this StaticVarCount()==0 is not good idea. Think about this why?
    One easy answer for this, is why I have to STOP myself to make another strategy that also needs staticVars?

  • I didn’t see somewhere in your code to use StaticVarGet();

  • Sometimes you don’t really need to use NumToStr() to write a number in a string
    Also We can use this as it is, see below line

dispatch = ""+open_or_close_pos+ ";" + Name() + "; "+ Lot;

  • I am not going to say anything about LastValue(Buy OR Sell)<1 if work for you is fine

See you again.

If you like sent a P.M to me for a little chat. I am really curious to see how you read the file.
Always I am writing code for fun that I will never use them. It is my habit.
And because it is for my hobby I never charge

Hello
here is my first step.

This function can handle when I am going to write a new file, and NOT overwrite the previous one.

// This function check if a specific file exist OR NOT in a folder 
function IsFileNameExist( Path, Filename ) // "R:\\nazwa.csv"
{
    local path, Filename;
    list = fdir( Path + "" + Filename ); 

    if( list != Filename )
        printf( "File does Not exist: " );
        // do something if file is NOT exist
    else
        printf( "File exist: " + Filename);
        
}

// how to use it, example
IsFileNameExist("R:\\","nazwa.csv");

or if you prefer we can leave the path out of the function

// Version 2
// This function check if a specific file EXIST or NOT in a folder 
Path ="R:\\temp\\";
function IfFileNameExist( Filename ) 
{
    local Filename;
    list = fdir( Path + Filename ); 

    if( list != Filename )
        printf( "File does Not exist: " );
        // do something if file is NOT exist
    else
        printf( "File exist: " + Filename);
        
}

// how to use it, example
IfFileNameExist("nazwa.csv");