I've got an indicator that signals an action by sound and alert:
PlaySound("news.wav");
Alert(Symbol()," make an action");
I wanted to add there the OrderSend function to auto buy-sell and it looks this way:
int ticket;
PlaySound("news.wav");
Alert(Symbol()," make an action");
ticket=OrderSend(Symbol(),OP_SELL,1.0,Bid,2,Bid+7*Point,Bid-7*Point,"Sell",0,0, Red);
When the time comes, there is the signal, there is the alert but there are no orders.
It is said that Trading functions can be used in experts and scripts in documentation: Trading Functions
but it has to be done in some way.
How can it be done?
You don't have permission to do trading in custom indicators, read below article.
http://docs.mql4.com/runtime/tradepermission
I think the easy way is to convert your custom indicator into an Expert Adviser. It won't take much time if you have the experience in MQL4 coding.
You can't trade in an indicator. There is a quick dirty way to do this. You can set a GlobalVariable from the indicator and then have a separate EA that constantly monitors the global. When the global variable is set the EA can make the trade and then reset the variable value.
Use GlobalVariableSet() in the indicator and GlobalVariableGet() in the EA.
Related
I am registering to receive updates from a CMMotionManager like so:
motionManager.startDeviceMotionUpdatesToQueue(deviceMotionQueue) {
[unowned self] (deviceMotion, error) -> Void in
// ... handle data ...
}
where deviceMotionQueue is an NSOperationQueue with the highest quality of service, i.e. the highest possible update rate:
self.deviceMotionQueue.qualityOfService = NSQualityOfService.UserInteractive
This means that I am getting updates often. Like really often. So I was wondering: what happens if I don't handle one update fast enough? If the update interval is shorter than the execution time of 'handle data'? Will the motion manager drop some information? Or will it queue up and after a while become run out of memory? Or is this not feasable at all?
It's hard to know what the internal CoreMotion implementation will do, and given that what it does is an "implementation detail", even if you could discern its current behavior, you wouldn't want to rely on that behavior moving forward.
I think the common solution to this is to do the minimum amount of work in the motion update handler, and then manage the work/rate-limiting/etc yourself. So, for instance, if you wanted to drop interstitial updates that arrived while you were processing the last update, you could have the update handler that you pass into CoreMotion do nothing but (safely) add a copy of deviceMotion to a mutable array, and then enqueue the "real" handler on a different queue. The real handler might then have a decision tree like:
if the array is empty, return immediately
otherwise (safely) take the last element, clear all elements from the array, and do the work based on the last element
This would have the effect of letting you take only the most recent reading, but also to have knowledge of how many updates were missed, and, if it's useful, what those missed updates were. Depending on your app, it might be useful to batch process the missed events as a group.
But the takeaway is this: if you want to be sure about how a system like this behaves, you have to manage it yourself.
I am a new learner of iOS and I am reading "iOS Programming 4th Edition-Big Nerd Ranch",there is a question while I am reading the 7th chapter.
it says
A button’s life is relatively simple. For objects with more complex lives, like a text field, Apple uses the delegation pattern. You introduce the text field to one of your objects: “This is your delegate, when anything interesting happens in your life, send a message to him.” The text field keeps a pointer to its delegate. Many of the message it sends to its delegates are informative: “OK, I am done editing!”.
It makes me confused,because at first,it means that the text field can be introduced to one of my objects as a delegate of them,but finally it says " the text field keeps a pointer to its delegate ". Isn't the text field itself a delegate of others,is it? So I don't understand who is whose delegate ? Does it mean that the text field can be delegate of others,but it can also have delegate of itself? or else?
Thanks in advance!
Your object is the delegate. The text field will be sending the messages to it.
Understand what delegate means: It's your delegate -- acting on behalf of your program logic, and interacting with the UI object to tell it what you want done. In a sense ambassador would be a better title, since it's representing you in some "remote" location.
Just as there might be a US ambassador to Thailand, your program might have an ambassador to the UITextField object. When you create the UITextField you tell it what object is it's ambassador/delegate and then the UITextField talks to that object when it needs to know what you want to do.
Many of Apple's framework objects take a delegate. A delegate is a pointer to some anonymous object that you know very little about. All you know about it is that it understands a certain set of calls (a protocol). It's like a private lingo.
The idea is that the system object sends information to the delegate to either tell it about what has happened (the user selected the picker item at index 4) or ask it about how it should behave (The user wants to scroll to the left. Should I allow it?)
By using the delegate design pattern, you can build general-purpose objects that can be used in a wide variety of situations, by a wide variety of different objects.
When you read delegate, think "customer". A system object is a shopkeeper. Its delegate is a customer.
The shopkeeper doesn't need to know much about his customer. He takes an order for a product, calls out the customer's number when the order is ready, hands over the product, takes some money, and moves on. The customer doesn't even have to speak very much of the shopkeeper's language - only enough to place the order, understand when the order is ready, and how to pay for it.
The protocol is the language that the object (shopkeeper) uses to talk to it's delegate (customer). It's a limited, formally defined language. Any delegate (customer) who understands the required words in the object's (shopkeeper's) language (protocol) can get services from the object (shopkeeper).
BTW, you should accept the answer that helped you first and/or best, and up-vote all answers that you find useful. In this case I think you should accept #MirekE's answer. He was the first one to give you a clear answer.
How do you use UILexicon in Objective-C? I find the documentation Apple provides is extremely unhelpful.
What does it do? Does it return a dictionary or proper spellings of words? Or do I provide a word like "hellllo" and it matches it with the proper spelling "Hello" and returns that as a string?
Any help would be appreciated.
requestSupplementaryLexiconWithCompletion:
Here's my error report, but obviously I'll have errors because I'm completely guessing how to use the function, no clue what goes inside the block statement (because the docs (at the time) don't say! (Beta 4 docs)) Hahahah!
I've never used this feature, but a quick web search for "UILexicon" landed me in Apple's documentation; reading and following links from there filled in the picture pretty quick.
App Extension Programming Guide has a quick explanation of what lexicons are for:
Every custom keyboard (independent of the value of its RequestsOpenAccess key) has access to a basic autocorrection lexicon through the UILexicon class. Make use of this class, along with a lexicon of your own design, to provide suggestions and autocorrections as users are entering text.
Clicking the UILexicon link on that page took me to the reference doc for that class, which explains that it's a read-only list of Apple-provided term pairs. Each of its entries is a UILexiconEntry object -- the docs for that class say it provides a userInput (what the user typed, e.g. "ipad") and a documentText (what to substitute for it, e.g. "iPad"). Since those classes are read-only, it follows that they're probably not a way for you to provide your own autocorrection pairs -- as stated in the docs, they're for supplementing whatever autocorrection system you implement.
At this point, I don't even have to look at the doc for requestSupplementaryLexiconWithCompletion: to get a good idea how to use it: just the declaration tells me:
It's a method on UIInputViewController, the class I'd have to subclass to create a custom keyboard. Somewhere in that subclass I should probably call it on self.
Its return type is void, so I can't get a lexicon by assigning the result of a requestSupplementaryLexiconWithCompletion call to to a variable.
It calls the block I provide, passing me a UILexicon object as a parameter to that block.
It's got words like "request" and "completionHander" in it, so it'll probably do something asynchronous that takes awhile, and call that block when it's done.
So, I'm guessing that if I were writing a custom keyboard, I'd call this method early on (in viewDidLoad, perhaps) and stash the UILexicon it provides so I can refer to it later when the user is typing. Something like this:
#property UILexicon *lexicon;
- (void)viewDidLoad {
[super viewDidLoad];
[self requestSupplementaryLexiconWithCompletion:^(UILexicon *lexicon){
self.lexicon = lexicon;
}];
}
Because it's unclear how long requestSupplementaryLexiconWithCompletion will take to complete, any place where I'm using self.lexicon I should check to see if it's nil.
Back in the App Extension Programming Guide, it lists "Autocorrection and suggestion" under "Keyboard Features That iOS Users Expect", right before saying:
You can decide whether or not to implement such features; there is no dedicated API for any of the features just listed
So it sounds like autocorrection is something you have to do yourself, with your own UI that's part of the view presented by your UIInputViewController subclass. The API Quick Start for Custom Keyboards section in the programming guide seems to hint at how you'd do that: use documentContextBeforeInput to see what the user has recently typed, deleteBackward to get rid of it, and insertText: to insert a correction.
I'm a bit sceptic wether this belongs to stackoverflow or not, please let me know if I should post to codereview or programmers instead.
I want to write a reusable component for iOS that does something like this:
Accepts a number as an input, let's call it inputNumber
Records audio for 10 seconds or until the user stops recording
During recording shows live metering
After the recording, checks the recording using the provided inputNumber (we don't really care about this part at the moment)
Allows the user to play the recorded audio
Returns a path to the recorded file
Returns YES or NO based on the check of step 4
The GUI is pretty simple, just two buttons (play/pause and record/stop) together with a view for showing the audio metering during recording.
Something like this:
Now, I have implemented all the logic I need in a singleton "manager" class and what I want to do is also provide the GUI. That means that the consumers will not care about enabling/disabling buttons, showing/hiding the meter etc.
I would like for others to be able to keep using this "manager" (and probably it will be refactored to stop being a singleton), but at the same time I would like to give the option to use it as a "drop in" view.
So, this is a question of how can I setup the whole architecture.
Right now my manager has only one method:
typedef void(^CompletionBlock)(BOOL isValid, NSString* filePath, NSError *error);
-(void)evaluateRecordingForInputNumber:(NSNumber *)inputNumber completion:(CompletionBlock)completionBlock;
and this works as I want.
But if I introduce a view, how should my API look? It doesn't seem correct to me to write a custom UIView -init that will take the role of the aforementioned method, since ideally I would like to reuse this view for different model classes (providing the inputNumber) that need to be evaluated.
How can I choose between subclassing NSObject, UIControl or UIView in my case? Is there a nice way to use both my "engine" as a standalone component and also optionally provide a backing view layer?
I think this coupling is largely dependent on how you envision the custom view/manager being used.
Will it be a lot of logic that people can use without the view, and the view is just an optional feature? If so it likely makes sense to subclass NSObject and prove the view as a property of the manager itself. That way people can use your manager class as a standalone, and in UIView's where it's needed they can do something like the following:
[self.view addSubview:myCustomManager.audioView];
On the other hand if the manager class has no value to your user without the UIView itself then I think it makes a lot of sense to subclass UIView, and hide your manager class behind that UIView. One example of a widget that uses this style of implementation is stripe: Stripe iOS Widget. Everything is based off of their 'STPView', like retrieving a charge token:
[self.stripeView createToken:^(STPToken *token, NSError *error) {
if (error) {
// Handle error
// [self handleError:error];
} else {
// Send off token to your server
// [self handleToken:token];
}
}];}
One can imagine a private 'manager' class behind the scenes of the stripeView doing all the work (this method is in addition to their delegate callback).
In your case this might be a fairly good pattern. You can add a property to the custom view for the number to be evaluated, add the view to the hierarchy, and then create a custom delegate that calls back automatically after it processes things; which would take the place of your manager class callback.
The final answer is that it depends a lot on how much of split between business logic and UIView treats this will provide. As long as the code is readable, maintainable, and you have some reasonable pattern to follow I don't think anyone is going to nail you to a cross in iOS land.
I've written a very simple ReactiveCocoa test application to try my hand at coding in RAC (rather than just reading about it endlessly). It's on Github, and I wanted to get some specific questions about it answered. I'll link to the code components as I go along.
First, a brief explanation of the application: it's a timer-driven iteration counter that can be paused by the user. (Its purpose is to count how many seconds have elapsed, eliding the ones where the user paused it.) Once a second, a timer increments a variable iff the user hasn't paused the incrementing behaviour.
There are three classes I'm concerned about hearing feedback for:
MPSTicker (.m), which performs "accumulate since initialization unless paused" and provides that result on a signal. It has a public BOOL property to control whether or not accumulation is running.
MPSViewModel (.m), which provides a ViewModel wrapping from MPSTicker to the view controller. It provides read-only strings which show the number of ticks and show the text for the action which, if taken, "pauses" or "resumes" ticks. It also has a read-write BOOL for pausing/unpausing ticks.
MPSViewController (.m), which consumes strings from MPSViewModel by binding a label to the ViewModel's tick string, binding a button's text to the "tick action" string, and mapping a button's press into the ViewModel's paused property.
My questions:
I don't like the BOOL property on MPSTicker for enabling/disabling its accumulation, but I didn't know how to do it more Reactive-ly. (This also runs downstream to the ViewModel and ViewController: how can I run a string through all three of these to control whether or not the ticker is running?)
The ViewModel exposes tickString and tickStateString as very traditional properties, but the ViewController which consumes these immediately maps them back into text on a label and button text with RACObserve. This feels wrong, but I don't know how to expose a signal from the ViewModel that's easy for the ViewController to consume for these two attributes.
The ViewController suffers an indignity when flipping the paused BOOL on the ViewModel. I think this is another downstream effect of #1, "This shouldn't be a BOOL property", but I'm not sure
(Notes: I think I shied away from a signal for the BOOL of paused on MPSTicker because I didn't know how to consume it in the ViewModel to derive two strings (one for the current tick count, and one for the action text), nor how to push UI-driven value changes when the user pushes the "pause" or "resume" button. This is my core concern in questions 1 and 3.)
Some screenshots to help you visualize this gorgeous design:
Ticking:
Paused:
This is such an awesome write-up!
I don't like the BOOL property on MPSTicker for enabling/disabling its accumulation, but I didn't know how to do it more Reactive-ly. (This also runs downstream to the ViewModel and ViewController: how can I run a string through all three of these to control whether or not the ticker is running?)
Broadly, there's nothing wrong or non-Reactive about using properties. KVO-able properties can be thought of as behaviors in the academic FRP sense: they're signals which have a value at all points in their lifetime. In fact, in Objective-C properties can be even better than signals because they preserve type information that we'd otherwise lose by wrapping it in a RACSignal.
So there's nothing wrong with using KVO-able properties if it's the right tool for the job. Just tilt your head, squint a bit, and they look like signals.
Whether something should be a property or RACSignal is more about the semantics you're trying to capture. Do you need the properties (ha!) of a property, or do you care more about the general idea of a value changing over time?
In the specific case of MPSTicker, I'd argue the transitions of accumulateEnabled are really the thing you care about.
So if MPSTicker had a accumulationEnabledSignal property, we'd do something like:
_accumulateSignal = [[[[RACSignal
combineLatest:#[ _tickSignal, self.accumulationEnabledSignal ]]
filter:^(RACTuple *t) {
NSNumber *enabled = t[1];
return enabled.boolValue;
}]
reduceEach:^(NSNumber *tick, NSNumber *enabled) {
return tick;
}]
scanWithStart:#(0) reduce:^id(NSNumber *previous, id next) {
// On each tick, we add one to the previous value of the accumulate signal.
return #(previous.unsignedIntegerValue + 1);
}];
We're combining both the tick and the enabledness, since it's the transitions of both that drive our logic.
(FWIW, RACCommand is similar and uses an enabled signal: https://github.com/ReactiveCocoa/ReactiveCocoa/blob/9503c6ef7f2f327f4db6440ddfbc4ee09b86857f/ReactiveCocoaFramework/ReactiveCocoa/RACCommand.h#L95.)
The ViewModel exposes tickString and tickStateString as very traditional properties, but the ViewController which consumes these immediately maps them back into text on a label and button text with RACObserve. This feels wrong, but I don't know how to expose a signal from the ViewModel that's easy for the ViewController to consume for these two attributes.
I may be missing your point here, but I think what you've described is fine. This goes back to the above point about the relationship between properties and signals.
With RAC and MVVM, a lot of the code is simply threading data through to other parts of the app, transforming it as needed in its particular context. It's about the flow of data through the app. It's boring—almost mechanical—but that's kinda the point. The less we have to re-invent or handle in an ah hoc way, the better.
FWIW, I'd change the implementation slightly:
RAC(self, tickString) = [[[[_ticker
accumulateSignal]
deliverOn:[RACScheduler mainThreadScheduler]]
// Start with 0.
startWith:#(0)]
map:^(NSNumber *tick) {
// Unpack the value and format our string for the UI.
NSUInteger count = tick.unsignedIntegerValue;
return [NSString stringWithFormat:#"%i tick%# since launch", count, (count != 1 ? #"s" : #"")];
}];
That way we're more explicitly defining the relationship of tickString to some transformation of ticker (and we can avoid doing the strong/weak self dance).
The ViewController suffers an indignity when flipping the paused BOOL on the ViewModel. I think this is another downstream effect of #1, "This shouldn't be a BOOL property", but I'm not sure
I'm probably just missing it due to tiredness, but what's the indignity you have in mind here?