Integrate with FeedHub Edge
Use REST to find canonical IDs and refresh prices before a bet. Use gRPC for feed changes, bet placement and settlements. The examples use the REST reference and gRPC reference.
Connect a client
Section titled “Connect a client”Use the REST and gRPC addresses of your sandbox Edge instance. Replace https://edge-rest.sandbox.example and https://edge-grpc.sandbox.example with the addresses supplied for your instance. The sandbox betting example requires a client entry enabled for catalog, betting and results. Install Edge in the sandbox
For .NET, restore FeedHub.Edge.Client 1.7.0 from the public BetFeedPro feed. Use the package source configuration and restore instructions to set up a net10.0 project.
using System.Globalization;using System.Net.Http.Json;using System.Text.Json;using FeedHub.Edge.V1;using Grpc.Core;using Grpc.Net.Client;using EdgeStatusCode = FeedHub.Edge.V1.Status;
using var rest = new HttpClient { BaseAddress = new Uri("https://edge-rest.sandbox.example") };using var channel = GrpcChannel.ForAddress("https://edge-grpc.sandbox.example");var feed = new FeedEdge.FeedEdgeClient(channel);To generate C# stubs, download feed_edge.proto from the Edge 1.1.0 client kit, verify its checksum against the kit’s SHA256SUMS, and place it alongside your project. Install Google.Protobuf, Grpc.Net.Client and the build-time Grpc.Tools dependency. Add this item and run dotnet build. Use the generated stubs or the prebuilt package in the project to avoid duplicate types. For another language, use the same proto with that language’s gRPC plugin and the standard google/protobuf/timestamp.proto import. Versioned downloads
<ItemGroup> <Protobuf Include="feed_edge.proto" GrpcServices="Client" /></ItemGroup>Read the catalog and markets
Section titled “Read the catalog and markets”Read all sport pages and choose an enabled sport. Then read the active events for its canonical ID and pass an event’s ID to the markets route. Each markets response item includes a market snapshot and a suspended flag. In an unsuspended item, choose a market from market.markets and a selection from its selections rows. Keep the returned marketId and selectionId for the refresh and placement below. Reference data · Events · Markets and selections
var sports = await ReadListAsync(rest, "/local/v1/sports?limit=50", stopping);var sportId = sports.Single(sport => sport.GetProperty("key").GetString() == "football") .GetProperty("id").GetString()!;
var events = await ReadListAsync(rest, $"/local/v1/events?sportId={Uri.EscapeDataString(sportId)}&isLive=false&limit=50", stopping);var eventId = events.First().GetProperty("event").GetProperty("eventId").GetString()!;var markets = await rest.GetFromJsonAsync<JsonElement>( $"/local/v1/events/{Uri.EscapeDataString(eventId)}/markets", stopping);This example assumes football and an active prematch event are available. If a list is empty, wait for data or choose a sport enabled for your client entry. An event can disappear between the event list and markets read. Use the status and problem code in the REST reference to distinguish a missing event from temporary unavailability.
The helper keeps the original list path and query parameters. It URL-encodes each opaque nextCursor, follows it on the same list, and stops at JSON null. A page can be short before the list ends.
static async Task<List<JsonElement>> ReadListAsync(HttpClient rest, string list, CancellationToken stopping){ var items = new List<JsonElement>(); var separator = list.Contains('?') ? '&' : '?'; string? cursor = null; do { var path = cursor is null ? list : $"{list}{separator}cursor={Uri.EscapeDataString(cursor)}"; var page = await rest.GetFromJsonAsync<JsonElement>(path, stopping); items.AddRange(page.GetProperty("items").EnumerateArray()); cursor = page.GetProperty("nextCursor").GetString(); } while (cursor is not null);
return items;}Apply a snapshot and follow changes
Section titled “Apply a snapshot and follow changes”Create new SubscriptionView(sportId) with the sport ID returned above, then call WatchAsync(feed, stopping) on that view. This example subscribes to both phases and keeps the applied view and token in memory. Give each filter its own view and token. If you persist the token across a restart, save it with its matching applied state in one transaction. Start with an empty token if that state is missing.
sealed class SubscriptionView(string sportId){ private sealed record HeldMarket(Market Market, bool HeldBack = false);
private sealed record HeldEvent(EventChanged Event, Dictionary<string, HeldMarket> Markets, bool Withdrawn = false) { public HeldEvent Withdraw() => this with { Withdrawn = true, Markets = Markets.ToDictionary(entry => entry.Key, entry => entry.Value with { HeldBack = true }), }; }
private readonly object gate = new(); private Dictionary<string, HeldEvent> applied = []; private string token = ""; private bool ready; private bool hasActiveView; private bool takingSnapshot;
public async Task WatchAsync(FeedEdge.FeedEdgeClient feed, CancellationToken stopping) { while (!stopping.IsCancellationRequested) { Dictionary<string, HeldEvent>? staged = null; var request = new SubscribeRequest { SportIds = { sportId }, Phase = Phase.Any, ResumeToken = token }; try { using var call = feed.Subscribe(request, cancellationToken: stopping); await foreach (var message in call.ResponseStream.ReadAllAsync(stopping)) { lock (gate) { switch (message.BodyCase) { case FeedEvent.BodyOneofCase.Status: ready = message.Status.Status.State == EdgeStatusCode.Ready; break; case FeedEvent.BodyOneofCase.SnapshotBegin: takingSnapshot = true; staged = []; break; case FeedEvent.BodyOneofCase.SnapshotEnd when staged is not null: foreach (var (id, previous) in applied) if (!staged.ContainsKey(id)) staged.Add(id, previous.Withdraw()); applied = staged; staged = null; takingSnapshot = false; break; default: Apply(staged ?? applied, message); break; }
if (staged is null && message.ResumeToken.Length > 0) { token = message.ResumeToken; hasActiveView = true; } } } } catch (RpcException ex) when (!stopping.IsCancellationRequested && ex.StatusCode is StatusCode.Unavailable or StatusCode.Internal or StatusCode.Cancelled) { } finally { lock (gate) { ready = false; hasActiveView = false; takingSnapshot = false; } }
await Task.Delay(TimeSpan.FromSeconds(2), stopping); } }
private static void Apply(Dictionary<string, HeldEvent> view, FeedEvent message) { switch (message.BodyCase) { case FeedEvent.BodyOneofCase.Event: view[message.Event.EventId] = new HeldEvent(message.Event, view.GetValueOrDefault(message.Event.EventId)?.Markets ?? []); break; case FeedEvent.BodyOneofCase.Market when view.TryGetValue(message.Market.EventId, out var marketEvent): foreach (var market in message.Market.Markets) marketEvent.Markets[market.MarketId] = new HeldMarket(market); break; case FeedEvent.BodyOneofCase.MarketRemoved when view.TryGetValue(message.MarketRemoved.EventId, out var removedEvent): removedEvent.Markets.Remove(message.MarketRemoved.MarketId); break; case FeedEvent.BodyOneofCase.EventWithdrawn when view.TryGetValue(message.EventWithdrawn.EventId, out var withdrawnEvent): view[message.EventWithdrawn.EventId] = withdrawnEvent.Withdraw(); break; case FeedEvent.BodyOneofCase.EventUnsubscribed: view.Remove(message.EventUnsubscribed.EventId); break; } }
public bool CanOffer(string eventId, string marketId, string selectionId) { lock (gate) { return ready && hasActiveView && !takingSnapshot && applied.TryGetValue(eventId, out var held) && !held.Withdrawn && !held.Event.IsFinished && held.Event.Content is not null && held.Markets.TryGetValue(marketId, out var market) && !market.HeldBack && !market.Market.Suspended && market.Market.Rows.SelectMany(row => row.Selections) .Any(selection => selection.SelectionId == selectionId && !selection.IsSuspended); } }}Run one WatchAsync loop per view. A fresh snapshot can follow any reconnect, including one that supplied a resume token. Stage that snapshot separately. If the stream ends mid-snapshot, the next call starts from the last applied view and token. Replay can repeat changes after the last applied token, so keep updates repeatable.
At SnapshotEnd, treat absent events as withdrawn. A withdrawal suspends the event and all its markets, and a later market update can restore a held market. Only an EventChanged with is_finished indicates a finish. EventUnsubscribed removes an event that left the filter. Remove individual markets on MarketRemoved and use the event manifest for information. While degraded, treat every market as suspended. When Edge returns to ready, the event, market and selection flags still apply. Event changes · Market suspension and removal
Refresh and place one sandbox attempt
Section titled “Refresh and place one sandbox attempt”Use a market and selection ID returned by Edge. Check their current tradability in the view, then send their market ID to POST /local/v1/refresh. Use only a Served reply for the intended active event with a matching market and selection. Take the price and isLive from that refresh. The bets model shows a worked refresh and placement exchange.
static async Task<(string Price, bool IsLive)?> RefreshOfferAsync( HttpClient rest, string eventId, string marketId, string selectionId, CancellationToken stopping){ using var response = await rest.PostAsJsonAsync("/local/v1/refresh", new { marketIds = new[] { marketId } }, stopping); response.EnsureSuccessStatusCode(); var refresh = await response.Content.ReadFromJsonAsync<JsonElement>(cancellationToken: stopping); if (refresh.GetProperty("unknownMarketIds").EnumerateArray().Any(id => id.GetString() == marketId)) return null;
foreach (var entry in refresh.GetProperty("events").EnumerateArray()) { if (entry.GetProperty("eventId").GetString() != eventId || entry.GetProperty("status").GetString() != "Served") continue;
var item = entry.GetProperty("event"); if (item.ValueKind == JsonValueKind.Null || item.GetProperty("isFinished").GetBoolean() || item.GetProperty("content").ValueKind == JsonValueKind.Null) return null;
var manifest = item.GetProperty("manifest"); if (manifest.ValueKind != JsonValueKind.Array) return null;
foreach (var snapshot in entry.GetProperty("markets").EnumerateArray()) { var hash = snapshot.GetProperty("contentHash").GetString(); if (!manifest.EnumerateArray().Any(m => m.GetProperty("marketId").GetString() == marketId && m.GetProperty("contentHash").GetString() == hash)) continue;
foreach (var market in snapshot.GetProperty("markets").EnumerateArray()) { if (market.GetProperty("marketId").GetString() != marketId) continue; foreach (var row in market.GetProperty("selections").EnumerateArray()) foreach (var selection in row.EnumerateArray()) { if (selection.GetProperty("selectionId").GetString() == selectionId && !selection.GetProperty("isSuspended").GetBoolean() && selection.GetProperty("value").GetString() is { } price && decimal.TryParse(price, NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out var value) && value > 1) return (price, item.GetProperty("isLive").GetBoolean()); } } } }
return null;}The example below places one attempt at the refreshed price when the calling application authorizes the sandbox stake. Implement saveAttempt as a durable write of the pending request before the RPC. The caller persists the reply or the recovered status under that key. Use a stake allowed by your sandbox and encode it as an invariant decimal string. view.CanOffer supplies the tradability check.
static async Task<(PlaceBetReply? Placement, BetStatus? Lookup)> PlaceSandboxAsync( FeedEdge.FeedEdgeClient feed, HttpClient rest, SubscriptionView view, string eventId, string marketId, string selectionId, decimal stake, Func<PlaceBetRequest, CancellationToken, Task> saveAttempt, CancellationToken stopping){ if (stake <= 0 || !view.CanOffer(eventId, marketId, selectionId)) return (null, null); var offer = await RefreshOfferAsync(rest, eventId, marketId, selectionId, stopping); if (offer is null || !view.CanOffer(eventId, marketId, selectionId)) return (null, null);
var request = new PlaceBetRequest { ClientBetKey = Guid.NewGuid().ToString("D"), MarketId = marketId, SelectionId = selectionId, Price = offer.Value.Price, Stake = stake.ToString(CultureInfo.InvariantCulture), AcceptPriceChanges = false, IsLive = offer.Value.IsLive, }; await saveAttempt(request, stopping);
try { var reply = await feed.PlaceBetAsync(request, deadline: DateTime.UtcNow.AddSeconds(18), cancellationToken: stopping); return (reply, null); } catch (RpcException ex) when (!stopping.IsCancellationRequested && ex.StatusCode is StatusCode.Unavailable or StatusCode.DeadlineExceeded or StatusCode.Cancelled or StatusCode.Internal) { return (null, await LookUpAttemptAsync(feed, request.ClientBetKey, stopping)); }}
static async Task<BetStatus> LookUpAttemptAsync(FeedEdge.FeedEdgeClient feed, string clientKey, CancellationToken stopping){ var request = new GetBetsRequest { ClientBetKeys = { clientKey } }; var reply = await feed.GetBetsAsync(request, deadline: DateTime.UtcNow.AddSeconds(8), cancellationToken: stopping); return reply.Bets.Single();}An Accepted placement includes the bet ID. PriceChanged refuses the bet at the requested price and can report the provider’s current_price. A new price requires a new decision and a new attempt key. Suspended, Unavailable, Failed, Refused and Conflict close this attempt with their respective outcomes. Treat an unknown outcome as Failed.
When the placement reply is lost, look up the saved key. Open, Settled or Expired identifies a recorded accepted bet, and NotPlaced includes the placement outcome. A failed lookup, Placing, NotFound during recovery or an unknown state leaves the attempt pending for further lookup or investigation. On cancellation or restart, recover the pending attempt by its saved key. Never generate a new key to retry an uncertain attempt. Set deadlines above the corresponding Edge timeouts, including when your instance overrides the defaults. Bet lookup and recovery
Apply and confirm settlements
Section titled “Apply and confirm settlements”Run one result reader per client entry. Use the same feed client and channel for ReadBetResults and ConfirmBetResult. The channel must route both calls to the replica serving the active stream. Settlements and result identity
static async Task ReadResultsAsync(FeedEdge.FeedEdgeClient feed, Func<SettledBet, CancellationToken, Task> applyOnceAsync, CancellationToken stopping){ while (!stopping.IsCancellationRequested) { try { using var call = feed.ReadBetResults(new ReadBetResultsRequest(), cancellationToken: stopping); await foreach (var delivery in call.ResponseStream.ReadAllAsync(stopping)) { await applyOnceAsync(delivery.Result, stopping); await feed.ConfirmBetResultAsync(new ConfirmBetResultRequest { DeliveryId = delivery.DeliveryId }, cancellationToken: stopping); } } catch (RpcException ex) when (!stopping.IsCancellationRequested && ex.StatusCode is StatusCode.Unavailable or StatusCode.Internal or StatusCode.Cancelled or StatusCode.NotFound) { }
await Task.Delay(TimeSpan.FromSeconds(2), stopping); }}Implement applyOnceAsync with a durable transaction. Use bet_id as a unique key for the applied settlement. If the transaction inserts that key, apply the result in the same transaction and commit. If the key is already present, keep the existing result and return after the transaction completes. Record unknown settlement results for manual settlement. Confirm only after the write succeeds.
If a result returns on a later stream, its bet_id stays the same and its delivery_id changes. The durable record prevents a second application. Confirm the new delivery ID on its current channel. If confirmation returns NOT_FOUND, reopen the stream and let Edge redeliver any unconfirmed result.