Re-MQL4 code limiting number of open symbols - mql4

Thanks Daniel for your response, the code is in start(){...} as below.
I am a bit confused why it is not working.
Hope the details I have provided are enough :
int SYMBOL_NUMBER_LIMIT = 3;
int start()
{
string COUNTED_SYMBOLS[]; ArrayResize( COUNTED_SYMBOLS, SYMBOL_NUMBER_LIMIT, 0 );
for ( int s = 0; s < SYMBOL_NUMBER_LIMIT; s++ ) COUNTED_SYMBOLS[s] = "";
int SYMBOLS_IN_TRADE_SO_FAR = 0;
bool NEW_TRADE_PERMISSION = True;
int ALL_POSITIONS = OrdersTotal(); // PositionsTotal();
if ( ALL_POSITIONS > 0 )
{
for ( int index = 0; index < ALL_POSITIONS; index++ )
{
string THIS_SYMBOL = OrderSymbol(); // PositionGetSymbol( index );
bool Symbol_already_counted = False;
for ( int i = 0; i < SYMBOL_NUMBER_LIMIT; i++ )
{
if ( COUNTED_SYMBOLS[i] == THIS_SYMBOL )
{
Symbol_already_counted = True;
break;
}
if ( Symbol_already_counted ) continue;
else
{
SYMBOLS_IN_TRADE_SO_FAR++;
// if ( SYMBOLS_IN_TRADE_SO_FAR >= SYMBOL_NUMBER_LIMIT )
if ( SYMBOLS_IN_TRADE_SO_FAR == SYMBOL_NUMBER_LIMIT )
{
NEW_TRADE_PERMISSION = False;
break;
}
for ( int j = 0; j < SYMBOL_NUMBER_LIMIT; j++ )
if ( COUNTED_SYMBOLS[j] == "" )
{
COUNTED_SYMBOLS[j] = THIS_SYMBOL;
break;
}
}
}
}
}

input int SYMBOL_NUMBER_LIMIT;
int start(){
// some logic
int direction; string symbol;//these parameters to initialize to send a new trade
// some function to get a new direction and symbol
if(direction!=0 && symbol!=NULL){
bool allowSendNewTrade=isNewTradeAllowed(symbol);
if(allowSendNewTrade)OrderSend(symbol,lot,direction>0?OP_BUY:OP_SELL,0,0,0);
}
return(0);
}
bool isNewTradeAllowed(string symbolInQuestion){
string symbols[];
int SYMBOLS_IN_TRADE_SO_FAR=0;
ArrayResize(symbols,OrdersTotal());
for(int i=OrdersTotal()-1;i>=0;i--){
if(!OrderSelect(i,SELECT_BY_POS))continue;
string currentSymbol=OrderSymbol();
boolean symbolAlreadyInList=false;
for(int j=SYMBOLS_IN_TRADE_SO_FAR-1;j>=0;j--){
if(symbols[j]==currentSymbol){
symbolAlreadyInList=true;
break;
}
}
if(!symbolAlreadyInList)
symbols[SYMBOLS_IN_TRADE_SO_FAR++]=currentSymbol;
}
if(SYMBOLS_IN_TRADE_SO_FAR>SYMBOL_NUMBER_LIMIT)
return false;
if(SYMBOLS_IN_TRADE_SO_FAR==SYMBOL_NUMBER_LIMIT){
for(int j=SYMBOLS_IN_TRADE_SO_FAR-1;j>=0;j--){
if(symbols[SYMBOLS_IN_TRADE_SO_FAR]==symbolInQuestion)
return true;
}
return false;
}
return true; //SYMBOLS_IN_TRADE_SO_FAR<SYMBOL_NUMBER_LIMIT
}

Your code was missing the {...}-code-block syntax closing-bracket.
int SYMBOL_NUMBER_LIMIT = 3;
int start()
{
string COUNTED_SYMBOLS[]; ArrayResize( COUNTED_SYMBOLS, SYMBOL_NUMBER_LIMIT, 0 );
for ( int s = 0; s < SYMBOL_NUMBER_LIMIT; s++ ) COUNTED_SYMBOLS[s] = "";
int SYMBOLS_IN_TRADE_SO_FAR = 0;
bool NEW_TRADE_PERMISSION = True;
int ALL_POSITIONS = OrdersTotal(); // PositionsTotal();
if ( ALL_POSITIONS > 0 )
{
for ( int index = 0; index < ALL_POSITIONS; index++ )
{
string THIS_SYMBOL = OrderSymbol(); // PositionGetSymbol( index );
bool Symbol_already_counted = False;
for ( int i = 0; i < SYMBOL_NUMBER_LIMIT; i++ )
{
if ( COUNTED_SYMBOLS[i] == THIS_SYMBOL )
{
Symbol_already_counted = True;
break;
}
if ( Symbol_already_counted ) continue;
else
{
SYMBOLS_IN_TRADE_SO_FAR++;
// if ( SYMBOLS_IN_TRADE_SO_FAR >= SYMBOL_NUMBER_LIMIT )
if ( SYMBOLS_IN_TRADE_SO_FAR == SYMBOL_NUMBER_LIMIT )
{
NEW_TRADE_PERMISSION = False;
break;
}
for ( int j = 0; j < SYMBOL_NUMBER_LIMIT; j++ )
if ( COUNTED_SYMBOLS[j] == "" )
{
COUNTED_SYMBOLS[j] = THIS_SYMBOL;
break;
}
}
}
}
}
} // <-------------------------------------THIS ONE WAS MISSING, COMPILER WAS NOT HAPPY

Related

EA - Multi Currency Multi TimeFrame

I have a problem when I'm trying to find a way to check if a trade was made on the current bar or not to stop the EA for making multiple entries on the same bar.
When I don't do a multi Currency EA I usually just use
static datetime lastTradeBar;
and
if(lastTradeBar!=Time[0])
{
if(PFTP_BuySignal > 0 && PFTP_BuySignal_Prev == 0 && PFTP_Rate > PFTP_Rate_Value)
{
myTP = PFTP_TP1;
mySL = PFTP_BuySL;
return (1);
}
if(PFTP_SellSignal > 0 && PFTP_SellSignal_Prev == 0 && PFTP_Rate > PFTP_Rate_Value)
{
myTP = PFTP_TP1;
mySL = PFTP_SellSL;
return (-1);
}
else
return (0);
lastTradeBar=Time[0];
};
return (0);
}
but this doesn't work when using it as I do now.
I'm thinking I need to make a myArray[sym,period,lastTradeBar] or myArray [sym][period][lastTradeBar]
but I can't wrap my head around how or where to put it.
this is the flow
int OnInit() ->
void OnTimer() ->
void LoopThruSym(stringlistOfSym) ->
void LoopThruPeriod(string sym, string listOfPeriods, int listOfSym) ->
void Trade(string sym, int period) ->
int Signal(string sym, int period)
This is how the flow is now.
int OnInit()
{
EventSetTimer(5);
return(INIT_SUCCEEDED);
}
....
void OnTimer()
{
LoopThruSym(symbols);
}
....
void LoopThruSym(string listOfSym)
{
if(Mode == All)
{
int i;
int numSymbolmarketWatch=SymbolsTotal(false);
numSymbols=numSymbolmarketWatch;
ArrayResize(symbolListFinal,numSymbolmarketWatch);
for(i=0; i<numSymbolmarketWatch; i++)
{
symbolListFinal[i]=SymbolName(i,false);
}
}
else
if(Mode == Selected)
{
string sep=",";
ushort u_sep;
int i;
u_sep=StringGetCharacter(sep,0);
StringSplit(listOfSym,u_sep,symbolList);
numSymbols=ArraySize(symbolList);
ArrayResize(symbolListFinal,numSymbols);
for(i=0; i<numSymbols; i++)
{
symbolListFinal[i]=symbolPrefix+symbolList[i]+symbolSuffix;
LoopThruPeriod(symbolListFinal[i],periods, numSymbols);
}
}
else
if(Mode == Current)
{
LoopThruPeriod(Symbol(),periods,numSymbols);
}
return;
}
....
void LoopThruPeriod(string sym, string listOfPeriods, int listOfSym)
{
if(ModePeriod == All_Period)
{
string periodsALL = "1,5,15,30,60,240,1440,10080,43200";
string sep=",";
ushort u_sep;
int i;
int lastTradeBarArrayCount;
u_sep=StringGetCharacter(sep,0);
StringSplit(periodsALL,u_sep,periodList);
numPeriods=ArraySize(periodList);
ArrayResize(periodListFinal,numPeriods);
lastTradeBarArrayCount = listOfSym+numPeriods;
ArrayResize(lastTradeBarArray,lastTradeBarArrayCount);
for(i=0; i<numPeriods; i++)
{
periodListFinal[i]=symbolPrefix+periodList[i]+symbolSuffix;
Trade(sym,StrToInteger(periodListFinal[i]));
Comment("lastTradeBarArrayCount = "+lastTradeBarArrayCount);
}
}
else
if(ModePeriod == Selected_Period)
{
string sep=",";
ushort u_sep;
int i;
int lastTradeBarArrayCount;
u_sep=StringGetCharacter(sep,0);
StringSplit(listOfPeriods,u_sep,periodList);
numPeriods=ArraySize(periodList);
ArrayResize(periodListFinal,numPeriods);
lastTradeBarArrayCount = listOfSym*numPeriods;
ArrayResize(lastTradeBarArray,lastTradeBarArrayCount);
for(i=0; i<numPeriods; i++)
{
periodListFinal[i]=symbolPrefix+periodList[i]+symbolSuffix;
Trade(sym,StrToInteger(periodListFinal[i]));
Comment("lastTradeBarArrayCount = "+lastTradeBarArrayCount);
}
}
if(ModePeriod == Current_Period)
{
Trade(sym,Period());
}
}
...
void Trade(string sym, int period)
{
//Print("Symbole = " + sym + " : " + period);
if(OrderMethod == BuyandSell)
{
if(Signal(sym,period) == 1 && CheckMoneyForTrade(sym,Lots,OP_BUY) && CheckVolumeValue(sym,Lots))
LimitBuy(sym,period);
else
if(Signal(sym,period) == -1 && CheckMoneyForTrade(sym,Lots,OP_SELL) && CheckVolumeValue(sym,Lots))
LimitSell(sym,period);
}
else
if(OrderMethod == BuyOnly)
{
if(Signal(sym,period) == 1 && CheckMoneyForTrade(sym,Lots,OP_BUY) && CheckVolumeValue(sym,Lots))
LimitBuy(sym,period);
}
else
if(OrderMethod == SellOnly)
{
if(Signal(sym,period) == -1 && CheckMoneyForTrade(sym,Lots,OP_SELL) && CheckVolumeValue(sym,Lots))
LimitSell(sym,period);
}
//Trail(sym);
return;
}
...
int Signal(string sym, int period)
{
if(lastTradeBar!=Time[0])
{
if(PFTP_BuySignal > 0 && PFTP_BuySignal_Prev == 0 && PFTP_Rate > PFTP_Rate_Value)
{
myTP = PFTP_TP1;
mySL = PFTP_BuySL;
return (1);
}
if(PFTP_SellSignal > 0 && PFTP_SellSignal_Prev == 0 && PFTP_Rate > PFTP_Rate_Value)
{
myTP = PFTP_TP1;
mySL = PFTP_SellSL;
return (-1);
}
else
return (0);
lastTradeBar=Time[0];
};
return (0);
}
Code a function on the "void OnTick()" like this:
void OnTick()
{
//---
CheckForSignal();
}
And then code the function "CheckForSignal()"
//+------------------------------------------------------------------+
//| Function "CheckForSignal()" |
//+------------------------------------------------------------------+
void CheckForSignal(){
//check here a bar until a Signal given Signal given then initialize it to Time[]
static datetime candletime=0;
if(candletime!=Time[0]){
double upArrow=iCustom(your Custom indicator or whatever parameters);
if(upArrow != EMPTY_VALUE){
EnterTrade(OP_BUY);
}
double downArrow=iCustom(your Custom indicator or whatever parameters);
if(downArrow != EMPTY_VALUE){
EnterTrade(OP_SELL);
}
// if we have a Signal we will initialize candle time to Time[0] to avoid multiple Orders
candletime=Time[0];
}
}
//+------------------------------------------------------------------+
Then Send Signal to Open or Close or whatever you need in my example we will open Trades
//+------------------------------------------------------------------+
//| Function "EnterTrade()" |
//+------------------------------------------------------------------+
void EnterTrade(int type){
int err=0;
double price=0;
double sl=0;
double tp=0;
if(type == OP_BUY){
price=Ask;
}else{
price=Bid;
}
//steppoin8-step15: replace function "OrderSend" parameter
// ->variablename "name" (magic)
//steppoint8-step16: end ";"
int ticket=OrderSend(Symbol(),type,LotSize,price,slippage,0,0,"EA Trade",magic,0,clrMagenta);
if(ticket>0){
if(OrderSelect(ticket,SELECT_BY_TICKET)){
if(OrderType()==OP_BUY){
sl=OrderOpenPrice()-(stopLoss*pips);
tp=OrderOpenPrice()+(takeProfit*pips);
}else if(OrderType()==OP_SELL){
sl= OrderOpenPrice()+(stopLoss*pips);
tp= OrderOpenPrice()-(takeProfit*pips);
}
if(!OrderModify(ticket,price,sl,tp,0,clrMagenta)){
err=GetLastError();
Print("Encountered an error during modification!"+(string)err+" "+ErrorDescription(err));
}
}else{
Print("Failed to Select Order",ticket);
err=GetLastError();
Print("Encountered an error while selecting order"+(string)ticket+" error number"+(string)err+" "+ErrorDescription(err));
}
}
else{
err=GetLastError();
Print("Encountered an error during order placement"+(string)err+" "+ErrorDescription(err));
}
}
//+------------------------------------------------------------------+
This is not an answer more of like progress.
So what i'm doing not instead of checking for candletime=Time[0] I check then the last trade close time is for that sym/magic nr and comment. and then runing it thru if(iBarShift(sym,period,OrderCloseTime()) > 1)
this kinda works but I'm getting problems down the road if I'm trying to use symbols with different miniLots. But that will come on another post.
bool getLastOrderClose(string sym, int period)
{
if(OrdersHistoryTotal() == 0)
return true;
string comment = "Multi Currency "+sym+":"+IntegerToString(period);
int count = 0;
int tradesPerSymbole =0;
for(int i=OrdersHistoryTotal()-1; i >= 0; i--)
if(OrderSelect(i, SELECT_BY_POS, MODE_HISTORY))
{
if(OrderSymbol() == sym)
{
if(OrderMagicNumber() == Magic)
{
tradesPerSymbole++;
if(StringFind(comment,OrderComment())<0)
{
if(iBarShift(sym,period,OrderCloseTime()) > 1)
{
return true;
}
}
}
}
}
else
{
Print(sym +" : "+"OrderSend() - getLastOrderClose - error - ", ErrorDescription(GetLastError()));
}
if(tradesPerSymbole == 0)
return true;
return false;
};
//OrderSend('EURUSD',blablabla Parameter)
//OrderSend('GBPUSD',blablabla Parameter)
//OrderSend('USDJPY',blablabla Parameter)
//OrderSend('EURCHF',blablabla Parameter)
int ticket=OrderSend('EURUSD',type,LotSize,price,slippage,0,0,"EA Trade",magic,0,clrMagenta);
for(int I=ticket;ticket<Orderstotal();i++){
if(OrderSelect(ticket,SELECT_BY_TICKET)){
if(OrderType()==OP_BUY){
sl=OrderOpenPrice()-(stopLoss*pips);
tp=OrderOpenPrice()+(takeProfit*pips);
}else if(OrderType()==OP_SELL){
sl= OrderOpenPrice()+(stopLoss*pips);
tp= OrderOpenPrice()-(takeProfit*pips);
}
if(!OrderModify(ticket,price,sl,tp,0,clrMagenta)){
err=GetLastError();
Print("Encountered an error during modification!"+(string)err+" "+ErrorDescription(err));
}
}else{
Print("Failed to Select Order",ticket);
err=GetLastError();
Print("Encountered an error while selecting order"+(string)ticket+" error number"+(string)err+" "+ErrorDescription(err));
}
}
else{
err=GetLastError();
Print("Encountered an error during order placement"+(string)err+" "+ErrorDescription(err));
}
}
//+------------------------------------------------------------------+
I think its not the pro solution but I would declare a Ordersend function for all the pairs where u want to open the order (I need not to say that the order send function should be declared in a conditional so only the the real ordersend be placed)
but the part where I want your attention is you can do it the hardware by declaring the Ordersend(not with Symbol() instead of that with "YourPairname");
hope this help you a little bit to reach your goal gl

Getting Illegal Instruction:4

I was trying to do this function in C but for some reason is giving me "Illegal instruction: 4"... From what I looked up it may be because I'm using iOs, but still I'm using VSCode and not a project so I have no idea how to correct it.
The function is the following:
void divideSocios(void){
int i;
for (i = 0; i < MAXFILA || socios[i].next != -1; i++){
if (socios[i].sc.pago >= 50){
if (semDiv[0].next == 0){
semDiv[0].next = -1;
semDiv[0].sc.id = socios[i].sc.id;
semDiv[0].sc.pago = socios[i].sc.pago;
strcpy(semDiv[0].sc.nome, socios[i].sc.nome);
}
else{
for (; i < MAXFILA && semDiv[i].next != -1; i++);
semDiv[i-1].next = i;
semDiv[i].next = -1;
semDiv[i].sc.pago = socios[i].sc.pago;
semDiv[i].sc.id = socios[i].sc.id;
strcpy(semDiv[i].sc.nome, socios[i].sc.nome);
}
} else {
if (comDiv[0].next == 0){
comDiv[0].next = -1;
comDiv[0].sc.id = socios[i].sc.id;
comDiv[0].sc.pago = socios[i].sc.pago;
strcpy(comDiv[0].sc.nome, socios[i].sc.nome);
}
else{
for (; i < MAXFILA && comDiv[i].next != -1; i++);
comDiv[i-1].next = i;
comDiv[i].next = -1;
comDiv[i].sc.pago = socios[i].sc.pago;
comDiv[i].sc.id = socios[i].sc.id;
strcpy(comDiv[i].sc.nome, socios[i].sc.nome);
}
}
}
}
I basically have 3 different linked lists by matrix, each node with a struct and the index of the current node, and depending on the "pago" atribute from the struct of the node I want to separate them from the original list between the other 2.

Spoj brackets segment tree

can anyone help me in my code. I am getting WA and m not able to rectify it plzzz
my code http://ideone.com/DkrwIg
problem link : http://www.spoj.com/problems/BRCKTS/
i am a bit doubtful in my modification function.
#include<iostream>
#include<cstdio>
#include<cstdlib>
using namespace std;
char str[40010];
struct node
{
int sum;
int minsum;
}tree[1000005];
void build(int id,int l,int r)
{
if(r-l<2)
{
if(str[l] == '(')
{
tree[id].sum = 1;
tree[id].minsum = 1;
}
else
{
tree[id].sum = -1;
tree[id].minsum = -1;
}
return;
}
int mid = (r+l)/2;
build(id*2,l,mid);
build(id*2+1,mid,r);
tree[id].sum = tree[id*2].sum + tree[id*2+1].sum;
tree[id].minsum = min(tree[id*2].minsum,tree[id*2].minsum+tree[id*2+1].minsum);
}
void modify(int index,int id,int l,int r)
{
if(r-l<2)
{
tree[id].sum = tree[id].minsum = -tree[id].sum;
return;
}
int mid = (r+l)/2;
if(index<mid)
modify(index,id*2,l,mid);
else
modify(index,id*2+1,mid,r);
tree[id].sum = tree[id*2].sum + tree[id*2+1].sum;
tree[id].minsum = min(tree[id*2].minsum,tree[id*2].minsum+tree[id*2+1].minsum);
}
int main()
{
int n,k;
int val;
int h = 1;
for(int h=1;h<=10;h++)
{
scanf("%d",&n);
scanf("%s",str);
build(1,0,n);
//cout<<"Test "<<h<<" :"<<endl;
printf("Test %d:\n",h);
//cin>>k;
scanf("%d",&k);
while(k--)
{
cin>>val;
if(!val)
{
if(tree[1].sum == 0 && tree[1].minsum == 0)
{
//cout<<"YES"<<endl;
printf("YES\n");
}
else
{
//cout<<"NO"<<endl;
printf("NO\n");
}
//cout<<tree[1].sum<<"------------"<<tree[1].minsum<<endl;
}
else
{
modify(val-1,1,0,n);
}
}
}
return 0;
}

How to allow trackwheel to scroll all direction?

Here is my navigationMovement():
protected boolean navigationMovement(int dx, int dy, int status, int time) {
int focusIndex = getFieldWithFocusIndex();
while (dy > 0) {
if (focusIndex >= getFieldCount()) {
return false;
} else {
Field f = getField(focusIndex);
if (f.isFocusable()) {
f.setFocus();
dy--;
}
}
}
while (dy < 0) {
if (focusIndex < 0) {
return false;
} else {
Field f = getField(focusIndex);
if (f.isFocusable()) {
f.setFocus();
dy++;
}
}
}
while (dx > 0) {
focusIndex++;
if (focusIndex >= getFieldCount()) {
return false;
} else {
Field f = getField(focusIndex);
if (f.isFocusable()) {
f.setFocus();
dx--;
}
}
}
while (dx < 0) {
focusIndex--;
if (focusIndex < 0) {
return false;
} else {
Field f = getField(focusIndex);
if (f.isFocusable()) {
f.setFocus();
dx++;
}
}
}
return true;
}
This only allows the track wheel to scroll left and right, but I want up, down, left and right.
my layout is this.
It is a 3 rows x 4 columns.
This code is checking getField(0->10), that's why it cannot from 0 to 4.
I want it to be movable in all directions. How to implement that?
Updated
protected void sublayout(int width, int height) {
int y = 0;
Field[] fields = new Field[columnWidths.length];
int currentColumn = 0;
int rowHeight = 0;
for (int i = 0; i < getFieldCount(); i++) {
fields[currentColumn] = getField(i);
fields[currentColumn]
.setChangeListener(new FieldChangeListener() {
public void fieldChanged(Field field, int context) {
final int focusIndex = getFieldWithFocusIndex();
if (focusIndex == position) {
Main.getUiApplication().popScreen(
mainscreen);
} else {
Main.getUiApplication().popScreen(
mainscreen);
Main.getUiApplication().pushScreen(
new Custom_LoadingScreen(1));
Main.getUiApplication().invokeLater(
new Runnable() {
public void run() {
if (focusIndex == 0)
Main.getUiApplication()
.pushScreen(
new Main_AllLatestNews());
else
Main.getUiApplication()
.pushScreen(
new Main_ParticularCategoryAllNews(
catnewsid[focusIndex],
focusIndex,
cattitle[focusIndex]));
}
}, 1 * 1000, false);
}
}
});
layoutChild(fields[currentColumn], columnWidths[currentColumn],
height - y);
if (fields[currentColumn].getHeight() > rowHeight) {
rowHeight = fields[currentColumn].getHeight() + 10;
}
currentColumn++;
if ((currentColumn == columnWidths.length)
|| (i == (getFieldCount() - 1))) {
int x = 0;
if (this.allRowHeight >= 0) {
rowHeight = this.allRowHeight;
}
for (int c = 0; c < currentColumn; c++) {
long fieldStyle = fields[c].getStyle();
int fieldXOffset = 0;
long fieldHalign = fieldStyle & Field.FIELD_HALIGN_MASK;
if (fieldHalign == Field.FIELD_RIGHT) {
fieldXOffset = columnWidths[c]
- fields[c].getWidth();
} else if (fieldHalign == Field.FIELD_HCENTER) {
fieldXOffset = (columnWidths[c] - fields[c]
.getWidth()) / 2;
}
int fieldYOffset = 0;
long fieldValign = fieldStyle & Field.FIELD_VALIGN_MASK;
if (fieldValign == Field.FIELD_BOTTOM) {
fieldYOffset = rowHeight - fields[c].getHeight();
} else if (fieldValign == Field.FIELD_VCENTER) {
fieldYOffset = (rowHeight - fields[c].getHeight()) / 2;
}
setPositionChild(fields[c], x + fieldXOffset, y
+ fieldYOffset);
x += columnWidths[c];
}
currentColumn = 0;
y += rowHeight;
}
if (y >= height) {
break;
}
}
int totalWidth = 0;
for (int i = 0; i < columnWidths.length; i++) {
totalWidth += columnWidths[i];
}
if (position > -1) {
Field f = getField(position);
f.setFocus();
}
setExtent(totalWidth, Math.min(y, height));
}
}
The issue with your code that you treat dx and dy in the same way. You need to calculate next previous index differently depends on if it's horizontal scroll or vertical.
Btw, what manager do you use? FlowFieldManager? Because I think it's should work as expected in default navigationMovement implementation.
navigationMovement default will provide focus on all focusable components.
It only matters what layout you have used & how did you arrange these managers. You have row, column wise structure, so if you used horizonal manager for a row, it's elements will get focus & after completing all elements, focus will be down to the second horizontal manager.
I just find the solution which is each move +/- column size
while (dy > 0) {
if (focusIndex + columnwidth.length >= getFieldCount()) {
return false;
} else {
Field f = getField(focusIndex + columnwidth.length);
if (f.isFocusable()) {
f.setFocus();
dy--;
}
}
}
while (dy < 0) {
if (focusIndex - columnwidth.length < 0) {
return false;
} else {
Field f = getField(focusIndex - columnwidth.length);
if (f.isFocusable()) {
f.setFocus();
dy++;
}
}
}

make analog clock for blackberry

I want to make an Analog Clock In blackberry, and I want the hands of the clock to be custom images.
I gone through this thread Help with analog clock code but didnt get it worked. Can any body help me to make an analog clock
Update
The code i am getting is from the supports forum
// How to use it
ClockBitmapField clock = new ClockBitmapField(face, Field.NON_FOCUSABLE | Field.FIELD_HCENTER,
hrPng, minPng, secPng);
I can i use this to make an analog clock
How Can i use this
add(clock);
// Clock Face
class ClockBitmapField extends BitmapField {
Bitmap _face = null;
UpdateClockThread _updateClockThread = null;
Bitmap [] _hourBitmaps = null;
Bitmap [] _minBitmaps = null;
Bitmap [] _secBitmaps = null;
public ClockBitmapField(Bitmap face, long style, String [] hourPngs, String [] minPngs, String [] secPngs) {
super(face, style);
_face = face;
_ourBitmap = new Bitmap(_face.getWidth(), _face.getHeight());
this.setBitmap(_ourBitmap); // Swap to using work area
_hourBitmaps = new Bitmap [hourPngs.length];
for ( int i = 0; i < hourPngs.length; i++ ) {
_hourBitmaps[i] = Bitmap.getBitmapResource(hourPngs[i]);
}
_minBitmaps = new Bitmap [minPngs.length];
for ( int i = 0; i < minPngs.length; i++ ) {
_minBitmaps[i] = Bitmap.getBitmapResource(minPngs[i]);
}
_secBitmaps = new Bitmap [secPngs.length];
for ( int i = 0; i < secPngs.length; i++ ) {
_secBitmaps[i] = Bitmap.getBitmapResource(secPngs[i]);
}
}
protected void onDisplay() {
onExposed();
}
protected void onUnDisplay() {
onObscured();
}
protected void onExposed() {
if ( _updateClockThread == null || !_updateClockThread.isAlive() ) {
_updateClockThread = new UpdateClockThread(_ourBitmap, _face, this, _hourBitmaps, _minBitmaps, _secBitmaps);
_updateClockThread.start();
}
}
protected void onObscured() {
if ( _updateClockThread != null ) {
_updateClockThread.stop();
_updateClockThread = null;
}
}
public void invalidate() {
super.invalidate();
}
class UpdateClockThread extends Thread {
private Calendar _cal = null;
int _curHr = 0;
int _curMin = 0;
int _curSec = 0;
Bitmap _face = null;
int _faceWidth = 0;
int _faceHeight = 0;
_ourBitmap = null;
Graphics _g = null;
ClockBitmapField _ourField = null;
long LONG_ONE_THOUSAND = 1000;
boolean _stopped = false;
Bitmap [] _hourBitmaps = null;
Bitmap [] _minBitmaps = null;
Bitmap [] _secBitmaps = null;
public UpdateClockThread(Bitmap ourBitmap, Bitmap face, ClockBitmapField fieldToInvalidate,
Bitmap [] hourBitmaps, Bitmap [] minBitmaps, Bitmap [] secBitmaps) {
super();
_cal = Calendar.getInstance();
_face = face;
_faceWidth = _face.getWidth();
_faceHeight = _face.getHeight();
_ourBitmap = ourBitmap;
_g = new Graphics(_ourBitmap);
_ourField = fieldToInvalidate;
}
public void run() {
long timeToSleep = 0;
while (!_stopped) {
_g.setBackgroundColor(0x00191919);
_g.clear();
_g.drawBitmap(0, 0, _faceWidth, _faceHeight, _face, 0, 0);
_cal.setTime(new Date(System.currentTimeMillis()));
_curHr = cal.get(Calendar.HOUR);
_curMin = cal.get(Calendar.MINUTE);
_curHr = (_curHr * 5) + (5 * _curMin / 60);
if (_curHr > 60) _curHr = _curHr - 60;
_curSec = cal.get(Calendar.SECOND);
_g.drawBitmap(0, 0, _faceWidth, _faceHeight, _secBitmaps[_curSec], 0, 0);
_g.drawBitmap(0, 0, _faceWidth, _faceHeight, _minBitmaps[_curMin], 0, 0);
_g.drawBitmap(0, 0, _faceWidth, _faceHeight, _hourBitmaps[_curHr], 0, 0);
_ourField.invalidate();
timeToSleep = LONG_ONE_THOUSAND - ( System.currentTimeMillis() % LONG_ONE_THOUSAND );
if ( timeToSleep > 20 ) {
try {
Thread.sleep(timeToSleep);
} catch (Exception e) {
}
}
}
}
public void stop() {
_stopped = true;
}
}
}
and make minutes as second
thanks and regards
Just by looking at the code, it appears that the inputs:
String [] hourPngs, String [] minPngs, String [] secPngs are each a list of filenames of images which represent the clock hands at each position.
In this snippet, he builds an array of 60 Bitmaps from the strings:
_secBitmaps = new Bitmap [secPngs.length];
for ( int i = 0; i < secPngs.length; i++ ) {
_secBitmaps[i] = Bitmap.getBitmapResource(secPngs[i]);
}
Then, in this snippet you can see he gets the Bitmap object from a array by passing in the current "second" as the index:
_g.drawBitmap(0, 0, _faceWidth, _faceHeight, _secBitmaps[_curSec], 0, 0);
There doesn't appear to be any code where he rotates the images or anything.
So I guess that means you need 60 images for each clock hand. (180 images in total, plus the clock face).

Resources