Optimization Samples

The code samples below provide examples of common optimization functions using the AdWords API. Client Library.

Estimate keyword traffic

// Copyright 2017, Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

using Google.Api.Ads.AdWords.Lib;
using Google.Api.Ads.AdWords.v201710;

using System;
using System.Collections.Generic;

namespace Google.Api.Ads.AdWords.Examples.CSharp.v201710 {

  /// <summary>
  /// This code example gets keyword traffic estimates.
  /// </summary>
  public class EstimateKeywordTraffic : ExampleBase {

    /// <summary>
    /// Main method, to run this code example as a standalone application.
    /// </summary>
    /// <param name="args">The command line arguments.</param>
    public static void Main(string[] args) {
      EstimateKeywordTraffic codeExample = new EstimateKeywordTraffic();
      Console.WriteLine(codeExample.Description);
      try {
        codeExample.Run(new AdWordsUser());
      } catch (Exception e) {
        Console.WriteLine("An exception occurred while running this code example. {0}",
            ExampleUtilities.FormatException(e));
      }
    }

    /// <summary>
    /// Returns a description about the code example.
    /// </summary>
    public override string Description {
      get {
        return "This code example gets keyword traffic estimates.";
      }
    }

    /// <summary>
    /// Runs the code example.
    /// </summary>
    /// <param name="user">The AdWords user.</param>
    public void Run(AdWordsUser user) {
      using (TrafficEstimatorService trafficEstimatorService =
          (TrafficEstimatorService) user.GetService(
              AdWordsService.v201710.TrafficEstimatorService)) {

        // Create keywords. Refer to the TrafficEstimatorService documentation for the maximum
        // number of keywords that can be passed in a single request.
        //   https://developers.google.com/adwords/api/docs/reference/latest/TrafficEstimatorService
        Keyword keyword1 = new Keyword();
        keyword1.text = "mars cruise";
        keyword1.matchType = KeywordMatchType.BROAD;

        Keyword keyword2 = new Keyword();
        keyword2.text = "cheap cruise";
        keyword2.matchType = KeywordMatchType.PHRASE;

        Keyword keyword3 = new Keyword();
        keyword3.text = "cruise";
        keyword3.matchType = KeywordMatchType.EXACT;

        Keyword[] keywords = new Keyword[] { keyword1, keyword2, keyword3 };

        // Create a keyword estimate request for each keyword.
        List<KeywordEstimateRequest> keywordEstimateRequests = new List<KeywordEstimateRequest>();

        foreach (Keyword keyword in keywords) {
          KeywordEstimateRequest keywordEstimateRequest = new KeywordEstimateRequest();
          keywordEstimateRequest.keyword = keyword;
          keywordEstimateRequests.Add(keywordEstimateRequest);
        }

        // Create negative keywords.
        Keyword negativeKeyword1 = new Keyword();
        negativeKeyword1.text = "moon walk";
        negativeKeyword1.matchType = KeywordMatchType.BROAD;

        KeywordEstimateRequest negativeKeywordEstimateRequest = new KeywordEstimateRequest();
        negativeKeywordEstimateRequest.keyword = negativeKeyword1;
        negativeKeywordEstimateRequest.isNegative = true;
        keywordEstimateRequests.Add(negativeKeywordEstimateRequest);

        // Create ad group estimate requests.
        AdGroupEstimateRequest adGroupEstimateRequest = new AdGroupEstimateRequest();
        adGroupEstimateRequest.keywordEstimateRequests = keywordEstimateRequests.ToArray();
        adGroupEstimateRequest.maxCpc = new Money();
        adGroupEstimateRequest.maxCpc.microAmount = 1000000;

        // Create campaign estimate requests.
        CampaignEstimateRequest campaignEstimateRequest = new CampaignEstimateRequest();
        campaignEstimateRequest.adGroupEstimateRequests = new AdGroupEstimateRequest[] {
            adGroupEstimateRequest};

        // Optional: Set additional criteria for filtering estimates.
        // See http://code.google.com/apis/adwords/docs/appendix/countrycodes.html
        // for a detailed list of country codes.
        Location countryCriterion = new Location();
        countryCriterion.id = 2840; //US

        // See http://code.google.com/apis/adwords/docs/appendix/languagecodes.html
        // for a detailed list of language codes.
        Language languageCriterion = new Language();
        languageCriterion.id = 1000; //en

        campaignEstimateRequest.criteria = new Criterion[] { countryCriterion, languageCriterion };

        try {
          // Create the selector.
          TrafficEstimatorSelector selector = new TrafficEstimatorSelector() {
            campaignEstimateRequests = new CampaignEstimateRequest[] { campaignEstimateRequest },

            // Optional: Request a list of campaign level estimates segmented by platform.
            platformEstimateRequested = true
          };

          // Get traffic estimates.
          TrafficEstimatorResult result = trafficEstimatorService.get(selector);

          // Display traffic estimates.
          if (result != null && result.campaignEstimates != null &&
              result.campaignEstimates.Length > 0) {
            CampaignEstimate campaignEstimate = result.campaignEstimates[0];

            // Display the campaign level estimates segmented by platform.
            if (campaignEstimate.platformEstimates != null) {
              foreach (PlatformCampaignEstimate platformEstimate in
                  campaignEstimate.platformEstimates) {
                string platformMessage = string.Format("Results for the platform with ID: " +
                    "{0} and name : {1}.", platformEstimate.platform.id,
                    platformEstimate.platform.platformName);

                DisplayMeanEstimates(platformMessage, platformEstimate.minEstimate,
                    platformEstimate.maxEstimate);
              }
            }

            // Display the keyword estimates.
            if (campaignEstimate.adGroupEstimates != null &&
                campaignEstimate.adGroupEstimates.Length > 0) {
              AdGroupEstimate adGroupEstimate = campaignEstimate.adGroupEstimates[0];

              if (adGroupEstimate.keywordEstimates != null) {
                for (int i = 0; i < adGroupEstimate.keywordEstimates.Length; i++) {
                  Keyword keyword = keywordEstimateRequests[i].keyword;
                  KeywordEstimate keywordEstimate = adGroupEstimate.keywordEstimates[i];

                  if (keywordEstimateRequests[i].isNegative) {
                    continue;
                  }
                  string kwdMessage = string.Format("Results for the keyword with text = '{0}' " +
                      "and match type = '{1}':", keyword.text, keyword.matchType);
                  DisplayMeanEstimates(kwdMessage, keywordEstimate.min, keywordEstimate.max);
                }
              }
            }
          } else {
            Console.WriteLine("No traffic estimates were returned.");
          }
          trafficEstimatorService.Close();
        } catch (Exception e) {
          throw new System.ApplicationException("Failed to retrieve traffic estimates.", e);
        }
      }
    }

    /// <summary>
    /// Displays the mean estimates.
    /// </summary>
    /// <param name="message">The message to display.</param>
    /// <param name="minEstimate">The minimum stats estimate.</param>
    /// <param name="maxEstimate">The maximum stats estimate.</param>
    private void DisplayMeanEstimates(string message, StatsEstimate minEstimate,
        StatsEstimate maxEstimate) {
      // Find the mean of the min and max values.
      long meanAverageCpc = 0;
      double meanAveragePosition = 0;
      float meanClicks = 0;
      long meanTotalCost = 0;

      if (minEstimate != null && maxEstimate != null) {
        if (minEstimate.averageCpc != null && maxEstimate.averageCpc != null) {
          meanAverageCpc = (minEstimate.averageCpc.microAmount +
              maxEstimate.averageCpc.microAmount) / 2;
        }
        if (minEstimate.averagePositionSpecified && maxEstimate.averagePositionSpecified) {
          meanAveragePosition = (minEstimate.averagePosition + maxEstimate.averagePosition) / 2;
        }
        if (minEstimate.clicksPerDaySpecified && maxEstimate.clicksPerDaySpecified) {
          meanClicks = (minEstimate.clicksPerDay + maxEstimate.clicksPerDay) / 2;
        }
        if (minEstimate.totalCost != null && maxEstimate.totalCost != null) {
          meanTotalCost = (minEstimate.totalCost.microAmount +
              maxEstimate.totalCost.microAmount) / 2;
        }
      }

      Console.WriteLine(message);
      Console.WriteLine("  Estimated average CPC: {0}", meanAverageCpc);
      Console.WriteLine("  Estimated ad position: {0:0.00}", meanAveragePosition);
      Console.WriteLine("  Estimated daily clicks: {0}", meanClicks);
      Console.WriteLine("  Estimated daily cost: {0}", meanTotalCost);
    }
  }
}

Get ad group bid simulations

// Copyright 2017, Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

using Google.Api.Ads.AdWords.Lib;
using Google.Api.Ads.AdWords.v201710;

using System;

namespace Google.Api.Ads.AdWords.Examples.CSharp.v201710 {

  /// <summary>
  /// This code example gets bid landscapes for an ad group. To get ad groups,
  /// run GetAdGroups.cs.
  /// </summary>
  public class GetAdGroupBidSimulations : ExampleBase {

    /// <summary>
    /// Main method, to run this code example as a standalone application.
    /// </summary>
    /// <param name="args">The command line arguments.</param>
    public static void Main(string[] args) {
      GetAdGroupBidSimulations codeExample = new GetAdGroupBidSimulations();
      Console.WriteLine(codeExample.Description);
      try {
        long adGroupId = long.Parse("INSERT_ADGROUP_ID_HERE");
        codeExample.Run(new AdWordsUser(), adGroupId);
      } catch (Exception e) {
        Console.WriteLine("An exception occurred while running this code example. {0}",
            ExampleUtilities.FormatException(e));
      }
    }

    /// <summary>
    /// Returns a description about the code example.
    /// </summary>
    public override string Description {
      get {
        return "This code example gets bid landscapes for an ad group. To get ad groups, run " +
            "GetAdGroups.cs";
      }
    }

    /// <summary>
    /// Runs the code example.
    /// </summary>
    /// <param name="user">The AdWords user.</param>
    /// <param name="adGroupId">Id of the ad group for which bid simulations are
    /// retrieved.</param>
    public void Run(AdWordsUser user, long adGroupId) {
      using (DataService dataService = (DataService) user.GetService(
          AdWordsService.v201710.DataService)) {

        // Create the selector.
        Selector selector = new Selector() {
          fields = new string[] {
            AdGroupBidLandscape.Fields.AdGroupId, AdGroupBidLandscape.Fields.LandscapeType,
            AdGroupBidLandscape.Fields.LandscapeCurrent, AdGroupBidLandscape.Fields.StartDate,
            AdGroupBidLandscape.Fields.EndDate, BidLandscapeLandscapePoint.Fields.Bid,
            BidLandscapeLandscapePoint.Fields.LocalClicks,
            BidLandscapeLandscapePoint.Fields.LocalCost,
            BidLandscapeLandscapePoint.Fields.LocalImpressions
          },
          predicates = new Predicate[] {
            Predicate.Equals(AdGroupBidLandscape.Fields.AdGroupId, adGroupId)
          }
        };

        try {
          // Get bid landscape for ad group.
          AdGroupBidLandscapePage page = dataService.getAdGroupBidLandscape(selector);
          if (page != null && page.entries != null && page.entries.Length > 0) {
            foreach (AdGroupBidLandscape bidLandscape in page.entries) {
              Console.WriteLine("Found ad group bid landscape with ad group id '{0}', " +
                  "type '{1}', current: '{2}', start date '{3}', end date '{4}', and " +
                  "landscape points",
                  bidLandscape.adGroupId, bidLandscape.type, bidLandscape.landscapeCurrent,
                  bidLandscape.startDate, bidLandscape.endDate);
              foreach (BidLandscapeLandscapePoint point in bidLandscape.landscapePoints) {
                Console.WriteLine("- bid: {0} => clicks: {1}, cost: {2}, impressions: {3}",
                    point.bid.microAmount, point.clicks, point.cost.microAmount,
                    point.impressions);
              }
            }
          } else {
            Console.WriteLine("No ad group bid landscapes were found.");
          }
        } catch (Exception e) {
          throw new System.ApplicationException("Failed to get ad group bid landscapes.", e);
        }
      }
    }
  }
}

Get keyword bid simulations

// Copyright 2017, Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

using Google.Api.Ads.AdWords.Lib;
using Google.Api.Ads.AdWords.v201710;

using System;

namespace Google.Api.Ads.AdWords.Examples.CSharp.v201710 {

  /// <summary>
  /// This code example gets a bid landscape for an ad group and a keyword.
  /// To get ad groups, run GetAdGroups.cs. To get keywords, run
  /// GetKeywords.cs.
  /// </summary>
  public class GetKeywordBidSimulations : ExampleBase {

    /// <summary>
    /// Main method, to run this code example as a standalone application.
    /// </summary>
    /// <param name="args">The command line arguments.</param>
    public static void Main(string[] args) {
      GetKeywordBidSimulations codeExample = new GetKeywordBidSimulations();
      Console.WriteLine(codeExample.Description);
      try {
        long adGroupId = long.Parse("INSERT_ADGROUP_ID_HERE");
        long keywordId = long.Parse("INSERT_KEYWORD_ID_HERE");
        codeExample.Run(new AdWordsUser(), adGroupId, keywordId);
      } catch (Exception e) {
        Console.WriteLine("An exception occurred while running this code example. {0}",
            ExampleUtilities.FormatException(e));
      }
    }

    /// <summary>
    /// Returns a description about the code example.
    /// </summary>
    public override string Description {
      get {
        return "This code example gets a bid landscape for an ad group and a keyword. " +
            "To get ad groups, run GetAdGroups.cs. To get keywords, run GetKeywords.cs.";
      }
    }

    /// <summary>
    /// Runs the code example.
    /// </summary>
    /// <param name="user">The AdWords user.</param>
    /// <param name="adGroupId">Id of the ad group for which keyword bid
    /// simulations are retrieved.</param>
    /// <param name="keywordId">Id of the keyword for which bid simulations are
    /// retrieved.</param>
    public void Run(AdWordsUser user, long adGroupId, long keywordId) {
      using (DataService dataService = (DataService) user.GetService(
          AdWordsService.v201710.DataService)) {

        // Create the selector.
        Selector selector = new Selector() {
          fields = new string[] {
            CriterionBidLandscape.Fields.AdGroupId, CriterionBidLandscape.Fields.CriterionId,
            CriterionBidLandscape.Fields.StartDate, CriterionBidLandscape.Fields.EndDate,
            BidLandscapeLandscapePoint.Fields.Bid, BidLandscapeLandscapePoint.Fields.LocalClicks,
            BidLandscapeLandscapePoint.Fields.LocalCost,
            BidLandscapeLandscapePoint.Fields.LocalImpressions
          },
          predicates = new Predicate[] {
            Predicate.Equals(CriterionBidLandscape.Fields.AdGroupId, adGroupId),
            Predicate.Equals(CriterionBidLandscape.Fields.CriterionId, keywordId)
          },
          paging = Paging.Default
        };

        CriterionBidLandscapePage page = new CriterionBidLandscapePage();
        int landscapePointsFound = 0;
        int landscapePointsInLastResponse = 0;

        try {
          do {
            // Get bid landscape for keywords.
            page = dataService.getCriterionBidLandscape(selector);
            landscapePointsInLastResponse = 0;

            // Display bid landscapes.
            if (page != null && page.entries != null) {
              foreach (CriterionBidLandscape bidLandscape in page.entries) {
                Console.WriteLine("Found criterion bid landscape with ad group id '{0}', " +
                    "keyword id '{1}', start date '{2}', end date '{3}', and landscape points:",
                    bidLandscape.adGroupId, bidLandscape.criterionId,
                    bidLandscape.startDate, bidLandscape.endDate);
                foreach (BidLandscapeLandscapePoint bidLandscapePoint in
                    bidLandscape.landscapePoints) {
                  Console.WriteLine("- bid: {0} => clicks: {1}, cost: {2}, impressions: {3}\n",
                      bidLandscapePoint.bid.microAmount, bidLandscapePoint.clicks,
                      bidLandscapePoint.cost.microAmount, bidLandscapePoint.impressions);
                  landscapePointsInLastResponse++;
                  landscapePointsFound++;
                }
              }
            }
            // Offset by the number of landscape points, NOT the number
            // of entries (bid landscapes) in the last response.
            selector.paging.IncreaseOffsetBy(landscapePointsInLastResponse);
          } while (landscapePointsInLastResponse > 0);
          Console.WriteLine("Number of keyword bid landscape points found: {0}",
              landscapePointsFound);
        } catch (Exception e) {
          throw new System.ApplicationException("Failed to retrieve keyword bid landscapes.", e);
        }
      }
    }
  }
}

Get keyword ideas

// Copyright 2017, Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

using Google.Api.Ads.AdWords.Lib;
using Google.Api.Ads.AdWords.v201710;

using System;
using System.Collections.Generic;

namespace Google.Api.Ads.AdWords.Examples.CSharp.v201710 {

  /// <summary>
  /// This code example retrieves keywords that are related to a given keyword.
  /// </summary>
  public class GetKeywordIdeas : ExampleBase {

    /// <summary>
    /// Main method, to run this code example as a standalone application.
    /// </summary>
    /// <param name="args">The command line arguments.</param>
    public static void Main(string[] args) {
      GetKeywordIdeas codeExample = new GetKeywordIdeas();
      Console.WriteLine(codeExample.Description);
      try {
        long adGroupId = long.Parse("INSERT_ADGROUP_ID_HERE");
        codeExample.Run(new AdWordsUser(), adGroupId);
      } catch (Exception e) {
        Console.WriteLine("An exception occurred while running this code example. {0}",
            ExampleUtilities.FormatException(e));
      }
    }

    /// <summary>
    /// Returns a description about the code example.
    /// </summary>
    public override string Description {
      get {
        return "This code example retrieves keywords that are related to a given keyword.";
      }
    }

    /// <summary>
    /// Runs the code example.
    /// </summary>
    /// <param name="user">The AdWords user.</param>
    /// <param name="adGroupId">ID of the ad group to use for generating ideas.</param>
    public void Run(AdWordsUser user, long? adGroupId) {
      using (TargetingIdeaService targetingIdeaService =
          (TargetingIdeaService) user.GetService(AdWordsService.v201710.TargetingIdeaService)) {

        // Create selector.
        TargetingIdeaSelector selector = new TargetingIdeaSelector();
        selector.requestType = RequestType.IDEAS;
        selector.ideaType = IdeaType.KEYWORD;
        selector.requestedAttributeTypes = new AttributeType[] {
          AttributeType.KEYWORD_TEXT,
          AttributeType.SEARCH_VOLUME,
          AttributeType.AVERAGE_CPC,
          AttributeType.COMPETITION,
          AttributeType.CATEGORY_PRODUCTS_AND_SERVICES
        };

        List<SearchParameter> searchParameters = new List<SearchParameter>();

        // Create related to query search parameter.
        RelatedToQuerySearchParameter relatedToQuerySearchParameter =
            new RelatedToQuerySearchParameter();
        relatedToQuerySearchParameter.queries = new String[] {
          "bakery", "pastries", "birthday cake"
        };
        searchParameters.Add(relatedToQuerySearchParameter);

        // Add a language search parameter (optional).
        // The ID can be found in the documentation:
        //   https://developers.google.com/adwords/api/docs/appendix/languagecodes
        LanguageSearchParameter languageParameter = new LanguageSearchParameter();
        Language english = new Language();
        english.id = 1000;
        languageParameter.languages = new Language[] { english };
        searchParameters.Add(languageParameter);

        // Add network search parameter (optional).
        NetworkSetting networkSetting = new NetworkSetting();
        networkSetting.targetGoogleSearch = true;
        networkSetting.targetSearchNetwork = false;
        networkSetting.targetContentNetwork = false;
        networkSetting.targetPartnerSearchNetwork = false;

        NetworkSearchParameter networkSearchParameter = new NetworkSearchParameter();
        networkSearchParameter.networkSetting = networkSetting;
        searchParameters.Add(networkSearchParameter);

        // Optional: Use an existing ad group to generate ideas.
        if (adGroupId != null) {
          SeedAdGroupIdSearchParameter seedAdGroupIdSearchParameter =
              new SeedAdGroupIdSearchParameter();
          seedAdGroupIdSearchParameter.adGroupId = adGroupId.Value;
          searchParameters.Add(seedAdGroupIdSearchParameter);
        }

        // Set the search parameters.
        selector.searchParameters = searchParameters.ToArray();

        // Set selector paging (required for targeting idea service).
        Paging paging = Paging.Default;

        TargetingIdeaPage page = new TargetingIdeaPage();

        try {
          int i = 0;
          do {
            // Get related keywords.
            page = targetingIdeaService.get(selector);

            // Display related keywords.
            if (page.entries != null && page.entries.Length > 0) {
              foreach (TargetingIdea targetingIdea in page.entries) {
                Dictionary<AttributeType, AdWords.v201710.Attribute> ideas =
                    targetingIdea.data.ToDict();

                string keyword = (ideas[AttributeType.KEYWORD_TEXT] as StringAttribute).value;
                IntegerSetAttribute categorySet =
                    ideas[AttributeType.CATEGORY_PRODUCTS_AND_SERVICES] as IntegerSetAttribute;

                string categories = string.Join(", ", categorySet.value);

                long averageMonthlySearches =
                    (ideas[AttributeType.SEARCH_VOLUME] as LongAttribute).value;

                Money averageCpc = (ideas[AttributeType.AVERAGE_CPC] as MoneyAttribute).value;
                double competition = (ideas[AttributeType.COMPETITION] as DoubleAttribute).value;
                Console.WriteLine("Keyword with text '{0}', average monthly search " +
                    "volume {1}, average CPC {2}, and competition {3:F2} was found with " +
                    "categories: {4}", keyword, averageMonthlySearches, averageCpc.microAmount,
                    competition, categories);

                Console.WriteLine("Keyword with text '{0}', and average monthly search volume " +
                    "'{1}' was found with categories: {2}", keyword, averageMonthlySearches,
                    categories);
                i++;
              }
            }
            selector.paging.IncreaseOffset();
          } while (selector.paging.startIndex < page.totalNumEntries);
          Console.WriteLine("Number of related keywords found: {0}", page.totalNumEntries);
        } catch (Exception e) {
          throw new System.ApplicationException("Failed to retrieve related keywords.", e);
        }
      }
    }
  }
}

Send feedback about...

AdWords API
AdWords API
Need help? Visit our support page.