Send opened positions from cAlgo to apache2 server via SSL - What is wrong ?

Created at 24 Mar 2014, 13:03
How’s your experience with the cTrader Platform?
Your feedback is crucial to cTrader's development. Please take a few seconds to share your opinion and help us improve your trading experience. Thanks!
breakermind's avatar

breakermind

Joined 17.07.2013

Send opened positions from cAlgo to apache2 server via SSL - What is wrong ?
24 Mar 2014, 13:03


Hi

I need send open positions to www server like apache2 via ssl connection but ...

why this robot does not show opened positions string in log window?

// -------------------------------------------------------------------------------
//
//    This is a Template used as a guideline to build your own Robot. 
//
// -------------------------------------------------------------------------------

using System;
using cAlgo.API;
using cAlgo.API.Indicators;
using cAlgo.API.Internals;
using cAlgo.API.Requests;
using cAlgo.Indicators;
using System.IO;
using System.Net;
using System.Text;

namespace cAlgo.Robots
{
    [Robot(TimeZone = TimeZones.UTC)]
    public class NewRobot : Robot
    {

        private string openPositionsString = "";
        protected override void OnStart()
        {
            // Put your initialization logic here

        }

//================================================================================
//                                                             OnPositionOpened
//================================================================================
        protected override void OnPositionOpened(Position openedPosition)
        {
            int BuyPos = 0;
            int SellPos = 0;

            foreach (var position in Account.Positions)
            {
                // Count opened positions
                if (position.TradeType == TradeType.Buy)
                {
                    BuyPos = BuyPos + 1;
                    Print("POS VOLUME: " + position.Volume);

                    // OPENED POSITION STRING
                    openPositionsString = "START" + position.EntryTime + "," + position.Id + "," + position.SymbolCode + ",TRUE" + "," + position.Volume + "," + position.EntryPrice + "," + position.StopLoss + "," + position.TakeProfit + "," + position.Label + "," + position.Comment + ",ZZZEND";
                    Print("HOW TO SHOW IN LOGS ======================================================");
                    Print("String : " + openPositionsString);


                }
                if (position.TradeType == TradeType.Sell)
                {

                    // OPENED POSITION STRING
                    openPositionsString = "START" + position.EntryTime + "," + position.Id + "," + position.SymbolCode + ",FALSE" + "," + position.Volume + "," + position.EntryPrice + "," + position.StopLoss + "," + position.TakeProfit + "," + position.Label + "," + position.Comment + ",ZZZEND";
                    Print("HOW TO SHOW IN LOGS ======================================================");
                    Print("String : " + openPositionsString);
                    SellPos = SellPos + 1;
                }
            }




            Print("All Buy positions: " + BuyPos);
            Print("All Sell positions: " + SellPos);


        }
        // end OnPositionOpened

        protected override void OnTick()
        {
            // Put your core logic here
            int BuyPos = 0;
            string sslServerHost = "breakermind.com";
            int sslServerPort = 443;

            WebRequest request = WebRequest.Create("https://" + sslServerHost + ":" + sslServerPort + "/send.php?line=" + openPositionsString + "&user=ml@breakermind.com&pass=pass987");
            request.Proxy = null;
            request.Credentials = CredentialCache.DefaultCredentials;

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream dataStream = response.GetResponseStream();
            StreamReader reader = new StreamReader(dataStream);
            string responseFromServer = reader.ReadToEnd();
            Print("All Buy positions:" + responseFromServer);
            //Console.WriteLine(responseFromServer);
            //Print("All Buy positions: " + BuyPos);
        }



        protected override void OnStop()
        {
            // Put your deinitialization logic here
        }
    }
    /*
        public static bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
        {
            return true;
        }
        */

}

 

Thanks bye


@breakermind
Replies

breakermind
24 Mar 2014, 13:19

RE:

breakermind said:

Hi

I need send open positions to www server like apache2 via ssl connection but ...

why this robot does not show opened positions string in log window?

// -------------------------------------------------------------------------------
//
//    This is a Template used as a guideline to build your own Robot. 
//
// -------------------------------------------------------------------------------

using System;
using cAlgo.API;
using cAlgo.API.Indicators;
using cAlgo.API.Internals;
using cAlgo.API.Requests;
using cAlgo.Indicators;
using System.IO;
using System.Net;
using System.Text;

namespace cAlgo.Robots
{
    [Robot(TimeZone = TimeZones.UTC)]
    public class NewRobot : Robot
    {

        private string openPositionsString = "";
        protected override void OnStart()
        {
            // Put your initialization logic here

        }

//================================================================================
//                                                             OnPositionOpened
//================================================================================
        protected override void OnPositionOpened(Position openedPosition)
        {
            int BuyPos = 0;
            int SellPos = 0;

            foreach (var position in Account.Positions)
            {
                // Count opened positions
                if (position.TradeType == TradeType.Buy)
                {
                    BuyPos = BuyPos + 1;
                    Print("POS VOLUME: " + position.Volume);

                    // OPENED POSITION STRING
                    openPositionsString = "START" + position.EntryTime + "," + position.Id + "," + position.SymbolCode + ",TRUE" + "," + position.Volume + "," + position.EntryPrice + "," + position.StopLoss + "," + position.TakeProfit + "," + position.Label + "," + position.Comment + ",ZZZEND";
                    Print("HOW TO SHOW IN LOGS ======================================================");
                    Print("String : " + openPositionsString);


                }
                if (position.TradeType == TradeType.Sell)
                {

                    // OPENED POSITION STRING
                    openPositionsString = "START" + position.EntryTime + "," + position.Id + "," + position.SymbolCode + ",FALSE" + "," + position.Volume + "," + position.EntryPrice + "," + position.StopLoss + "," + position.TakeProfit + "," + position.Label + "," + position.Comment + ",ZZZEND";
                    Print("HOW TO SHOW IN LOGS ======================================================");
                    Print("String : " + openPositionsString);
                    SellPos = SellPos + 1;
                }
            }




            Print("All Buy positions: " + BuyPos);
            Print("All Sell positions: " + SellPos);


        }
        // end OnPositionOpened

        protected override void OnTick()
        {
            // Put your core logic here
            int BuyPos = 0;
            string sslServerHost = "breakermind.com";
            int sslServerPort = 443;

            WebRequest request = WebRequest.Create("https://" + sslServerHost + ":" + sslServerPort + "/send.php?line=" + openPositionsString + "&user=ml@breakermind.com&pass=pass987");
            request.Proxy = null;
            request.Credentials = CredentialCache.DefaultCredentials;

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream dataStream = response.GetResponseStream();
            StreamReader reader = new StreamReader(dataStream);
            string responseFromServer = reader.ReadToEnd();
            Print("All Buy positions:" + responseFromServer);
            //Console.WriteLine(responseFromServer);
            //Print("All Buy positions: " + BuyPos);
        }



        protected override void OnStop()
        {
            // Put your deinitialization logic here
        }
    }
    /*
        public static bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
        {
            return true;
        }
        */

}

 

Thanks bye

 

and on server side  validate function for

openPositionsString

is

$isLineOK = preg_match("/^START([0-9]{1,99},[0-9]{1,99},[A-Z0-9\/]{1,10},[A-Z]{1,6},[0-9]{5,30},[0-9\.]{5,30},[0-9\.]{5,30},[0-9\.]{5,30},[a-zA-Z0-9]{1,100},[a-zA-Z0-9]{1,100},ZZZ)+END$/", $line);

 


@breakermind

Spotware
24 Mar 2014, 14:05

instead of overriding OnPositionOpened method you need to subscribe to Positions.Opened event:

        protected override void OnStart()
        {
            Positions.Opened += OnPositionsOpened;
        }
        
        void OnPositionsOpened(PositionOpenedEventArgs obj)
        {
            ...
        }

 


@Spotware

breakermind
24 Mar 2014, 15:11

RE:

server side php file send.php save/update and delete opened positions into mysql database and then return recived positions line back 

send.php

<?php
include('functions.php');
// line example
// START1395336294584,59923886,GBP/JPY,true,1.0,169.199,167.195,171.195,jf1nikmw1,null,ZZZ1395336294584,59923886,GBP/JPY,true,1.0,169.199,167.195,171.195,jf1nikmw1,null,ZZZEND

//======================================================================================= connect mysql
$mysqlcon = isConnect('localhost','root', 'toor');


//======================================================================================= get input strings
$user_ip = $_SERVER['REMOTE_ADDR'];
$user_time = time();
$user = md5($_GET['user']);
$pass = md5($_GET['pass']);
$line = htmlspecialchars($_GET['line'], ENT_QUOTES, 'UTF-8');
echo "<pre>";
echo $line;
echo "</pre>";
$userID = 0;
$out = "";
$positions[] = 0;


//======================================================================================= if user and password correct
$q = mysql_query("SELECT * FROM users WHERE user_email_hash='$user' AND user_pass='$pass'");
$userExist = mysql_num_rows($q);

// user istnieje pobierz rekord z bazy (id usera)
if($userExist != 0){
	while ($row = mysql_fetch_assoc($q)){
		//echo "user id: " . $userID = $row['user_id'];
		$userID = $row['user_id'];
	}
}

if($line == "STARTEND"){
	$q5 = mysql_query("UPDATE positionsTest1 SET pos_close='$user_time' WHERE pos_close = 0 AND user_id =".$userID) or die( "#ERROR-1#" . mysql_error());
	die($line);
}

//========================================================================================== preg_match for correct positions settings

$isLineOK = preg_match("/^START([0-9]{1,99},[0-9]{1,99},[A-Z0-9\/]{1,10},[A-Z]{1,6},[0-9]{5,30},[0-9\.]{5,30},[0-9\.]{5,30},[0-9\.]{5,30},[a-zA-Z0-9]{1,100},[a-zA-Z0-9]{1,100},ZZZ)+END$/", $line);



//======================================================================================== sprawdzenie danych wejściowych
if(isPositionString($line) && isAllowedChar($line) && $userExist == 1 && $userID != 0 && $isLineOK == 1){
	
	$cutline =  isPositionStringCut($line);

	$posLines = explode('ZZZ', $cutline);

	$i = 0;
	foreach ($posLines as $line1){
		$positions[$i] = explode(',', substr($line1, 0, -3));
		$i++;
	}

	$positionsExists = "";
	$z =0;
	foreach ($positions as $value) {
		
		$positionsExists = $positionsExists.$userID.$positions[$z][1].",";
		$positionsExists = $positionsExists."0";
		//echo "==".$positionsExists."++";
		$z++;
	}		

	$j =0;
	foreach ($positions as $value) {
		
		$pos_id = $userID.$positions[$j][1];
		$pos_currency = $positions[$j][2];
		$pos_volume = $positions[$j][4];
		$pos_stoploss = (float)$positions[$j][6];
		$pos_takeprofit = (float)$positions[$j][7];
		$pos_isLong = $positions[$j][3];
		$pos_open = $positions[$j][0];
		$pos_open_price = (float)$positions[$j][5];
		$pos_label = $positions[$j][8];
		$pos_comment = $positions[$j][9];
		
		if($pos_volume = $positions[$j][4] <= 10000){
			$pos_volume = 10000;
		}

		// INSERT INTO table (primarykeycol,col1,col2) VALUES (1,2,3) ON DUPLICATE KEY UPDATE col1=0, col2=col2+1

		//$q2 = mysql_query("DELETE FROM positionsTest WHERE pos_id NOT IN ( $positionsExists)");
		$q4 = mysql_query("UPDATE positionsTest1 SET pos_close='$user_time' WHERE pos_close = 0 AND user_id =".$userID." AND pos_id NOT IN (".$positionsExists.")") or die( "#ERROR-1#" . mysql_error());

		//$q3 = mysql_query("UPDATE positionsTest SET pos_currency='$pos_currency',pos_volume='$pos_volume',pos_stoploss='$pos_stoploss',pos_takeprofit='$pos_takeprofit',pos_isLong='$pos_isLong',pos_open='$pos_open',pos_open_price='$pos_open_price',pos_label='$pos_label',pos_comment='$pos_comment', user_ip='$user_ip', user_time='$user_time' WHERE pos_id = '$pos_id'");
		$q1 = mysql_query("INSERT INTO positionsTest1(pos_id,pos_currency,pos_volume,pos_stoploss,pos_takeprofit,pos_isLong,pos_open,pos_open_price,pos_label,pos_comment, user_id, user_ip, user_time) VALUES('$pos_id','$pos_currency','$pos_volume','$pos_stoploss','$pos_takeprofit','$pos_isLong','$pos_open','$pos_open_price','$pos_label','$pos_comment', '$userID', '$user_ip', '$user_time') ON DUPLICATE KEY UPDATE pos_currency='$pos_currency',pos_volume='$pos_volume',pos_stoploss='$pos_stoploss',pos_takeprofit='$pos_takeprofit',pos_isLong='$pos_isLong',pos_label='$pos_label',pos_comment='$pos_comment', user_ip='$user_ip', user_time='$user_time'") or die( "#ERROR-1#" . mysql_error());
		$j++;
	}

	//echo microtime();
	//$nanotime = system('date +%s%N');
	
	//function microtime_float()
	//{
	//	list($usec, $sec) = explode(" ", microtime());
	//	return ((float)$usec + (float)$sec);
	//}
	
	//echo microtime_float();
	
	
	if (!empty($_GET)) {
		//echo "<br>";
		//echo $user."<br>";
		//echo $pass."<br>";
		//echo $line."<br>";
	}	
	
	$out = $line;
}else{$out = '##SEND##CORRECT##DATA##';}
mysql_close($mysqlcon);

//========================================================================================= send output string
//echo $out;
echo $out;
?>

 

 

file functions.php

<?php


function isConnect($host, $user, $password, $db = 'db'){
	$link = mysql_connect($host, $user, $password) or die('Not connected : ' . mysql_error());

	// make foo the current db
	$db_selected = mysql_select_db($db, $link) or die ('Can\'t use foo : ' . mysql_error());
	
	mysql_query("SET character_set_results = 'utf8', character_set_client = 'utf8', character_set_connection = 'utf8', character_set_database = 'utf8', character_set_server = 'utf8'");
	mysql_query("SET NAMES utf8");
	mysql_query("SET CHARACTER SET utf8");
	mysql_query("SET collation_connection = utf8_generali_ci");

	return $link;
}


function isAllowedChar($line){
if (preg_match("#^[a-zA-Z0-9\.\,\/]+$#", $line)) {	return 1;} else { return 0;}
}


function isPositionString($string){
	// start end check
	if(substr($string, 0, 5) == "START" && substr($string, -3) == "END"){return 1;}else{return 0;}
}

function isPositionStringCut($string){
	// start end check
	$string = substr($string, 5);
	$string = substr($string, 0, -6);
	return $string;
}


// clean input from $_GET $_POST USE:     $_CLEAN['GET'] = cleanInput($_GET);
function cleanInput($elem)
{
	if(!is_array($elem))
		$elem = htmlentities($elem, ENT_QUOTES,"UTF-8");
	else{
		foreach ($elem as $key => $value){
			$elem[$key] = cleanInput($value);
		}
	}
	return $elem;
}

//$isLineOK = preg_match("/^START([0-9]{1,99}AAA[0-9]{1,99}AAA[A-Z0-9\/]{1,10}AAA[A-Z]{1,6}AAA[0-9]{5,30}AAA[0-9\.]{5,30}AAA[0-9\.]{5,30}AAA[0-9\.]{5,30}AAA[a-zA-Z0-9]{1,100}AAA[a-zA-Z0-9]{1,100}AAAZZZ)+END$/", $line);
 

?>

and mysql database file

## mysql database

CREATE DATABASE db CHARACTER SET utf8 COLLATE utf8_general_ci;

# CREATE DATABASE `db` CHARACTER SET utf8 COLLATE utf8_general_ci;
# GRANT ALL ON `mydb`.* TO `username`@localhost IDENTIFIED BY 'password';
# FLUSH PRIVILEGES;
# `user_time` TIMESTAMP DEFAULT NOW(),

USE db;

## create table users
CREATE TABLE `users`
(
`user_id` int(11) NOT NULL AUTO_INCREMENT,
`user_alias` varchar(100) CHARACTER SET utf8 collate utf8_general_ci ,
`user_email` varchar(200) CHARACTER SET utf8 collate utf8_general_ci ,
`user_email_hash` varchar(100) CHARACTER SET utf8 collate utf8_general_ci ,
`user_pass` varchar(100) CHARACTER SET utf8 collate utf8_general_ci ,
`user_ip` text CHARACTER SET utf8 collate utf8_general_ci,
`user_time` int(21),
`user_code` varchar(100) CHARACTER SET utf8 collate utf8_general_ci ,
`user_active` char(1) CHARACTER SET utf8 collate utf8_general_ci DEFAULT '0',
PRIMARY KEY (`user_id`),
UNIQUE (`user_email` , `user_alias`)
)ENGINE=innoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COLLATE utf8_general_ci;


insert into users VALUES('','zix','xx#email.com', md5('xx@email.com'), md5('pass'),null,null,null,0);



## create table users_all
CREATE TABLE `users_all`
(
`user_id` bigint(21) NOT NULL AUTO_INCREMENT,
`user_alias` varchar(100) CHARACTER SET utf8 collate utf8_general_ci ,
`user_email` varchar(200) CHARACTER SET utf8 collate utf8_general_ci ,
`user_email_hash` varchar(100) CHARACTER SET utf8 collate utf8_general_ci ,
`user_pass` varchar(100) CHARACTER SET utf8 collate utf8_general_ci ,
`user_ip` text CHARACTER SET utf8 collate utf8_general_ci,
`user_time` int(21),
`user_code` varchar(100) CHARACTER SET utf8 collate utf8_general_ci ,
`user_active` char(1) CHARACTER SET utf8 collate utf8_general_ci DEFAULT '0',
`user_firstname` char(2) CHARACTER SET utf8 collate utf8_general_ci ,
`user_lastname` varchar(100) CHARACTER SET utf8 collate utf8_general_ci ,
`user_country` char(2) CHARACTER SET utf8 collate utf8_general_ci ,
`user_town` varchar(100) CHARACTER SET utf8 collate utf8_general_ci ,
`user_gender` varchar(100) CHARACTER SET utf8 collate utf8_general_ci ,
`user_dofb` varchar(100) CHARACTER SET utf8 collate utf8_general_ci ,
`user_mobile` varchar(100) CHARACTER SET utf8 collate utf8_general_ci ,
`user_startbalance` varchar(100) CHARACTER SET utf8 collate utf8_general_ci ,
`user_descripion` text CHARACTER SET utf8 collate utf8_general_ci,
`user_ip_mask` varchar(200) CHARACTER SET utf8 collate utf8_general_ci ,
PRIMARY KEY (`user_id`),
UNIQUE (`user_email` , `user_alias`)
)ENGINE=innoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COLLATE utf8_general_ci;


CREATE TABLE `positionsTest1`
(
`pos_id` varchar(200) CHARACTER SET utf8 collate utf8_general_ci ,
`pos_currency` varchar(25) CHARACTER SET utf8 collate utf8_general_ci ,
`pos_volume` bigint(21) DEFAULT 10000,
`pos_stoploss` float,
`pos_takeprofit` float,
`pos_isLong` char(5) NOT NULL DEFAULT 0,
`pos_open` bigint(21) NOT NULL DEFAULT 0,
`pos_open_price` float,
`pos_close` int(11) NOT NULL DEFAULT 0,
`pos_close_price` float DEFAULT 0,
`pos_label` varchar(100) CHARACTER SET utf8 collate utf8_general_ci ,
`pos_comment` varchar(100) CHARACTER SET utf8 collate utf8_general_ci ,
`user_id` bigint(21) DEFAULT 0,
`user_ip` text CHARACTER SET utf8 collate utf8_general_ci,
`user_time` text CHARACTER SET utf8 collate utf8_general_ci,
`user_microtime` text CHARACTER SET utf8 collate utf8_general_ci,
`user_nanotime` text CHARACTER SET utf8 collate utf8_general_ci,
PRIMARY KEY (`pos_id`),
UNIQUE (`pos_id`)
)ENGINE=innoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COLLATE utf8_general_ci;

may be useful for someone ... bye.


@breakermind

breakermind
25 Mar 2014, 13:28

RE: RE: RE:

Hi,

how to convert this price (position.EntryPrice)

1,777  ==> 1.777

ane how convert date (position.EntryTime)

2014-03-25 11:11:11     ===>   seconds (133658232763)

Thanks


@breakermind

breakermind
25 Mar 2014, 17:36

RE: RE: RE: RE:

breakermind said:

Hi,

how to convert this price (position.EntryPrice)

1,777  ==> 1.777

ane how convert date (position.EntryTime)

2014-03-25 11:11:11     ===>   seconds (133658232763)

Thanks

 

Does calgo has the ability to specify the time in milliseconds for position.EntryTime ?

if Yes how to do that ?


@breakermind

breakermind
26 Mar 2014, 13:35

RE: RE: RE: RE: RE:

Hi all,

Send  positions to www server method $_POST

 

using System;
using cAlgo.API;
using cAlgo.API.Indicators;
using cAlgo.API.Internals;
using cAlgo.API.Requests;
using cAlgo.Indicators;
using System.IO;
using System.Net;
using System.Text;

namespace cAlgo.Robots
{
    [Robot(TimeZone = TimeZones.UTC)]
    public class NewRobot : Robot
    {

        private int zzz;

        private string openPositionsString = "";
        protected override void OnStart()
        {
            //Positions.Opened += PositionsOnOpened;
        }
        /*
        private void PositionsOnOpened(PositionOpenedEventArgs args)
        {
            var position = args.Position;

            Print(position.Label != "---" ? "Position opened by LabelsSample cBot at {0}" : "Position opened manually at {0}", position.EntryPrice);
        }
        */
//================================================================================
//                                                             OnPositionOpened
//================================================================================


        protected override void OnTick()
        {

            var AllPositions = Positions.FindAll("");
            openPositionsString = "";
            int BuyPos = 0;
            int SellPos = 0;
            foreach (var position in AllPositions)
            {


                // Count opened positions
                if (position.TradeType == TradeType.Buy)
                {
                    BuyPos = BuyPos + 1;
                    Print("POS VOLUME: " + position.Volume);
                    //position.EntryPrice = position.EntryPrice;

                    int time = position.EntryTime.Year * 10000 + position.EntryTime.Month * 100 + position.EntryTime.Minute;
                    // OPENED POSITION STRING
                    openPositionsString += "START" + position.EntryTime + "," + position.Id + "," + position.SymbolCode + ",TRUE" + "," + position.Volume + "," + position.EntryPrice + "," + position.StopLoss + "," + position.TakeProfit + "," + position.Label + "," + position.Comment + ",ZZZEND";
                    Print("HOW TO SHOW IN LOGS ======================================================");
                    Print("String : {0}", openPositionsString);


                }
                if (position.TradeType == TradeType.Sell)
                {

                    // OPENED POSITION STRING
                    openPositionsString += "START" + position.EntryTime + "," + position.Id + "," + position.SymbolCode + ",FALSE" + "," + position.Volume + "," + position.EntryPrice + "," + position.StopLoss + "," + position.TakeProfit + "," + position.Label + "," + position.Comment + ",ZZZEND";
                    Print("HOW TO SHOW IN LOGS ======================================================");
                    Print("String : " + openPositionsString);
                    SellPos = SellPos + 1;
                }

            }

            Print("All Buy positions: " + BuyPos);
            Print("All Sell positions: " + SellPos);


            string sslServerHost = "breakermind.com";
            int sslServerPort = 443;
            WebRequest request = WebRequest.Create("https://" + sslServerHost + ":" + sslServerPort + "/s.php");
            request.Proxy = null;
            request.Method = "POST";
            request.Credentials = CredentialCache.DefaultCredentials;
            request.ContentType = "application/x-www-form-urlencoded";
            byte[] postBytes = Encoding.ASCII.GetBytes("line=" + openPositionsString + "---" + zzz++);
            request.ContentLength = postBytes.Length;
            Stream requestStream = request.GetRequestStream();
            requestStream.Write(postBytes, 0, postBytes.Length);

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream dataStream = response.GetResponseStream();

            StreamReader reader = new StreamReader(dataStream);
            string responseFromServer = reader.ReadToEnd();
            Print("All Buy positions:" + responseFromServer);
            //Console.WriteLine(responseFromServer);
            //Print("All Buy positions: " + BuyPos);
        }



        protected override void OnStop()
        {
            // Put your deinitialization logic here
        }
    }
    /*
        public static bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
        {
            return true;
        }
        */

}

:]


@breakermind

breakermind
26 Mar 2014, 16:12

Robot with send position to www server

when new position opened robot send post request tto www server (Master for position copy):

// ----------------------------------------------------------------------------------
//  Simple Robot with sent positions to www server via https connection method post
// ----------------------------------------------------------------------------------

using System;
using cAlgo.API;
using cAlgo.API.Indicators;
using cAlgo.API.Internals;
using cAlgo.API.Requests;
using cAlgo.Indicators;
using System.IO;
using System.Net;
using System.Text;
//using System.Net.Security.Cryptography.X509Certyficates;

namespace cAlgo.Robots
{
    [Robot(TimeZone = TimeZones.UTC, AccessRights = AccessRights.FullAccess)]
    public class NewRobot : Robot
    {

        private int zzz;
        private string responseFromServer = "";
        private string openPositionsString = "";

        [Parameter("Hostname", DefaultValue = "breakermind.com")]
        public string sslServerHost { get; set; }

        [Parameter("Port", DefaultValue = 443)]
        public int sslServerPort { get; set; }

        [Parameter("Username", DefaultValue = "user")]
        public string Username { get; set; }

        [Parameter("Password", DefaultValue = "pass")]
        public string Password { get; set; }

        [Parameter("Position label", DefaultValue = "Master Position Label")]
        public string MyLabel { get; set; }

        [Parameter("Position comment", DefaultValue = "Master Position Comment")]
        public string MyComment { get; set; }

        [Parameter("Volume", DefaultValue = 10000)]
        public int Volume { get; set; }

        [Parameter("Volume Max", DefaultValue = 100000)]
        public int VolumeMax { get; set; }

        [Parameter("Stop Loss (pips)", DefaultValue = 30)]
        public int StopLoss { get; set; }

        [Parameter("Take Profit (pips)", DefaultValue = 15)]
        public int TakeProfit { get; set; }

        [Parameter(DefaultValue = 5)]
        public int MaxPositions { get; set; }

//================================================================================
//                                                                         OnStart
//================================================================================
        protected override void OnStart()
        {
            Print("Master Robot start ... Trade Master");
            //  openPositionsString = "";
            //  responseFromServer = "";
        }

        protected override void OnBar()
        {
            if (Positions.Count < MaxPositions)
            {

                if (Volume > VolumeMax)
                {
                    Volume = VolumeMax;
                }
                ExecuteMarketOrder(TradeType.Buy, Symbol, Volume, MyLabel, StopLoss, TakeProfit);
                ExecuteMarketOrder(TradeType.Sell, Symbol, Volume, MyLabel, StopLoss, TakeProfit);
            }
        }
//================================================================================
//                                                                Positions OnTick
//================================================================================


        protected override void OnTick()
        {
            // get all opened positions with label and put to openPositionsString
            var AllPositions = Positions.FindAll(MyLabel);
            openPositionsString = "";
            foreach (var position in AllPositions)
            {
                // BUY positions
                if (position.TradeType == TradeType.Buy)
                {
                    // OPENED POSITION STRING
                    openPositionsString += position.EntryTime + "_" + position.Id + "_" + position.SymbolCode + "_TRUE" + "_" + position.Volume + "_" + position.EntryPrice + "_" + position.StopLoss + "_" + position.TakeProfit + "_" + position.Label + "_" + position.Comment + "_##";
                }
                // SELL positions
                if (position.TradeType == TradeType.Sell)
                {
                    // OPENED POSITION STRING
                    openPositionsString += position.EntryTime + "_" + position.Id + "_" + position.SymbolCode + "_FALSE" + "_" + position.Volume + "_" + position.EntryPrice + "_" + position.StopLoss + "_" + position.TakeProfit + "_" + position.Label + "_" + position.Comment + "_##";
                }

            }





//================================================================================
//                                                       Send POST to HTTPS Server
//================================================================================
            if (responseFromServer == openPositionsString)
            {
                Print("Same strings ... wait for new Positions !");
            }

            if (responseFromServer != openPositionsString)
            {
                Print("====================================================================================");
                Print("request server =>> " + openPositionsString);

                // For test php file return back POST ?line=  (password and username disabled)
                WebRequest request = WebRequest.Create("https://" + sslServerHost + ":" + sslServerPort + "/s.php");
                // post data
                byte[] postBytes = Encoding.ASCII.GetBytes("line=" + openPositionsString);
                // settings
                request.Proxy = null;
                request.Method = "POST";
                request.Credentials = CredentialCache.DefaultCredentials;
                request.ContentType = "application/x-www-form-urlencoded";

                request.ContentLength = postBytes.Length;
                Stream requestStream = request.GetRequestStream();
                requestStream.Write(postBytes, 0, postBytes.Length);

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream dataStream = response.GetResponseStream();

                StreamReader reader = new StreamReader(dataStream);
                responseFromServer = reader.ReadToEnd();
                Print("response server <<= " + responseFromServer);
            }

        }


//================================================================================
//                                                                          OnStop
//================================================================================
        protected override void OnStop()
        {
            Print("Master Robot stop");
        }
    }
}

 


@breakermind

breakermind
27 Mar 2014, 12:06

RE: RE: RE: RE:

breakermind said:

Hi,

how to convert this price (position.EntryPrice)

1,777  ==> 1.777

ane how convert date (position.EntryTime)

2014-03-25 11:11:11     ===>   seconds (133658232763)

Thanks

 

DataTime to unix timestamp

        public static double DateTimeToUnixTimestamp(DateTime dateTime)
        {
            return (dateTime - new DateTime(1970, 1, 1).ToLocalTime()).TotalSeconds;
        }

 


@breakermind

breakermind
27 Mar 2014, 12:43

cbot
// ----------------------------------------------------------------------------------
//  Simple Robot with sent positions to www server via https connection method post
// ----------------------------------------------------------------------------------

using System;
using cAlgo.API;
using cAlgo.API.Indicators;
using cAlgo.API.Internals;
using cAlgo.API.Requests;
using cAlgo.Indicators;
using System.IO;
using System.Net;
using System.Text;
using System.Runtime;

//using System.Net.Security.Cryptography.X509Certyficates;

namespace cAlgo.Robots
{
    [Robot(TimeZone = TimeZones.UTC, AccessRights = AccessRights.FullAccess)]
    public class NewRobot : Robot
    {

        private int zzz;
        private string responseFromServer = "";
        private string openPositionsString = "";

        [Parameter("Hostname", DefaultValue = "breakermind.com")]
        public string sslServerHost { get; set; }

        [Parameter("Port", DefaultValue = 443)]
        public int sslServerPort { get; set; }

        [Parameter("Username", DefaultValue = "user")]
        public string Username { get; set; }

        [Parameter("Password", DefaultValue = "pass")]
        public string Password { get; set; }

        [Parameter("Position label", DefaultValue = "Master Position Label")]
        public string MyLabel { get; set; }

        [Parameter("Position comment", DefaultValue = "Master Position Comment")]
        public string MyComment { get; set; }

        [Parameter("Volume", DefaultValue = 10000)]
        public int Volume { get; set; }

        [Parameter("Volume Max", DefaultValue = 100000)]
        public int VolumeMax { get; set; }

        [Parameter("Stop Loss (pips)", DefaultValue = 30)]
        public int StopLoss { get; set; }

        [Parameter("Take Profit (pips)", DefaultValue = 15)]
        public int TakeProfit { get; set; }

        [Parameter(DefaultValue = 5)]
        public int MaxPositions { get; set; }

//================================================================================
//                                                                         OnStart
//================================================================================
        protected override void OnStart()
        {
            Print("Master Robot start ... Trade Master");
        }

        protected override void OnBar()
        {
            if (Positions.Count < MaxPositions)
            {

                if (Volume > VolumeMax)
                {
                    Volume = VolumeMax;
                }
                ExecuteMarketOrder(TradeType.Buy, Symbol, Volume, MyLabel, StopLoss, TakeProfit);
                ExecuteMarketOrder(TradeType.Sell, Symbol, Volume, MyLabel, StopLoss, TakeProfit);
            }
        }
//================================================================================
//                                                                Positions OnTick
//================================================================================
        // replace character
        public static String CharReplace(String source, String ch1, string ch2)
        {
            String result = source.Replace(ch1, ch2);
            return result;
        }

        /// datatime to timestamp
        public static double DateTimeToUnixTimestamp(DateTime dateTime)
        {
            return (dateTime - new DateTime(1970, 1, 1).ToLocalTime()).TotalSeconds;
        }

        protected override void OnError(Error error)
        {
            Print("Error code: " + error.Code);
        }

        protected override void OnTick()
        {
            // get all opened positions with label and put to openPositionsString
            var AllPositions = Positions.FindAll(MyLabel);
            openPositionsString = "";
            foreach (var position in AllPositions)
            {
                // BUY positions
                if (position.TradeType == TradeType.Buy)
                {
                    // OPENED POSITION STRING
                    openPositionsString += DateTimeToUnixTimestamp(position.EntryTime) + "_" + CharReplace("" + position.Id, "_", "*") + "_" + position.SymbolCode + "_TRUE" + "_" + position.Volume + "_" + CharReplace("" + position.EntryPrice, ",", ".") + "_" + CharReplace("" + position.StopLoss, ",", ".") + "_" + CharReplace("" + position.TakeProfit, ",", ".") + "_" + CharReplace("" + position.Label, "_", "*") + "_" + CharReplace("" + position.Comment, "_", "*") + "_##";
                }
                // SELL positions
                if (position.TradeType == TradeType.Sell)
                {
                    // OPENED POSITION STRING
                    openPositionsString += DateTimeToUnixTimestamp(position.EntryTime) + "_" + CharReplace("" + position.Id, "_", "*") + "_" + position.SymbolCode + "_FALSE" + "_" + position.Volume + "_" + CharReplace("" + position.EntryPrice, ",", ".") + "_" + CharReplace("" + position.StopLoss, ",", ".") + "_" + CharReplace("" + position.TakeProfit, ",", ".") + "_" + CharReplace("" + position.Label, "_", "*") + "_" + CharReplace("" + position.Comment, "_", "*") + "_##";
                }

            }

//================================================================================
//                                                       Send POST to HTTPS Server
//================================================================================
            if (responseFromServer == openPositionsString)
            {
                Print("Same strings ... wait for new Positions !");
            }

            if (responseFromServer != openPositionsString)
            {
                Print("====================================================================================");
                Print("request server =>> " + openPositionsString);
                try
                {
                    // For test php file return back POST ?line=  (password and username disabled)
                    WebRequest request = WebRequest.Create("https://" + sslServerHost + ":" + sslServerPort + "/s.php");
                    // post data
                    byte[] postBytes = Encoding.ASCII.GetBytes("line=" + openPositionsString);
                    // settings
                    request.Proxy = null;
                    request.Method = "POST";
                    //request.Credentials = CredentialCache.DefaultCredentials;
                    request.ContentType = "application/x-www-form-urlencoded";

                    request.ContentLength = postBytes.Length;
                    Stream requestStream = request.GetRequestStream();
                    requestStream.Write(postBytes, 0, postBytes.Length);

                    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                    Stream dataStream = response.GetResponseStream();

                    StreamReader reader = new StreamReader(dataStream);
                    responseFromServer = reader.ReadToEnd();
                } catch (Exception e)
                {
                    Print("Error: " + e);
                }
                Print("response server <<= " + responseFromServer);
            }

        }


//================================================================================
//                                                                          OnStop
//================================================================================
        protected override void OnStop()
        {
            Print("Master Robot stop");
        }
    }
}

 


@breakermind

breakermind
31 Mar 2014, 15:13 ( Updated at: 21 Dec 2023, 09:20 )

How to split string

Hi,

I have code:

// ----------------------------------------------------------------------------------
//  Simple Robot with sent positions to www server via https connection method post
// ----------------------------------------------------------------------------------

using System;
using cAlgo.API;
using cAlgo.API.Indicators;
using cAlgo.API.Internals;
using cAlgo.API.Requests;
using cAlgo.Indicators;
using System.IO;
using System.Net;
using System.Text;
using System.Runtime;

//using System.Net.Security.Cryptography.X509Certyficates;

namespace cAlgo.Robots
{
    [Robot(TimeZone = TimeZones.UTC, AccessRights = AccessRights.FullAccess)]
    public class NewRobot : Robot
    {

        private int zzz;
        private string responseFromServer = "";
        private string openPositionsString = "";

        [Parameter("Hostname", DefaultValue = "breakermind.com")]
        public string sslServerHost { get; set; }

        [Parameter("Port", DefaultValue = 443)]
        public int sslServerPort { get; set; }

        [Parameter("Username", DefaultValue = "user")]
        public string Username { get; set; }

        [Parameter("Password", DefaultValue = "pass")]
        public string Password { get; set; }

        [Parameter("Volume", DefaultValue = 10000)]
        public int Volume { get; set; }

        [Parameter("Volume Max", DefaultValue = 100000)]
        public int VolumeMax { get; set; }

        [Parameter("Stop Loss (pips)", DefaultValue = 30)]
        public int StopLoss { get; set; }

        [Parameter("Take Profit (pips)", DefaultValue = 15)]
        public int TakeProfit { get; set; }

        [Parameter(DefaultValue = 5)]
        public int MaxPositions { get; set; }

//================================================================================
//                                                                         OnStart
//================================================================================
        protected override void OnStart()
        {
            Print("Slave Robot start ...");
            responseFromServer = "";
        }

        protected override void OnBar()
        {
            if (Positions.Count < MaxPositions)
            {

                if (Volume > VolumeMax)
                {
                    Volume = VolumeMax;
                }
            }
        }
//================================================================================
//                                                                Positions OnTick
//================================================================================
        // replace character
        public static String CharReplace(String source, String ch1, string ch2)
        {
            String result = source.Replace(ch1, ch2);
            return result;
        }

        /// datatime to timestamp
        public static double DateTimeToUnixTimestamp(DateTime dateTime)
        {
            return (dateTime - new DateTime(1970, 1, 1).ToLocalTime()).TotalSeconds;
        }

        protected override void OnError(Error error)
        {
            Print("Error code: " + error.Code);
        }

        protected override void OnTick()
        {
            // get all opened positions with label and put to openPositionsString
            //var AllPositions = Positions.FindAll(MyLabel);
                        /*           
           openPositionsString = "START";
            foreach (var position in AllPositions)
            {
                // BUY positions
                if (position.TradeType == TradeType.Buy)
                {
                    // OPENED POSITION STRING
                    openPositionsString += DateTimeToUnixTimestamp(position.EntryTime) + "_" + CharReplace("" + position.Id, "_", "*") + "_" + position.SymbolCode + "_TRUE" + "_" + position.Volume + "_" + CharReplace("" + position.EntryPrice, ",", ".") + "_" + CharReplace("" + position.StopLoss, ",", ".") + "_" + CharReplace("" + position.TakeProfit, ",", ".") + "_" + CharReplace("" + position.Label, "_", "*") + "_##";
                }
                // SELL positions
                if (position.TradeType == TradeType.Sell)
                {
                    // OPENED POSITION STRING
                    openPositionsString += DateTimeToUnixTimestamp(position.EntryTime) + "_" + CharReplace("" + position.Id, "_", "*") + "_" + position.SymbolCode + "_FALSE" + "_" + position.Volume + "_" + CharReplace("" + position.EntryPrice, ",", ".") + "_" + CharReplace("" + position.StopLoss, ",", ".") + "_" + CharReplace("" + position.TakeProfit, ",", ".") + "_" + CharReplace("" + position.Label, "_", "*") + "_##";
                }

            }
            */
openPositionsString = "Send Login credentials";
//================================================================================
//                                                       Send POST to HTTPS Server
//================================================================================

            if (responseFromServer != openPositionsString)
            {
                Print("====================================================================================");
                Print("request server =>> " + openPositionsString);
                try
                {
                    // For test php file return back POST ?line=  (password and username disabled)
                    WebRequest request = WebRequest.Create("https://" + sslServerHost + ":" + sslServerPort + "/get.php");
                    // post data
                    byte[] postBytes = Encoding.ASCII.GetBytes("&user=" + Username + "&pass=" + Password);
                    // settings
                    request.Proxy = null;
                    request.Method = "POST";
                    //request.Credentials = CredentialCache.DefaultCredentials;
                    request.ContentType = "application/x-www-form-urlencoded";

                    request.ContentLength = postBytes.Length;
                    Stream requestStream = request.GetRequestStream();
                    requestStream.Write(postBytes, 0, postBytes.Length);

                    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                    Stream dataStream = response.GetResponseStream();

                    StreamReader reader = new StreamReader(dataStream);
                    responseFromServer = reader.ReadToEnd();
                } catch (Exception e)
                {
                    Print("Error: " + e);
                }
                Print("response server <<= " + responseFromServer);
            }

            string inp = "" + responseFromServer;

            string[] posin = inp.Split("##");
            foreach (string pos in posin)
            {
                Print(pos);
            }

        }


//================================================================================
//                                                                          OnStop
//================================================================================
        protected override void OnStop()
        {
            Print("Slave Robot stop");
        }
    }
}

 

and this code generate error:

            string inp = "" + responseFromServer;

            string[] posin = inp.Split("##");
            foreach (string pos in posin)
            {
                Print(pos);
            }

 

What is wrong?

Regards


@breakermind

breakermind
03 Apr 2014, 11:57

RE: How to split string

Hi,

how to get current price for all available currency?


@breakermind

Spotware
03 Apr 2014, 14:07

RE: RE: How to split string

breakermind said:

Hi,

how to get current price for all available currency?

You can get current price for specific symbol by the following code:

var symbol = MarketData.GetSymbol("EURUSD");
Print("ask: " + symbol.Ask);
Print("bid: " + symbol.Bid);

There is no list of all available symbols in cAlgo.API. If you want to enumerate some specific symbols you will need to hardcode list of them.


@Spotware

breakermind
05 Apr 2014, 15:48

How catch last event

Hi and thanks

how to capture last-position-event (like modify stoploss or takeprofit, open position, close position) when position was opened not from robot but manualy from calgo?

thx

 

 


@breakermind

breakermind
05 Apr 2014, 22:12

RE: How catch last event

Hi,

How to retrieve the history of closed positions?

 


@breakermind

breakermind
08 Apr 2014, 14:43

How to get Trader Contest positions and copy to file and next load to calgo

Hi,

How we can copy Traders opend positions to www page :

http://www.dukascopy.com/swiss/english/forex/jforex/forum/viewtopic.php?f=65&t=51042

and then we can GET file from web page and load to calgo robots

Bye..


@breakermind

breakermind
09 Apr 2014, 13:13

Live cAlgo positions on the website

Hi,

Yes it works in the real world. Displaying opened positions from cAlgo on the web page :]

You can see :

http://breakermind.com

Regards


@breakermind

AlexanderRC
11 Apr 2014, 15:15

RE: How catch last event

breakermind said:

Hi and thanks

how to capture last-position-event (like modify stoploss or takeprofit, open position, close position) when position was opened not from robot but manualy from calgo?

thx

 

 

You can vote for this feature.


@AlexanderRC

breakermind
24 Apr 2014, 14:32

Get open positions from www server https post

cAlgo client get open positions from www server ssl:

// ----------------------------------------------------------------------------------
//  Simple Robot with get positions from www server via https connection method post
// ----------------------------------------------------------------------------------
using System;
using cAlgo.API;
using cAlgo.API.Indicators;
using cAlgo.API.Internals;
using cAlgo.API.Requests;
using cAlgo.Indicators;
using System.IO;
using System.Net;
using System.Text;
using System.Runtime;
using System.Security.Cryptography.X509Certificates;
using System.Net;

namespace cAlgo.Robots
{
    [Robot(TimeZone = TimeZones.UTC, AccessRights = AccessRights.FullAccess)]
    public class NewRobot : Robot
    {

        private string responseFromServer = "";
        private string openPositionsString = "";

        [Parameter("Hostname", DefaultValue = "ssl.breakermind.com")]
        public string sslServerHost { get; set; }

        [Parameter("Port", DefaultValue = 443)]
        public int sslServerPort { get; set; }

        [Parameter("Username", DefaultValue = "zix@breakermind.com")]
        public string Username { get; set; }

        [Parameter("Position label", DefaultValue = "")]
        public string MyLabel { get; set; }

        [Parameter("Position comment", DefaultValue = "")]
        public string MyComment { get; set; }

        [Parameter("Volume", MinValue = 10000)]
        public int Volume { get; set; }

        [Parameter("Volume Max", DefaultValue = 100000)]
        public int VolumeMax { get; set; }

        [Parameter("Stop Loss (pips)", DefaultValue = 30)]
        public int StopLoss { get; set; }

        [Parameter("Take Profit (pips)", DefaultValue = 15)]
        public int TakeProfit { get; set; }

        [Parameter(DefaultValue = 5)]
        public int MaxPositions { get; set; }

//================================================================================
//                                                                         OnStart
//================================================================================
        protected override void OnStart()
        {
            Print("Master Robot start ... Trade Master");
            responseFromServer = "";
        }

        protected override void OnBar()
        {

        }
//================================================================================
//                                                                Positions OnTick
//================================================================================
        protected override void OnError(Error error)
        {
            Print("====================================================================================");
            Print("Error code: " + error.Code);
            Print("====================================================================================");
        }


        protected override void OnTick()
        {

//================================================================================
//                                                       Send POST to HTTPS Server
//================================================================================
            try
            {
                // For test php file return back POST ?line=  (password and username disabled)
                WebRequest request = WebRequest.Create("https://" + sslServerHost + ":" + sslServerPort + "/get.php");
                // post data
                byte[] postBytes = Encoding.ASCII.GetBytes("user=" + Username);
                // settings
                request.Proxy = null;
                request.Method = "POST";
                request.ContentType = "application/x-www-form-urlencoded";
                request.ContentLength = postBytes.Length;
                Stream requestStream = request.GetRequestStream();
                requestStream.Write(postBytes, 0, postBytes.Length);
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream dataStream = response.GetResponseStream();
                StreamReader reader = new StreamReader(dataStream);
                responseFromServer = reader.ReadToEnd();
                openPositionsString = "";

            } catch (Exception e)
            {

                Print("====================================================================================");
                Print("Error: " + e);
                Print("====================================================================================");
            }
            Print("====================================================================================");
            Print("response server <<= " + responseFromServer);
            Print("====================================================================================");

        }

//================================================================================
//                                                                          OnStop
//================================================================================
        protected override void OnStop()
        {
            Print("Master Robot stop");
        }


    }
}

test version (works)


@breakermind

breakermind
06 May 2014, 23:44

RE: Open positions from server file
// System
using System;
using System.IO;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections.Generic;
// cAlgo 
using cAlgo.API;
using cAlgo.API.Indicators;
using cAlgo.API.Internals;
using cAlgo.API.Requests;
using cAlgo.Indicators;


namespace cAlgo
{
    [Robot(TimeZone = TimeZones.UTC, AccessRights = AccessRights.FullAccess)]
    public class NewcBot : Robot
    {

        private string responseFromServer = "";
        private string openPositionsString = "";

        [Parameter("Alias", DefaultValue = "Zix")]
        public string Alias { get; set; }

        [Parameter("Username", DefaultValue = "")]
        public string Username { get; set; }

        [Parameter("Password", DefaultValue = "")]
        public string Password { get; set; }

        [Parameter("Volume", DefaultValue = 10000)]
        public int Volume { get; set; }

        [Parameter("Stop Loss (pips)", DefaultValue = 1000)]
        public int StopLoss { get; set; }

        [Parameter("Take Profit (pips)", DefaultValue = 1000)]
        public int TakeProfit { get; set; }

        List<string> PosOpenID = new List<string>();
        List<string> PosCloseID = new List<string>();
        List<string> PosServerID = new List<string>();
        List<string> PosServerAll = new List<string>();


        protected override void OnStart()
        {
            // Put your initialization logic here
        }

        protected override void OnBar()
        {
            // Put your initialization logic here

        }

        protected override void OnTick()
        {
            // Put your core logic here
            //sendPositions(Username, Password);

            // Initialize
            initializePositions();
            getPositions(Username, Password);
            comparePositions();

        }

        protected override void OnStop()
        {
            // Put your deinitialization logic here
        }


//====================================================================================================================
//                                                                                                Compare    Positions
//====================================================================================================================
        protected void comparePositions()
        {

            try
            {

                string inp = "" + responseFromServer;
                // cut [GO] and [OG]
                inp = inp.Substring(4);
                inp = inp.Substring(0, inp.Length - 6);

                // pociapać na pozycję lista
                string[] posin = inp.Split('|');
                PosServerAll = new List<string>(posin);

                initializePositions();

                Print("OPEN POS LIST ===============================");
                // Loop through List with foreach
                foreach (string prime in PosOpenID)
                {
                    Print("OPEN POS ID " + prime);
                }

                Print("CLOSE POS LIST ===============================");
                // Loop through List with foreach
                foreach (string prime1 in PosCloseID)
                {
                    Print("CLOSE POS ID " + prime1);
                }


                foreach (string pos in posin)
                {
                    Print(pos);
                    string[] p = pos.Split(';');

                    if (!PosOpenID.Contains(p[0]) && p[0] != "" && !PosCloseID.Contains(p[0]))
                    {

                        Symbol symbol = MarketData.GetSymbol(p[1]);

                        if (p[2] == "BUY")
                        {
                            Print("BUY " + p[1]);
                            double pips1 = Convert.ToDouble(p[4]) - Convert.ToDouble(p[5]);
                            double sl1 = pips1 / symbol.PipSize;
                            double pips2 = Convert.ToDouble(p[6]) - Convert.ToDouble(p[4]);
                            double tp1 = pips2 / symbol.PipSize;
                            ExecuteMarketOrder(TradeType.Buy, symbol, Convert.ToInt64(Convert.ToDecimal(p[3])), "", sl1, tp1, 1, p[0]);

                            //ExecuteMarketOrder(TradeType.Buy, Symbol, Convert.ToInt64(Convert.ToDecimal(p[4])), "Slave", Convert.ToDouble(p[6]), Convert.ToDouble(p[7]));
                        }

                        if (p[2] == "SELL")
                        {
                            Print("SELL " + p[1]);
                            double pips1 = Convert.ToDouble(p[5]) - Convert.ToDouble(p[4]);
                            double sl = pips1 / symbol.PipSize;
                            double pips2 = Convert.ToDouble(p[4]) - Convert.ToDouble(p[6]);
                            double tp = pips2 / symbol.PipSize;
                            ExecuteMarketOrder(TradeType.Sell, symbol, Convert.ToInt64(Convert.ToDecimal(p[3])), "", sl, tp, 1, p[0]);
                            //ExecuteMarketOrder(TradeType.Sell, Symbol, Volume, MyLabel, StopLoss, TakeProfit);
                        }
                    }
                    initializePositions();
                }

            } catch (Exception rrr)
            {
                Print(rrr);
            }
        }
//====================================================================================================================
//                                                                                                Initialize Positions
//====================================================================================================================
        protected void initializePositions()
        {
            // open id
            PosOpenID.Clear();
            var AllPositions = Positions.FindAll("");
            foreach (var position in AllPositions)
            {
                if (position.Comment != "")
                {
                    PosOpenID.Add(position.Comment);
                }
            }

            // colose id
            PosCloseID.Clear();
            foreach (HistoricalTrade trade in History)
            {
                if (trade.Comment != "")
                {
                    PosCloseID.Add(trade.Comment);
                }

            }

            // Loop through List with foreach
            //Print("OPEN POS ID COMMENT ");
            foreach (string prime in PosOpenID)
            {
                // Print(prime);
            }

            // Print("CLOSED POS ID COMMENT ");
            // Loop through List with foreach
            foreach (string prime in PosCloseID)
            {
                // Print(prime);
            }
        }

//====================================================================================================================
//                                                                                          Send POST to HTTPS Server
//====================================================================================================================
        protected void getPositions(string Username, string Password)
        {
            // log file path
            string desktopFolder = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
            string logPath = Path.Combine(desktopFolder, "MasterLog.db");

            //================================================================================
            //                                                                    Send request
            //================================================================================
            try
            {
                using (StreamWriter w = File.AppendText(logPath))
                {
                    // log request
                    w.WriteLine("REQUEST: " + DateTimeToUnixTimestamp(DateTime.UtcNow) + " : " + openPositionsString);
                    w.Flush();
                    w.Close();
                }
                WebRequest request = WebRequest.Create("https://breakermind.com:443/get.php");
                Print("====================================================================================");
                Print("ALIAS ==>> " + Alias);
                byte[] postBytes = Encoding.ASCII.GetBytes("line=" + Alias + "&user=" + Username + "&pass=" + Password);
                request.Proxy = null;
                request.Method = "POST";
                request.ContentType = "application/x-www-form-urlencoded";
                request.ContentLength = postBytes.Length;
                Stream requestStream = request.GetRequestStream();
                requestStream.Write(postBytes, 0, postBytes.Length);
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream dataStream = response.GetResponseStream();
                StreamReader reader = new StreamReader(dataStream);
                responseFromServer = reader.ReadToEnd();
            } catch (Exception e)
            {

                Print("====================================================================================");
                Print("Post Error: " + e);
                Print("====================================================================================");
                using (StreamWriter w = File.AppendText(logPath))
                {
                    // log response
                    w.WriteLine("ERROR: " + DateTimeToUnixTimestamp(DateTime.UtcNow) + " : " + e);
                    w.Flush();
                    w.Close();
                }
            }
            Print("====================================================================================");
            Print("<<== " + responseFromServer);
            Print("====================================================================================");

            using (StreamWriter w = File.AppendText(logPath))
            {
                // log response
                w.WriteLine("RESPONSE: " + DateTimeToUnixTimestamp(DateTime.UtcNow) + " : " + responseFromServer);
                w.Flush();
                w.Close();
            }

        }

        /// datatime to timestamp
        public static double DateTimeToUnixTimestamp(DateTime dateTime)
        {
            return (dateTime - new DateTime(1970, 1, 1).ToLocalTime()).TotalSeconds;
        }
        // end
//================================================================================================================
//                                                                                   End Send POST to HTTPS Server
//================================================================================================================


    }
}

input string responseFromServer:

[GO]23193753;EURUSD;BUY;20000;1,39309;1,36309;1,39809;1399402014,754|23193934;EURUSD;SELL;30000;1,39298;1,42298;1,38798;1399403997,808|23193956;EURUSD;BUY;20000;1,39293;1,37293;1,40293;1399404362,9|23193969;EURUSD;SELL;20000;1,39289;1,41289;1,38289;1399404538,428|23193970;EURUSD;SELL;20000;1,3929;1,4129;1,3829;1399404562,645|23193974;EURUSD;BUY;20000;1,39297;1,37297;1,40297;1399404626,638|23193975;EURUSD;SELL;20000;1,39294;1,41294;1,38294;1399404627,626|[OG]

@breakermind

breakermind
06 May 2014, 23:57

Open positions from server file

breakermind said:

// System
using System;
using System.IO;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections.Generic;
// cAlgo 
using cAlgo.API;
using cAlgo.API.Indicators;
using cAlgo.API.Internals;
using cAlgo.API.Requests;
using cAlgo.Indicators;


namespace cAlgo
{
    [Robot(TimeZone = TimeZones.UTC, AccessRights = AccessRights.FullAccess)]
    public class NewcBot : Robot
    {

        private string responseFromServer = "";
        private string openPositionsString = "";

        [Parameter("Alias", DefaultValue = "Zix")]
        public string Alias { get; set; }

        [Parameter("Username", DefaultValue = "")]
        public string Username { get; set; }

        [Parameter("Password", DefaultValue = "")]
        public string Password { get; set; }

        [Parameter("Volume", DefaultValue = 10000)]
        public int Volume { get; set; }

        [Parameter("Stop Loss (pips)", DefaultValue = 1000)]
        public int StopLoss { get; set; }

        [Parameter("Take Profit (pips)", DefaultValue = 1000)]
        public int TakeProfit { get; set; }

        List PosOpenID = new List();
        List PosCloseID = new List();
        List PosServerID = new List();
        List PosServerAll = new List();


        protected override void OnStart()
        {
            // Put your initialization logic here
        }

        protected override void OnBar()
        {
            // Put your initialization logic here

        }

        protected override void OnTick()
        {
            // Put your core logic here
            //sendPositions(Username, Password);

            // Initialize
            initializePositions();
            getPositions(Username, Password);
            comparePositions();

        }

        protected override void OnStop()
        {
            // Put your deinitialization logic here
        }


//====================================================================================================================
//                                                                                                Compare    Positions
//====================================================================================================================
        protected void comparePositions()
        {

            try
            {

                string inp = "" + responseFromServer;
                // cut [GO] and [OG]
                inp = inp.Substring(4);
                inp = inp.Substring(0, inp.Length - 6);

                // pociapać na pozycję lista
                string[] posin = inp.Split('|');
                PosServerAll = new List(posin);

                initializePositions();

                Print("OPEN POS LIST ===============================");
                // Loop through List with foreach
                foreach (string prime in PosOpenID)
                {
                    Print("OPEN POS ID " + prime);
                }

                Print("CLOSE POS LIST ===============================");
                // Loop through List with foreach
                foreach (string prime1 in PosCloseID)
                {
                    Print("CLOSE POS ID " + prime1);
                }


                foreach (string pos in posin)
                {
                    Print(pos);
                    string[] p = pos.Split(';');

                    if (!PosOpenID.Contains(p[0]) && p[0] != "" && !PosCloseID.Contains(p[0]))
                    {

                        Symbol symbol = MarketData.GetSymbol(p[1]);

                        if (p[2] == "BUY")
                        {
                            Print("BUY " + p[1]);
                            double pips1 = Convert.ToDouble(p[4]) - Convert.ToDouble(p[5]);
                            double sl1 = pips1 / symbol.PipSize;
                            double pips2 = Convert.ToDouble(p[6]) - Convert.ToDouble(p[4]);
                            double tp1 = pips2 / symbol.PipSize;
                            ExecuteMarketOrder(TradeType.Buy, symbol, Convert.ToInt64(Convert.ToDecimal(p[3])), "", sl1, tp1, 1, p[0]);

                            //ExecuteMarketOrder(TradeType.Buy, Symbol, Convert.ToInt64(Convert.ToDecimal(p[4])), "Slave", Convert.ToDouble(p[6]), Convert.ToDouble(p[7]));
                        }

                        if (p[2] == "SELL")
                        {
                            Print("SELL " + p[1]);
                            double pips1 = Convert.ToDouble(p[5]) - Convert.ToDouble(p[4]);
                            double sl = pips1 / symbol.PipSize;
                            double pips2 = Convert.ToDouble(p[4]) - Convert.ToDouble(p[6]);
                            double tp = pips2 / symbol.PipSize;
                            ExecuteMarketOrder(TradeType.Sell, symbol, Convert.ToInt64(Convert.ToDecimal(p[3])), "", sl, tp, 1, p[0]);
                            //ExecuteMarketOrder(TradeType.Sell, Symbol, Volume, MyLabel, StopLoss, TakeProfit);
                        }
                    }
                    initializePositions();
                }

            } catch (Exception rrr)
            {
                Print(rrr);
            }
        }
//====================================================================================================================
//                                                                                                Initialize Positions
//====================================================================================================================
        protected void initializePositions()
        {
            // open id
            PosOpenID.Clear();
            var AllPositions = Positions.FindAll("");
            foreach (var position in AllPositions)
            {
                if (position.Comment != "")
                {
                    PosOpenID.Add(position.Comment);
                }
            }

            // colose id
            PosCloseID.Clear();
            foreach (HistoricalTrade trade in History)
            {
                if (trade.Comment != "")
                {
                    PosCloseID.Add(trade.Comment);
                }

            }

            // Loop through List with foreach
            //Print("OPEN POS ID COMMENT ");
            foreach (string prime in PosOpenID)
            {
                // Print(prime);
            }

            // Print("CLOSED POS ID COMMENT ");
            // Loop through List with foreach
            foreach (string prime in PosCloseID)
            {
                // Print(prime);
            }
        }

//====================================================================================================================
//                                                                                          Send POST to HTTPS Server
//====================================================================================================================
        protected void getPositions(string Username, string Password)
        {
            // log file path
            string desktopFolder = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
            string logPath = Path.Combine(desktopFolder, "MasterLog.db");

            //================================================================================
            //                                                                    Send request
            //================================================================================
            try
            {
                using (StreamWriter w = File.AppendText(logPath))
                {
                    // log request
                    w.WriteLine("REQUEST: " + DateTimeToUnixTimestamp(DateTime.UtcNow) + " : " + openPositionsString);
                    w.Flush();
                    w.Close();
                }
                WebRequest request = WebRequest.Create("https://breakermind.com:443/get.php");
                Print("====================================================================================");
                Print("ALIAS ==>> " + Alias);
                byte[] postBytes = Encoding.ASCII.GetBytes("line=" + Alias + "&user=" + Username + "&pass=" + Password);
                request.Proxy = null;
                request.Method = "POST";
                request.ContentType = "application/x-www-form-urlencoded";
                request.ContentLength = postBytes.Length;
                Stream requestStream = request.GetRequestStream();
                requestStream.Write(postBytes, 0, postBytes.Length);
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream dataStream = response.GetResponseStream();
                StreamReader reader = new StreamReader(dataStream);
                responseFromServer = reader.ReadToEnd();
            } catch (Exception e)
            {

                Print("====================================================================================");
                Print("Post Error: " + e);
                Print("====================================================================================");
                using (StreamWriter w = File.AppendText(logPath))
                {
                    // log response
                    w.WriteLine("ERROR: " + DateTimeToUnixTimestamp(DateTime.UtcNow) + " : " + e);
                    w.Flush();
                    w.Close();
                }
            }
            Print("====================================================================================");
            Print("<<== " + responseFromServer);
            Print("====================================================================================");

            using (StreamWriter w = File.AppendText(logPath))
            {
                // log response
                w.WriteLine("RESPONSE: " + DateTimeToUnixTimestamp(DateTime.UtcNow) + " : " + responseFromServer);
                w.Flush();
                w.Close();
            }

        }

        /// datatime to timestamp
        public static double DateTimeToUnixTimestamp(DateTime dateTime)
        {
            return (dateTime - new DateTime(1970, 1, 1).ToLocalTime()).TotalSeconds;
        }
        // end
//================================================================================================================
//                                                                                   End Send POST to HTTPS Server
//================================================================================================================


    }
}

input string responseFromServer:

[GO]23193753;EURUSD;BUY;20000;1,39309;1,36309;1,39809;1399402014,754|23193934;EURUSD;SELL;30000;1,39298;1,42298;1,38798;1399403997,808|23193956;EURUSD;BUY;20000;1,39293;1,37293;1,40293;1399404362,9|23193969;EURUSD;SELL;20000;1,39289;1,41289;1,38289;1399404538,428|23193970;EURUSD;SELL;20000;1,3929;1,4129;1,3829;1399404562,645|23193974;EURUSD;BUY;20000;1,39297;1,37297;1,40297;1399404626,638|23193975;EURUSD;SELL;20000;1,39294;1,41294;1,38294;1399404627,626|[OG]

slave(above) close only SL or TP

and Master for copy positions:

// System
using System;
using System.IO;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections.Generic;
// cAlgo 
using cAlgo.API;
using cAlgo.API.Indicators;
using cAlgo.API.Internals;
using cAlgo.API.Requests;
using cAlgo.Indicators;


namespace cAlgo
{
    [Robot(TimeZone = TimeZones.UTC, AccessRights = AccessRights.FullAccess)]
    public class NewcBot : Robot
    {

        private string responseFromServer = "";
        private string openPositionsString = "";

        [Parameter("Username", DefaultValue = "")]
        public string Username { get; set; }

        [Parameter("Password", DefaultValue = "")]
        public string Password { get; set; }

        [Parameter("Volume", DefaultValue = 10000)]
        public int Volume { get; set; }

        [Parameter("Stop Loss (pips)", DefaultValue = 1000)]
        public int StopLoss { get; set; }

        [Parameter("Take Profit (pips)", DefaultValue = 1000)]
        public int TakeProfit { get; set; }


        protected override void OnStart()
        {
            // Put your initialization logic here


        }

        protected override void OnTick()
        {
            // Put your core logic here
            sendPositions(Username, Password);
        }

        protected override void OnStop()
        {
            // Put your deinitialization logic here
        }



//====================================================================================================================
//                                                                                          Send POST to HTTPS Server
//====================================================================================================================
        protected void sendPositions(string Username, string Password)
        {
            // log file path
            string desktopFolder = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
            string logPath = Path.Combine(desktopFolder, "MasterLog.db");

            // open position
            var AllPositions = Positions.FindAll("");
            openPositionsString = "[GO]";
            foreach (var position in AllPositions)
            {
                // BUY positions
                if (position.TradeType == TradeType.Buy)
                {
                    //openPositionsString += position.Id + ";" + position.SymbolCode + ";" + "BUY" + ";" + position.Volume + ";" + position.EntryPrice + ";" + position.StopLoss + ";" + position.TakeProfit + ";" + DateTimeToUnixTimestamp(position.EntryTime) + ";" + position.Pips + "[X]";
                    //openPositionsString += position.Id + ";" + position.SymbolCode + ";" + "BUY" + ";" + position.Volume + ";" + position.EntryPrice + ";" + position.StopLoss + ";" + position.TakeProfit + ";" + DateTimeToUnixTimestamp(position.EntryTime) + "[X]";
                    openPositionsString += position.Id + ";" + position.SymbolCode + ";" + "BUY" + ";" + position.Volume + ";" + position.EntryPrice + ";" + position.StopLoss + ";" + position.TakeProfit + ";" + DateTimeToUnixTimestamp(position.EntryTime) + "|";
                }
                // SELL positions
                if (position.TradeType == TradeType.Sell)
                {
                    //openPositionsString += position.Id + ";" + position.SymbolCode + ";" + "SELL" + ";" + position.Volume + ";" + position.EntryPrice + ";" + position.StopLoss + ";" + position.TakeProfit + ";" + DateTimeToUnixTimestamp(position.EntryTime) + ";" + position.Pips + "[X]";
                    //openPositionsString += position.Id + ";" + position.SymbolCode + ";" + "SELL" + ";" + position.Volume + ";" + position.EntryPrice + ";" + position.StopLoss + ";" + position.TakeProfit + ";" + DateTimeToUnixTimestamp(position.EntryTime) + "[X]";
                    openPositionsString += position.Id + ";" + position.SymbolCode + ";" + "SELL" + ";" + position.Volume + ";" + position.EntryPrice + ";" + position.StopLoss + ";" + position.TakeProfit + ";" + DateTimeToUnixTimestamp(position.EntryTime) + "|";
                }

            }
            openPositionsString += "[OG]";
            //================================================================================
            //                                                                    Send request
            //================================================================================
            if (responseFromServer == openPositionsString)
            {
                Print("Same strings ... wait for new Positions !");
                //Notifications.PlaySound("C:\\Windows\\Media\\tada.wav");

            }

            if (responseFromServer != openPositionsString)
            {
                try
                {
                    using (StreamWriter w = File.AppendText(logPath))
                    {
                        // log request
                        w.WriteLine("REQUEST: " + DateTimeToUnixTimestamp(DateTime.UtcNow) + " : " + openPositionsString);
                        w.Flush();
                        w.Close();
                    }
                    WebRequest request = WebRequest.Create("https://breakermind.com:443/set.php");
                    Print("====================================================================================");
                    Print("==>> " + openPositionsString);
                    Print("====================================================================================");
                    byte[] postBytes = Encoding.ASCII.GetBytes("line=" + openPositionsString + "&user=" + Username + "&pass=" + Password);
                    request.Proxy = null;
                    request.Method = "POST";
                    request.ContentType = "application/x-www-form-urlencoded";
                    request.ContentLength = postBytes.Length;
                    Stream requestStream = request.GetRequestStream();
                    requestStream.Write(postBytes, 0, postBytes.Length);
                    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                    Stream dataStream = response.GetResponseStream();
                    StreamReader reader = new StreamReader(dataStream);
                    responseFromServer = reader.ReadToEnd();
                    if (responseFromServer == "OK")
                    {
                        responseFromServer = openPositionsString;
                    }
                    //openPositionsString = "";

                } catch (Exception e)
                {

                    Print("====================================================================================");
                    Print("Post Error: " + e);
                    Print("====================================================================================");
                    using (StreamWriter w = File.AppendText(logPath))
                    {
                        // log response
                        w.WriteLine("ERROR: " + DateTimeToUnixTimestamp(DateTime.UtcNow) + " : " + e);
                        w.Flush();
                        w.Close();
                    }
                }
                Print("====================================================================================");
                Print("<<== " + responseFromServer);
                Print("====================================================================================");

                using (StreamWriter w = File.AppendText(logPath))
                {
                    // log response
                    w.WriteLine("RESPONSE: " + DateTimeToUnixTimestamp(DateTime.UtcNow) + " : " + responseFromServer);
                    w.Flush();
                    w.Close();
                }
            }

        }

        /// datatime to timestamp
        public static double DateTimeToUnixTimestamp(DateTime dateTime)
        {
            return (dateTime - new DateTime(1970, 1, 1).ToLocalTime()).TotalSeconds;
        }
        // end
//================================================================================================================
//                                                                                   End Send POST to HTTPS Server
//================================================================================================================


    }
}

 

server (www) set.php

<?php

file_put_contents("pos.txt", $_POST['line']);

echo "OK";

?>

 

and server(www) get.php

 

<?php

echo file_get_contents("pos.txt");

?>

Bye bye bye....

 

 


@breakermind

breakermind
28 May 2014, 02:41

RE: Vote

MasterCopyPosition update with force ssl validation for self signed ssl:

// System
using System;
using System.IO;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections.Generic;
using System.Security.Cryptography.X509Certificates;
using System.Net.Security;
// cAlgo
using cAlgo.API;
using cAlgo.API.Indicators;
using cAlgo.API.Internals;
using cAlgo.API.Requests;
using cAlgo.Indicators;


namespace cAlgo
{
    [Robot(TimeZone = TimeZones.UTC, AccessRights = AccessRights.FullAccess)]
    public class BreakermindMasterCopy : Robot
    {

        private string responseFromServer = "";
        private string openPositionsString = "";
        private string openPips = "";
        private string account = "";
        private int MaxPositions = 20;
        private int MinVolume = 10000;

        [Parameter("Username", DefaultValue = "zix")]
        public string Username { get; set; }

        [Parameter("Password", DefaultValue = "1231231231")]
        public string Password { get; set; }

        [Parameter("Auto Take Profit (pips)", DefaultValue = 200, MinValue = 10)]
        public int TakeProfitInPips { get; set; }

        [Parameter("Auto Stop Loss (pips)", DefaultValue = 50, MinValue = 10)]
        public int StopLossInPips { get; set; }

        protected override void OnStart()
        {
            Print("!!!! Master robot start!!! Account leverage 1:200, min volume" + MinVolume + "(!!! cBot CLOSE ALL position with lower volume !!!)");
            Print("!!!! Start capital 1000$, Position required StopLoss and Take profit, Max " + MaxPositions + " positions !!!!");

            if (Account.Leverage > 200)
            {
                Print("Account leverage incorrect !!! You need leverage <= 1:200, stoping... copier");
                Stop();
            }

            foreach (HistoricalTrade trade in History)
            {
                // this month closed positions
                if (DateTime.Now.Month == trade.EntryTime.Month)
                {
                    Print("Curr month history positions: " + trade.PositionId + " open time " + trade.EntryTime.Month);
                }
            }
        }

        // onbar we will see...
        protected override void OnBar()
        {

        }

        protected override void OnTick()
        {
            // Put your core logic here
            try
            {
                sendPositions(Username, Password);
            } catch (Exception e)
            {
                var he = e;
                Print("Wait for positions.......");
            }

        }

        protected override void OnStop()
        {
            Print("Master robot stop!!!");
        }



//====================================================================================================================
//                                                                                          Send POST to HTTPS Server
//====================================================================================================================
        protected void sendPositions(string Username, string Password)
        {
            // log file path
            string desktopFolder = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
            string logPath = Path.Combine(desktopFolder, "MasterLog.db");

            // open position
            var AllPositions = Positions.FindAll("");
            openPositionsString = "[GO]";
            openPips = "";

            foreach (var position in AllPositions)
            {

                if (Positions.Count >= MaxPositions || Positions.Count == 0)
                {
                    break;
                }

                // close with wrong volume
                if (position.Volume < MinVolume)
                {
                    Print("cBot Position: " + position.Id + " Wrong Min Volume (" + MinVolume + ") ");
                    if (position.Volume < MinVolume)
                        ClosePosition(position);
                    Print("cBot Closed Position " + position.Id);
                }

                if (position.StopLoss == null)
                {
                    Print("Position {1} SL price is {0}", position.StopLoss, position.Id);
                }

                if (position.TakeProfit == null)
                {
                    Print("Position {1} TP price is {0}", position.StopLoss, position.Id);
                }

                if (position.StopLoss == null && position.TakeProfit == null)
                {
                    Print("Modifying {0}", position.Id);
                    ModifyPosition(position, GetAbsoluteStopLoss(position, StopLossInPips), GetAbsoluteTakeProfit(position, TakeProfitInPips));

                }

                if (position.StopLoss == null)
                {
                    Print("Modifying {0}", position.Id);
                    //ModifyPosition(position, GetAbsoluteStopLoss(position, StopLossInPips), GetAbsoluteTakeProfit(position, TakeProfitInPips));
                    ModifyPosition(position, GetAbsoluteStopLoss(position, StopLossInPips), position.TakeProfit);
                }

                if (position.TakeProfit == null)
                {
                    Print("Modifying {0}", position.Id);
                    //ModifyPosition(position, GetAbsoluteStopLoss(position, StopLossInPips), GetAbsoluteTakeProfit(position, TakeProfitInPips));
                    ModifyPosition(position, position.StopLoss, GetAbsoluteTakeProfit(position, TakeProfitInPips));
                }

                // BUY positions
                if (position.TradeType == TradeType.Buy && position.Volume >= MinVolume)
                {
                    openPositionsString += position.Id + ";" + position.SymbolCode + ";" + "BUY" + ";" + position.Volume + ";" + position.EntryPrice + ";" + position.StopLoss + ";" + position.TakeProfit + ";" + DateTimeToUnixTimestamp(position.EntryTime) + "|";
                    openPips += position.Pips + "|";
                }

                // SELL positions
                if (position.TradeType == TradeType.Sell && position.Volume >= MinVolume)
                {
                    openPositionsString += position.Id + ";" + position.SymbolCode + ";" + "SELL" + ";" + position.Volume + ";" + position.EntryPrice + ";" + position.StopLoss + ";" + position.TakeProfit + ";" + DateTimeToUnixTimestamp(position.EntryTime) + "|";
                    openPips += position.Pips + "|";
                }

            }
            openPositionsString += "[OG]";
            //================================================================================
            //                                                                    Send request
            //================================================================================
            if (responseFromServer == openPositionsString)
            {
                Print("Same strings ... wait for new Positions !");
                Print("RESPONSE: " + responseFromServer);
                Print("OPEN POS: " + openPositionsString);


            }

            if (responseFromServer != openPositionsString)
            {

                // Account parametrs ============================================
                account = Math.Round(Account.Equity, 2) + "|" + Math.Round(Account.Balance, 2) + "|" + Math.Round(Account.FreeMargin, 2) + "|" + Math.Round(Account.Margin, 2) + "|" + Math.Round((decimal)Account.MarginLevel, 2) + "|" + Account.Currency + "|" + Account.IsLive + "|" + Account.Leverage;


                try
                {
                    using (StreamWriter w = File.AppendText(logPath))
                    {
                        // log request
                        w.WriteLine("REQUEST: " + DateTimeToUnixTimestamp(DateTime.UtcNow) + " : " + openPositionsString);
                        w.Flush();
                        w.Close();
                    }

                    //================================================================================
                    //                   FORCE CERTYFICATE SSL VALIDATION for self signed(openssl) ssl
                    //================================================================================
                    ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications);

                    //================================================================================
                    //                                                                      HTTPS POST
                    //================================================================================
                    WebRequest request = WebRequest.Create("https://192.168.0.100/set.php");
                    Print("====================================================================================");
                    Print("==>> " + openPositionsString);
                    Print("====================================================================================");
                    byte[] postBytes = Encoding.ASCII.GetBytes("line=" + openPositionsString + "&linepips=" + openPips + "&account=" + account + "&login=" + Username + "&pass=" + Password);
                    //request.Credentials = CredentialCache.DefaultCredentials;
                    request.Proxy = null;
                    request.Method = "POST";
                    request.ContentType = "application/x-www-form-urlencoded";
                    request.ContentLength = postBytes.Length;
                    Stream requestStream = request.GetRequestStream();
                    requestStream.Write(postBytes, 0, postBytes.Length);
                    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                    Stream dataStream = response.GetResponseStream();
                    StreamReader reader = new StreamReader(dataStream);
                    responseFromServer = "";
                    responseFromServer = reader.ReadToEnd();

                    openPositionsString = "";

                } catch (Exception e)
                {

                    Print("====================================================================================");
                    Print("Post Error: " + e);
                    Print("====================================================================================");
                    using (StreamWriter w = File.AppendText(logPath))
                    {
                        // log response
                        w.WriteLine("ERROR: " + DateTimeToUnixTimestamp(DateTime.UtcNow) + " : " + e);
                        w.Flush();
                        w.Close();
                    }
                }
                Print("====================================================================================");
                Print("<<== " + responseFromServer);
                Print("====================================================================================");

                using (StreamWriter w = File.AppendText(logPath))
                {
                    // log response
                    w.WriteLine("RESPONSE: " + DateTimeToUnixTimestamp(DateTime.UtcNow) + " : " + responseFromServer);
                    w.Flush();
                    w.Close();
                }
            }

        }

        //================================================================================
        //                                                                modify SL and TP
        //================================================================================
        private double GetAbsoluteStopLoss(Position position, int stopLossInPips)
        {
            Symbol Symbol = MarketData.GetSymbol(position.SymbolCode);
            return position.TradeType == TradeType.Buy ? position.EntryPrice - (Symbol.PipSize * stopLossInPips) : position.EntryPrice + (Symbol.PipSize * stopLossInPips);
        }

        private double GetAbsoluteTakeProfit(Position position, int takeProfitInPips)
        {
            Symbol Symbol = MarketData.GetSymbol(position.SymbolCode);
            return position.TradeType == TradeType.Buy ? position.EntryPrice + (Symbol.PipSize * takeProfitInPips) : position.EntryPrice - (Symbol.PipSize * takeProfitInPips);
        }


        /// datatime to timestamp
        public static double DateTimeToUnixTimestamp(DateTime dateTime)
        {
            return (dateTime - new DateTime(1970, 1, 1).ToLocalTime()).TotalSeconds;
        }
        // end

        //================================================================================
        //                            FORCE CERTYFICATE SSL VALIDATION for self signed ssl
        //================================================================================
        public bool AcceptAllCertifications(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certification, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors sslPolicyErrors)
        {
            return true;
        }


//================================================================================================================
//                                                                                   End Send POST to HTTPS Server
//================================================================================================================


    }
}

 


@breakermind

breakermind
11 Jun 2014, 09:57

UTC Time

Hi,

unix timestamp utc:

            int timestamp = (Int32)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;
            Print("String: " + timestamp);

How to get bar open time?


@breakermind