I can't figure out why this is not doing long sells, yet only long buy and why it drops after hitting into this Month. Been trying to correct this for a week now... I'm still a noob, lol...
| ||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|
| ||||||||||||
- Machine learning in trading: theory, models, practice and algo-trading
- Can I send an order for a Stop order, as soon as I close a previous order at the stop loss value within the same function ?
- A business approach to the EURUSD pair. We discuss analysis methods for this currency pair, advisors, indicators (we correct errors and refine them)
-
Why did you post your MT4 question in the MT5 General section instead of the MQL4 section, (bottom of the Root page)?
General rules and best pratices of the Forum. - General - MQL5 programming forum? (2017)
Next time, post in the correct place. The moderators will likely move this thread there soon. -
int OnInit(){ riskAmount = AccountBalance()
Why is riskAmount constant? Don't try to use any price (or indicator) or server related functions in OnInit (or on load or in OnTimer before you've received a tick), as there may be no connection/chart yet:- Terminal starts.
- Indicators/EAs are loaded. Static and globally declared variables are initialized. (Do not depend on a specific order.)
- OnInit is called.
- For indicators OnCalculate is called with any existing history.
- Human may have to enter password, connection to server begins.
- New history is received, OnCalculate called again.
- A new tick is received, OnCalculate/OnTick is called. Now TickValue, TimeCurrent, account information and prices are valid.
-
double lotSize = riskAmount / (100 * Point);
Risk depends on your initial stop loss, lot size, and the value of the symbol. It does not depend on margin or leverage. No SL means you have infinite risk (on leveraged symbols). Never risk more than a small percentage of your trading funds, certainly less than 2% per trade, 6% account total.
-
You place the stop where it needs to be — where the reason for the trade is no longer valid. E.g. trading a support bounce, the stop goes below the support. Then you compute your lot size.
-
AccountBalance * percent/100 = RISK = OrderLots * (|OrderOpenPrice - OrderStopLoss| * DeltaPerLot + CommissionPerLot) (Note OOP-OSL includes the spread, and DeltaPerLot is usually around $10/PIP, but it takes account of the exchange rates of the pair vs. your account currency.)
-
Do NOT use TickValue by itself - DeltaPerLot and verify that MODE_TICKVALUE is returning a value in your deposit currency, as promised by the documentation, or whether it is returning a value in the instrument's base currency.
MODE_TICKVALUE is not reliable on non-fx instruments with many brokers - MQL4 programming forum (2017)
Is there an universal solution for Tick value? - Currency Pairs - General - MQL5 programming forum (2018)
Lot value calculation off by a factor of 100 - MQL5 programming forum (2019) -
You must normalize lots properly and check against min and max.
-
You must also check Free Margin to avoid stop out
-
For MT5, see 'Money Fixed Risk' - MQL5 Code Base (2017)
Most pairs are worth about $10 per PIP. A $5 risk with a (very small) 5 PIP SL is $5/$10/5 or 0.1 Lots maximum.
-
-
stopLossPrice = DoubleToString(trailingStopLevel, Point);
№ 3.4
-
entryPrice = IsBreakoutUp() || IsBreakoutDown() ? Ask : Bid; stopLossPrice = DoubleToString(entryPrice - StopLoss_Pips * Point); takeProfitPrice = DoubleToString(entryPrice + TakeProfit_Pips * Point);
You buy at the Ask and sell at the Bid. Pending Buy Stop orders become market orders when hit by the Ask.
-
Your buy order's TP/SL (or Sell Stop's/Sell Limit's entry) are triggered when the Bid / OrderClosePrice reaches it. Using Ask±n, makes your SL shorter and your TP longer, by the spread. Don't you want the specified amount used in either direction?
-
Your sell order's TP/SL (or Buy Stop's/Buy Limit's entry) will be triggered when the Ask / OrderClosePrice reaches it. To trigger close at a specific Bid price, add the average spread.
MODE_SPREAD (Paul) - MQL4 programming forum - Page 3 #25 -
The charts show Bid prices only. Turn on the Ask line to see how big the spread is (Tools → Options (control+O) → charts → Show ask line.)
Most brokers with variable spreads widen considerably at end of day (5 PM ET) ± 30 minutes.
My GBPJPY shows average spread = 26 points, average maximum spread = 134.
My EURCHF shows average spread = 18 points, average maximum spread = 106.
(your broker will be similar).
Is it reasonable to have such a huge spreads (20 PIP spreads) in EURCHF? - General - MQL5 programming forum (2022)
-
-
No need to open the order and then set the stops.
-
if (OrderSelect(ticket, SELECT_BY_TICKET) && OrderType()== true) { // Check if order selection is successful
Order type is either OP_BUY or OP_SELL. It is not true.
-
EAs must be coded to recover. If the power fails, OS crashes, terminal or chart is accidentally closed, on the next tick, any static / global ticket variables will have been lost. You will have an open order / position but don't know it, so the EA will never try to close it, trail SL, etc. How are you going to recover?
Use a OrderSelect / Position select loop on the first tick, or persistent storage (GV+flush or files) of ticket numbers required.
- Aldan Parris: I can't figure out
Use the debugger or print out your variables, including _LastError and prices and find out why. Do you really expect us to debug your code for you?
Code debugging - Developing programs - MetaEditor Help
Error Handling and Logging in MQL5 - MQL5 Articles (2015)
Tracing, Debugging and Structural Analysis of Source Code - MQL5 Articles (2011)
Introduction to MQL5: How to write simple Expert Advisor and Custom Indicator - MQL5 Articles (2010)
-
Why did you post your MT4 question in the MT5 General section instead of the MQL4 section, (bottom of the Root page)?
General rules and best pratices of the Forum. - General - MQL5 programming forum? (2017)
Next time, post in the correct place. The moderators will likely move this thread there soon. - Why is riskAmount constant? Don't try to use any price (or indicator) or server related functions in OnInit (or on load or in OnTimer before you've received a tick), as there may be no connection/chart yet:
- Terminal starts.
- Indicators/EAs are loaded. Static and globally declared variables are initialized. (Do not depend on a specific order.)
- OnInit is called.
- For indicators OnCalculate is called with any existing history.
- Human may have to enter password, connection to server begins.
- New history is received, OnCalculate called again.
- A new tick is received, OnCalculate/OnTick is called. Now TickValue, TimeCurrent, account information and prices are valid.
-
Risk depends on your initial stop loss, lot size, and the value of the symbol. It does not depend on margin or leverage. No SL means you have infinite risk (on leveraged symbols). Never risk more than a small percentage of your trading funds, certainly less than 2% per trade, 6% account total.
-
You place the stop where it needs to be — where the reason for the trade is no longer valid. E.g. trading a support bounce, the stop goes below the support. Then you compute your lot size.
-
AccountBalance * percent/100 = RISK = OrderLots * (|OrderOpenPrice - OrderStopLoss| * DeltaPerLot + CommissionPerLot) (Note OOP-OSL includes the spread, and DeltaPerLot is usually around $10/PIP, but it takes account of the exchange rates of the pair vs. your account currency.)
-
Do NOT use TickValue by itself - DeltaPerLot and verify that MODE_TICKVALUE is returning a value in your deposit currency, as promised by the documentation, or whether it is returning a value in the instrument's base currency.
MODE_TICKVALUE is not reliable on non-fx instruments with many brokers - MQL4 programming forum (2017)
Is there an universal solution for Tick value? - Currency Pairs - General - MQL5 programming forum (2018)
Lot value calculation off by a factor of 100 - MQL5 programming forum (2019) -
You must normalize lots properly and check against min and max.
-
You must also check Free Margin to avoid stop out
-
For MT5, see 'Money Fixed Risk' - MQL5 Code Base (2017)
Most pairs are worth about $10 per PIP. A $5 risk with a (very small) 5 PIP SL is $5/$10/5 or 0.1 Lots maximum.
-
-
№ 3.4
-
You buy at the Ask and sell at the Bid. Pending Buy Stop orders become market orders when hit by the Ask.
-
Your buy order's TP/SL (or Sell Stop's/Sell Limit's entry) are triggered when the Bid / OrderClosePrice reaches it. Using Ask±n, makes your SL shorter and your TP longer, by the spread. Don't you want the specified amount used in either direction?
-
Your sell order's TP/SL (or Buy Stop's/Buy Limit's entry) will be triggered when the Ask / OrderClosePrice reaches it. To trigger close at a specific Bid price, add the average spread.
MODE_SPREAD (Paul) - MQL4 programming forum - Page 3 #25 -
The charts show Bid prices only. Turn on the Ask line to see how big the spread is (Tools → Options (control+O) → charts → Show ask line.)
Most brokers with variable spreads widen considerably at end of day (5 PM ET) ± 30 minutes.
My GBPJPY shows average spread = 26 points, average maximum spread = 134.
My EURCHF shows average spread = 18 points, average maximum spread = 106.
(your broker will be similar).
Is it reasonable to have such a huge spreads (20 PIP spreads) in EURCHF? - General - MQL5 programming forum (2022)
-
-
No need to open the order and then set the stops.
-
Order type is either OP_BUY or OP_SELL. It is not true.
-
EAs must be coded to recover. If the power fails, OS crashes, terminal or chart is accidentally closed, on the next tick, any static / global ticket variables will have been lost. You will have an open order / position but don't know it, so the EA will never try to close it, trail SL, etc. How are you going to recover?
Use a OrderSelect / Position select loop on the first tick, or persistent storage (GV+flush or files) of ticket numbers required.
-
Use the debugger or print out your variables, including _LastError and prices and find out why. Do you really expect us to debug your code for you?
Code debugging - Developing programs - MetaEditor Help
Error Handling and Logging in MQL5 - MQL5 Articles (2015)
Tracing, Debugging and Structural Analysis of Source Code - MQL5 Articles (2011)
Introduction to MQL5: How to write simple Expert Advisor and Custom Indicator - MQL5 Articles (2010)
Hi can I ask you to teach me and over-view my code and test them so they can be corrected and seek growth in this field?
Hi can I ask you to teach me and over-view my code and test them so they can be corrected and seek growth in this field?
can you look over this code here please it does 2 trades only and stops
// Define indicator parameters input int rsiPeriod = 14; input int stochasticK = 14; input int stochasticD = 3; input int superTrendPeriod = 10; input double superTrendMultiplier = 1.5; // Define trading parameters input double riskPercentage = 2.0; input double takeProfitMultiplier = 2.0; input int maxOpenTrades = 100; // Maximum number of open trades input int slippage = 3; // Maximum allowed slippage input double lotSize = 0.01; // Stop Loss and Take Profit input int stopLoss = 100; // Stop Loss in points input int takeProfit = 200; // Take Profit in points // Trailing Stop Loss and Take Profit input int trailingStop = 98; // Trailing Stop Loss in points input int trailingTakeProfit = 198; // Trailing Take Profit in points // Define global variables int ticketBuy = 0, ticketSell = 0; double superTrendValue; // Declare superTrendValue at the global level int openTradesCount = 0; int consecutiveCandleBodies = 10; double lastHigh = 1.0; int AB = 100; // Calculate lot size based on risk percentage void CalculateLotSize() { double accountBalance = AccountBalance(); double marginRequired = MarketInfo(_Symbol, MODE_MARGINREQUIRED); double accountFreeMargin = AccountFreeMarginCheck(_Symbol, OP_BUY, 0.1); AB = (accountBalance * riskPercentage / 100.0) / (100 * marginRequired); } // Define trading function void OnTick() { // Calculate indicators double rsiValue = iRSI(_Symbol, PERIOD_CURRENT, rsiPeriod, PRICE_CLOSE, 0); double stochasticValue = iStochastic(_Symbol, PERIOD_CURRENT, stochasticK, stochasticD, 0, MODE_SMA, 0, MODE_MAIN, 0); superTrendValue = iCustom(_Symbol, PERIOD_CURRENT, "SuperTrend", superTrendPeriod, superTrendMultiplier, 0, 0); // Calculate lot size CalculateLotSize(); // Check for stable pattern of 10 candle bodies double currentClose = iClose(_Symbol, PERIOD_CURRENT, 0); double previousClose = iClose(_Symbol, PERIOD_CURRENT, 1); if (currentClose < previousClose) { consecutiveCandleBodies++; } else { consecutiveCandleBodies = 10; } // Check for trade conditions if (consecutiveCandleBodies >= 10) { // Open short trade if conditions met if (ticketSell == 0 && currentClose > lastHigh) { ticketSell = OrderSend(_Symbol, OP_SELL, lotSize, Bid, slippage, Bid + stopLoss * Point, Bid - takeProfit * Point, "Sell Order", 1, 0, Red); if (ticketSell > 0) { openTradesCount++; lastHigh = High[1]; } ticketSell = OrderSend(_Symbol, OP_BUY, lotSize, Ask, slippage, Ask - stopLoss * Point, Ask + takeProfit * Point, "Buy Order", 1, 0, Red); if (ticketSell > 0) { openTradesCount++; lastHigh = High[0]; } } } // Check for open orders and manage them ManageOrders(); } // Function to manage open orders void ManageOrders() { for (int i = OrdersTotal() - 1; i >= 100; i--) { if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) { // Check for open sell orders if (OrderSymbol() == _Symbol && OrderType() == OP_SELL) { // Close sell order if conditions are met if (iClose(_Symbol, PERIOD_M5, 1) > superTrendValue) { if (OrderClose(OrderTicket(), OrderLots(), Ask, slippage, Green)) { ticketSell = 0; openTradesCount--; } } } } } }

- Free trading apps
- Over 8,000 signals for copying
- Economic news for exploring financial markets
You agree to website policy and terms of use