Turtle Project Java - turtle-graphics

I'm working on a project where we are supposed to have a turtle that can take the commands forward, left, right, penUp, penDown, penColor and quit. When the pen is down it's supposed to draw a line between points. As the turtle moves it should leave a footprint. Left and right are supposed to change the direction in degrees. So far I can't get it to draw more points. This is the code I have so far one class main and one turtle
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Turtle t = new Turtle();
Scanner keyboard = new Scanner(System.in);
String command;
StdDraw.setPenRadius(0.05);
t.Draw();
do {
System.out.println("Enter A Command: forward, right, left, penup, pendown, pencolor, or quit");
command = keyboard.next();
if (command.equalsIgnoreCase("quit")){
break;
}
else if (command.equalsIgnoreCase("pencolor")) {
System.out.println("Enter A Color: Red, Green, Black, Yellow, Blue");
String color = keyboard.next();
t.setColor(color);
t.Draw();
}
else if (command.equalsIgnoreCase("forward")) {
System.out.println("Enter The Number of Steps You Would Like To Move");
int steps = keyboard.nextInt();
t.moveForward(steps);
t.Draw();
} else if (command.equalsIgnoreCase("right")) {
System.out.println("Enter The Number Of Degrees You Would Like To Move");
String radAngle = keyboard.next();
t.Draw();
} else if (command.equalsIgnoreCase("left")) {
System.out.println("Enter The Number Of Degrees You Would Like To Move");
String radAngle = keyboard.next();
t.Draw();
} else if (command.equalsIgnoreCase("penup")) {
t.putPenUp();
t.Draw();
} else if (command.equalsIgnoreCase("pendown")) {
t.putPenDown();
t.Draw();
}} while (!(command.equalsIgnoreCase("quit")));
}
}
public class Turtle {
private double location;
public double xCoord;
public double yCoord;
double direction;
private boolean penPosition;
public static boolean penDown = false;
public static boolean penUp = true;
private int red;
private int green;
private int blue;
private int steps;
public Turtle() {
xCoord = .5;
yCoord = .5;
penPosition = penUp;
location = 90;
}
public void Draw(){
StdDraw.setPenColor(StdDraw.BLACK);
StdDraw.point(xCoord, yCoord);
}
public void setColor(String color) {
if (color.equalsIgnoreCase("red")) {
red = 255;
green = 0;
blue = 0;
} else if (color.equalsIgnoreCase("green")) {
red = 0;
green = 255;
blue = 0;
} else if(color.equalsIgnoreCase("blue")) {
red = 0;
green = 0;
blue = 255;
} else if(color.equalsIgnoreCase("yellow")) {
red = 255;
green = 255;
blue = 0;
} else if(color.equalsIgnoreCase("black")) {
red = 0;
green = 0;
blue = 0;
} else {
red = 0;
green = 0;
blue = 0;
}
}
public void moveForward(int steps) {
double radAngle = Math.toRadians(location);
double newx = xCoord + (Math.cos(radAngle) * steps);
double newy = yCoord + (Math.sin(radAngle) * steps);
StdDraw.point(newx, newy);
StdDraw.line(xCoord, yCoord, newx, newy);
StdDraw.show();
}
public void putPenDown() {
penPosition = penDown;
if (true) {
// StdDraw.line(x, y, xCoord, yCoord);
}
} public void putPenUp() {
penPosition = penUp;
// StdDraw.line(xCoord, yCoord, newx, newy);
}
}

Your program has several problems: StdDraw thinks of the coordinate plane as going from 0.0 to 1.0 so your integer steps don't make sense unless you scale it into StdDraw coordinates -- in my example below I divide the plane into 100 steps; your moveForward() function didn't set the xCoord and yCoord variables to the new location after the move so the turtle never really went anywhere; it isn't clear why you rely on your Draw() so much as it doesn't really do much; the program exit logic was broken; the turning logic was broken and incomplete.
In my rework below, I've made some simplifications for example purposes: I've moved the main() routine into Turtle to avoid the extra file/class; I've implemented simpler colors since what you had wasn't working -- you can add back your RGB model; I've simplified the pen up/down logic to make it more practical.
import java.awt.Color;
import java.util.Scanner;
public class Turtle {
private double degAngle;
public double xCoord;
public double yCoord;
private boolean penDown;
private Color penColor;
private int steps;
public Turtle() {
xCoord = 0.5;
yCoord = 0.5;
penDown = true;
penColor = StdDraw.BLACK;
degAngle = 90;
StdDraw.setPenRadius(0.01);
}
public void Draw() {
if (penDown) {
StdDraw.setPenColor(penColor);
StdDraw.point(xCoord, yCoord);
}
}
public void setColor(String color) {
if (color.equalsIgnoreCase("red")) {
penColor = StdDraw.RED;
} else if (color.equalsIgnoreCase("green")) {
penColor = StdDraw.GREEN;
} else if (color.equalsIgnoreCase("blue")) {
penColor = StdDraw.BLUE;
} else if (color.equalsIgnoreCase("yellow")) {
penColor = StdDraw.YELLOW;
} else {
penColor = StdDraw.BLACK;
}
this.Draw(); // show new color
}
public void moveForward(int steps) {
double radAngle = Math.toRadians(degAngle);
double newx = xCoord + (Math.cos(radAngle) * steps / 100);
double newy = yCoord + (Math.sin(radAngle) * steps / 100);
if (penDown) {
StdDraw.setPenColor(penColor);
StdDraw.line(xCoord, yCoord, newx, newy);
}
xCoord = newx;
yCoord = newy;
}
public void turnRight(double angle) {
degAngle += -angle;
}
public void turnLeft(double angle) {
degAngle += angle;
}
public void putPenDown() {
penDown = true;
}
public void putPenUp() {
penDown = false;
}
public static void main(String[] args) {
Turtle t = new Turtle();
Scanner keyboard = new Scanner(System.in);
String command;
t.Draw(); // show turtle
do {
System.out.println("Enter a command: forward, right, left, penup, pendown, pencolor, or quit");
command = keyboard.next();
if (command.equalsIgnoreCase("quit")) {
break;
} else if (command.equalsIgnoreCase("pencolor")) {
System.out.println("Enter a color: red, green, black, yellow, blue");
t.setColor(keyboard.next());
} else if (command.equalsIgnoreCase("forward")) {
System.out.println("Enter the number of steps you would like to move");
t.moveForward(keyboard.nextInt());
} else if (command.equalsIgnoreCase("right")) {
System.out.println("Enter the number of degrees you would like to turn");
t.turnRight(keyboard.nextDouble());
} else if (command.equalsIgnoreCase("left")) {
System.out.println("Enter the number of degrees you would like to turn");
t.turnLeft(keyboard.nextDouble());
} else if (command.equalsIgnoreCase("penup")) {
t.putPenUp();
} else if (command.equalsIgnoreCase("pendown")) {
t.putPenDown();
}
} while (true);
System.exit(0);
}
}
USAGE
% java Turtle
Enter a command: forward, right, left, penup, pendown, pencolor, or quit
pencolor
Enter a color: red, green, black, yellow, blue
green
Enter a command: forward, right, left, penup, pendown, pencolor, or quit
forward
Enter the number of steps you would like to move
20
Enter a command: forward, right, left, penup, pendown, pencolor, or quit
left
Enter the number of degrees you would like to turn
120
Enter a command: forward, right, left, penup, pendown, pencolor, or quit
forward
Enter the number of steps you would like to move
20
Enter a command: forward, right, left, penup, pendown, pencolor, or quit
left
Enter the number of degrees you would like to turn
120
Enter a command: forward, right, left, penup, pendown, pencolor, or quit
forward
Enter the number of steps you would like to move
20
Enter a command: forward, right, left, penup, pendown, pencolor, or quit
quit
%
OUTPUT

Related

EA Opens more orders than expected in MQL4

Everything seems fine. But EA usually opens multiple trades in the same second... The way I built it is very linear and i can't seem to spot the logical mistake. It is basically a random martingale EA to test stuff out. Any indicator (that's why I called it random, haven't decided myself) can be put in there.
Basic idea is that it has an upper and lower threshold which determines when it is in buy zone and when at sell zone. Once it is in either zone, if trend goes against it (determined by indicator's value, not symbol's price) it opens another trade with the same SL/TP of the initial order. Also it checks whether initial trade still runs so it does not open other ones and once the initial trade is open. After that the criterias about the rest of the trades (that go against the trade are different).
The problem is that it opens multiple trades at times that it shouldn't, or like 3-4 trades within the same second or two. Any idea why this happens?
#property copyright "Copyright 2020, MetaQuotes Software Corp."
#property link "https://www.mql5.com"
#property version "1.00"
#property strict
input int stepValue = 5;
input double lotsize = 0.01;
input int stoploss = 2000;
input int takeprofit = 140;
input int slippage = 10;
input double upper_border = 60.0;
input double lower_border = 40.0;
const string EAComment = "Xind";
string mode = "";
bool first_trade = false;
int InitTicket = 1;
double X = 0.0;
double X_Last = 0.0;
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
//---
first_trade = false;
//---
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
//---
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
//---
SearchSignal();
if (mode == "Buy")
{
if (first_trade == false)
{
Buy();
}
if (first_trade == true)
{
MartinCheck();
CloseCheck();
}
}
if (mode == "Sell")
{
if (first_trade == false)
{
Sell();
}
if (first_trade == true)
{
MartinCheck();
CloseCheck();
}
}
}
//+------------------------------------------------------------------+
void Buy()
{
X_Last = X;
first_trade = true;
InitTicket = OrderSend(NULL,OP_BUY,lotsize,Ask,slippage,Ask-stoploss*Point,Ask+takeprofit*Point,EAComment,1,0,clrDarkBlue);
}
//---
void Sell()
{
X_Last = X;
first_trade = true;
InitTicket = OrderSend(NULL,OP_SELL,lotsize,Bid,slippage,Bid+stoploss*Point,Bid-takeprofit*Point,EAComment,1,0,clrDarkRed);
}
//---
void MartinBuy()
{
if (OrderSelect(InitTicket, SELECT_BY_TICKET) == true)
{
double new_SL = OrderStopLoss();
double new_TP = OrderTakeProfit();
int dont_care = OrderSend(NULL,OP_BUY,lotsize,Ask,slippage,new_SL,new_TP,EAComment+" martin",1,0,clrDarkBlue);
}
}
//---
void MartinSell()
{
if (OrderSelect(InitTicket, SELECT_BY_TICKET) == true)
{
double new_SL = OrderStopLoss();
double new_TP = OrderTakeProfit();
int dont_care = OrderSend(NULL,OP_SELL,lotsize,Bid,slippage,new_SL,new_TP,EAComment+" martin",1,0,clrDarkRed);
}
}
//---
void SearchSignal()
{
X = 0.0; //where 0.0, put here the iCustom for external indicators, or some built-in indicator
if (X >= upper_border)
{
mode = "Sell";
}
else if (X <= lower_border)
{
mode = "Buy";
}
else
{
mode = "";
first_trade = false;
InitTicket = 1;
X_Last = 0.0;
}
}
//---
void CloseCheck()
{
if (OrderSelect(InitTicket, SELECT_BY_TICKET))
{
if (OrderCloseTime() == 0)
{
first_trade = true;
}
else if (OrderCloseTime() != 0)
{
first_trade = false;
}
else
{
return;
}
}
}
//---
void MartinCheck()
{
if (mode == "Buy")
{
if ((X_Last - stepValue) >= X)
{
X_Last = X;
MartinBuy();
}
}
if (mode == "Sell")
{
if ((X_Last + stepValue) <= X)
{
X_Last = X;
MartinSell();
}
}
}
The layout of your code makes it possible for several processes to happen in sequence all on the same tick which I assume you do not want. Try changing your code initially to this and work from there:
void OnTick()
{
SearchSignal();
if(mode=="Buy")
{
if(!first_trade) Buy();
else
{
MartinCheck();
CloseCheck();
}
}
else if(mode=="Sell")
{
if(!first_trade) Sell();
else
{
MartinCheck();
CloseCheck();
}
}
}
Remember to use if(...) else to stop executing all functions when it should only be an either/or situation.

Why does this EA (in early development) not produce an alert, or an error?

#property strict
string subfolder = "ipc\\";
int last_read = 0;
int t = 0;
struct trade_message
{
int time; // time
string asset; // asset
string direction; // direction
double open_price; // open
double stop_price; // open
double close_price;// open
float fraction; // fraction
string comment; // comment
string status; // status
};
trade_message messages[];
int OnInit()
{
int FH = FileOpen(subfolder+"processedtime.log",FILE_BIN);
if(FH >=0)
{
last_read = FileReadInteger(FH,4);
FileClose(FH);
}
return(INIT_SUCCEEDED);
}
void OnTick()
{
int FH=FileOpen(subfolder+"data.csv",FILE_READ|FILE_CSV, ","); //open file
int p=0;
while(!FileIsEnding(FH))
{
t = StringToInteger(FileReadString(FH));
if(t<=last_read)
{
break;
}
do
{
messages[p].time = t; // time
messages[p].direction = FileReadString(FH); // direction
messages[p].open_price = StringToDouble(FileReadString(FH)); // open
messages[p].stop_price = StringToDouble(FileReadString(FH)); // stop
messages[p].close_price = StringToDouble(FileReadString(FH)); // close
messages[p].fraction = StringToDouble(FileReadString(FH)); // fraction (?float)
messages[p].comment = FileReadString(FH); // comment
messages[p].status = FileReadString(FH); // status
Alert(messages[p].comment);
}
while(!FileIsLineEnding(FH));
p++;
Alert("P = ",p,"; Array length = ", ArraySize(messages));
}
FileClose(FH);
last_read = t;
FileDelete(subfolder+"processedtime.log");
FH = FileOpen(subfolder+"processedtime.log",FILE_BIN);
FileWriteInteger(FH,t,4);
FileClose(FH);
ArrayFree(messages);
}
The code is in tick function in order to test it before taking it out to a function.
The data.csv file is:
Timestamp
Asset
Direction
Price
Stop
Profit
Fraction
Comment
Status
xxx
yyy
SHORT
13240
13240
13220
0.5
yyy SHORT 13240 - taken half at 13220 and stop to breakeven
U
xxx
yyy
SHORT
13240
13262
13040
1.0
55%
DP
The processedtime.log is not being created.
So 2 problems, both of my own making.
Not skipping the header row, simply remedied by inserting
do f = FileReadString(FH);
while(!FileIsLineEnding(FH));
after FileOpen() (easier than altering my source for data.csv), and
forgetting about the asset part of my structure, thus ensuring my structures got out of sync with my lines!! Remedied by adding messages[p].asset = FileReadString(FH); between messages[p].time = t and messages[p].direction = FileReadString(FH);

MQL4 automatic stop

My Martingale EA should be stopped automatically if the previously manually set limit has been reached or exceeded. The last trade should expire normally and not be interrupted.
So far, I've tried the following code, without interruption, etc. the code works fine.
I also heard about RemoveExpert, but I do not know how to do it. Am grateful for any help :)
enum tradeD{Buy=1, Sell=2};
input tradeD TradeType = Buy;
input double Initial_Lot = 0.01;
input double Lot_Factor = 2;
input int Max_Spread = 30;
input double Pct_SL = 0.1; // Percentage Stop Loss
input double Pct_TP = 0.1; // Percentage Take Profit
input int Magic_Number= 73726;
input int interrupt = 1,0000;
input bool StopEA = false;
int OnInit()
{
return(INIT_SUCCEEDED);
}
void OnDeinit(const int reason)
{
}
int start()
{
if (StopEA == true) { return(0); } //This line will skip the execution of EA.
}
void OnTick()
{
if(OpenOrders()==0 && (SymbolInfoInteger(Symbol(),SYMBOL_SPREAD)<Max_Spread||Max_Spread==0)){
if(TradeType==Buy){
double flot=Initial_Lot;
double etp=Ask+(Ask*(Pct_TP/100));
etp=NormalizeDouble(etp,Digits);
double esl=Ask-(Ask*(Pct_TP/100));
esl=NormalizeDouble(esl,Digits);
if (ask <= interrupt) { StopEA = true; return(0); }
if(lastProfit()<0){
flot=NormalizeDouble(lastLot()*Lot_Factor,2);
}
int snd=OrderSend(Symbol(),OP_BUY,flot,Ask,10,esl,etp,NULL,Magic_Number,0,clrAliceBlue);
}
if(TradeType==Sell){
double flot=Initial_Lot;
double etp=Bid-(Bid*(Pct_TP/100));
etp=NormalizeDouble(etp,Digits);
double esl=Bid+(Bid*(Pct_TP/100));
esl=NormalizeDouble(esl,Digits);
if (bid >= interrupt) { StopEA = true; return(0); }
if(lastProfit()<0){
flot=NormalizeDouble(lastLot()*Lot_Factor,2);
}
int snd=OrderSend(Symbol(),OP_SELL,flot,Bid,10,esl,etp,NULL,Magic_Number,0,clrAliceBlue);
}
}
//checkProfit();
}
int checkProfit(){
int total=0;
for(int i=OrdersTotal()+5; i >= 0; i--)
{
if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)){
string ordsymB = OrderSymbol();
int ordtypeB =OrderType();
int magicnB = OrderMagicNumber();
int magicn=magicnB;
double ordProfit=OrderProfit();
int tick=OrderTicket();
double oLots=OrderLots();
if(ordsymB==Symbol() && magicnB==Magic_Number){
double pctBalT=AccountBalance()*(Pct_TP/100);
double pctBalS=AccountBalance()*(Pct_SL/100);
if(ordProfit>=pctBalT){
int clo=OrderClose(tick,oLots,Close[0],10,clrAntiqueWhite);
}
if(ordProfit<0 && MathAbs(ordProfit)>=pctBalS){
int clo=OrderClose(tick,oLots,Close[0],10,clrAntiqueWhite);
}
}
}
}
return (total);
}
int OpenOrders(){
int total=0;
for(int i=OrdersTotal()+5; i >= 0; i--)
{
if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)){
string ordsymB = OrderSymbol();
int ordtypeB =OrderType();
int magicnB = OrderMagicNumber();
int magicn=magicnB;
if(ordsymB==Symbol() && magicnB==Magic_Number){
total++;
}
}
}
return (total);
}
double lastProfit(){
double total=0;
datetime lastTime=0;
for(int i=OrdersHistoryTotal(); i >= 0; i--)
{
if(OrderSelect(i,SELECT_BY_POS,MODE_HISTORY)){
string ordSym=OrderSymbol();
int ordType=OrderType();
datetime ordTime=OrderOpenTime();
double ordLot=OrderLots();
double ordOp=OrderOpenPrice();
int ordMag=OrderMagicNumber();
double ordProfit=OrderProfit();
if(ordSym==Symbol() && ordTime>lastTime && ordMag==Magic_Number){
lastTime=ordTime;
total=ordProfit;
}
}
}
return(total);
}
double lastLot(){
double total=0;
datetime lastTime=0;
for(int i=OrdersHistoryTotal(); i >= 0; i--)
{
if(OrderSelect(i,SELECT_BY_POS,MODE_HISTORY)){
string ordSym=OrderSymbol();
int ordType=OrderType();
datetime ordTime=OrderOpenTime();
double ordLot=OrderLots();
double ordOp=OrderOpenPrice();
int ordMag=OrderMagicNumber();
if(ordSym==Symbol() && ordTime>lastTime && ordMag==Magic_Number){
lastTime=ordTime;
total=ordLot;
}
}
}
return(total);
}
if(tick_counter>=ticks_to_close)
{
ExpertRemove();
Print(TimeCurrent(),": ",__FUNCTION__," expert advisor will be unloaded");
}

How to make Break even trigger more than one time in one entry

I now trying to make Break Even Code trigger more than one time,
example EA entry is 1.28000 and stop loss 1.28500
if current price reach 1.175000(50pips), sl move to break even such as to 1.28000(5pips).
EA will not make more modify order after condition are meet.
so how to trigger break even again if price reach 1.17000(100pips), sl move to (1.175000)(50 pips)
and again price reach 1.165000(150pips),sl move to 1.17000(100pips)
I want to make
BE_B_M(sl move to(example:5))
and
BE_B_T(price reach(example:50))
as variable and every time price reach target variable change to next value
so became
BE_B_M(sl move to(example:50)) and BE_B_T(price reach(example:100))
The entire code is as follows
extern double BE_T_1 = 50;
extern double BE_M_1 = 5;
extern double BE_T_2 = 100;
extern double BE_M_2 = 50;
extern double BE_T_3 = 150;
extern double BE_M_3 = 100;
double BE_S_M;
double BE_S_T;
void MOVE_BE_1()
{
for(int b=OrdersTotal()-1;b>=0;b--)
{
if(OrderSelect(b,SELECT_BY_POS,MODE_TRADES))
if(OrderMagicNumber()!=M_Number)continue;
if(OrderSymbol()==Symbol())
if(OrderType()==OP_BUY)
if(Bid-OrderOpenPrice()>BE_S_T*Pips)
if(OrderOpenPrice()>OrderStopLoss())
if(!OrderModify(OrderTicket(),OrderOpenPrice(),OrderOpenPrice()+(BE_S_M*Pips),OrderTakeProfit(),0,CLR_NONE))
Print("eror");
}
for(int s=OrdersTotal()-1;s>=0;s--)
{
if(OrderSelect(s,SELECT_BY_POS,MODE_TRADES))
if(OrderMagicNumber()!=M_Number)continue;
if(OrderSymbol()==Symbol())
if(OrderType()==OP_SELL)
if(OrderOpenPrice()-Ask>BE_S_T*Pips)
if(OrderOpenPrice()<OrderStopLoss())
if(!OrderModify(OrderTicket(),OrderOpenPrice(),OrderOpenPrice()-(BE_S_M*Pips),OrderTakeProfit(),0,CLR_NONE))
Print("eror");
}
}
i expect sl will move after price reach every 50pips from entry
Here you can put all the 3 break even levels on one function.
Note: you can use 1 for-loop for both OP_BUY and OP_SELL
Here is my OnInit()
// Global variable
double point;
int OnInit()
{
if(Digits == 5 || Digits == 3) point=Point*10;
else point=Point;
return(INIT_SUCCEEDED);
}
Here is the BreakEven() function
//+------------------------------------------------------------------+
//| Break even the trade at 3 levels |
//+------------------------------------------------------------------+
void BreakEven()
{
// get the stop level for that symbol
double stopLevel = SymbolInfoInteger(Symbol(),SYMBOL_TRADE_STOPS_LEVEL)*Point;
for(int i=OrdersTotal()-1;i>=0;i--)
{
if(!OrderSelect(i,SELECT_BY_POS,MODE_TRADES)) continue;
if(OrderMagicNumber()!=M_Number)continue;
if(OrderSymbol()!=Symbol())continue;
if(OrderType()==OP_BUY)
{
double profitPips=Bid-OrderOpenPrice();
double newSL=OrderStopLoss();
if(profitPips>=BE_T_1*point && OrderStopLoss()<OrderOpenPrice()) // Break Even
{
newSL=OrderOpenPrice()+BE_M_1*point;
}
else if(profitPips>=BE_T_3*point) // 150/100
{
newSL=OrderOpenPrice()+BE_M_3*point;
}
else if(profitPips>=BE_T_2*point) // 100/50
{
newSL=OrderOpenPrice()+BE_M_2*point;
}
if(newSL>=OrderStopLoss()+Point && newSL<Bid-stopLevel)
if(!OrderModify(OrderTicket(),OrderOpenPrice(),NormalizeDouble(newSL,Digits),OrderTakeProfit(),0))
Print("Error at BE: ",GetLastError());
}
else if(OrderType()==OP_SELL)
{
double profitPips=OrderOpenPrice()-Ask;
double newSL=OrderStopLoss();
if(profitPips>=BE_T_1*point && (OrderStopLoss()>OrderOpenPrice() || OrderStopLoss()==0)) // Break Even
{
newSL=OrderOpenPrice()-BE_M_1*point;
}
else if(profitPips>=BE_T_3*point) // 150/100
{
newSL=OrderOpenPrice()-BE_M_3*point;
}
else if(profitPips>=BE_T_2*point) // 100/50
{
newSL=OrderOpenPrice()-BE_M_2*point;
}
if(newSL<=OrderStopLoss()-Point && newSL>Ask+stopLevel)
if(!OrderModify(OrderTicket(),OrderOpenPrice(),NormalizeDouble(newSL,Digits),OrderTakeProfit(),0))
Print("Error at BE: ",GetLastError());
}
}
}
I didn't test this myself in a trade, but it should work.

Using videoGrabber with ofMesh in OpenFrameworks on iOS

First time diving into OF on iOS...exciting! As a first run I'm trying to port an app I made before into an iOS app. Its a pretty simple rutt etra-like effect on video coming in from the video camera. I have it working as a mac app, but I can't seem to get it displaying properly on my iPhone. The mesh is drawing, but I don't think I'm getting pixel values from my camera to vidPixels in order to change the color of my mesh. I'm basing this off of the videoGrabberExample in OF iOS 0072. I'm on a MacBook Pro, 10.7.5, running Xcode 4.5.2.
Can anyone give this a look and let me know if I'm doing something wrong? :) Thanks so much in advance.
Code:
testApp.mm
#include "testApp.h"
#include "ofGLUtils.h"
#include "ofGLRenderer.h"
//--------------------------------------------------------------
void testApp::setup(){
ofxiPhoneSetOrientation(OFXIPHONE_ORIENTATION_LANDSCAPE_RIGHT);
ofSetFrameRate(30);
grabber.initGrabber(480, 360);
yStep = 5;
xStep = 5;
// drawRuttEtra = false;
ofBackground(0, 0, 0);
}
//--------------------------------------------------------------
void testApp::update(){
//ofBackground(255,255,255);
grabber.update();
if(grabber.isFrameNew()){
vidPixels = grabber.getPixelsRef();
}
}
//--------------------------------------------------------------
void testApp::draw(){
glEnable(GL_DEPTH_TEST);
ofMesh mesh;
int rowCount = 0;
for (int y = 0; y<grabber.height; y+=yStep){
ofNoFill();
mesh.setMode(OF_PRIMITIVE_LINE_STRIP);
if (rowCount % 2 == 0) {
for (int x = 0; x < grabber.width; x += xStep){
ofColor curColor = vidPixels.getColor(x, y);
mesh.addColor(ofColor(curColor));
mesh.addVertex(ofVec3f(x,y, curColor.getBrightness() * 0.3));
}
} else {
for (int x = grabber.width-1; x >= 0; x -= xStep){
ofColor curColor = vidPixels.getColor(x, y);
mesh.addColor(ofColor(curColor));
mesh.addVertex(ofVec3f(x,y, curColor.getBrightness() * 0.3)); }
}
rowCount++;
}
mesh.draw();
// grabber.draw(0,0);
}
testApp.h
#pragma once
#include "ofMain.h"
#include "ofxiPhone.h"
#include "ofxiPhoneExtras.h"
class testApp : public ofxiPhoneApp{
public:
void setup();
void update();
void draw();
void exit();
void touchDown(ofTouchEventArgs & touch);
void touchMoved(ofTouchEventArgs & touch);
void touchUp(ofTouchEventArgs & touch);
void touchDoubleTap(ofTouchEventArgs & touch);
void touchCancelled(ofTouchEventArgs & touch);
void lostFocus();
void gotFocus();
void gotMemoryWarning();
void deviceOrientationChanged(int newOrientation);
ofVideoGrabber grabber;
ofTexture tex;
unsigned char * pix;
//rutt etra effect
int yStep;
int xStep;
bool drawRuttEtra;
ofPixels vidPixels;
};
main.mm
#include "ofMain.h"
#include "testApp.h"
int main(){
ofSetupOpenGL(1024,768, OF_FULLSCREEN); // <-------- setup the GL context
ofRunApp(new testApp);
}
I tried doing some debugging to see what might be happening.
I wanted to make sure ifFrameNew() works. Trying:
if(grabber.isFrameNew()){
cout<< "i'm grabbing new pixels!" << endl;
vidPixels = grabber.getPixelsRef();
}
prints "i'm grabbing new pixels!", so that if block is working.
In my double for loop, if I cout the value of vidPixels.getColor(x,y)
cout<<vidPixels.getColor(x,y) << endl;
I get all 255...which makes me think grabber.getPixelsRef() isn't working how I thought it should.
Any ideas?

Resources